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 7. Pause with Your Brush Off the Page

Tip 7. Pause with Your Brush Off the Page

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

Chapter 2. Normal Mode



• 16



How much time do you reckon artists spend with their paint brushes in

contact with the canvas? No doubt it would vary from artist to artist, but I’d

be surprised if it counted for as much as half of the time painters spend at

work.

Think of all of the things that painters do besides paint. They study their

subject, adjust the lighting, and mix paints into new hues. And when it comes

to applying paint to the canvas, who says they have to use brushes? A painter

might switch to a palette knife to achieve a different texture or use a cotton

swab to touch up the paint that’s already been applied.

The painter does not rest with a brush on the canvas. And so it is with Vim.

Normal mode is the natural resting state. The clue is in the name, really.

Just as painters spend a fraction of their time applying paint, programmers

spend a fraction of their time composing code. More time is spent thinking,

reading, and navigating from one part of a codebase to another. And when

we do want to make a change, who says we have to switch to Insert mode?

We can reformat existing code, duplicate it, move it around, or delete it. From

Normal mode, we have many tools at our disposal.



Tip 8



Chunk Your Undos

In other text editors, invoking the undo command after typing a few words

might revert the last typed word or character. However, in Vim we can control

the granularity of the undo command.

The u key triggers the undo command, which reverts the most recent change.

A change could be anything that modifies the text in the document. That

includes commands triggered from Normal, Visual, and Command-Line modes,

but a change could also encompass any text entered (or deleted) in Insert

mode. So we could also say that i {insert some text} constitutes a change.

In nonmodal text editors, triggering the undo command after typing a few

words could do one of two things. It could undo the last character that was

typed. Or, more helpfully, it could chunk a set of characters together so that

each undo operation removed a word instead of a character.

In Vim, we can control the granularity of the undo command. From the

moment we enter Insert mode until we return to Normal mode, everything we

type (or delete) counts as a single change. So we can make the undo command



www.it-ebooks.info



report erratum • discuss



Compose Repeatable Changes



• 17



operate on words, sentences, or paragraphs just by moderating our use of

the key.

So how often should you leave Insert mode? It’s a matter of preference, but

I like to make each “undoable chunk” correspond to a thought. As I write this

text (in Vim, of course!), I often pause at the end of a sentence to consider

what I’ll write next. No matter how brief its duration, each pause forms a

natural break point, giving me a cue to leave Insert mode. When I’m ready to

continue writing, I press A and carry on where I left off.

If I decide that I’ve taken a wrong turn, I’ll switch to Normal mode and press

u . Each time I undo, my text decomposes in coherent chunks that correspond

to my thought process as I was writing the original text. It means that I can

easily try out a sentence or two and then throw them away with a couple of

keystrokes.

If I’m in Insert mode with my cursor at the end of a line, the quickest way to

open a new line is to press . And yet I sometimes prefer to press o

just because I anticipate that I might want that extra granularity from the

undo command. If this sounds hard core, don’t worry. As you become adept

with Vim, switching modes feels more and more lightweight.

As a general rule, if you’ve paused for long enough to ask the question, “Should

I leave Insert mode?” then do it.



Moving Around in Insert Mode Resets the Change

When I said that the undo command would revert all characters entered (or deleted)

during a trip into Insert mode and back, I was glossing over a small detail. If we use

the , , , or cursor keys while in Insert mode, a new undo

chunk is created. It’s just as though we had switched back to Normal mode to move

around with the h , j , k , or l commands, except that we don’t have to leave Insert

mode. This also has implications on the operation of the dot command.



Tip 9



Compose Repeatable Changes

Vim is optimized for repetition. In order to exploit this, we have to be mindful

of how we compose our changes.

In Vim, we always have more than one way of doing something. In evaluating

which way is best, the most obvious metric is efficiency: which technique



www.it-ebooks.info



report erratum • discuss



Chapter 2. Normal Mode



• 18



requires the fewest keystrokes (a.k.a. VimGolf1). But how should we pick a

winner in the event of a tie?

Suppose that our cursor is positioned on the “h” at the end of this line of text,

and we want to delete the word “nigh.”

normal_mode/the_end.txt

The end is nigh



Delete Backward

Since our cursor is already at the end of the word, we might begin by deleting

backward.

Keystrokes



Buffer Contents



{start}



The end is nigh



db



The end is h



x



The end is



Pressing db deletes from the cursor’s starting position to the beginning of the

word, but it leaves the final “h” intact. We can delete this rogue character by

pressing x . That gives us a Vim golf score of 3.



Delete Forward

This time, let’s try deleting forward instead.

Keystrokes



Buffer Contents



{start}



The end is nigh



b



The end is nigh



dw



The end is



We have to start by maneuvering our cursor into position with the b motion.

Once it’s in place, we can excise the word with a single dw command. Once

again, our Vim golf score is 3.



Delete an Entire Word

Both of our solutions so far have involved some kind of preparation or cleanup. We can be more surgical by using the aw text object instead of a motion

(see :h aw ):



1.



http://vimgolf.com/



www.it-ebooks.info



report erratum • discuss



Compose Repeatable Changes



Keystrokes



Buffer Contents



{start}



The end is nigh



daw



The end is



• 19



The daw command is easily remembered by the mnemonic delete a word. We’ll

go into more detail on text objects in Tip 51, on page 120, and Tip 52, on page

124.



Tie-Breaker: Which Is Most Repeatable?

We’ve tried three techniques for deleting a word: dbx , bdw , and daw . In each

case, our Vim golf score is 3. So how can we settle the question of which is

best?

Remember, Vim is optimized for repetition. Let’s go through these techniques

again. This time, we’ll finish by invoking the dot command and see what

happens. I urge you to try these out for yourself.

The backward deletion technique involves two operations: db deletes to the

start of the word and then x deletes a single character. If we invoke the dot

command, it repeats the single character deletion ( . == x ). That’s not what I

would call a big win.

The forward deletion technique also involves two steps. This time, b is just a

plain motion, while dw makes a change. The dot command repeats dw , deleting

from the cursor position to the beginning of the next word. It so happens that

we’re already at the end of the line. There is no “next word,” so in this context

the dot command isn’t useful. But at least it’s shorthand for something longer

( . == dw ).

The final solution only invokes a single operation: daw . This technique doesn’t

just remove the word, it also deletes a whitespace character. As a result, our

cursor ends up on the last character of the word “is.” If we invoke the dot

command, it will repeat the instruction to delete a word. This time, the dot

command does something truly useful ( . == daw ).



Discussion

The daw technique invests the most power into the dot command, so I declare

it the winner of this round.

Making effective use of the dot command often requires some forethought. If

you notice that you have to make the same small change in a handful of

places, you can attempt to compose your changes in such a way that they

can be repeated with the dot command. Recognizing those opportunities takes



www.it-ebooks.info



report erratum • discuss



Chapter 2. Normal Mode



• 20



practice. But if you develop a habit of making your changes repeatable

wherever possible, then Vim will reward you for it.

Sometimes, I won’t see an opportunity to use the dot command. After making

a change—and finding that I need to perform an identical edit—I realize that

the dot command is primed and ready to do the work for me. It makes me

grin every time.



Tip 10



Use Counts to Do Simple Arithmetic

Most Normal mode commands can be executed with a count. We can exploit

this feature to do simple arithmetic.

Many of the commands that are available in Normal mode can be prefixed

with a count. Instead of executing the command just once, Vim will attempt

to execute the command the specified number of times (see :h count ).

The and commands perform addition and subtraction on numbers.

When run without a count they increment by one, but if we prefix a number,

then we can add or subtract by any whole number. For example, if we positioned our cursor on a 5 character, running 10 would modify it to read

15.

But what happens if the cursor is not positioned on a numeric digit? The

documentation says that the command will “add [count] to the number

at or after the cursor” (see :h ctrl-a ). So if the cursor is not already positioned

on a number, then the command will look ahead for a digit on the current line. If it finds one, it jumps straight to it. We can use this to our

advantage.

Here’s a snippet of CSS:

normal_mode/sprite.css

.blog, .news { background-image: url(/sprite.png); }

.blog { background-position: 0px 0px }



We’re going to duplicate the last line and make two small modifications to it:

replace the word “blog” with “news,” and change “0px” to “-180px.” We can

duplicate the line by running yyp and then using cw to change the first word.

But how should we deal with that number?



www.it-ebooks.info



report erratum • discuss



Use Counts to Do Simple Arithmetic



• 21



One approach would be to jump to the digit with f0 and then dip into Insert

mode to change the value by hand: i -18. But it’s quicker just to run

180 . Since our cursor isn’t on a digit to begin with, it jumps forward to

the first one that it finds. That saves us the step of moving the cursor by

hand. Let’s see this work flow in action:

Keystrokes



Buffer Contents



{start}



.blog, .news { background-image: url(/sprite.png); }

.blog { background-position: 0px 0px }



yyp



.blog, .news { background-image: url(/sprite.png); }

.blog { background-position: 0px 0px }

.blog { background-position: 0px 0px }



cW.news



.blog, .news { background-image: url(/sprite.png); }

.blog { background-position: 0px 0px }

.news { background-position: 0px 0px }



180



.blog, .news { background-image: url(/sprite.png); }

.blog { background-position: 0px 0px }

.news { background-position: -180px 0px }



In this example, we’ve only duplicated the line once and made changes. But

suppose we had to make ten copies, subtracting 180 from the number in

each successive copy. If we were to switch to Insert mode to amend each

number, we’d have to type something different each time (-180, then -360, and

so on). But by using the 180 command, our work flow is identical for each

successive line. We could even record our keystrokes as a macro (see Chapter

11, Macros, on page 157) and then play it back as many times as needed.



Number Formats

What follows 007? No, this isn’t a James Bond gag; I’m asking what result would you

expect if you added one to 007.

If you answered 008, then you might be in for a surprise when you try using Vim’s

command on any number with a leading zero. As is the convention in some

programming languages, Vim interprets numerals with a leading zero to be in octal

notation rather than in decimal. In the octal numeric system, 007 + 001 = 010, which

looks like the decimal ten but is actually an octal eight. Confused?

If you work with octal numbers frequently, Vim’s default behavior might suit you. If

you don’t, you probably want to add the following line to your vimrc:

set nrformats=



This will cause Vim to treat all numerals as decimal, regardless of whether they are

padded with zeros.



www.it-ebooks.info



report erratum • discuss



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

Tip 7. Pause with Your Brush Off the Page

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

×