How to create a new directory and file in Vim

When using Vim as a text editor, is there a way to create new directories and files in text editor mode? Instead of returning to the command line and creating a new directory and file.

+31
source share
4 answers

Assuming you are working in a shell, I would lay out for any of these commands. Enter command mode using Esc , and then:

:! touch new-file.txt :! mkdir new-directory 

A great plugin for these actions is vim-eunuch , which gives you a lot of sugar for UNIX shell commands. Here is the latest example using vim-eunuch:

 :Mdkir new-directory 
+27
source

Switch to file view

:Ex or if this does not work, use :Explore

then click

d

and add a new directory name.

+31
source

If you are in explorer mode, you can use:

d to create a directory

% for creating a new file

No need to call external commands with !

+14
source

To complete the picture:

  • Shell and use regular commands like :!mkdir my_dir and :!mkdir my_dir :!touch foo.txt (as mentioned in Jake's answer here ) will create a directory and a file in the CURRENT working directory, which is the directory when you started the current vim process at the beginning, but It is NOT MANDATORY the same directory of the file you are currently editing, or the same directory that your is viewing :Explore explorer. If in doubt, always use :!pwd to check your current working directory first, and use the relative path if necessary.

  • Therefore, if your project contains several subdirectories, a more convenient way:

    1. Type :Explore to enter Explorer mode first,
    2. and then you can easily go to any subdirectory you like by typing up-arrow or down-arrow (or j or k ) to move the cursor by typing Enter to enter a subdirectory by typing [TG25] to go up to the directory level . (Note that all of these navigations DO NOT change your current working directory);
    3. Now you can type d to request a directory name or type % to request a file name, and then they will be created in the directory that is currently displayed on the screen. PS: these keys are actually mentioned in F1's built-in help.
+6
source

All Articles