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)
usr_10.txt  ForVim version 9.2.  Last change: 2026 Feb 14     VIM USER MANUALbyBramMoolenaar     Making big changesIn chapter 4 several ways to make small changes were explained.  This chaptergoes into making changes that are repeated or can affecta large amount oftext.  TheVisual mode allows doingvarious things with blocks of text.  Usean external program todo really complicated things.10.1  Record and playback commands10.2  Substitution10.3  Command ranges10.4  The global command10.5Visual block mode10.6  Reading andwriting part ofa file10.7  Formatting text10.8  Changingcase10.9  Using an external program     Next chapter:usr_11.txt  Recovering froma crash Previous chapter:usr_09.txt  Using theGUITable of contents:usr_toc.txt==============================================================================10.1  Record and playback commandsThe "." command repeats the preceding change.  But what if you want todosomething more complex thana single change?  That's where commandrecordingcomes in.  There are three steps:1. The "q{register}" command startsrecording keystrokes into the register   named{register}.  The register namemust be betweena andz.2. Type your commands.3. To finish recording, pressq (without any extra character).You can now execute themacro by typing the command "@{register}".Takea lookat how to use these commands in practice.  You havealist offilenames that look like this:stdio.hfcntl.hunistd.hstdlib.hAnd what you wantis the following:#include "stdio.h"#include "fcntl.h"#include "unistd.h"#include "stdlib.h"You start by moving to the first character of the first line.  Next youexecute the following commands:qaStartrecordingamacro in register a.^Move to the beginning of the line.i#include "<Esc>Insert thestring #include "at the beginningof the line.$Move to theend of the line.a"<Esc>Append the character double quotationmark(")to theend of the line.jGo to the next line.qStoprecording the macro.Now that you have done the work once, you can repeat the change by typing thecommand "@a" three times.   The "@a" command can be preceded bya count, which will cause themacro tobe executed that number of times.  In thiscase you would type:3@aMOVE AND EXECUTEYou might have the lines you want to change invarious places.  Just move thecursor to each location and use the "@a" command.  If you have done that once,you candoit again with "@@".  That'sa bit easier to type.  If you nowexecute registerb with "@b", the next "@@" will use register b.   If you compare the playbackmethod with using ".", there are severaldifferences.  First of all, "." can only repeat one change.  As seen in theexample above, "@a" cando several changes, and move aroundas well.Secondly, "." can only remember the last change.  Executinga register allowsyou to make any changes and then still use "@a" to replay the recordedcommands.  Finally, you can use 26 different registers.  Thus you can remember26 different command sequences to execute.USING REGISTERSTheregisters used forrecording are the same ones you used foryank anddelete commands.  This allows you to mixrecording with other commands tomanipulate the registers.   Suppose you have recordeda few commands in register n.  When you executethis with "@n" you notice you did something wrong.  You could tryrecordingagain, but perhaps you will make another mistake.  Instead, use this trick:GGo to theend of the file.o<Esc>Create an empty line."npPut the text from then register.  You now seethe commands you typedas text in the file.{edits}Change the commands that were wrong.  Thisisjust like editing text.0Go to the start of the line."ny$Yank the corrected commands into thenregister.ddDelete the scratch line.Now you can execute the corrected commands with "@n".  (If your recordedcommands include line breaks, adjust the last two items in the example toinclude all the lines.)APPENDING TO A REGISTERSo far we have usedalowercaseletter for the register name.  To append toaregister, use anuppercase letter.   Suppose you have recordeda command to changeaword to register c.  Itworks properly, but you would like to adda search for the nextword tochange.  This can be done with:qC/word<Enter>qYou start with "qC", which records to thec register and appends.  Thuswriting to anuppercase register name means to append to the register withthe same letter, but lowercase.This works both withrecording and withyank and delete commands.  Forexample, you want to collecta sequence of lines into thea register.  Yankthe first line with:"aYNow move to the second line, and type:"AYRepeat this command for all lines.  Thea register now contains all thoselines, in the order you yanked them.==============================================================================10.2  Substitutionfind-replaceThe ":substitute" command enables you to performstring replacements onawhole range of lines.  The general form of this commandisas follows::[range]substitute/from/to/[flags]This command changes the "from"string to the "to"string in the linesspecified with[range].  For example, you can change "Professor" to "Teacher"in all lines with the following command::%substitute/Professor/Teacher/Note:The ":substitute" commandis almost never spelled out completely.Most of the time, people use the abbreviated version ":s".  From hereon the abbreviation will be used.The "%" before the commandspecifies the command works on all lines.  Withouta range, ":s" only works on the current line.  More about ranges in the nextsection10.3.By default, the ":substitute" command changes only the first occurrence oneach line.  For example, the preceding command changes the line:Professor Smith criticized Professor Johnson today.to:Teacher Smith criticized Professor Johnson today.To change every occurrence on the line, you need to add theg (global) flag.The command::%s/Professor/Teacher/gresults in (starting with the original line):Teacher Smith criticized Teacher Johnson today.Other flags includep (print), which causes the ":substitute" command to printout the last lineit changes.  Thec (confirm) flag tells ":substitute" to askyou for confirmation beforeit performs each substitution.  Enter thefollowing::%s/Professor/Teacher/cVim finds the first occurrence of "Professor" and displays the textitisabout to change.  You get the following prompt:replace with Teacher (y/n/a/q/l/^E/^Y)?At this point, youmust enter one of the following answers:yYes; make this change.nNo; skip this match.aAll; make this change and all remaining ones withoutfurther confirmation.qQuit; don't make any more changes.lLast; make this change and then quit.CTRL-EScroll the text one line up.CTRL-YScroll the text one line down.The "from" part of the substitute commandis actuallya pattern.  The samekindas used for the search command.  For example, this command onlysubstitutes "the" whenit appearsat the start ofa line::s/^the/these/If you are substituting witha "from" or "to" part that includesa slash, youneed toputabackslash before it.A simpler wayis to use another characterinstead of the slash.A plus, for example::s+one/two+one or two+==============================================================================10.3  Command rangesThe ":substitute" command, and many other: commands, can be applied toaselection of lines.  Thisis calleda range.   The simple form ofa rangeis{number},{number}.  For example::1,5s/this/that/gExecutes the substitute command on the lines 1 to 5.  Line 5is included.The rangeis always placed before the command.A single number can be used to address one specific line::54s/President/Fool/Some commands work on the whole file when youdo not specifya range.  To makethem work on the current line the "." addressis used.  The ":write" commandworks like that.  Withouta range,it writes the whole file.  To makeit writeonly the current line intoa file::.write otherfileThe first line always has number one.  How about the last line?  The "$"characteris used for this.  For example, to substitute in the lines from thecursor to the end::.,$s/yes/no/The "%" range that we used before,is actuallya short way to say "1,$", fromthe first to the last line.USING A PATTERN IN A RANGESuppose you are editinga chapter ina book, and want to replace alloccurrences of "grey" with "gray".  But only in this chapter, not in the nextone.  You know that only chapter boundaries have theword "Chapter" in thefirst column.  This command will work then::?^Chapter?,/^Chapter/s=grey=gray=gYou can seea searchpatternis used twice.  The first "?^Chapter?" finds theline above the current position that matches this pattern.  Thus the ?pattern?rangeis used to search backwards.  Similarly, "/^Chapter/"is used to searchforward for the start of the next chapter.   To avoid confusion with the slashes, the "=" character was used in thesubstitute command here.A slash or another character would have workedaswell.ADD AND SUBTRACTThereisa slight error in the above command: If the title of the next chapterhad included "grey"it would be replacedas well.  Maybe that's what youwanted, but what if you didn't?  Then you can specify an offset.   To search forapattern and then use the line above it:/Chapter/-1You can use any number instead of the 1.  To address the second line below thematch:/Chapter/+2The offsets can also be used with the other items ina range.  Lookat thisone::.+3,$-5Thisspecifies the range that starts three lines below the cursor and endsfive lines before the last line in the file.USING MARKSInstead of figuring out the line numbers of certain positions, rememberingthem and typing them ina range, you can use marks.   Place the marksas mentioned in chapter 3.  For example, use "mt" tomarkthe top of an area and "mb" tomark the bottom.  Then you can use this rangeto specify the lines between the marks (including the lines with the marks)::'t,'bVISUAL MODE AND RANGESYou can select text withVisual mode.  If you then press ":" to starta coloncommand, you will see this::'<,'>Now you can type the command andit will be applied to the range of lines thatwas visually selected.Note:When usingVisual mode to select part ofa line, or usingCTRL-V toselecta block of text, the colon commands will still apply to wholelines.  This might change ina future version of Vim.The'< and'> are actually marks, placedat the start andend of theVisualselection.  The marks remainat their position until anotherVisual selectionis made.  Thus you can use the "'<" command to jump to position where theVisual area started.  And you can mix the marks with other items::'>,$This addresses the lines from theend of theVisual area to theend of thefile.A NUMBER OF LINESWhen you know how many lines you want to change, you can type the number andthen ":".  For example, when you type "5:", you will get::.,.+4Now you can type the command you want to use.  It will use the range "."(current line) until ".+4" (four lines down).  Thusit spans five lines.See also:range, for an overview of all possible ways to specifya range.==============================================================================10.4  The global commandThe ":global" commandis one of the more powerful features of Vim.  It allowsyou to finda match forapattern and executea command there.  The generalform is::[range]global/{pattern}/{command}Thisis similar to the ":substitute" command.  But, instead ofreplacing thematched text with other text, the command{command}is executed.Note:The command executed for ":global"must be one that starts withacolon.Normal mode commands can not be used directly.  The:normalcommand cando this for you.Suppose you want to change "foobar" to "barfoo", but only in C++ stylecomments.  These comments start with "//".  Use this command::g+//+s/foobar/barfoo/gThis starts with ":g".  Thatis short for ":global", just like ":s"is shortfor ":substitute".  Then the pattern, enclosed in plus characters.  Since thepattern we are looking for containsa slash, this uses the plus character toseparate the pattern.  Next comes the substitute command that changes "foobar"into "barfoo".   The default range for the global commandis the whole file.  Thus no rangewas specified in this example.  Thisis different from ":substitute", whichworks on one line withouta range.   The command isn't perfect, sinceit also matches lines where "//" appearshalfway througha line, and the substitution will also take place before the"//".Just like with ":substitute", anypattern can be used.  When you learn morecomplicated patterns later, you can use them here.==============================================================================10.5Visual block modeWithCTRL-V you can start selection ofa rectangular area of text.  There area few commands thatdo something special with the text block.Thereis something special about using the "$" command inVisual block mode.When the last motion command used was "$", all lines in theVisual selectionwill extend until theend of the line, also when the line with the cursorisshorter.  This remains effective until you usea motion command that moves thecursor horizontally.  Thus using "j" keeps it, "h" stops it.INSERTING TEXTThe command  "I{string}<Esc>" inserts the text{string} in each line, justleft of the visual block.  You start by pressingCTRL-V to enter visual blockmode.  Now you move the cursor to define your block.  Next you typeI to enterInsert mode, followed by the text to insert.  As you type, the text appears onthe first line only.   After you press<Esc> toend the insert, the text will magically beinserted in the rest of the lines contained in the visual selection.  Example:include oneinclude twoinclude threeinclude fourMove the cursor to the "o" of "one" and pressCTRL-V.  Moveit down with "3j"to "four".  You now havea block selection that spans four lines.  Now type:Imain.<Esc>The result:include main.oneinclude main.twoinclude main.threeinclude main.fourIf the block spans short lines thatdo not extend into the block, the textisnot inserted in that line.  For example, makeaVisual block selection thatincludes theword "long" in the first and last line of this text, and thus hasno text selected in the second line:This is a long lineshortAny other long line  ^^^^ selected blockNow use the command "Ivery<Esc>".  The result is:This is a very long lineshortAny other very long lineIn the short line no text was inserted.If thestring youinsert containsa newline, the "I" acts just likeaNormalinsert command and affects only the first line of the block.The "A" command works the same way, except thatit appends after the rightside of the block.  Andit doesinsert text ina short line.  Thus you canmakea choice whether youdo or don't want to append text toa short line.   Thereis one specialcase for "A":SelectaVisual block and then use "$"to make the block extend to theend of each line.  Using "A" now will appendthe text to theend of each line.   Using the same example from above, and then typing "$A XXX<Esc>, you getthis result:This is a long line XXXshort XXXAny other long line XXXThis really requires using the "$" command.  Vim remembers thatit was used.Making the same selection by moving the cursor to theend of the longest linewith othermovement commands will not have the same result.CHANGING TEXTTheVisual block "c" command deletes the block and then throws you intoInsertmode to enable you to type ina string.  Thestring will be inserted in eachline in the block.   Starting with the same selection of the "long" wordsas above, then typing"c_LONG_<Esc>", you get this:This is a _LONG_ lineshortAny other _LONG_ lineJust like with "I" the short lineis not changed.  Also, you can't enteranewline in the new text.The "C" command deletes text from the left edge of the block to theend ofline.  It then puts you inInsert mode so that you can type ina string,whichis added to theend of each line.   Starting with the same text again, and typing "Cnew text<Esc>" you get:This is a new textshortAny other new textNotice that, even though only the "long"word was selected, the text afteritis deletedas well.  Thus only the location of the left edge of the visualblock really matters.   Again, short lines thatdo not reach into the block are excluded.Other commands that change the characters in the block:~swapcase(a->A andA->a)Umakeuppercase  (a->A andA-> A)umakelowercase  (a->a andA->a)FILLING WITH A CHARACTERTo fill the whole block with one character, use the "r" command.  Again,starting with the same example text from above, and then typing "rx":This is a xxxx lineshortAny other xxxx lineNote:If you want to include characters beyond theend of the line in theblock, check out the'virtualedit' feature in chapter 25.SHIFTINGThe command ">" shifts the selected text to the right oneshift amount,inserting whitespace.  Thestarting point for thisshiftis the left edge ofthe visual block.   With the same example again, ">" gives this result:This is a  long lineshortAny other  long lineTheshift amountis specified with the'shiftwidth' option.  To changeit touse 4 spaces::set shiftwidth=4The "<" command removes oneshift amount ofwhitespaceat the leftedge of the block.  This commandis limited by the amount of text thatisthere; so if thereisless thanashift amount ofwhitespace available,itremoves whatit can.JOINING LINESThe "J" command joins all selected lines together into one line.  Thusitremoves the line breaks.  Actually, the line break, leading whitespace andtrailing whitespaceis replaced by one space.  Two spaces are used afteraline ending (that can be changed with the'joinspaces' option).   Let's use the example that we got so familiar with now.  The result ofusing the "J" command:This is a long line short Any other long lineThe "J" command doesn't requirea blockwise selection.  It works with "v" and"V" selection in exactly the same way.If you don't want the whitespace to be changed, use the "gJ" command.==============================================================================10.6  Reading andwriting part ofa fileWhen you arewriting an e-mail message, you may want to include another file.This can be done with the ":read{filename}" command.  The text of the fileisput below the cursor line.   Starting with this text:Hi John,Here is the diff that fixes the bug:Bye, Pierre.Move the cursor to the second line and type::read patchThe file named "patch" will be inserted, with this result:Hi John,Here is the diff that fixes the bug:2c2<for (i = 0; i <= length; ++i)--->for (i = 0; i < length; ++i)Bye, Pierre.The ":read" command acceptsa range.  The file will beput below the last linenumber of this range.  Thus ":$r patch" appends the file "patch"at theend ofthe file.   What if you want to read the file above the first line?  This can be donewith the line number zero.  This line doesn't really exist, you will get anerror message when usingit with most commands.  But this commandis allowed::0read patchThe file "patch" will beput above the first line of the file.WRITING A RANGE OF LINESTo writea range of lines toa file, the ":write" command can be used.Withouta rangeit writes the whole file.  Witha range only the specifiedlines are written::.,$write tempoThis writes the lines from the cursor until theend of the file into the file"tempo".  If this file already exists you will get an error message.  Vimprotects you from accidentally overwriting an existing file.  If you know whatyou are doing and want to overwrite the file, append !::.,$write! tempoCAREFUL: The!must follow the ":write" command immediately, without whitespace.  Otherwiseit becomesafilter command, whichis explained later inthis chapter.APPENDING TO A FILEIn the firstsection of this chapter was explained how to collecta number oflines intoa register.  The same can be done to collect lines ina file.Write the first line with this command::.write collectionNow move the cursor to the second line you want to collect, and type this::.write >>collectionThe ">>" tells Vim the "collection" fileis not to be writtenasa new file,but the linemust be appendedat the end.   You can repeat thisas many timesas you like.==============================================================================10.7  Formatting textWhen you are typing plain text, it's nice if the length of each lineisautomatically trimmed to fit in the window.  To make this happen whileinserting text, set the'textwidth' option::set textwidth=72You might remember that in the examplevimrc file this command was used forevery text file.  Thus if you are using thatvimrc file, you were alreadyusing it.  To check the current value of'textwidth'::set textwidthNow lines will be broken to take only up to 72 characters.  But when youinsert text halfway througha line, or when you deletea few words, the lineswill get too long or too short.  Vim doesn't automatically reformat the text.   To tell Vim to format the current paragraph:gqapThis starts with the "gq" command, whichis an operator.  Followingis "ap",the textobject that stands for "aparagraph".Aparagraphis separated fromthe nextparagraph by an empty line.Note:A blank line, which contains white space, does NOT separateparagraphs.  Thisis hard to notice!Instead of "ap" you could use any motion or text object.  If your paragraphsare properly separated, you can use this command to format the whole file:gggqG"gg" takes you to the first line, "gq"is the formatoperator and "G" themotion that jumps to the last line.Incase your paragraphs aren't clearly defined, you can format just the linesyou manually select.  Move the cursor to the first line you want to format.Start with the command "gqj".  This formats the current line and the one belowit.  If the first line was short, words from the next line will be appended.Ifit was too long, words will be moved to the next line.  The cursor moves tothe second line.  Now you can use "." to repeat the command.  Keep doing thisuntil you areat theend of the text you want to format.==============================================================================10.8  ChangingcaseYou have text withsection headers in lowercase.  You want to make theword"section" all uppercase.  Do this with the "gU" operator.  Start with thecursor in the first column:     gUwsection header    ---->      SECTION headerThe "gu"operator does exactly the opposite:     guwSECTION header    ---->section headerYou can also use "g~" to swap case.  All these are operators, thus they workwith any motion command, with textobjects and inVisual mode.   To make anoperator work on lines you double it.  The deleteoperatoris"d", thus to deletea line you use "dd".  Similarly, "gugu" makesa whole linelowercase.  This can be shortened to "guu".  "gUgU"is shortened to "gUU" and"g~g~" to "g~~".  Example:g~~Some GIRLS have Fun    ---->   sOME girls HAVE fUN==============================================================================10.9  Using an external programVim hasa very powerful set of commands,it cando anything.  But there maystill be something that an external command cando better or faster.   The command "!{motion}{program}" takesa block of text and filtersitthrough an external program.  In other words,it runs the system commandrepresented by{program}, givingit the block of text represented by{motion}as input.  The output of this command then replaces the selected block.   Because this summarizes badly if you are unfamiliar with UNIX filters, takea lookat an example.  The sort command sortsa file.  If you execute thefollowing command, the unsorted file input.txt will be sorted and written tooutput.txt.  (This works on both UNIX and Microsoft Windows.)sort <input.txt >output.txtNowdo the same thing in Vim.  You want to sort lines 1 through 5 ofa file.You start by putting the cursor on line 1.  Next you execute the followingcommand:!5GThe "!" tells Vim that you are performingafilter operation.  The Vim editorexpectsa motion command to follow, indicating which part of the file tofilter.  The "5G" command tells Vim togo to line 5, soit now knows thatitis tofilter lines 1 (the current line) through 5.   In anticipation of the filtering, the cursor drops to the bottom of thescreen anda! prompt displays.  You can now type in the name of thefilterprogram, in thiscase "sort".  Therefore, your full commandisas follows:!5Gsort<Enter>The resultis that the sort programis run on the first 5 lines.  The outputof the program replaces these lines.line 55      line 11line 33      line 22line 11-->      line 33line 22      line 44line 44      line 55last line      last lineThe "!!" command filters the current line througha filter.  InUnix the"date" command prints the current time and date.  "!!date<Enter>" replaces thecurrent line with the output of "date".  Thisis useful to addatimestamp toa file.Note: Thereisa difference between "!cmd" (e.g. usingit without any filerange) and "{range}!cmd".  While the former will simply execute the externalcommand and Vim will show the output, the latter willfilter{range}linesthrough thefilter and replace that range by the result of thefilter command.See:! and:range! for details.WHEN IT DOESN'T WORKStartinga shell, sendingit text and capturing the output requires that Vimknows how the shell works exactly.  When you have problems with filtering,check the values of these options:'shell'specifies the program that Vim uses to executeexternal programs.'shellcmdflag'argument to passa command to the shell'shellquote'quote to be used around the command'shellxquote'quote to be used around the command and redirection'shelltype'kind of shell (only for the Amiga)'shellslash'use forward slashes in the command (only forMS-Windows and alikes)'shellredir'string used to write the command output intoa fileOnUnix thisis hardly evera problem, because there are two kinds of shells:"sh" like and "csh" like.  Vim checks the'shell' option and sets relatedoptions automatically, depending on whetherit sees "csh" somewhere in'shell'.   On MS-Windows, however, there are many different shells and you might haveto tune theoptions to make filtering work.  Check thehelp for theoptionsfor more information.READING COMMAND OUTPUTTo read the contents of the current directory into the file, use this:on Unix::read !lson MS-Windows::read !dirThe output of the "ls" or "dir" commandis captured and inserted in the text,below the cursor.  Thisis similar to readinga file, except that the "!"isused to tell Vim thata command follows.   The command may have arguments.  Anda range can be used to tell where Vimshouldput the lines::0read !date -uThis inserts the current time and date in UTC formatat the top of the file.(Well, if you havea date command that accepts the "-u" argument.)Note thedifference with using "!!date": that replaceda line, while ":read !date" willinserta line.WRITING TEXT TO A COMMANDTheUnix command "wc" counts words.  Tocount the words in the current file::write !wcThisis the same write commandas before, but instead ofa file name the "!"characteris used and the name of an external command.  The written text willbe passed to the specified commandas its standard input.  The output couldlook like this:       4      47     249The "wc" command isn't verbose.  This means you have 4 lines, 47 words and 249characters.Watch out for this mistake::write! wcThis will write the file "wc" in the current directory, with force.  Whitespaceis important here!REDRAWING THE SCREENIf the external command produced an error message, the display may have beenmessed up.  Vimis very efficient and only redraws those parts of the screenthatit knows need redrawing.  Butit can't know about what another programhas written.  To tell Vim to redraw the screen:CTRL-L==============================================================================Next chapter:usr_11.txt  Recovering froma crashCopyright: seemanual-copyright  vim:tw=78:ts=8:noet:ft=help:norl:

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


[8]ページ先頭

©2009-2026 Movatter.jp