Home > Enterprise >  Using vim gf command with "@" webpack alias
Using vim gf command with "@" webpack alias

Time:01-05

I regularly use Vuejs and Webpack with the "@" character for file resolution, like so

import MyComponent from "@/components/MyComponent.vue";

However, I cannot use the vim gf command to move to this file.

E447: Can't find file "/components/MyComponent.vue" in path

I have spent a couple of hours googling, messing around with the vim path and includeexpr. I have also tried a couple of plugins, like vim-npr or vim-gotofile.

Has anyone encountered the same problem and found a solution?

edit

Best thing I came up with so far is this:

:set inex=substitute(v:fname,'^\\@\/','src/','')

found it in another stackoverflow thread where they where using the ~ character for this. However it doesn't work with @. I get this error when trying to gf

E869: (NFA) Unknown operator '\@/'

My Solution

With help from @romainl I now have this set up in both after/ftplugin/vue.vim and after/ftplugin/javascript.vim

setlocal isfname =@-@
setlocal includeexpr=substitute(v:fname,'^@\/','src/','')

Thank you for your help!

CodePudding user response:

In the linked question, ~ is escaped because ~ has a special meaning for Vim's regexp engine: "matches the last given substitute string".

But @ is not special in any way so there is no need to escape it:

setlocal includeexpr=substitute(v:fname,'^@\/','src/','')

As you noticed, there is another problem. Vim uses :help 'isfname' to define v:fname but the option's value doesn't contain the @ character by default so it is left out out of v:fname. Since there is no @ in v:fname, the pattern in substitute() doesn't match and we end up with:

Actual string v:fname After includeexpr Outcome
@/foo/bar.vue /foo/bar.vue /foo/bar.vue Not found

The solution is to add @ to isfname:

setlocal isfname =@-@

which gives us:

Actual string v:fname After includeexpr Outcome
@/foo/bar.vue @/foo/bar.vue src/foo/bar.vue Found

Tested to work with $ vim -Nu NONE file.js.

Now, the settings above being filetype-specific, it is best to put them in a ftplugin. Assuming the filetype of your buffers is javascript, a proper location would be:

" on Unix-like systems
~/.vim/after/ftplugin/javascript.vim

" on Windows
%USERPROFILE%\vimfiles\after\ftplugin\javascript.vim

YMMV.


Note that, in the answers to the linked questions, ^\\~ is incorrect and throws an error E874. The correct pattern is ^\~.

  •  Tags:  
  • Related