Skip to content

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

@mxxk

Description

@mxxk

(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>

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions