hjm
hjm

Reputation: 1943

How to make a new directory and a file in Vim

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

Upvotes: 132

Views: 128781

Answers (6)

Ondřej Kolín
Ondřej Kolín

Reputation: 1602

If you are in the file explorer mode, you can use:

d for creating a directory

% for creating a new file

You can get into the explorer mode with issuing a command :Sexplore or :Vexplore

There is no need to call external commands with !

Upvotes: 139

Jake Worth
Jake Worth

Reputation: 5852

Assuming you're running a shell, I would shell out for either of these commands. Enter command mode with Esc, and then:

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

A great plugin for these actions is vim-eunuch, which gives you syntactic sugar for shell commands. Here's the latter example, using vim-eunuch:

:Mdkir new-directory

Upvotes: 83

alvinMemphis
alvinMemphis

Reputation: 352

Alternatively you can use :e . to get to explorer mode and then hit d .to create the new directory .Thought a shorter answer might be better

Upvotes: 6

ggguser
ggguser

Reputation: 2682

Assuming you just ran vim on new file in the directory that does not exist:

vim new_dir/new_file.txt

When you try :w you will get 'E212: Can't open file for writing'
To create new directory and file use this:

:!mkdir -p %:h

Upvotes: 64

RayLuo
RayLuo

Reputation: 19230

For the sake of completeness:

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

  • So if your project contains multiple sub-directories, a more convenient way is to:

    1. type :Explore to enter the explorer mode first,
    2. and then you can easily navigate to whatever sub-directory you like, by typing up-arrow or down-arrow (or j or k) to move cursor, typing Enter to enter a sub-directory, typing - to go up a level of directory. (Note that, all these navigation does NOT change your current working directory either);
    3. Now you can type d to be prompted for a directory name, or type % to be prompted for a file name, and then they will be created in the directory currently shown on screen. PS: These keys are actually mentioned in the built-in help F1.

Upvotes: 10

bonyiii
bonyiii

Reputation: 2883

Switch to file browsing mode

:Ex or if that is not working use :Explore

then press

d

and add the new directory name.

Upvotes: 65

Related Questions