Practical Vim< /a> vit Practical Vim< /a> Note that the styling for a Visual selection is the... development I thought I knew Vim, but Practical" name="description"/>
Tải bản đầy đủ - 0 (trang)
Tip 86. Search for the Current Visual Selection

Tip 86. Search for the Current Visual Selection

Tải bản đầy đủ - 0trang

Search for the Current Visual Selection

• 213

We start off in Visual mode with the first three words selected and our cursor

placed on the word “sea.” When we invoke the * command, it searches forward

for the next occurrence of the word “sea,” extending the range of the visual

selection. Although this behavior is consistent with the Normal mode * command, I rarely find it useful.

Before I became hooked on Vim, I used another text editor, which included

a “Use selection for find” command. I had the keyboard shortcut for this

burned into my fingers and used it all the time. When I switched to Vim, I

was surprised to find that it didn’t have such a feature. It always felt to me

that triggering the * command from Visual mode should search for the current

selection, not the current word. With a small amount of Vim script, we can

add this feature to Vim.

Search for the Current Selection (Prior Art)

If you look up :h visual-search

, you’ll find this suggestion:

Here is an idea for a mapping that makes it possible to do a search for the

selected text:

:vmap X y/"

Note that special characters (like “.” and “*”) will cause problems.

The y command yanks the current visual selection, and /" brings up

the search prompt, pastes the contents of the default register, and then executes the search. That solution is simple, but as the cautionary note in Vim’s

documentation says, it has limitations.

In Tip 78, on page 193, we learned how to overcome these limitations. Now

let’s put that theory into practice and create a mapping that searches for the

current selection without being derailed by special characters.

Search for the Current Selection (Redux)

This snippet of Vim script does the trick:


xnoremap * :call VSetSearch()/=@/

xnoremap # :call VSetSearch()?=@/

function! s:VSetSearch()

let temp = @s

norm! gv"sy

let @/ = '\V' . substitute(escape(@s, '/\'), '\n', '\\n', 'g')

let @s = temp


report erratum • discuss

Chapter 13. Search

• 214

You can either paste this into your vimrc file directly or install the visual star

search plugin.1

As well as overriding the * command, we’ve customized the # command,

which searches backward for selected text. The xnoremap keyword specifies

that the mappings should apply to Visual mode but not to Select mode (see

:h mapmode-x ).


report erratum • discuss



You might think that the substitute command is just for simple find and

replace operations, but in fact, it’s one of the most powerful Ex commands

available. By the time we’ve reached the end of this chapter, we’ll have learned

all the many roles that the substitute command can play, from simple to very


We’ll look at a few tips and tricks that allow us to compose substitution

commands more quickly by reusing the last search pattern. We’ll also look

at a special case, where Vim allows us to eyeball every occurrence before

confirming the substitution. We’ll learn how we can fill out the replacement

field without typing, and we’ll examine some of the special behaviors that are

available through the replacement field. We’ll also learn how to repeat the

last substitute command over a different range without having to retype the

whole command.

We can execute Vim script expressions in the replacement field. We’ll study

an advanced example that exploits this to perform arithmetic on a series of

numerical matches. Then we’ll learn how to swap two (or more) words with

a single substitute command.

We’ll finish by looking at a couple of strategies for performing search and

replace across multiple files.

report erratum • discuss

Chapter 14. Substitution

• 216

Tip 87

Meet the Substitute Command

The :substitute command is complex: in addition to providing a search pattern

and replacement string, we have to specify the range over which it will execute.

Optionally, we can also provide flags to tweak its behavior.

The substitute command allows us to find and replace one chunk of text with

another. The command’s syntax looks like this:


The substitute command has many parts to it. The rules for the [range] are

just the same as for every other Ex command, which we covered in-depth in

Tip 28, on page 54. As for the {pattern}, that was covered in Chapter 12,

Matching Patterns and Literals, on page 183.

Tweak the Substitute Command Using Flags

We can tweak the behavior of the substitute command using flags. The best

way to understand what a flag does is to see it in action, so let’s briefly define

a handful of flags that are used in other tips. (For a complete reference, look

up :h :s_flags .)

The g flag makes the substitute command act globally, causing it to change

all matches within a line rather than just changing the first one. We’ll meet

it in Tip 88, on page 217.

The c flag gives us the opportunity to confirm or reject each change. We’ll see

it in action in Tip 89, on page 219.

The n flag suppresses the usual substitute behavior, causing the command

to report the number of occurrences that would be affected if we ran the

substitute command. Tip 82, on page 204, gives an example of usage.

If we run the substitute command using a pattern that has no matches in

the current file, Vim will report an error saying “E486: Pattern not found.”

We can silence these errors by including the e flag, as we’ll see in Tip 96, on

page 233.

The & flag simply tells Vim to reuse the same flags from the previous substitute

command. Tip 92, on page 224, shows a scenario where it comes in handy.

report erratum • discuss

Find and Replace Every Match in a File

• 217

Special Characters for the Replacement String

In Chapter 12, Matching Patterns and Literals, on page 183, we saw that some

characters take on special meaning when used in search patterns. The

replacement field also has a handful of special characters. You can find the

complete list by looking up :h sub-replace-special , but some of the highlights

are summarized in this table:




Insert a carriage return


Insert a tab character


Insert a single backslash


Insert the first submatch


Insert the second submatch (and so on, up to \9)


Insert the entire matched pattern


Insert the entire matched pattern


Use {string} from the previous invocation of :substitute

\={Vim script}

Evaluate {Vim script} expression; use result as replacement


The \r, \t and \\ tokens should be fairly self-explanatory. In Tip 92, on page 224,

we’ll see how the ~ token works, but we’ll also learn about a couple of shortcuts that make it even faster to repeat a substitute command. We’ll see \1

and \2 in use in Tip 93, on page 228.

The \={Vim script} token is very powerful. It allows us to execute code and use

the result as our replacement {string}. In Tip 94, on page 229, and Tip 95, on

page 230, we’ll see a couple of examples of usage.

Tip 88

Find and Replace Every Match in a File

By default, the substitute command acts on the current line, changing the first

occurrence only. To change every match throughout a file, we have to specify

a range and use the g flag. For demonstration purposes, we’ll use this text:


When the going gets tough, the tough get going.

If you are going through hell, keep going.

report erratum • discuss

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tip 86. Search for the Current Visual Selection

Tải bản đầy đủ ngay(0 tr)