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_12.txt  ForVim version 9.2.  Last change: 2026 Feb 14     VIM USER MANUALbyBramMoolenaarClever tricksBy combining several commands you can make Vimdo nearly everything.  In thischaptera number of useful combinations will be presented.  This uses thecommands introduced in the previous chapters anda few more.12.1Replaceaword12.2  Change "Last, First" to "First Last"12.3  Sortalist12.4  Reverse line order12.5  Count words12.6  Finda man page12.7  Trim blanks12.8  Find whereawordis used     Next chapter:usr_20.txt  Typing command-line commands quickly Previous chapter:usr_11.txt  Recovering froma crashTable of contents:usr_toc.txt==============================================================================12.1ReplaceawordThe substitute command can be used to replace all occurrences ofaword withanother word::%s/four/4/gThe "%" range means to replace in all lines.  The "g" flagat theend causesall words ina line to be replaced.   This will notdo the right thing if your file also contains "thirtyfour".It would be replaced with "thirty4".  To avoid this, use the "\<" item tomatch the start ofa word::%s/\<four/4/gObviously, this still goes wrong on "fourteen".  Use "\>" to match theend ofa word::%s/\<four\>/4/gIf you are programming, you might want to replace "four" in comments, but notin the code.  Since thisis difficult to specify, add the "c" flag to have thesubstitute command prompt you for each replacement::%s/\<four\>/4/gcREPLACING IN SEVERAL FILESSuppose you want to replaceaword in more than one file.  You could edit eachfile and type the command manually.  It'sa lot faster to use record andplayback.   Let's assume you havea directory with C++ files, all ending in ".cpp".Thereisa function called "GetResp" that you want to rename to "GetAnswer".vim *.cppStart Vim, defining the argumentlist tocontain all the C++ files.  You are now in thefirst file.qqStartrecording into theq register:%s/\<GetResp\>/GetAnswer/gDo the replacements in the first file.:wnextWrite this file and move to the next one.qStop recording.@qExecute theq register.  This will replay thesubstitution and ":wnext".  You can verifythat this doesn't produce an error message.999@qExecute theq register on the remaining files.At the last file you will get an error message, because ":wnext" cannot moveto the next file.  This stops the execution, and everythingis done.Note:When playing backa recorded sequence, an error stops the execution.Therefore, make sure you don't get an error message when recording.Thereis one catch: If one of the .cpp files does not contain theword"GetResp", you will get an error andreplacing will stop.  To avoid this, addthe "e" flag to the substitute command::%s/\<GetResp\>/GetAnswer/geThe "e" flag tells ":substitute" that not findinga matchis not an error.==============================================================================12.2  Change "Last, First" to "First Last"You havealist of names in this form:Doe, JohnSmith, PeterYou want to change that to:John DoePeter SmithThis can be done with just one command::%s/\([^,]*\), \(.*\)/\2 \1/Let's break this down in parts.  Obviouslyit starts witha substitutecommand.  The "%"is the line range, which stands for the whole file.  Thusthe substitutionis done in every line in the file.   The arguments for the substitute command are "/from/to/".  The slashesseparate the "from"pattern and the "to" string.  Thisis what the "from"pattern contains:\([^,]*\), \(.*\)The first part between \( \) matches "Last"\(     \)    match anything buta comma  [^,]    any number of times      *matches ", " literally,The second part between \( \) matches "First"   \(  \)    any character.    any number of times      *In the "to" part we have "\2" and "\1".  These are called backreferences.They refer to the text matched by the "\( \)" parts in the pattern.  "\2"refers to the text matched by the second "\( \)", whichis the "First" name."\1" refers to the first "\( \)", whichis the "Last" name.   You can use up to nine backreferences in the "to" part ofa substitutecommand.  "\0" stands for the whole matched pattern.  There area few morespecial items ina substitute command, seesub-replace-special.==============================================================================12.3  SortalistIna Makefile you often havealist of files.  For example:OBJS = \version.o \pch.o \getopt.o \util.o \getopt1.o \inp.o \patch.o \backup.oTo sort this list,filter the text through the external sort command:/^OBJSj:.,/^$/-1!sortThis goes to the first line, where "OBJS"is the first thing in the line.Thenit goes one line down and filters the lines until the next empty line.You could also select the lines inVisual mode and then use "!sort".  That'seasier to type, but more work when there are many lines.   The resultis this:OBJS = \backup.ogetopt.o \getopt1.o \inp.o \patch.o \pch.o \util.o \version.o \Notice thatabackslashat theend of each lineis used to indicate the linecontinues.  After sorting, thisis wrong!  The "backup.o" line that wasattheend didn't havea backslash.  Now thatit sorts to another place,itmust havea backslash.   The simplest solutionis to add thebackslash with "A \<Esc>".  You cankeep thebackslash in the last line, if you make sure an empty line comesafter it.  That way you don't have this problem again.==============================================================================12.4  Reverse line orderThe:global command can be combined with the:move command to move all thelines before the first line, resulting ina reversed file.  The command is::global/^/move 0Abbreviated::g/^/m 0The "^" regularexpression matches the beginning of the line (even if the lineis blank).  The:move command moves the matching line to after the imaginaryzeroth line, so the current matching line becomes the first line of the file.As the:global commandis not confused by thechanging line numbering,:global proceeds to match all remaining lines of the file and puts eachasthe first.This also works ona range of lines.  First move to above the first line andmarkit with "mt".  Then move the cursor to the last line in the range andtype::'t+1,.g/^/m 't==============================================================================12.5  Count wordsSometimes you have to writea text witha maximum number of words.  Vim cancount the words for you.   When the whole fileis what you want tocount the words in, use thiscommand:g CTRL-GDo not typeaspace after theg, thisis just used here to make the commandeasy to read.   The output looks like this:Col 1 of 0; Line 141 of 157; Word 748 of 774; Byte 4489 of 4976You can see on whichword you are (748), and the total number of words in thefile (774).When the textis only part ofa file, you could move to the start of the text,type "gCTRL-G", move to theend of the text, type "gCTRL-G" again, and thenuse your brain to compute the difference in theword position.  That'sa goodexercise, but thereis an easier way.  WithVisual mode, select the text youwant tocount words in.  Then typegCTRL-G.  The result:Selected 5 of 293 Lines; 70 of 1884 Words; 359 of 10928 BytesFor other ways tocount words, lines and other items, seecount-items.==============================================================================12.6  Finda man pagefind-manpageWhile editinga shellscript orC program, you are usinga command or functionthat you want to find the man page for (thisis on Unix).  Let's first useasimple way: Move the cursor to theword you want to findhelp on and pressKVim will run the external "man" program on the word.  If the man pageisfound,itis displayed.  This uses the normalpager to scroll through the text(mostly the "more" program).  When you get to theend pressing<Enter> willget you back into Vim.A disadvantageis that you can't see the man page and the text you are workingonat the same time.  Thereisa trick to make the man page appear ina Vimwindow.  First, load the manfiletype plugin::runtime! ftplugin/man.vimPut this command in yourvimrc file if you intend todo this often.  Now youcan use the ":Man" command to openawindow ona man page::Man cshYou can scroll around and the textis highlighted.  This allows you to findthehelp you were looking for.  UseCTRL-Ww to jump to thewindow with thetext you were working on.   To finda man page ina specific section,put thesection number first.For example, to look insection 3 for "echo"::Man 3 echoTo jump to another man page, whichis in the text with the typical form"word(1)", pressCTRL-] on it.  Further ":Man" commands will use the samewindow.To displaya man page for theword under the cursor, use this:\K(If you redefined the<Leader>, useit instead of the backslash).For example, you want to know the return value of "strstr()" while editingthis line:if ( strstr (input, "aap") == )Move the cursor to somewhere on "strstr" and type "\K".Awindow will opento display the man page for strstr().==============================================================================12.7  Trim blanksSome people find spaces and tabsat theend ofa line useless, wasteful, andugly.  To removewhitespaceat theend of every line, execute the followingcommand::%s/\s\+$//The line range "%"is used, thus this works on the whole file.  Thepatternthat the ":substitute" command matches withis "\s\+$".  This finds whitespace characters (\s), 1 or more of them (\+), before the end-of-line ($).Later will be explained how you write patterns like this, seeusr_27.txt.   The "to" part of the substitute commandis empty: "//".  Thusit replaceswith nothing, effectivelydeleting the matched white space.Another wasteful use of spacesis placing them beforea tab.  Often these canbe deleted withoutchanging the amount of white space.  But not always!Therefore, you can bestdo this manually.  Use this search command:/You cannot see it, but thereisaspace beforeatab in this command.  Thusit's "/<Space><Tab>".   Now use "x" to delete thespace and check that theamount of whitespace doesn't change.  You might have toinsertatab ifitdoes change.  Type "n" to find the next match.  Repeat this until no morematches can be found.==============================================================================12.8  Find whereawordis usedIf you area UNIX user, you can usea combination of Vim and thegrep commandto edit all the files that containa given word.  Thisis extremely useful ifyou are working ona program and want toview or edit all the files thatcontaina specific variable.   For example, suppose you want to edit all theC program files that containtheword "frame_counter".  Todo this you use the command:vim `grep -l frame_counter *.c`Let's lookat this command in detail.  Thegrep command searches througha setof files fora given word.  Because the-l argumentis specified, the commandwill onlylist the files containing theword and not print the matching lines.Theworditis searching foris "frame_counter".  Actually, this can be anyregular expression.  (Note: Whatgrep uses for regular expressionsis notexactly the sameas what Vim uses.)   The entire commandis enclosed in backticks (`).  This tells the UNIX shellto run this command and pretend that the results were typed on the commandline.  So what happensis that thegrep commandis run and producesalist offiles, these files areput on the Vim command line.  This results in Vimediting the filelist thatis the output of grep.  You can then use commandslike ":next" and ":first" to browse through the files.FINDING EACH LINEThe above command only finds the files in which thewordis found.  You stillhave to find theword within the files.   Vim hasa built-in command that you can use to searcha set of files foragiven string.  If you want to find all occurrences of "error_string" in allCprogram files, for example, enter the following command::grep error_string *.cThis causes Vim to search for thestring "error_string" in all the specifiedfiles(*.c).  The editor will now open the first file wherea matchis foundand position the cursor on the first matching line.  Togo to the nextmatching line (no matter in what fileit is), use the ":cnext" command.  Togoto the previous match, use the ":cprev" command.  Use ":clist" to see all thematches and where they are.   The ":grep" command uses the external commandsgrep (on Unix) or findstr(on Windows).  You can change this by setting the option'grepprg'.==============================================================================Next chapter:usr_20.txt  Typing command-line commands quicklyCopyright: 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