Reputation: 1943
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
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
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
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
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
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:
:Explore
to enter the explorer mode first,Upvotes: 10
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