4

When I use search in vim with / command, while typing in characters, I am able to see first occurrence of searched regular expression pattern via highlighting in text area of vim. However, while using :s command, I want to be able to see first occurrence highlighted as I type pattern for what-to-substitute block, but I see no highlighting, as I understand, it is because of command-mode, which is give no highlighting even for search via / in it.

For example, as I type :s/foo/bar, if there's any fo sequence in text, I want it to be highlighted after I typed in :s/fo, but it is not.

Does anybody knows any workaround for this? thx.

sandric
  • 2,310
  • 3
  • 21
  • 26

1 Answers1

13

You can't: :s is a : command, not a search command, and highlighting can only be done on search commands.

But despair not!

/foo highlights stuff, then :s//bar replaces stuff using the last search string.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • what if I wanted to capture parts of `foo`? – Max Coplan Feb 10 '20 at 21:15
  • @MaxCoplan Sorry, but that's too vague, I don't understand what you're asking. Can you make a specific example? – Amadan Feb 10 '20 at 22:32
  • As in using regex capture groups in `vim`. So if I have a bunch of `h3` tags like `

    stuff

    `and I wanted to capture the inside of the tag and do something with `stuff`
    – Max Coplan Feb 10 '20 at 22:51
  • 1
    @MaxCoplan Yes, you can do that, exactly as if you wrote the pattern in `:s` itself. For example, `/

    \zs.*\ze<\/h3>` followed by `:s//chuff/` does exactly the same thing as `:s/

    \zs.*\ze<\/h3>/chuff/`, and `/\(

    \).*\(<\/h3>\)` followed by `:s//\1chuff\2/` does exactly the same thing as `:s//\1chuff\2/`. However, [beware Zalgo](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags).

    – Amadan Feb 10 '20 at 23:00
  • Ah, perfect! Thank you – Max Coplan Feb 10 '20 at 23:18
  • this seems to only replace instances on the same line, not across the whole document – Max Coplan Feb 11 '20 at 14:31
  • @MaxCoplan Yes, just like `:s/foo/bar` in OP's example. If you want the whole document, you have to say so, using the range `1,$`, or `%` in short: `:%s/foo/bar`. It also only replaces once per line; if you want it to replace all occurrences in each line, use the `g` modifier: `:%s/foo/bar/g`. When you use the previous pattern, this would boil down to `:%s//bar/g`. – Amadan Feb 11 '20 at 14:33