0

When I use Vim and type in the :w command, sometimes I will tap ] or \ by accident before I tap the Enter key because these keys are close to each other. As a result, I will get files such as ']' in my directory.

So I want to execute some autocmd in Vim to check if the file name which is going to be saved contains such special characters.

I have searched through the Internet, almost all of them give the solution of something like expand("%:p") to get file name. But after testing it by myself, this function can only obtain the current file name instead of the one I passed to :w command.

Is there any idea of obtaining the file name passed to :w command in Vim's autocmd?

2
  • 1
    If you hit wrong keys a lot it's maybe time to think about improving your typing skills. You will benefit from more speed, accuracy and confidence. Fix the root cause of your problem.
    – Friedrich
    Mar 3, 2023 at 13:00
  • Thanks for your suggestion! In fact, I'm not quite sure whether it's my typo or it's just something wrong with my keyboard because I haven't encountered this problem several weeks ago. Anyway, before I decide to further check my keyboard, I have to bother Vim to help check my typo :)
    – rqdmap
    Mar 5, 2023 at 7:32

1 Answer 1

0

I would propose you to introduce a command expression mapping cnoremap on the <CR> character. In the expression you could parse the command line and adapt it if it is wrong.

Here is a (too) simple example that detect ']' in your w[rite] leading command and replace it with \ waiting for your confirmation and do nothing otherwise.

function! CorrectWritePath()
  if getcmdtype() != ':'
    return "\<CR>"
  endif

  if matchstr(getcmdline(), '^w\%[rite]!\?\>') == ''
    return "\<CR>"
  endif

  let l:cmdline = getcmdline()

  " Parse the cmd line
  let l:newcmdline = l:cmdline
  let l:good = v:true
  if matchstr(l:cmdline, ']') != ''
    echo 'match'
    let l:newcmdline = substitute(l:cmdline, ']', '\', 'g')
    let l:good = v:false
  endif

  if l:good
    return "\<CR>"
  else
    return "\<C-u>" . l:newcmdline  
  endif

endfunction
cnoremap <expr> <CR> CorrectWritePath()
4
  • 1
    For the match on getcmdline(), try w\%[rite]
    – D. Ben Knoble
    Mar 3, 2023 at 14:20
  • Thanks @Ben! With you everyday is chance to learn :-) Mar 3, 2023 at 14:26
  • 1
    Thanks a lot! This works!
    – rqdmap
    Mar 5, 2023 at 7:35
  • Wecome to Vim :-) Thanks for the feedback! Mar 5, 2023 at 8:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.