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_25.txt  ForVim version 9.1.  Last change: 2025 Feb 01     VIM USER MANUAL- byBramMoolenaar     Editing formatted textText hardly ever comes in onesentence per line.  This chapteris aboutbreaking sentences to make them fit ona page and other formatting.Vim also has useful features for editing single-line paragraphs and tables.25.1  Breaking lines25.2  Aligning text25.3  Indents and tabs25.4  Dealing with long lines25.5  Editing tables     Next chapter:usr_26.txt  Repeating Previous chapter:usr_24.txt  Inserting quicklyTable of contents:usr_toc.txt==============================================================================25.1  Breaking linesVim hasa number offunctions that make dealing with text easier.  By default,the editor does not perform automatic line breaks.  In other words, you haveto press<Enter> yourself.  Thisis useful when you arewriting programs whereyou want to decide where the line ends.  Itis not so good when you arecreating documentation and want the text to beat most 70 character wide.   If you set the'textwidth' option, Vim automatically inserts line breaks.Suppose, for example, that you wanta very narrow column of only 30characters.  You need to execute the following command::set textwidth=30Now you start typing (ruler added): 1   2     312345678901234567890123456789012345I taught programming for a whiIf you type "l" next, this makes the line longer than the 30-character limit.When Vim sees this,it insertsa line break and you get the following: 1   2     312345678901234567890123456789012345I taught programming for awhilContinuing on, you can type in the rest of the paragraph: 1   2     312345678901234567890123456789012345I taught programming for awhile. One time, I was stoppedby the Fort Worth police,because my homework was toohard. True story.Youdo not have to type newlines; Vim puts them in automatically.Note:The'wrap' option makes Vim display lines witha line break, but thisdoesn'tinserta line break in the file.REFORMATTINGThe Vim editoris notaword processor.  Inaword processor, if you deletesomethingat the beginning of the paragraph, the line breaks are reworked.  InVim they are not; so if you delete theword "programming" from the first line,all you getisa short line: 1   2     312345678901234567890123456789012345I taught for awhile. One time, I was stoppedby the Fort Worth police,because my homework was toohard. True story.This does not look good.  To get theparagraph into shape you use the "gq"operator.   Let's first use this withaVisual selection.  Starting from the firstline, type:v4jgq"v" to startVisual mode, "4j" to move to theend of theparagraph and thenthe "gq" operator.  The result is: 1   2     312345678901234567890123456789012345I taught for a while. Onetime, I was stopped by theFort Worth police, because myhomework was too hard. Truestory.Note: thereisa way todo automaticformatting for specific types of textlayouts, seeauto-format.Since "gq"is an operator, you can use one of the three ways to select thetextit works on: WithVisual mode, withamovement and witha text object.   The example above could also be done with "gq4j".  That'sless typing, butyou have to know the line count.A more useful motion commandis "}".  Thismoves to theend ofa paragraph.  Thus "gq}" formats from the cursor to theend of the current paragraph.A very useful textobject to use with "gq"is the paragraph.  Try this:gqap"ap" stands for "a-paragraph".  This formats the text of oneparagraph(separated by empty lines).  Also the part before the cursor.   If you have your paragraphs separated by empty lines, you can format thewhole file by typing this:gggqG"gg" to move to the first line, "gqG" to format until the last line.   Warning: If your paragraphs are not properly separated, they will be joinedtogether.A common mistakeis to havea line withaspace or tab.  That'sablank line, but not an empty line.Vimis able to format more than just plain text.  Seefo-table for how tochange this.  See the'joinspaces' option to change the number of spaces usedaftera full stop.   Itis possible to use an external program for formatting.  Thisis usefulif your text can't be properly formatted with Vim's builtin command.  See the'formatprg' option.==============================================================================25.2  Aligning textTo centera range of lines, use the following command::{range}center [width]{range}is the usual command-line range.[width]is an optional line width touse for centering.  If[width]is not specified,it defaults to the value of'textwidth'.  (If'textwidth'is 0, the defaultis 80.)   For example::1,5center 40results in the following:       I taught for a while. One       time, I was stopped by the     Fort Worth police, because my      homework was too hard. True story.RIGHT ALIGNMENTSimilarly, the ":right" command right-justifies the text::1,5right 37gives this result:    I taught for a while. One   time, I was stopped by theFort Worth police, because my  homework was too hard. True       story.LEFT ALIGNMENTFinally thereis this command::{range}left [margin]Unlike ":center" and ":right", however, the argument to ":left"is not thelength of the line.  Insteaditis the left margin.  Ifitis omitted, thetext will beput against the left side of the screen (usinga zero marginwoulddo the same).  Ifitis 5, the text will be indented 5 spaces.  Forexample, use these commands::1left 5:2,5leftThis results in the following:     I taught for a while. Onetime, I was stopped by theFort Worth police, because myhomework was too hard. Truestory.JUSTIFYING TEXTjustify:JustifyJustify()package-justifyVim has no built-in way of justifying text.  However, thereisa neatmacropackage that does the job.  To use this package, execute the followingcommand::packadd justifyOrput this line in yourvimrc:packadd! justifyThis Vimscript file definesa new visual command "_j".  Tojustifya block oftext, highlight the text inVisual mode and then execute "_j".   Look in the file for more explanations.  Togo there,do "gf" on this name:$VIMRUNTIME/pack/dist/opt/justify/plugin/justify.vim.An alternativeis tofilter the text through an external program.  Example::%!fmt==============================================================================25.3  Indents and tabsIndents can be used to make text stand out from the rest.  The example textsin this manual, for example, are indented by eight spaces ora tab.  You wouldnormally enter this by typingatabat the start of each line.  Take thistext:the first linethe second lineThisis entered by typinga tab, some text,<Enter>,tab and more text.   The'autoindent' option inserts indents automatically::set autoindentWhena new lineis startedit gets the same indentas the previous line.  Inthe above example, thetab after the<Enter>is not needed anymore.INCREASING INDENTTo increase the amount of indent ina line, use the ">" operator.  Often thisis usedas ">>", which adds indent to the current line.   The amount of indent addedis specified with the'shiftwidth' option.  Thedefault valueis 8.  To make ">>"insert four spaces worth of indent, forexample, type this::set shiftwidth=4When used on the second line of the example text, thisis what you get:the first line    the second line"4>>" will increase the indent of four lines.TABSTOPIf you want to make indentsa multiple of 4, you set'shiftwidth' to 4.  Butwhen pressinga<Tab> you still get 8 spaces worth of indent.  To change this,set the'softtabstop' option::set softtabstop=4This will make the<Tab> keyinsert 4 spaces worth of indent.  If there arealready four spaces,a<Tab> characteris used (saving seven characters in thefile).  (If you always want spaces and notab characters, set the'expandtab'option.)Note:You could set the'tabstop' option to 4.  However, if you edit thefile another time, with'tabstop' set to the default value of 8,itwill look wrong.  In other programs and whenprinting the indent willalso be wrong.  Thereforeitis recommended to keep'tabstop'at eightall the time.  That's the standard value everywhere.CHANGING TABSYou edita file which was written witha tabstop of 3.  In Vimit looks ugly,becauseit uses the normal tabstop value of 8.  You can fix this by setting'tabstop' to 3.  But you have todo this every time you edit this file.   Vim can change the use of tabstops in your file.  First, set'tabstop' tomake the indents look good, then use the ":retab" command::set tabstop=3:retab 8The ":retab" command will change'tabstop' to 8, whilechanging the text suchthatit looks the same.  It changes spans of whitespace into tabs and spacesfor this.  You can now write the file.  Next time you editit the indents willbe right without setting an option.   Warning: When using ":retab" ona program,it may change whitespace insideastring constant.  Therefore it'sa good habit to use "\t" instead ofareal tab.==============================================================================25.4  Dealing with long linesSometimes you will be editinga file thatis wider than the number of columnsin the window.  When that occurs, Vim wraps the lines so that everything fitson the screen.   If you switch the'wrap' option off, each line in the file shows upas oneline on the screen.  Then the ends of the long lines disappear off the screento the right.   When you move the cursor toa character that can't be seen, Vim will scrollthe text to show it.  Thisis like movinga viewport over the text in thehorizontal direction.   By default, Vim does not displaya horizontal scrollbar in the GUI.  If youwant to enable one, use the following command::set guioptions+=bOne horizontal scrollbar will appearat the bottom of the Vim window.If you don't havea scrollbar or don't want to use it, use these commands toscroll the text.  The cursor will stay in the same place, but it's moved backinto the visible text if necessary.zhscroll right4zhscroll four characters rightzHscroll halfawindow width rightzescroll right toput the cursorat theendzlscroll left4zlscroll four characters leftzLscroll halfawindow width leftzsscroll left toput the cursorat the startLet's attempt to show this with one line of text.  The cursoris on the "w" of"which".  The "currentwindow" above the line indicates the text thatiscurrently visible.  The "window"s below the text indicate the text thatisvisible after the command left of it.      |<-- currentwindow -->|some long text, part of which is visible in the windowze  |<--window     -->|zH   |<--window     -->|4zh  |<--window     -->|zh     |<--window -->|zl       |<--window   -->|4zl  |<--window     -->|zL|<--window     -->|zs       |<--window   -->|MOVING WITH WRAP OFFWhen'wrap'is off and the text has scrolled horizontally, you can use thefollowing commands to move the cursor toa character you can see.  Thus textleft and right of thewindowis ignored.  These never cause the text toscroll:g0to first visible character in this lineg^to first non-blank visible character in this linegmto middle of screen linegMto middle of the text in this lineg$to last visible character in this line|<--window     -->|some long    text, part of which is visible in one lineg0g^gmgMg$BREAKING AT WORDSedit-no-breakWhen preparing text for use by another program, you might have to makeparagraphs withouta line break.A disadvantage of using'nowrap'is that youcan't see the wholesentence you are working on.  When'wrap'is on, words arebroken halfway, which makes them hard to read.A good solution for editing this kind ofparagraphis setting the'linebreak' option.  Vim then breaks linesat an appropriate place whendisplaying the line.  The text in the file remains unchanged.   Without'linebreak' text might look like this:+---------------------------------+|letter generation program forab||ank.  They wanted to send outas||pecial, personalizedletter to th||eir richest 1000 customers.  Unfo||rtunately for the programmer, he |+---------------------------------+After::set linebreakit looks like this:+---------------------------------+|letter generation program fora  ||bank.  They wanted to send outa ||special, personalizedletter to  ||their richest 1000 customers.    ||Unfortunately for the programmer,|+---------------------------------+Related options:'breakat'specifies the characters wherea break can be inserted.'showbreak'specifiesastring to showat the start of broken line.Set'textwidth' to zero to avoidaparagraph to be split.MOVING BY VISIBLE LINESThe "j" and "k" commands move to the next and previous lines.  When used ona long line, this means movinga lot of screen linesat once.   To move only one screen line, use the "gj" and "gk" commands.  Whena linedoesn't wrap theydo the sameas "j" and "k".  When the line does wrap, theymove toa character displayed one line below or above.   You might like to use these mappings, which bind thesemovement commands tothe cursor keys::map <Up> gk:map <Down> gjTURNING A PARAGRAPH INTO ONE LINEedit-paragraph-joinIf you want to import text intoa program like MS-Word, eachparagraph shouldbea single line.  If your paragraphs are currently separated with emptylines, thisis how you turn eachparagraph intoa single line::g/./,/^$/joinThat looks complicated.  Let's breakit up in pieces::g/./A ":global" command that finds all lines that containat least one character.     ,/^$/A range,starting from the current line (the non-emptyline) until an empty line.  joinThe ":join" command joins the range of lines togetherinto one line.Starting with this text, containing eight lines brokenat column 30:+----------------------------------+|Aletter generation program   ||fora bank.  They wanted to   ||send outa special,   ||personalized letter.   ||   ||To their richest 1000   ||customers.  Unfortunately for   ||the programmer,   |+----------------------------------+Youend up with two lines:+----------------------------------+|Aletter generation program fora ||bank.They wanted to send outas||pecial, personalized letter.   ||To their richest 1000 customers.  ||Unfortunately for the programmer, |+----------------------------------+Note that this doesn't work when the separating lineis blank but not empty;whenit contains spaces and/or tabs.  This command does work with blank lines::g/\S/,/^\s*$/joinThis still requiresa blank or empty lineat theend of the file for the lastparagraph to be joined.==============================================================================25.5  Editing tablesSuppose you are editinga table with four columns:nice table  test 1test 2    test 3input A  0.534input B  0.913You need to enter numbers in the third column.  You could move to the secondline, use "A", entera lot of spaces and type the text.   For this kind of editing thereisa special option:set virtualedit=allNow you can move the cursor to positions where there isn't any text.  Thisiscalled "virtualspace".  Editinga tableisa lot easier this way.   Move the cursor by searching for the header of the last column:/test 3Now press "j" and you are right where you can enter the value for "inputA".Typing "0.693" results in:nice table  test 1     test 2 test 3input A  0.534 0.693input B  0.913Vim has automatically filled the gap in front of the new text for you.  Now,to enter the next field in this column use "Bj".  "B" moves back to the startofa whitespace separated word.  Then "j" moves to the place where the nextfield can be entered.Note:You can move the cursor anywhere in the display, also beyond theendofa line.  But Vim will notinsert spaces there, until youinsertacharacter in that position.COPYING A COLUMNYou want to adda column, which should bea copy of the third column andplaced before the "test 1" column.  Do this in seven steps:1.  Move the cursor to the left upper corner of this column, e.g., with    "/test 3".2.  PressCTRL-V to start blockwiseVisual mode.3.  Move the cursor down two lines with "2j".  You are now in "virtualspace":    the "inputB" line of the "test 3" column.4.  Move the cursor right, to include the whole column in the selection, plus    thespace that you want between the columns.  "9l" shoulddo it.5.  Yank the selected rectangle with "y".6.  Move the cursor to "test 1", where the new columnmust be placed.7.  Press "P".The result should be:nice table  test 3    test 1     test 2   test 3input A  0.693     0.534   0.693input B    0.913Notice that the whole "test 1" column was shifted right, also the line wherethe "test 3" column didn't have text.Go back to non-virtual cursor movements with::set virtualedit=VIRTUAL REPLACE MODEThe disadvantage of using'virtualedit'is thatit "feels" different.  Youcan't recognize tabs or spaces beyond theend of line when moving the cursoraround.  Anothermethod can be used: VirtualReplace mode.   Suppose you havea line ina table that contains both tabs and othercharacters.  Use "rx" on the first tab:inp0.693   0.5340.693       |   rx  |Vinpx0.693   0.5340.693The layoutis messed up.  To avoid that, use the "gr" command:inp0.693   0.5340.693       |  grx  |Vinpx0.693   0.5340.693What happensis that the "gr" command makes sure the new character takes theright amount of screen space.  Extra spaces or tabs are inserted to fill thegap.  Thus what actually happensis thatatabis replaced by "x" and thenblanks added to make the text afterit keep its place.  In thiscaseatabis inserted.   When you need to replace more than one character, you use the "R" commandtogo toReplace mode (see04.9).  This messes up the layout and replacesthe wrong characters:inp00.5340.693| R0.786 |Vinp0.786340.693The "gR" command uses VirtualReplace mode.  This preserves the layout:inp00.5340.693|gR0.786 |Vinp0.7860.5340.693==============================================================================Next chapter:usr_26.txt  RepeatingCopyright: 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-2025 Movatter.jp