I am wondering about a regex that would enable me to get the final "directory/file" from a path. I'll explain the reason why. After using vim for 20+ years, I've finally had cause to edit "over scp". To keep things simple between my remote systems and my local git clone, I edit the files remotely (because I have to build on the remote host), but I only commit/push from the local clone. I've written a simple function, WriteLocal()
, which I've mapped to some simple keystrokes to pull the components I need to write the file into the local repo (working copy). The function now looks like this
function! WriteLocal()
let ldir = matchstr(expand('%:h'), '\w\+$')
let lfile = expand('%:t')
execute 'w!' ldir . "/" . lfile
endfunction
I resorted to this because I just couldn't get a regex to work that would pull apart the "scp path" and give me just the final directory and file name. These are some of my attempts
let foo = matchstr(expand('%'), '\w\+/\{-}.\+$')
" or this one
let foo = matchstr(expand('%'), '\w\{-}/\{1}.\+$')
Neither of these worked as g:foo
was empty. I do have a solution and though it works, if there is a way to make it concise to a single line, I'd like that solution. Perhaps a solution exists which doesn't use regex? I didn't even consider that until writing this. Does vimscript have a way to split a string into an array?
expand
/fnamemodify
can do dirname/basename so easily? – D. Ben Knoble♦ Oct 12 '20 at 22:20fnamemodify
existed. I've just tried it in some experiments and I likely don't understand it. It doesn't seem to work for me. Yesterday, I eventually settled on a solution usingexpand
andfindfile
. This had the benefit of returning a path relative topwd
, which is what I wanted. – Andrew Falanga Oct 13 '20 at 14:34expand('%:h')
andexpand('%:t')
. For a general string,fnamemodify(file, ':h')
,fnamemodify(file, ':t')
. For just the last directory, use:h:t
. Does "path" in the title refer to the option'path'
or to a generic file-path? – D. Ben Knoble♦ Oct 13 '20 at 14:44:.
to get paths relative to the current directory (if possible) – D. Ben Knoble♦ Oct 13 '20 at 14:47path
in the title. I meant it as a general path because I am editing over scp. The directory path to the point of the git clone on the remote would be different than my local, but once in the clone, it's the same. Because I am editing code on a remote system that is in the same repo, I put my shell at the root. A path relative to that point was the goal. Thanks for the help. Learning how to script vim is great. – Andrew Falanga Oct 13 '20 at 15:02