Movatterモバイル変換


[0]ホーム

URL:


Quick links:help overview ·quick reference ·user manual toc ·reference manual toc·faq
Go to keyword (shortcut:k)
Site search (shortcut:s)
motion.txt    ForVim version 9.1.  Last change: 2024 Dec 17VIM REFERENCE MANUAL    by Bram MoolenaarCursor motionscursor-motionsnavigationThese commands move the cursor position.  If the new positionis off of thescreen, the screenis scrolled to show the cursor (see also'scrolljump' and'scrolloff' options).1. Motions and operatorsoperator2. Left-right motionsleft-right-motions3. Up-down motionsup-down-motions4. Word motionsword-motions5. Textobject motionsobject-motions6. Textobject selectionobject-select7. Marksmark-motions8. Jumpsjump-motions9. Various motionsvarious-motionsGeneral remarks:If you want to know where you are in the file use the "CTRL-G" commandCTRL-G or the "gCTRL-G" commandg_CTRL-G.  If you set the'ruler' option,the cursor positionis continuously shown in the status line (which slows downVima little).Experienced users prefer thehjkl keys because they are always right undertheir fingers.  Beginners often prefer the arrow keys, because theydo notknow what thehjkl keys do.  The mnemonic value ofhjklis clear from lookingat the keyboard.  Think ofjas an arrow pointing downwards.The'virtualedit' option can be set to makeit possible to move the cursor topositions where thereis no character or withina multi-column character (likea tab).==============================================================================1. Motions and operatorsoperatorThe motion commands can be used after anoperator command, to have the commandoperate on the text that was moved over.  Thatis the text between the cursorposition before and after the motion.  Operators are generally used to deleteor change text.  The following operators are available:ccchangedddeleteyyyank intoregister (does not change the text)~~swapcase (only if'tildeop'is set)g~g~swapcasegugumakelowercasegUgUmakeuppercase!!filter through an external program==filter through'equalprg' orC-indenting if emptygqgqtextformattinggwgwtextformatting with no cursormovementg?g?ROT13 encoding>>shift right<<shift leftzfzfdefinea foldg@g@call function set with the'operatorfunc' optionmotion-count-multipliedIf the motion includesacount and theoperator also hadacount before it,the two counts are multiplied.  For example: "2d3w" deletes six words.operator-doubledWhen doubling theoperatorit operates ona line.  When usinga count, beforeor after the first character, that many lines are operated upon.  Thus3dddeletes three lines.Acount before and after the first characterismultiplied, thus2y3y yanks six lines.operator-resulting-posAfter applying theoperator the cursoris mostly leftat the start of the textthat was operated upon.  For example, "yfe" doesn't move the cursor, but "yFe"moves the cursor leftwards to the "e" where theyank started.The'startofline' option applies only to the "d", "<<", "==" and ">>"linewiseoperations.linewisecharacterwiseTheoperator either affects whole lines, or the characters between the startandend position.  Generally, motions that move between lines affect lines(are linewise), and motions that move withina line affect characters (arecharacterwise).  However, there are some exceptions.exclusiveinclusiveA character motionis eitherinclusive or exclusive.  When inclusive, thestart andend position of the motion are included in the operation.  Whenexclusive, the last character towards theend of the bufferis not included.Linewise motions always include the start andend position.Which motions are linewise,inclusive orexclusiveis mentioned with thecommand.  There are however, two general exceptions:1. If the motionisexclusive and theend of the motionis in column 1, theend of the motionis moved to theend of the previous line and the motion   becomes inclusive.  Example: "}" moves to the first line aftera paragraph,   but "d}" will not include that line.exclusive-linewise2. If the motionis exclusive, theend of the motionis in column 1 and the   start of the motion wasat or before the first non-blank in the line, the   motion becomes linewise.  Example: Ifaparagraph begins with some blanks   and youdo "d}" while standing on the first non-blank, all the lines of   theparagraph are deleted, including the blanks.  If youdoaput now, the   deleted lines will be inserted below the cursor position.Note that when theoperatoris pending (theoperator commandis typed, but themotion isn't yet),a special set of mappings can be used.  See:omap.Instead of first giving theoperator and thena motion you can useVisualmode:mark the start of the text with "v", move the cursor to theend of thetext thatis to be affected and then hit the operator.  The text between thestart and the cursor positionis highlighted, so you can see what text willbe operated upon.  This allows much more freedom, but requires more keystrokes and has limitedredo functionality.  See the chapter onVisual modeVisual-mode.You can usea ":" command fora motion.  For example "d:call FindEnd()".But this can't be repeated with "." if the commandis more than one line.This can be repeated:d:call search("f")<CR>This cannot be repeated:d:if 1<CR>   call search("f")<CR>endif<CR>Note that when using ":" any motion becomescharacterwise exclusive.inclusive-motion-selection-exclusiveWhen'selection'is "exclusive",Visual modeis active and aninclusivemotion has been used, the cursor position will be adjusted by anothercharacter to the right, so that theVisual selection includes the expectedtext and can be acted upon.forced-motionFORCING A MOTION TO BE LINEWISE, CHARACTERWISE OR BLOCKWISEWhena motionis not of the type you would like to use, you can force anothertype by using "v", "V" orCTRL-V just after the operator.Example:djdeletes two linesdvjdeletes from the cursor position until the character below the cursord<C-V>jdeletes the character under the cursor and the character below the cursor.Be careful with forcingalinewisemovement to be usedcharacterwise orblockwise, the column may not always be defined.o_vvWhen used after an operator, before the motion command: Forcetheoperator to work characterwise, also when the motionislinewise.  If the motion was linewise,it will becomeexclusive.If the motion already was characterwise,toggleinclusive/exclusive.  This can be used to make anexclusivemotioninclusive and aninclusive motion exclusive.o_VVWhen used after an operator, before the motion command: Forcetheoperator to work linewise, also when the motionischaracterwise.o_CTRL-VCTRL-VWhen used after an operator, before the motion command: Forcetheoperator to work blockwise.  This works likeVisual blockmode selection, with the corners defined by the cursorposition before and after the motion.==============================================================================2. Left-right motionsleft-right-motionsThese commands move the cursor to the specified column in the current line.They stopat the first column andat theend of the line, except "$", whichmay move to one of the next lines.  See'whichwrap' option to make some of thecommands move across line boundaries.horh<Left>or<Left>CTRL-HorCTRL-H<BS><BS>[count] characters to the left.exclusive motion.Note: If you prefer<BS> to deletea character, usethe mapping::map CTRL-V<BS>X(to enter "CTRL-V<BS>" type theCTRL-V key, followedby the<BS> key)See:fixdel if the<BS> key does notdo what youwant.lorl<Right>or<Right><Space><Space>[count] characters to the right.exclusive motion.See the'whichwrap' option for adjusting the behavioratend of line00To the first character of the line.exclusivemotion.<Home><kHome><Home>To the first character of the line.exclusivemotion.  When moving up or down next, stay in sameTEXT column (if possible).  Most other commands stayin the same SCREEN column.<Home> works like "1|",which differs from "0" when the line starts witha<Tab>.^^To the first non-blank character of the line.exclusive motion.  Anycountis ignored.$<End><kEnd>$  or<End>To theend of the line.  Whenacountis given alsogo[count- 1] lines downward, oras faris possible.inclusive motion.  Ifacount of 2 or largerisgiven and the cursoris on the last line, thatis anerror and the cursor doesn't move.InVisual mode the cursor goes to just after the lastcharacter in the line.When'virtualedit'is active, "$" may move the cursorback from past theend of the line to the lastcharacter in the line.g_g_To the last non-blank character of the line and[count- 1] lines downwardinclusive.g0g<Home>g0 org<Home>When lines wrap ('wrap' on): To the first character ofthe screen line.exclusive motion.  Differs from"0" whena lineis wider than the screen.When lines don't wrap ('wrap' off): To the leftmostcharacter of the current line thatis on the screen.Differs from "0" when the first character of the lineis not on the screen.g^g^When lines wrap ('wrap' on): To the first non-blankcharacter of the screen line.exclusive motion.Differs from "^" whena lineis wider than the screen.When lines don't wrap ('wrap' off): To the leftmostnon-blank character of the current line thatis on thescreen.  Differs from "^" when the first non-blankcharacter of the lineis not on the screen.gmgmLike "g0", but halfa screenwidth to the right (orasmuchas possible).gMgMLike "g0", but to halfway the text of the line.Witha count: to this percentage of text in the line.Thus "10gM"is near the start of the text and "90gM"is near theend of the text.g$g$When lines wrap ('wrap' on): To the last character ofthe screen line and [count- 1] screen lines downwardinclusive.  Differs from "$" whena lineis widerthan the screen.When lines don't wrap ('wrap' off): To the rightmostcharacter of the current line thatis visible on thescreen.  Differs from "$" when the last character ofthe lineis not on the screen or whenacountis used.Additionally, vertical movements keep the column,instead of going to theend of the line.When'virtualedit'is enabled moves to theend of thescreen line.g<End>g<kEnd>g<End>Likeg$ but to the last non-blank characterinstead of the last character.bar|To screen column[count] in the current line.exclusive motion.  Ceci n'est pas une pipe.ff{char}To[count]'th occurrence of{char} to the right.  Thecursoris placed on{char}inclusive.{char} can be enteredasadigraphdigraph-arg.When'encoding'is set to Unicode, composingcharacters may be used, seeutf-8-char-arg.:lmap mappings apply to{char}.  TheCTRL-^ commandinInsert mode can be used to switch this on/offi_CTRL-^.FF{char}To the[count]'th occurrence of{char} to the left.The cursoris placed on{char}exclusive.{char} can be entered like with thef command.tt{char}Till before[count]'th occurrence of{char} to theright.  The cursoris placed on the character left of{char}inclusive.{char} can be entered like with thef command.TT{char}Till after[count]'th occurrence of{char} to theleft.  The cursoris placed on the character right of{char}exclusive.{char} can be entered like with thef command.;;Repeat latest f, t,F orT[count] times. Seecpo-;,,Repeat latest f, t,F orT in opposite direction[count] times. See alsocpo-;==============================================================================3. Up-down motionsup-down-motionskork<Up>or<Up>CTRL-PCTRL-P[count] lines upwardlinewise.jorj<Down>or<Down>CTRL-JorCTRL-J<NL>or<NL>CTRL-NCTRL-N[count] lines downwardlinewise.gkorgkg<Up>g<Up>[count] display lines upward.exclusive motion.Differs from 'k' when lines wrap, and when used withan operator, because it's not linewise.gjorgjg<Down>g<Down>[count] display lines downward.exclusive motion.Differs from 'j' when lines wrap, and when used withan operator, because it's not linewise.--<minus>[count] lines upward, on the first non-blankcharacterlinewise.+or+CTRL-MorCTRL-M<CR><CR>[count] lines downward, on the first non-blankcharacterlinewise.__<underscore>[count]- 1 lines downward, on the first non-blankcharacterlinewise.GGGoto line[count], default last line, on the firstnon-blank characterlinewise.  If'startofline' notset, keep the same column.Gis one of thejump-motions.<C-End><C-End>Goto line[count], default last line, on the lastcharacterinclusive.<C-Home>orgg<C-Home>ggGoto line[count], default first line, on the firstnon-blank characterlinewise.  If'startofline' notset, keep the same column.:[range]:[range]Set the cursor on the last line number in[range].InEx mode, print the lines in[range].[range] can also be just one line number, e.g., ":1"or ":'m".In contrast withG this command does not modify thejumplist.N%{count}%Go to{count} percentage in the file, on the firstnon-blank in the linelinewise.  To compute the newline number this formulais used:    ({count} * number-of-lines+ 99)/ 100See also'startofline' option.:[range]go[to][count]:go:gotogo[count]goGo to[count] byte in the buffer.exclusive motion.Default[count]is one, start of the file.  Whengiving[range], the last number init usedas the bytecount.  End-of-line characters are counted dependingon the current'fileformat' setting.Also see theline2byte() function, and the 'o'option in'statusline'.{not available when compiled without the+byte_offset feature}These commands move to the specified line.  They stop when reaching the firstor the last line.  The first two commandsput the cursor in the same column(if possible)asit was after the last command that changed the column,except after the "$" command, then the cursor will beput on the lastcharacter of the line.If "k", "-" orCTRL-Pis used witha[count] and there areless than[count]lines above the cursor and the'cpo' option includes the "-" flagitis anerror.cpo--.==============================================================================4. Word motionsword-motions<S-Right>or<S-Right>ww[count] words forward.exclusive motion.<C-Right>or<C-Right>WW[count] WORDS forward.exclusive motion.If<C-Right> does not work, check outarrow_modifiers.eeForward to theend ofword[count]inclusive.Does not stop in an empty line.EEForward to theend ofWORD[count]inclusive.Does not stop in an empty line.<S-Left>or<S-Left>bb[count] words backward.exclusive motion.<C-Left>or<C-Left>BB[count] WORDS backward.exclusive motion.If<C-Left> does not work, check outarrow_modifiers.gegeBackward to theend ofword[count]inclusive.gEgEBackward to theend ofWORD[count]inclusive.These commands move over words or WORDS.wordAword consists ofa sequence of letters, digits and underscores, orasequence of other non-blank characters, separated with whitespace (spaces,tabs,<EOL>).  This can be changed with the'iskeyword' option.  An empty lineis also considered to bea word.WORDAWORD consists ofa sequence of non-blank characters, separated with whitespace.  An empty lineis also considered to bea WORD.A sequence of folded linesis counted for oneword ofa single character."w" and "W", "e" and "E" move to the start/end of the firstword orWORD aftera range of folded lines.  "b" and "B" move to the start of the firstword orWORD before the fold.Special case: "cw" and "cW" are treated like "ce" and "cE" if the cursorisona non-blank.  Thisis because "cw"is interpretedas change-word, andaword does not include the following whitespace (see alsocw).Another special case: When using the "w" motion in combination with anoperator and the lastword moved overisat theend ofa line, theend ofthatword becomes theend of the operated text, not the firstword in thenext line.The originalVi implementation of "e"is buggy.  For example, the "e" commandwill stop on the first character ofa line if the previous line was empty.But when you use "2e" this does not happen.  In Vim "ee" and "2e" are thesame, whichis more logical.  However, this causesa small incompatibilitybetweenVi and Vim.==============================================================================5. Textobject motionsobject-motions(([count]sentences backward.exclusive motion.))[count]sentences forward.exclusive motion.{{[count]paragraphs backward.exclusive motion.}}[count]paragraphs forward.exclusive motion.]]]][count]sections forward or to the next '{' in thefirst column.  When used after an operator, then alsostops belowa '}' in the first column.exclusiveNote thatexclusive-linewise often applies.][][[count]sections forward or to the next '}' in thefirst column.exclusiveNote thatexclusive-linewise often applies.[[[[[count]sections backward or to the previous '{' inthe first column.exclusiveNote thatexclusive-linewise often applies.[][][count]sections backward or to the previous '}' inthe first column.exclusiveNote thatexclusive-linewise often applies.These commands move over three kinds of text objects.sentenceAsentenceis definedas endingata '.', '!' or '?' followed by either theend ofa line, or byaspace or tab.  Any number of closing ')', ']','"'and ''' characters may appear after the '.', '!' or '?' before the spaces,tabs orend of line.Aparagraph andsection boundaryis alsoasentenceboundary.If the 'J' flagis present in'cpoptions',at least two spaces have tofollow the punctuation mark;<Tab>s are not recognizedas white space.The definition ofasentence cannot be changed.paragraphAparagraph begins after each empty line, and alsoat each ofa set ofparagraph macros, specified by the pairs of characters in the'paragraphs'option.  The defaultis "IPLPPPQPP TPHPLIPpLpItpplpipbp", which corresponds tothe macros ".IP", ".LP", etc.  (These are nroff macros, so the dotmust be inthe first column).Asection boundaryis alsoaparagraph boundary.Note thata blank line (only containing white space)is NOTaparagraphboundary.Alsonote that this does not includea '{' or '}' in the first column.  Whenthe '{' flagis in'cpoptions' then '{' in the first columnis usedasaparagraph boundaryposix.sectionAsection begins aftera form-feed (<C-L>) in the first column andat each ofa set ofsection macros, specified by the pairs of characters in the'sections' option.  The defaultis "SHNHH HUnhsh", which definesasection tostartat the nroff macros ".SH", ".NH", ".H", ".HU", ".nh" and ".sh".The "]]" and "[[" commands stopat the '{' in the first column.  Thisisuseful to find the start ofa function inaC program.  To search fora '}' inthe first column, theend ofaC function, use "][" (forward) or "[]"(backward).Note that the first character of the command determines thesearch direction.If your '{' or '}' are not in the first column, and you would like to use "[["and "]]" anyway, try these mappings:   :map [[ ?{<CR>w99[{   :map ][ /}<CR>b99]}   :map ]] j0[[%/{<CR>   :map [] k$][%?}<CR>[type these literally, see<>]==============================================================================6. Textobject selectionobject-selecttext-objectsv_av_iThisisa series of commands that can only be used while inVisual mode orafter an operator.  The commands that start with "a" select "a"nobjectincluding white space, the commandsstarting with "i" select an "inner"objectwithout white space, or just the white space.  Thus the "inner" commandsalways selectless text than the "a" commands.Also seegn andgN, operating on the last search pattern.v_awawaw"aword", select[count] words (seeword).Leading or trailing whitespaceis included, but notcounted.When used inVisuallinewise mode "aw" switches toVisualcharacterwise mode.v_iwiwiw"innerword", select[count] words (seeword).Whitespace between wordsis counted too.When used inVisuallinewise mode "iw" switches toVisualcharacterwise mode.v_aWaWaW"aWORD", select[count] WORDs (seeWORD).Leading or trailing whitespaceis included, but notcounted.When used inVisuallinewise mode "aW" switches toVisualcharacterwise mode.v_iWiWiW"innerWORD", select[count] WORDs (seeWORD).Whitespace between wordsis counted too.When used inVisuallinewise mode "iW" switches toVisualcharacterwise mode.v_asasas"asentence", select[count] sentences (seesentence).When used inVisual modeitis made characterwise.v_isisis"innersentence", select[count] sentences (seesentence).When used inVisual modeitis made characterwise.v_apapap"aparagraph", select[count] paragraphs (seeparagraph).Exception:a blank line (only containing white space)is alsoaparagraph boundary.When used inVisual modeitis made linewise.v_ipipip"innerparagraph", select[count] paragraphs (seeparagraph).Exception:a blank line (only containing white space)is alsoaparagraph boundary.When used inVisual modeitis made linewise.a]v_a]v_a[a]a[a["a[] block", select[count] '[' ']' blocks.  Thisgoes backwards to the[count] unclosed '[', and findsthe matching ']'.  The enclosed textis selected,including the '[' and ']'.  Thecpo-M option flagis used to handle escaped brackets.When used inVisual modeitis made characterwise.i]v_i]v_i[i]i[i["inner[] block", select[count] '[' ']' blocks.  Thisgoes backwards to the[count] unclosed '[', and findsthe matching ']'.  The enclosed textis selected,excluding the '[' and ']'.  It's an error to select anempty inner block like "[]".  Thecpo-M option flagis used to handle escaped brackets.When used inVisual modeitis made characterwise.a)v_a)a)a(a(vabv_abv_a(abab"a block", select[count] blocks, from "[count][(" tothe matching ')', including the '(' and ')' (see[().  Does not include whitespace outside of theparenthesis.  Thecpo-M option flagis used tohandle escaped parenthesis.When used inVisual modeitis made characterwise.i)v_i)i)i(i(vibv_ibv_i(ibib"inner block", select[count] blocks, from "[count][("to the matching ')', excluding the '(' and ')' (see[().  If the cursoris not insidea () block, thenfind the next "(".  It's an error to select an emptyinner block like "()".  Thecpo-M option flagis used to handle escaped parenthesis.When used inVisual modeitis made characterwise.a>v_a>v_a<a>a<a<"a<> block", select[count]<> blocks, from the[count]'th unmatched '<' backwards to the matching'>', including the '<' and '>'.  Thecpo-M option flagis used to handle escaped '<' and '>'.When used inVisual modeitis made characterwise.i>v_i>v_i<i>i<i<"inner<> block", select[count]<> blocks, fromthe[count]'th unmatched '<' backwards to the matching'>', excluding the '<' and '>'.  It's an error toselect an empty inner block like "<>".  Thecpo-Moption flagis used to handle escaped '<' and '>'.When used inVisual modeitis made characterwise.v_atatat"atag block", select[count]tag blocks, from the[count]'th unmatched "<aaa>" backwards to the matching"</aaa>", including the "<aaa>" and "</aaa>".Seetag-blocks about the details.When used inVisual modeitis made characterwise.Only available when compiled with the+eval feature.v_ititit"innertag block", select[count]tag blocks, from the[count]'th unmatched "<aaa>" backwards to the matching"</aaa>", excluding the "<aaa>" and "</aaa>".Seetag-blocks about the details.When used inVisual modeitis made characterwise.a}v_a}a}a{a{v_aBv_a{aBaB"a Block", select[count] Blocks, from "[count][{" tothe matching '}', including the '{' and '}' (see[{).  Thecpo-M option flagis used to handleescaped braces.When used inVisual modeitis made characterwise.i}v_i}i}i{i{v_iBv_i{iBiB"inner Block", select[count] Blocks, from "[count][{"to the matching '}', excluding the '{' and '}' (see[{).  It's an error to select an empty inner blocklike "{}".  Thecpo-M option flagis used to handleescaped braces.When used inVisual modeitis made characterwise.a"v_aquoteaquotea'v_a'a'a`v_a`a`"a quotedstring".  Selects the text from the previousquote until the nextquote.  The'quoteescape' optionis used to skip escaped quotes.Only works within one line.When the cursor starts ona quote, Vim will figure outwhichquote pairs formastring by searching from thestart of the line.Any trailing whitespaceis included, unless thereisnone, then leading whitespaceis included.When used inVisual modeitis made characterwise.Repeating thisobject inVisual mode anotherstringisincluded.Acountis currently not used.i"v_iquoteiquotei'v_i'i'i`v_i`i`Likea",a' and a`, but exclude thequotes andrepeating won't extend theVisual selection.Special case: Withacount of 2 thequotes areincluded, but no extra whitespaceas witha"/a'/a`.o_object-selectWhen used after an operator:For non-block objects:For the "a" commands: Theoperator applies to theobject and the whitespace after the object.  If thereis no whitespace after theobjector when the cursor was in the whitespace before the object, the whitespace before theobjectis included.For the "inner" commands: If the cursor was on the object, theoperator applies to the object.  If the cursor was on white space, theoperator applies to the white space.Fora block object:Theoperator applies to the block where the cursoris in, or the blockon which the cursoris on one of the braces.  For the "inner" commandsthe surrounding braces are excluded.  For the "a" commands, the bracesare included.v_object-selectWhen used inVisual mode:When start andend of theVisual area are the same (just after typing "v"):Oneobjectis selected, the sameas for using an operator.When start andend of theVisual area are not the same:For non-blockobjects the areais extended by oneobject or the whitespace up to the next object, or both for the "a" objects.  Thedirection in which this happens depends on which side of theVisualarea the cursor is.  For the blockobjects the blockis extended onelevel outwards.For illustration, hereisalist of delete commands, grouped from small to bigobjects.Note that fora single character anda whole line the existingvimovement commands are used."dl"delete character (alias: "x")dl"diw"delete innerworddiw"daw"deleteaworddaw"diW"delete innerWORD (seeWORD)diW"daW"deleteaWORD (seeWORD)daW"dgn"   delete the next searchpattern matchdgn"dd"delete one linedd"dis"delete innersentencedis"das"deleteasentencedas"dib"delete inner '(' ')' blockdib"dab"deletea '(' ')' blockdab"dip"delete innerparagraphdip"dap"deleteaparagraphdap"diB"delete inner '{' '}' blockdiB"daB"deletea '{' '}' blockdaBNote the difference between usingamovement command and an object.  Themovement command operates from here (cursor position) to where themovementtakes us.  When using anobject the wholeobjectis operated upon, no matterwhere on theobject the cursor is.  For example, compare "dw" and "daw": "dw"deletes from the cursor position to the start of the next word, "daw" deletestheword under the cursor and thespace after or before it.Tag blockstag-blocksFor the "it" and "at" textobjects an attemptis done to select blocks betweenmatchingtags for HTML and XML.  But since these are not completely compatiblethere area few restrictions.The normalmethodis to selecta<tag> until the matching </tag>.  For "at"thetags are included, for "it" they are excluded.  But when "it"is repeatedthetags will be included (otherwise nothing would change).  Also, "it" usedonatag block with no contents will select the leading tag."<aaa/>" items are skipped.  Caseis ignored, also for XML wherecase doesmatter.In HTMLitis possible to haveatag like<br> or <meta ...> withoutamatchingend tag.  These are ignored.The textobjects are tolerant about mistakes.  Strayendtags are ignored.==============================================================================7. Marksmark-motionsE20E78Jumping toamark can be done in two ways:1. With` (backtick):  The cursoris positionedat the specified location  and the motionisexclusive.2. With' (single quote): The cursoris positioned on the first non-blank  character in the line of the specified location and  the motionis linewise.mmarkMarkm{a-zA-Z}Setmark{a-zA-Z}at cursor position (does not movethe cursor, thisis nota motion command).m'm`m'  orm`Set the previous context mark.  This can be jumped towith the "''" or "``" command (does not move thecursor, thisis nota motion command).m[m]m[  orm]Set the'[ or'] mark.  Useful when anoperatoristo be simulated by multiple commands.  (does not movethe cursor, thisis nota motion command).m<m>m<  orm>Set the'< or'> mark.  Useful to change what thegv command selects.  (does not move the cursor, thisis nota motion command).Note that theVisual mode cannot be set, only thestart andend position.:ma:markE191:[range]ma[rk]{a-zA-Z'}Setmark{a-zA-Z'}at last line number in[range],column 0.  Defaultis cursor line.:k:[range]k{a-zA-Z'}Sameas :mark, but thespace before themark name canbe omitted.This commandis not supported inVim9 script,becauseitis too easily confused witha variablename.''a``a'{a-z}  `{a-z}Jump to themark{a-z} in the current buffer.'A'0`A`0'{A-Z0-9}  `{A-Z0-9}To themark{A-Z0-9} in the file whereit was set (nota motion command when in another file).g'g'ag`g`ag'{mark}  g`{mark}Jump to the{mark}, but don't change thejumplist whenjumping within the current buffer.  Example:g`"jumps to the last known position ina file.  See$VIMRUNTIME/vimrc_example.vim.Also see:keepjumps.:marks:marksList all the current marks (nota motion command).The'(,'),'{ and'} marks are not listed.The first column has number zero.E283:marks{arg}List the marks that are mentioned in{arg} (notamotion command).  For example::marks aBtolist marks 'a' and 'B'.:delm:delmarks:delm[arks]{marks}Delete the specified marks.  Marks that can be deletedinclude A-Z and 0-9.  You cannot delete the' mark.They can be specified by giving thelist ofmarknames, or witha range, separated witha dash.  Spacesare ignored.  Examples:   :delmarks a      deletes mark a   :delmarks a b 1    deletes marks a, b and 1   :delmarks Aa       deletes marks A and a   :delmarks p-z      deletes marks in the range p to z   :delmarks ^.[]     deletes marks ^ . [ ]   :delmarks \"      deletes mark ":delm[arks]!Delete all marks for the current buffer, but not marksA-Z or 0-9.Amarkis not visible in any way.  Itis justa position in the file thatisremembered.  Do not confuse marks with named registers, they are totallyunrelated.'a- 'zlowercase marks, valid within one file'A- 'Zuppercase marks, also called file marks, valid between files'0- '9numbered marks, set from .viminfo fileLowercase marks'a to 'z are rememberedas longas the file remains in thebuffer list.  If you remove the file from the buffer list, all its marks arelost.  If you deletea line that containsa mark, thatmarkis erased.Lowercase marks can be used in combination with operators.  For example: "d't"deletes the lines from the cursor position tomark 't'.  Hint: Usemark 't' forTop, 'b' for Bottom, etc..  Lowercase marks are restored when usingundo andredo.Uppercase marks'A to 'Z include the file name.  You can use them to jump fromfile to file.  You can only use anuppercasemark with anoperator if themarkis in the current file.  The line number of themark remains correct, even ifyou insert/delete lines or edit another file fora moment.  When the'viminfo'optionis not empty,uppercase marks are kept in the .viminfo file.  Seeviminfo-file-marks.Numbered marks'0 to '9 are quite different.  They can not be set directly.They are only present when usingaviminfo fileviminfo-file.  Basically'0is the location of the cursor when you last exited Vim, '1 the last but onetime, etc.  Use the "r" flag in'viminfo' to specify files for which noNumberedmark should be stored.  Seeviminfo-file-marks.'[`['[`[To the first character of the previously changedor yanked text.']`]']`]To the last character of the previously changed oryanked text.After executing anoperator the Cursorisputat the beginning of the textthat was operated upon.  Afteraput command("p" or "P") the cursorissometimes placedat the first inserted line and sometimes on the last insertedcharacter.  The four commands aboveput the cursorat either end.  Example:After yanking 10 lines you want togo to the last one of them: "10Y']".  Afterinserting several lines with the "p" command you want to jump to the lowestinserted line: "p']".  This also works for text that has been inserted.Note: Afterdeleting text, the start andend positions are the same, exceptwhen using blockwiseVisual mode.  These commandsdo not work when no changewas made yet in the current file.'<`<'<`<To the first line or character of the last selectedVisual area in the current buffer.  For block modeitmay also be the last character in the first line (tobe able to define the block).'>`>'>`>To the last line or character of the last selectedVisual area in the current buffer.  For block modeitmay also be the first character of the last line (tobe able to define the block).Note that'selection'applies, the position may be just after theVisualarea.''``''``To the position before the latest jump, or where thelast "m'" or "m`" command was given.  Not set when the:keepjumps command modifier was used.Also seerestore-position.'quote`quote'"`"To the cursor position when lastexiting the currentbuffer.  Defaults to the first character of the firstline.  Seelast-position-jump for how to use thisfor each opened file.Only one positionis remembered per buffer, not onefor each window.  As longas the bufferis visible inawindow the position won't be changed.'^`^'^`^To the position where the cursor was the last timewhenInsert mode was stopped.  Thisis used by thegi command.  Not set when the:keepjumps commandmodifier was used.'.`.'.`.To the position where the last change was made.  Thepositionisat or near where the change started.Sometimesa commandis executedas several changes,then the position can be near theend of what thecommand changed.  For example wheninsertinga word,the position will be on the last character.To jump to older changes useg;.'(`('(`(To the start of the current sentence, like the(command.')`)')`)To theend of the current sentence, like the)command.'{`{'{`{To the start of the current paragraph, like the{command.'}`}'}`}To theend of the current paragraph, like the}command.These commands are not marks themselves, but jump toa mark:]']'[count] times to next line withalowercasemark belowthe cursor, on the first non-blank character in theline.]`]`[count] times tolowercasemark after the cursor.['['[count] times to previous line withalowercasemarkbefore the cursor, on the first non-blank character inthe line.[`[`[count] times tolowercasemark before the cursor.:loc[kmarks]{command}:loc:lock:lockmarksExecute{command} without adjusting marks.  Thisisuseful whenchanging text ina way that the linecountwill be the same when the change has completed.WARNING: When the linecount does change, marks belowthe change will keep their line number, thus move toanother text line.These items will not be adjusted for deleted/insertedlines:- lowercaseletter marks'a- 'z- uppercaseletter marks'A- 'Z- numbered marks'0- '9- lastinsert position'^- last change position'.- last affected text area'[ and']- theVisual area'< and'>- line numbers in placedsigns- line numbers inquickfix positions- positions in thejumplist- positions in thetagstackThese items will still be adjusted:- previous contextmark''- the cursor position- theview ofawindow ona buffer-folds- diffs:kee[pmarks]{command}:kee:keep:keepmarksCurrently only has effect for thefilter command:range!:- When the number of lines after filteringis equal to  or larger than before, all marks are keptat the  same line number.- When the number of lines decreases, the marks in the  lines that disappeared are deleted.In anycase the marks below the filtered text havetheir line numbers adjusted, thus stick to the text,as usual.When the 'R' flagis missing from'cpoptions' this hasthe same effectas using ":keepmarks".:keepj:keepjumps:keepj[umps]{command}Moving around in{command} does not change the'','. and'^ marks, thejumplist or thechangelist.Useful when makinga change orinserting textautomatically and the user doesn't want togo to thisposition.  E.g., when updatinga "Last change"timestamp in the first line::let lnum = line("."):keepjumps normal gg:call SetLastChange():keepjumps exe "normal " .. lnum .. "G"Note that ":keepjumps"must be used for every command.When invokinga function the commands in that functioncan still change the jumplist.  Also, for":keepjumps exe 'command'" the "command" won't keepjumps.  Instead use: ":exe 'keepjumps command'"==============================================================================8. Jumpsjump-motionsA "jump"isa command that normally moves the cursor several lines away.  Ifyou make the cursor "jump" the position of the cursor before the jumpisremembered.  You can return to that position with the "''" and "``" commands,unless the line containing that position was changed or deleted.  Thefollowing commands are "jump" commands: "'", "`", "G", "/", "?", "n", "N","%", "(", ")", "[[", "]]", "{", "}", ":s", ":tag", "L", "M", "H" and thecommands that start editinga new file.CTRL-OCTRL-OGo to[count] Older cursor position in jumplist(nota motion command).<Tab>orCTRL-I<Tab>CTRL-IGo to[count] newer cursor position in jumplist(nota motion command).NOTE: In theGUI and inaterminal supportingmodifyOtherKeys,CTRL-I can be mapped separatelyfrom<Tab>, on the condition thatCTRL-Iismapped before<Tab>, otherwise themapping applies toboth.:ju:jumps:ju[mps]Print the jumplist (nota motion command).:cle:clearjumps:cle[arjumps]Clear the jumplist of the current window.jumplistJumps are remembered ina jump list.  With theCTRL-O andCTRL-I command youcango to cursor positions before older jumps, and back again.  Thus you canmove up and down the list.  Thereisa separate jumplist for each window.The maximum number of entriesis fixedat 100.For example, after three jump commands you have this jump list:    jump line  col file/text      3     1    0 some text      2    70    0 another line      1  1154   23 end.   >The "file/text" column shows the file name, or the textat the jump ifitisin the current file (an indentis removed anda long lineis truncated to fitin the window).The marker ">" indicates the current position in the jumplist.  It may not beshown when filtering the:jumps command using:filterYou are currently in line 1167.  If you then use theCTRL-O command, thecursorisput in line 1154.  This results in:    jump line  col file/text      2     1    0 some text      1    70    0 another line   >  0  1154   23 end.      1  1167    0 foo barThe pointer will be setat the last used jump position.  The nextCTRL-Ocommand will use the entry above it, the nextCTRL-I command will use theentry below it.  If the pointeris below the last entry, this indicates thatyou did not useaCTRL-I orCTRL-O before.  In thiscase theCTRL-O commandwill cause the cursor position to be added to the jump list, so you can getback to the position before theCTRL-O.  In thiscase thisis line 1167.With moreCTRL-O commands you willgo to lines 70 and 1.  If you useCTRL-Iyou cango back to 1154 and 1167 again.Note that the number in the "jump"column indicates thecount for theCTRL-O orCTRL-I command that takes you tothis position.If you usea jump command, the current line numberis insertedat theend ofthe jump list.  If the same line was already in the jump list,itis removed.The resultis that whenrepeatingCTRL-O you will get back to old positionsonly once.When the:keepjumps command modifieris used, jumps are not stored in thejumplist.  Jumps are also not stored in other cases, e.g., ina:globalcommand.  You can explicitly adda jump by setting the'mark with "m'".Notethat callingsetpos() does notdo this.After theCTRL-O command that got you into line 1154 you could give anotherjump command (e.g., "G").  The jumplist would then become:    jump line  col file/text      4     1    0 some text      3    70    0 another line      2  1167    0 foo bar      1  1154   23 end.   >The line numbers will be adjusted for deleted and inserted lines.  This failsif you stop editinga file without writing, like with ":n!".When you splita window, thejumplist will be copied to the new window.If you have included the' item in the'viminfo' option thejumplist will bestored in theviminfo file and restored whenstarting Vim.jumplist-stackWhen'jumpoptions' option includes "stack", thejumplist behaves like thetagstack.  When jumping toa new location from the middle of the jumplist, thelocations after the current position will be discarded. With this option setyou can move througha tree of jump locations. When going back upa branch andthen down another branch,CTRL-O still takes you further up the tree.Givenajumplist like the following in whichCTRL-O has been used to move backthree times to location X:     jump line  col file/text       2  1260    8 mark.c<-- location X-2       1   685    0 eval.c<-- location X-1    >  0   462   36 eval.c<-- location X       1   479   39 eval.c       2   213    2 mark.c       3   181    0 mark.cjumping to (new) locationY results in the locations after the currentlocations being removed:     jump line  col file/text       3  1260    8 mark.c<-- location X-2       2   685    0 eval.c<-- location X-1       1   462   36 eval.c<-- location X    >Then, when yet another location Zis jumped to, the new locationY appearsdirectly after locationX in thejumplist and locationX remains in the sameposition relative to the locations (X-1, X-2, etc., ...) that had been beforeit prior to the original jump fromX to Y:     jump line  col file/text       4  1260    8 mark.c<-- location X-2       3   685    0 eval.c<-- location X-1       2   462   36 eval.c<-- location X       1   100    0 buffer.c<-- location Y    >CHANGE LIST JUMPSchangelistchange-list-jumpsE664When makinga change the cursor positionis remembered.  One positionisremembered for every change that can be undone, unlessitis close toaprevious change.  Two commands can be used to jump to positions of changes,also those that have been undone:g;E662g;Go to[count] older position in change list.If[count]is larger than the number of older changepositionsgo to the oldest change.If thereis no older change an error messageis given.(nota motion command)g,E663g,Go to[count] newer position in change list.Just likeg; but in the opposite direction.(nota motion command)When usingacount you jumpas far back or forwardas possible.  Thus you canuse "999g;" togo to the first change for which the positionis stillremembered.  The number of entries in the changelistis fixed andis the sameas for thejumplist.When two undo-able changes are in the same line andata column positionlessthan'textwidth' apart only the last oneis remembered.  This avoids thatasequence of small changes ina line, for example "xxxxx", adds many positionsto the change list.  When'textwidth'is zero'wrapmargin'is used.  When thatalso isn't seta fixed number of 79is used.  Detail: For the computationsbytes are used, not characters, to avoida speed penalty (this only mattersformultibyte encodings).Note that when text has been inserted or deleted the cursor position might bea bit different from the position of the change.  Especially when lines havebeen deleted.When the:keepjumps command modifieris used the position ofa changeis notremembered.:changes:changesPrint the change list.A ">" character indicates thecurrent position.  Just aftera changeitis below thenewest entry, indicating thatg; takes you to thenewest entry position.  The first column indicates thecount needed to take you to this position.  Example:change line  col text    3     9    8 bla bla bla    2    11   57 fooisabar    1    14   54 the latest changed line>The3g; command takes you to line 9.  Then theoutput of:changes is:change line  col text>0     9    8 bla bla bla    1    11   57 fooisabar    2    14   54 the latest changed lineNow you can use "g," togo to line 11 and "2g," togoto line 14.==============================================================================9. Various motionsvarious-motions%%Find the next item in this line after or under thecursor and jump to its match.inclusive motion.Items can be:([{}])parenthesis or (curly/square) brackets(this can be changed with the'matchpairs' option)/* */start orend of C-style comment#if, #ifdef, #else, #elif, #endifC preprocessor conditionals (when thecursoris on the# or no ([{is following)For other items thematchitplugin can be used, seematchit-install.  Thisplugin also helps to skipmatches in comments.When'cpoptions' contains "M"cpo-M backslashesbefore parens and braces are ignored.  Without "M" thenumber of backslashes matters: an even number doesn'tmatch with an odd number.  Thus in "( \))" and "\((\)" the first and last parenthesis match.When the '%' characteris not present in'cpoptions'cpo-%, parens and braces inside doublequotes areignored, unless the number of parens/braces ina lineis uneven and this line and the previous one does notend ina backslash.  '(', '{', '[', ']', '}' and ')'are also ignored (parens and braces inside singlequotes).Note that this works fine for C, but not forPerl, where singlequotes are used for strings.Nothing specialis done for matches in comments.  Youcan either use thematchitpluginmatchit-install orputquotes around matches.Nocountis allowed,{count}% jumps toa line{count}percentage down the fileN%.  Using '%' on#if/#else/#endif makes themovement linewise.[([(Go to[count] previous unmatched '('.exclusive motion.[{[{Go to[count] previous unmatched '{'.exclusive motion.])])Go to[count] next unmatched ')'.exclusive motion.]}]}Go to[count] next unmatched '}'.exclusive motion.The above four commands can be used togo to the start orend of the currentcode block.  Itis like doing "%" on the '(', ')', '{' or '}'at the otherend of the code block, but you cando this from anywhere in the code block.Very useful forC programs.  Example: When standing on "case x:", "[{" willbring you back to the switch statement.]m]mGo to[count] next start ofamethod (for Java orsimilar structured language).  When not before thestart ofa method, jump to the start orend of theclass.exclusive motion.]M]MGo to[count] nextend ofamethod (for Java orsimilar structured language).  When not before theendofa method, jump to the start orend of the class.exclusive motion.[m[mGo to[count] previous start ofamethod (for Java orsimilar structured language).  When not after thestart ofa method, jump to the start orend of theclass.  When no '{'is found before the cursor thisisan error.exclusive motion.[M[MGo to[count] previousend ofamethod (for Java orsimilar structured language).  When not after theend ofa method, jump to the start orend of theclass.  When no '}'is found before the cursor thisisan error.exclusive motion.The above four commands assume that the file containsaclass with methods.Theclass definitionis surrounded in '{' and '}'.  Eachmethod in theclassis also surrounded with '{' and '}'.  This applies to the Java language.  Thefile looks like this:// commentclass foo {int method_one() {body_one();}int method_two() {body_two();}}[To try this out copy the text andputit ina new buffer, thehelp text aboveconfuses the jump commands]Starting with the cursor on "body_two()", using "[m" will jump to the '{'atthe start of "method_two()" (obviously thisis much more useful when themethodis long!).  Using "2[m" will jump to the start of "method_one()".Using "3[m" will jump to the start of the class.[#[#Go to[count] previous unmatched "#if" or "#else".exclusive motion.]#]#Go to[count] next unmatched "#else" or "#endif".exclusive motion.These two commands work inC programs that contain #if/#else/#endifconstructs.  It brings you to the start orend of the #if/#else/#endif wherethe current lineis included.  You can then use "%" togo to the matching line.[star[/[*  or[/Go to[count] previous start ofaC comment "/*".exclusive motion.]star]/]*  or]/Go to[count] nextend ofaC comment "*/".exclusive motion.HHTo line[count] from top (Home) ofwindow (default:first line on the window) on the first non-blankcharacterlinewise.  See also'startofline' option.Cursoris adjusted for'scrolloff' option, unless anoperatoris pending, in whichcase the text mayscroll.  E.g. "yH" yanks from the first visible lineuntil the cursor line (inclusive).MMTo Middle line of window, on the first non-blankcharacterlinewise.  See also'startofline' option.LLTo line[count] from bottom ofwindow (default: Lastline on the window) on the first non-blank characterlinewise.  See also'startofline' option.Cursoris adjusted for'scrolloff' option, unless anoperatoris pending, in whichcase the text mayscroll.  E.g. "yL" yanks from the cursor to the lastvisible line.<LeftMouse>Moves to the position on the screen where the mouseclickisexclusive.  See also<LeftMouse>.  If thepositionis ina status line, thatwindowis made theactivewindow and the cursoris not moved. vim:tw=78:ts=8:noet:ft=help:norl:

Quick links:help overview ·quick reference ·user manual toc ·reference manual toc·faq


[8]ページ先頭

©2009-2025 Movatter.jp