如何在 Vim 中创建新的目录和文件

当使用 Vim 作为文本编辑器时,是否有办法在文本编辑器模式下创建新的目录和文件?而不是返回到命令行并创建一个新的目录和文件。

71422 次浏览

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

Switch to file browsing mode

:Ex or if that is not working use :Explore

then press

d

and add the new directory name.

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.

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

d for creating a directory

% for creating a new file

In explorer mode you can get with issuing a command :Sexplore or :Vexplore

There is no need to call external commands with !

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

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