Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chapter 32: Escaping special characters with shellescape(..., 1) #111

Open
mxxk opened this issue Dec 22, 2020 · 0 comments
Open

Chapter 32: Escaping special characters with shellescape(..., 1) #111

mxxk opened this issue Dec 22, 2020 · 0 comments

Comments

@mxxk
Copy link

mxxk commented Dec 22, 2020

(Since this issue will likely not be addressed in the book itself due to #95, may it hopefully be informative to whomever happens to come across it...)

Chapter 32, section "Escaping Shell Command Arguments", ends with

Now that we know how to get a fully-escaped version of the word under the cursor, it's time to concatenate it into our mapping! Run the following command:

:nnoremap <leader>g :exe "grep -R " . shellescape(expand("<cWORD>")) . " ."<cr>

Try it out. This mapping won't break if the word we're searching for happens to contain strange characters.

However, the above mapping breaks if there are special characters in the current WORD under the cursor. A couple examples of such WORDs are:

  1. %-percent-char, which ends up invoking :grep -R '%-percent-char' and % expands to the current file name, and
  2. <afile>-string, which errors out with E497: no autocommand match name to substitute for "<afile>".

A simple fix for this is to pass a non-zero {special} arg to shellescape({string} [, {special}]), which will escape special items as well. With this knowledge, the final mapping can be further refined as follows:

:nnoremap <leader>g :exe "grep -R " . shellescape(expand("<cWORD>"), 1) . " ."<cr>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant