Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All the special characters that need escaping in vim pattern searching/replacment?

Tags:

vim

Is there a list of them? I have a trouble when I want to replace {inspect.stack()[0][3]} to {inspect.stack()[0][3]} called from {inspect.stack()[1][3]} in my python code. And I cannot find a full list from internet.

like image 530
Feng Wang Avatar asked Nov 27 '18 10:11

Feng Wang


People also ask

How do I find special characters in vim?

For example, to search for the string “anything?” type /anything\? and press Return. You can use these special characters as commands to the search function. If you want to search for a string that includes one or more of these characters, you must precede the special character with a backslash.

How do you do a search and replace string in vim?

The simplest way to perform a search and replace in Vim editor is using the slash and dot method. We can use the slash to search for a word, and then use the dot to replace it. This will highlight the first occurrence of the word “article”, and we can press the Enter key to jump to it.

How do you get out of replace in vim?

Press y to replace the match or l to replace the match and quit. Press n to skip the match and q or Esc to quit substitution. The a option substitutes the match and all remaining occurrences of the match. To scroll the screen down, use CTRL+Y , and to scroll up, use CTRL+E .

How do I find and replace every incident of a text string in vim?

When you want to search for a string of text and replace it with another string of text, you can use the syntax :[range]s/search/replace/. The range is optional; if you just run :s/search/replace/, it will search only the current line and match only the first occurrence of a term.


1 Answers

:substitute (the command)

To do a literal substitution, specify "very-nomagic" :help /\V (or escape all special search characters ^$.*[~) and "case-sensitive" /\C, and escape the :substitute separator (usually /) and any backslashes (\) in the source. Line breaks must be changed from ^M to \n. Taken together, for the pattern:

'\V\C' . substitute(escape(literalPattern, '/\'), "\n", '\\n', 'ge')

In the replacement, & and ~ must be escaped (in addition to / and \) if the 'magic' option is set. (\V doesn't work here). Cp. :help sub-replace-special

escape(literalReplacement, '/\' . (&magic ? '&~' : ''))

substitute() (the function)

Something similar applies to substitute() as well; & must always be escaped, as 'magic' is always set, and only ~ must not be escaped:

substitute(input, '\V\C' . escape(literalPattern, '\'), escape(literalReplacement, '\&')), 'g')
like image 70
Ingo Karkat Avatar answered Oct 10 '22 09:10

Ingo Karkat