usr_03.txt ForVim version 9.2. Last change: 2026 Feb 14 VIM USER MANUALbyBramMoolenaar Moving aroundBefore you caninsert or delete text the cursor has to be moved to the rightplace. Vim hasa large number of commands to position the cursor. Thischapter shows you how to use the most important ones. You can findalist ofthese commands belowQ_lr.03.1 Wordmovement03.2 Moving to the start orend ofa line03.3 Moving toa character03.4 Matchinga parenthesis03.5 Moving toa specific line03.6 Telling where you are03.7 Scrolling around03.8 Simple searches03.9 Simple search patterns03.10 Using marks Next chapter:usr_04.txt Making small changes Previous chapter:usr_02.txt The first steps in VimTable of contents:usr_toc.txt==============================================================================03.1 WordmovementTo move the cursor forward one word, use the "w" command. Like most Vimcommands, you can usea numeric prefix to move past multiple words. Forexample, "3w" moves three words. This figure shows howit works (startingatthe position marked with "x"):This is a line with example text x-->-->->----------------->www 3wNotice that "w" moves to the start of the nextword ifit alreadyisat thestart ofa word. The "b" command moves backward to the start of the previous word:This is a line with example text<----<--<-<---------<--xbbb 2bbThereis also the "e" command that moves to the nextend ofaword and "ge",which moves to the previousend ofa word:This is a line with example text <----<----x---->------------> 2gegee 2eIf you areat the lastword ofa line, the "w" command will take you to thefirstword in the next line. Thus you can use this to move throughaparagraph, much faster than using "l". "b" does the same in the otherdirection.Aword endsata non-word character, suchasa ".", "-" or ")". To changewhat Vim considers to bea word, see the'iskeyword' option. If you try thisout in thehelp directly,'iskeyword' needs to be reset for the examples towork::set iskeyword&Itis also possible to move bywhite-space separated WORDs. Thisis notaword in the normal sense, that's why theuppercaseis used. The commands formoving by WORDs are also uppercase,as this figure shows:gebwe <- <- ---> --->This is-a line, with special/separated/words (and some more). <----- <----- --------------------> ----->gEBWEWith this mix oflowercase anduppercase commands, you can quickly moveforward and backward througha paragraph.==============================================================================03.2 Moving to the start orend ofa lineThe "$" command moves the cursor to theend ofa line. If your keyboard hasan<End> keyit willdo the same thing.The "^" command moves to the first non-blank character of the line. The "0"command (zero) moves to the very first character of the line, and the<Home>key does the same thing. Ina picture("." indicatesa space):^ <-----------x.....This is a line with example text<----------------x x-------------->0$(the "....." indicates blanks here) The "$" command takesa count, like mostmovement commands. But moving totheend of the line several times doesn't make sense. Thereforeit causes theeditor to move to theend of another line. For example, "1$" moves you totheend of the first line (the one you're on), "2$" to theend of the nextline, and so on. The "0" command doesn't takeacount argument, because the "0" would bepart of the count. Unexpectedly, usingacount with "^" doesn't have anyeffect.==============================================================================03.3 Moving toa characterOne of the most usefulmovement commandsis the single-character searchcommand. The command "fx" searches forward in the line for the singlecharacter x. Hint: "f" stands for "Find". For example, you areat the beginning of the following line. Suppose youwant togo to theh of human. Just execute the command "fh" and the cursorwill be positioned over the h:To err is human. To really foul up you need a computer.---------->---------------> fh fyThis also shows that the command "fy" moves to theend of theword really. You can specifya count; therefore, you cango to the "l" of "foul" with"3fl":To err is human. To really foul up you need a computer. ---------------------> 3flThe "F" command searches to the left:To err is human. To really foul up you need a computer. <--------------------- FhThe "tx" command works like the "fx" command, exceptit stops one characterbefore the searched character. Hint: "t" stands for "To". The backwardversion of this commandis "Tx".To err is human. To really foul up you need a computer. <------------ ------------->ThtnThese four commands can be repeated with ";". "," repeats in the otherdirection. The cursoris never moved to another line. Not even when thesentence continues.Sometimes you will starta search, only to realize that you have typed thewrong command. You type "f" to search backward, for example, only to realizethat you really meant "F". To aborta search, press<Esc>. So "f<Esc>"is anaborted forward search and doesn'tdo anything.Note:<Esc> cancels mostoperations, not just searches.==============================================================================03.4 Matchinga parenthesisWhenwritinga program you oftenend up with nested () constructs. Then the"%" commandis very handy: It moves to the matching paren. If the cursorisona "("it will move to the matching ")". If it's ona ")"it will move tothe matching "(".%<----->if (a == (b * c) / d)<---------------->%This also works for[] and{} pairs. (This can be defined with the'matchpairs' option.)When the cursoris not ona useful character, "%" will search forward to findone. Thus if the cursorisat the start of the line of the previous example,"%" will search forward and find the first "(". Thenit moves to its match:if (a == (b * c) / d)---+---------------->%Other ways to move around code can be found inusr_29.txt.==============================================================================03.5 Moving toa specific lineIf you areaC or C++ programmer, you are familiar with errormessages suchasthe following:prog.c:33: j undeclared (first use in this function)This tells you that you might want to fix something on line 33. So howdo youfind line 33? One wayis todo "9999k" togo to the top of the file and "32j"togo down thirty-two lines. Itis nota good way, butit works.A muchbetter way of doing thingsis to use the "G" command. Witha count, thiscommand positions youat the given line number. For example, "33G" puts youon line 33. (Fora better way of going througha compiler's error list, seeusr_30.txt, for information on the:make command.) With no argument, "G" positions youat theend of the file.A quick way togo to the start ofa file use "gg". "1G" willdo the same, butisa tiny bitmore typing. |first line ofa file^ |text text text text | |text text text text |gg7G |text text text text | |text text text text |text text text textVtext text text text |text text text text |Gtext text text text |last line ofa fileVAnother way to move toa lineis using the "%" command witha count. Forexample "50%" moves you to halfway the file. "90%" goes to near the end.The previous assumes that you want to move toa line in the file, no matter ifit's currently visible or not. What if you want to move to one of the linesyou can see? This figure shows the three commands you can use:+---------------------------+H -->| text sample text || sample text || text sample text || sample text |M -->| text sample text || sample text || text sample text || sample text |L -->| text sample text |+---------------------------+Hints: "H" stands for Home, "M" for Middle and "L" for Last. Alternatively,"H" for High, "M" for Middle and "L" for Low.==============================================================================03.6 Telling where you areTo see where you are ina file, there are three ways:1. Use theCTRL-G command. You geta message like this (assuming the'ruler' optionis off):"usr_03.txt" line 233 of 650 --35%-- col 45-52 This shows the name of the file you are editing, the line number where the cursor is, the total number of lines, the percentage of the way through the file and the column of the cursor. Sometimes you will seea split column number. For example, "col 2-9". This indicates that the cursoris positioned on the second character, but because character oneisa tab, occupying eight spaces worth of columns, the screen columnis 9.2. Set the'number' option. This will displaya line number in front of every line::set number To switch this off again::set nonumber Since'number'isaboolean option, prepending "no" to its name has the effect of switchingit off.Aboolean option has only these two values,itis either on or off. Vim has many options. Besides theboolean ones there areoptions witha numerical value andstring options. You will see examples of this where they are used.3. Set the'ruler' option. This will display the cursor position in the lower right corner of the Vim window::set rulerUsing the'ruler' option has the advantage thatit doesn't take much room,thus thereis morespace for your text.==============================================================================03.7 Scrolling aroundTheCTRL-U command scrolls down halfa screen of text. Think of lookingthrougha viewingwindowat the text and moving thiswindow up by half theheight of the window. Thus thewindow moves up over the text, whichisbackward in the file. Don't worry if you havea little trouble rememberingwhichendis up. Most users have the same problem. TheCTRL-D command moves the viewingwindow down halfa screen in the file,thus scrolls the text up halfa screen. +----------------+ | some text| | some text| | some text|+---------------+ | some text|| some text|CTRL-U --> |||| | 123456|| 123456| +----------------+| 7890||| +----------------+| example|CTRL-D --> | 7890|+---------------+ || | example| | example| | example| | example| +----------------+To scroll one lineata time useCTRL-E (scroll up) andCTRL-Y (scroll down).Think ofCTRL-E to give you one line Extra. (If you useMS-Windows compatiblekey mappingsCTRL-Y willredoa change instead of scroll.)To scroll forward bya whole screen (except for two lines) useCTRL-F. Toscroll backwards, useCTRL-B. These should beeasy to remember:F forForwards andB for Backwards.A common issueis that after moving down many lines with "j" your cursorisatthe bottom of the screen. You would like to see the context of the line withthe cursor. That's done with the "zz" command.+------------------+ +------------------+| earlier text | | earlier text || earlier text | | earlier text || earlier text | | earlier text || earlier text |zz --> | line with cursor || earlier text | | later text || earlier text | | later text || line with cursor | | later text |+------------------+ +------------------+The "zt" command puts the cursor lineat the top, "zb"at the bottom. Therearea few morescrolling commands, seeQ_sc. To always keepa few lines ofcontext around the cursor, use the'scrolloff' option.==============================================================================03.8 Simple searchesTo search fora string, use the "/string" command. To find theword include,for example, use the command:/includeYou will notice that when you type the "/" the cursor jumps to the last lineof the Vim window, like with colon commands. Thatis where you type the word.You can press thebackspace key (backarrow or<BS>) to make corrections. Usethe<Left> and<Right> cursor keys when necessary. Pressing<Enter> executes the command.Note:The characters.*[]^%/\?~$ have special meanings. If you want to usethem ina search youmustputa \ in front of them. See below.To find the next occurrence of the samestring use the "n" command. Use thisto find the first #include after the cursor:/#includeAnd then type "n" several times. You will move to each #include in the text.You can also useacount if you know which match you want. Thus "3n" findsthe third match. You can also useacount with "/": "4/the" goes to thefourth match of "the".The "?" command works like "/" but searches backwards:?wordThe "N" command repeats the last search the opposite direction. Thus using"N" aftera "/" command searches backwards, using "N" after "?" searchesforwards.IGNORING CASENormally you have to type exactly what you want to find. If you don't careabout upper orlowercase ina word, set the'ignorecase' option::set ignorecaseIf you now search for "word",it will also match "Word" and "WORD". To matchcase again::set noignorecaseHISTORYSuppose youdo three searches:/one/two/threeNow let's start searching by typinga simple "/" without pressing<Enter>. Ifyou press<Up> (the cursor key), Vim puts "/three" on the command line.Pressing<Enter>at this point searches for three. If youdo not press<Enter>, but press<Up> instead, Vim changes the prompt to "/two". Anotherpress of<Up> moves you to "/one". You can also use the<Down> cursor key to move through thehistory ofsearch commands in the other direction.If you know whata previously usedpattern starts with, and you want to useitagain, type that character before pressing<Up>. With the previous example,you can type "/o<Up>" and Vim willput "/one" on the command line.The commandsstarting with ":" also havea history. That allows you to recalla previous command and executeit again. These two histories are separate.SEARCHING FOR A WORD IN THE TEXTSuppose you see theword "TheLongFunctionName" in the text and you want tofind the next occurrence of it. You could type "/TheLongFunctionName", butthat'sa lot of typing. And when you makea mistake Vim won't find it. Thereis an easier way: Position the cursor on theword and use the "*"command. Vim will grab theword under the cursor and useitas the searchstring. The "#" command does the same in the other direction. You can prependacount: "3*" searches for the third occurrence of theword under the cursor.SEARCHING FOR WHOLE WORDSIf you type "/the"it will also match "there". To only find words thatendin "the" use:/the\>The "\>" itemisa special marker that only matchesat theend ofa word.Similarly "\<" only matchesat the beginning ofa word. Thus to search fortheword "the" only:/\<the\>This does not match "there" or "soothe". Notice that the "*" and "#" commandsuse these start-of-word and end-of-word markers to only find whole words (youcan use "g*" and "g#" to matchpartial words).HIGHLIGHTING MATCHESWhile editinga program you seea variable called "nr". You want to checkwhere it's used. You could move the cursor to "nr" and use the "*" commandand press "n" togo along all the matches. Thereis another way. Type this command::set hlsearchIf you now search for "nr", Vim will highlight all matches. Thatisa verygood way to see where the variableis used, without the need to type commands. To switch this off::set nohlsearchThen you need to switchit on again if you want to useit for the next searchcommand. If you only want to remove the highlighting, use this command::nohlsearchThis doesn't reset the option. Instead,it disables the highlighting. Assoonas you executea search command, the highlighting will be used again.Also for the "n" and "N" commands.TUNING SEARCHESThere area fewoptions that change how searching works. These are theessential ones::set incsearchThis makes Vim display the match for thestring while you are still typing it.Use this to check if the right match will be found. Then press<Enter> toreally jump to that location. Or type more to change the search string.:set nowrapscanThis stops the searchat theend of the file. Or, when you are searchingbackwards,it stops the searchat the start of the file. The'wrapscan'optionis on by default, thus searching wraps around theend of the file.INTERMEZZOIf you like one of theoptions mentioned before, and setit each time you useVim, you canput the command in your Vimstartup file. Edit the file,as mentionedatnot-compatible. Or use this command tofind out whereit is::scriptnamesEdit the file, for example with::edit ~/.vimrcThen adda line with the command to set the option, just like you typedit inVim. Example:Go:set hlsearch<Esc>"G" moves to theend of the file. "o" startsa new line, where you type the":set" command. Youendinsert mode with<Esc>. Then write and close thefile:ZZIf you now start Vim again, the'hlsearch' option will already be set.==============================================================================03.9 Simple search patternsThe Vim editor uses regular expressions to specify what to search for.Regular expressions are an extremely powerful and compact way to specifyasearch pattern. Unfortunately, this power comesata price, because regularexpressions area bit tricky to specify. In thissection we mention onlya few essential ones. More about searchpatterns and commands can be found in chapter 27usr_27.txt. You can findthe full explanation here:pattern.BEGINNING AND END OF A LINEThe^ character matches the beginning ofa line. On an English-US keyboardyou findit above the 6. Thepattern "include" matches theword includeanywhere on the line. But thepattern "^include" matches theword includeonly ifitisat the beginning ofa line. The$ character matches theend ofa line. Therefore, "was$" matches theword was only ifitisat theend ofa line.Let'smark the places where "/the" matches in this example line with "x"s:the solder holding one of the chips melted and thexxx xxx xxxUsing "/the$" we find this match:the solder holding one of the chips melted and the xxxAnd with "/^the" we find this one:the solder holding one of the chips melted and thexxxYou can try searching with "/^the$";it will only matcha single lineconsisting entirely of "the". Whitespace does matter here, thus ifa linecontainsaspace after the word, like "the ", thepattern will not match.MATCHING ANY SINGLE CHARACTERThe. (dot) character matches any existing character. For example, thepattern "c.m" matchesastring whose first characterisa c, whose secondcharacteris anything, and whose third characteris m. Example:We use a computer that became the cummin winter. xxx xxx xxxMATCHING SPECIAL CHARACTERSIf you really want to matcha dot, youmust avoid its special meaning byputtingabackslash before it. If you search for "ter.", you will find these matches:We use a computer that became the cummin winter. xxxx xxxxSearching for "ter\." only finds the second match.==============================================================================03.10 Using marksWhen you makea jump toa position with the "G" command, Vim remembers theposition from before this jump. This positionis calleda mark. Togo backwhere you came from, use this command:``This`isa backtick or open single-quote character. If you use the same commanda second time you will jump back again. That'sbecause the "`" commandisa jump itself, and the position from before thisjumpis remembered.Generally, every time youdoa command that can move the cursor further thanwithin the same line, thisis calleda jump. This includes the searchcommands "/" and "n" (it doesn't matter how far away the match is). But notthe character searches with "fx" and "tx" or theword movements "w" and "e". Also, "j" and "k" are not considered to bea jump, even when you useacount to make them move the cursor quitea long way away.The "``" command jumps back and forth, between two points. TheCTRL-O commandjumps to older positions (Hint:O for older).CTRL-I then jumps back to newerpositions (Hint: for many common keyboard layouts,Iis just next to O).Consider this sequence of commands:33G/^TheCTRL-OYou first jump to line 33, then search fora line that starts with "The".Then withCTRL-O you jump back to line 33. AnotherCTRL-O takes you back towhere you started. If you now useCTRL-I you jump to line 33 again. Andto the match for "The" with anotherCTRL-I. |example text^ |33G |example text |CTRL-O |CTRL-I |example text | |Vline 33 text^V |example text | | /^The |example text |CTRL-O |CTRL-IVThere you are |Vexample textNote:CTRL-Iis the sameas<Tab>.The ":jumps" command givesalist of positions you jumped to. The entry whichyou used lastis marked witha ">".NAMED MARKSbookmarkVim enables you to place your own marks in the text. The command "ma" marksthe place under the cursorasmark a. You can place 26 marks (a through z) inyour text. You can't see them, it's justa position that Vim remembers. Togo toa mark, use the command `{mark}, where{mark}is themark letter.Thus to move to thea mark:`aThe command "'mark" (single quotation mark, or apostrophe) moves you to thebeginning of the line containing the mark. This differs from the "`mark"command, which also moves you to the marked column.The marks can be very useful when working on two related parts ina file.Suppose you have some text near the start of the file you need to look at,while working on some text near theend of the file. Move to the textat the start and place thes (start)mark there:msThen move to the text you want to work on andput thee (end)mark there:meNow you can move around, and when you want to lookat the start of the file,you use this to jump there:'sThen you can use'' to jump back to where you were, or 'e to jump to the textyou were working onat the end. Thereis nothing special about usings for start ande for end, they arejusteasy to remember.You can use this command to getalist of marks::marksYou will noticea few special marks. These include:'The cursor position before doinga jump"The cursor position when last editing the file[Start of the last change]End of the last change==============================================================================Next chapter:usr_04.txt Making small changesCopyright: seemanual-copyright vim:tw=78:ts=8:noet:ft=help:norl: