How to set working/current directory in Vim?
Asked Answered
S

10

155

So when I want to create a new file by using the :e command I don't want to specify the whole path, just the new filename. Can it be done?

Sulfapyridine answered 18/2, 2010 at 13:6 Comment(0)
R
214

As already suggested, you can use autochdir, which will change to the directory of the file you opened, the other option is

:cd mydirectory

which will change the directory. This can be an absolute or relative path, so :cd .. will move up one level. Or you can use :cd %:h which will also change to the directory the current file is in, but without setting autochdir.

:cd

will change directory to your home directory (or on windows, print the current directory).

:cd -

will change the directory to the previous directory you visited.

Roswell answered 18/2, 2010 at 13:11 Comment(6)
if you're using multiple windows, you can even use :lcd to change directory for the current window only.Impulse
@Useless: interesting... I don't think I'd ever want that, but I suppose that's a matter of taste. Thanks for the info.Roswell
I'm trying to figure out what the %:h means, any help?Gaby
@Gaby % translates to the current file name including path, : adds modifier, h is head, i.e. the path up to the last path separator, that is excluding the file name itself.Roswell
@falstro, do you know how :cd command can apply to all windows within the same vim running instances? Ex: when using split :spScarlettscarp
When using multiple tabs, you can use :tcd to change directory for the current tab only.Mcguinness
S
21

Also if you are browsing the filesystem with the netrw file explorer you can set the current directory by pressing the cd key.

It used to be just c in older versions, but it may not work now.

Shading answered 18/2, 2010 at 17:29 Comment(2)
also use set autochdir to make the 'c' key take effect in shell, so that you can use !command args under changed dir.Turkish
Note that it's changed from c to cd now.Jell
M
15

Try adding set autochdir to your .vimrc. If you want to change it just this once, use :cd (or :cd! to force it).

Myrilla answered 18/2, 2010 at 13:8 Comment(2)
the help says this breaks some plugins (i don't know which ones) so I've taken the precaution of adding mapping in my .vimrc: cnoremap cd. lcd %:p:h and nnoremap ,cd :cd %:p:h<CR>:pwd<CR> insteadTit
also use 'c' key in netrw file explorer to accompany this.Turkish
I
5

With netrw: in addition to pressing the c key to set the current directory, you may also put:

let g:netrw_keepdir= 0

in your .vimrc; this means that netrw will keep the browsing directory the same as the current directory.

Intratelluric answered 11/7, 2011 at 19:17 Comment(1)
This seems to have an equivalent behavior as :lcd for each netrw folder change. Do you have an idea how this setting could be the equivalent as a :cd instead (change dir for all windows)? Thanks!Scarlettscarp
S
4

I don't know what is wrong with vim. I want the directory where I start up vim as the current.

I have followed the tip about autochd above and set that to noautcd in my .vimrc.

I haven't done it yet, but I am about to start up vim like this from now on:

vim —cmd 'cd `pwd`'

That will make it stick to the current directory!

Shakta answered 23/1, 2013 at 14:33 Comment(1)
There's a (em-dash) character in your code, you probably mean --.Jell
J
3

Adding this to my .vimrc automatically changes Vim's working dir to the current file:

autocmd BufEnter * silent! :lcd%:p:h
Jehu answered 23/1, 2015 at 16:39 Comment(1)
set autochdir does that as well :-)Academic
P
1

Update: Now I just use those code instead of install a plugin

" 自动切nvim到当前文件所在路径, 避免leaderF每个命令前都要敲一下 :pwd.
    " 代替autochdir:  Switch to the directory of the current file unless it breaks something.
    au AG BufEnter * call AutoDiR()
    func! AutoDiR()
        " Don't mess with vim on startup.
        let should_cd = (!exists("v:vim_did_enter") || v:vim_did_enter)
                                                  " 或
                                " v:vim_did_enter :
                                "     0 during startup
                                "     1 just before VimEnter.
        "  forbid for some filetypes
            " let should_cd = should_cd && david#init#find_ft_match(['help', 'dirvish', 'qf']) < 0
        " Only change to real files:
        let should_cd = should_cd && filereadable(expand("%"))
                                    " filereadable()
                                            " The result is a Number, which is |TRUE| when a file with the
                                            " name {file} exists, and can be read.
        if should_cd
            silent! cd %:p:h
        endif
    endf

    " cdh:   cd here
    nno cd :cd %:p:h<cr><cmd>pwd<cr><cmd>let g:Lf_WorkingDirectory=getcwd()<cr><cmd>echo "Lf目录:"..g:Lf_WorkingDirectory<cr>
    " nno cdh
    cnorea <expr> cdh ( getcmdtype() == ":" && getcmdline() == 'cdh') ?
                      \ 'cd %:p:h<cr>  :pwd<cr>'
                      \ :  'cdh'


    " 方法2: 不好使? 要敲一次pwd触发?
        " au AG VimEnter * set autochdir | pwd | echom '设置了autochdir'
                                " Note: When this option is on,  some plugins may not work.
    " 貌似不行:
        " Plug 'https://github.com/airblade/vim-rooter'


    " 对于vscode-nvim
        " vscode用wsl的nvim作为bin时,pwd永远是Microsoft VS Code.  等邮件通知更新吧. 其实不影响使用?
        " 我的笔记: https://github.com/vscode-neovim/vscode-neovim/issues/520#issuecomment-1013853745
        "
        "  这个也不行:
        " au AG BufEnter * silent! lcd %:p:h
                " lcd: local window cd ?
                "      Like |:cd|, but only set the current directory for the  current window.

You could install the Rooter Vim plugin, which automatically changes the working directory to the automatically-detected project root when you open a file or directory. After Rooter has set the working directory for you, if you try to edit a file like :e example.txt, Vim will edit example.txt in the project root.

If you’re using the vim-plug plugin manager, you can install Rooter by adding the following to your .vimrc, then reloading Vim and running :PlugInstall.

Plug 'airblade/vim-rooter'
Projector answered 20/1, 2022 at 2:51 Comment(0)
R
1

This was solution to my problem when using Nvim NvChad.

I did try to use set autochdir but that still didn't work.

So next thing I did was set custom mapping.

  1. Add to custom/chadrc.lua this line of code M.mappings = require "custom.mappings"
  2. Create new file mappings.lua in folder custom
  3. Add this lines of code to mappings.lua
local M = {}
M.abc = {
    n = {
        ["<leader>cf"] = {"<cmd>cd %:h <CR>", "Set Files Location As Dir"} 
    }
}
return M
  1. Open nvim and to change dir to current file location press <leader>cf

Hope this helps!

Remillard answered 28/5, 2023 at 18:18 Comment(0)
H
0

For those wondering about %:h the relevant Vim help topic is:

:help filename-modifiers

Once there, if you scroll down, there are several examples that demonstrate the various modifiers.


% and # are a bit further up the page. They're covered at:

:help cmdline-special


Hearken answered 20/3 at 16:46 Comment(0)
Z
0

cd can be used in netrw to change the vim's directory to browsing directory.

[ above was also shared in this comment by @user202729 : How to set working/current directory in Vim? ]

Following illustrative steps show how to find where it's documented in netrw's inbuilt help. These will expose you on how to explore & learn other inbuilt features of netrw on your own. 😃

<:Ex to enter netrw>

"   Quick Help: <F1>:help

<press F1>

    Quick Reference: Maps         |netrw-quickmap|

<move cursor to '|' in this line, press 'ctrl-]' to select this topic>
<scroll down to find the following>

      cd   Make browsing directory the current directory        netrw-cd

<:q to exit netrw help>
<:Rex to exit netrw>

(reference for :Rex: Vim - Quit/Close Netrw without selecting any file)

Zinnia answered 22/4 at 10:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.