I want to set up a key mapping to open an absolute path filename highlighted in visual mode that may have a line break in the middle.
Most files I have are formatted in the following way, and I would like to highlight the path between the single quotes and open that file (formatted for MSC NASTRAN for those curious):
INCLUDE '/directory/directory/directory/directory/
directory/filename'
What's difficult is yanking that whole section results in a ^M newline character in the middle of the path. My approach was the following (walking through the :map command below):
Open file path in @f
map <F8> y \| :let @f=substitute(strtrans(@0),'\^@','','g') \| :e <C-R>f<CR>
The problem is that if it's run a second time on a new file path, vim uses the previous path stored in the @f register before updating @f
Any ideas to fix it or another approach? Clearing the register with :let @f='' at the end didn't seem to work either.
I also don't have admin rights, since this is a work computer, so I don't think I can install plugins, but I'm still new to vim, any thoughts appreciated. Thanks!
An auxiliary register is unnecessary; use :exec
in order to evaluate an expression and use the result as an argument to a command. I'm not sure whether strtrans()
is somehow advantageous, but replacing \n
directly seems to work. Either way, make sure to use fnameescape()
. Also, use noremap
in order to avoid recursive mappings unless you need them. If this particular mapping is intended only for visual mode, xnoremap
is even better.
xnoremap <F8> y \| :exec "e" fnameescape(substitute(getreg('"'),'\n','','g'))<CR>