bram moolenaar &olegraiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfcommands 48 12.1...

30
VIM 5.6 R EFERENCE G UIDE Bram Moolenaar & Oleg Raisky 2000

Upload: others

Post on 24-Mar-2020

9 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

VIM 5.6REFERENCEGUIDE

Bram Moolenaar& Oleg Raisky

2000

Page 2: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

2

VIM

5.6ReferenceGuide

Conventions:

:marks

denotesVIM

commandtypedinExmode

visual

denotesVIM

commandtypedinVisualmode

[..]

denotesanoptionalpartofthecommand

�le

denotescommandargument(s)

f..g

denotesasetofcharacters

Space

meanspressedkey/combinationofkeys

,

thiscommand/featureisVIM

speci�c(notfoundinVi)

Contents

1

MovementCommands

4

1.1

Left-rightmotions.................................

4

1.2

Up-downmotions.................................

4

1.3

Textobjectmotions................................

4

1.4

Scrolling......................................

5

1.5

Variousmotions..................................

5

1.6

Marksandmotions................................

5

1.7

Usingtags.....................................

6

2

EditingCommands

6

2.1

Insertingtext...................................

6

2.2

KeysinInsertmode

...............................

6

2.3

SpecialkeysinInsertmode

...........................

7

2.4

Digraphs,

.....................................

7

2.5

Specialinserts...................................

7

2.6

Deletingtext

...................................

7

2.7

Copyingandmovingtext.............................

8

2.8

Changingtext...................................

8

2.9

Complexchanges.................................

9

2.10Visualmode,

...................................

10

2.11Textobjects....................................

10

2.12RepeatingCommands

..............................

11

2.13Undo/RedoCommands..............................

11

2.14Command-lineediting

..............................

12

2.15Encryption

....................................

12

3

KeyMappingsAbbreviations

13

3.1

Keymapping

...................................

13

3.2

Abbreviations...................................

13

3.3

User-de�nedcommands,

............................

14

4

Options

15

4.1

SettingOptions..................................

15

4.2

Optionexplanation................................

15

5

OtherCommands

19

5.1

ShellCommands

.................................

19

5.2

QuickFixCommands,

..............................

20

5.3

ViminfoCommands,

...............................

20

5.4

VariousCommands................................

21

Page 3: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

CONTENTS

3

6

Exrangesandsearchpatterns

22

6.1

Ranges.......................................

22

6.2

SpecialExcharacters...............................

22

6.3

Patternsearches..................................

22

6.4

Specialcharactersinsearchpatterns

......................

23

6.5

O�setsallowedaftersearchcommand......................

24

7

Starting,WritingandQuittingCommands

25

7.1

StartingVIM

...................................

25

7.2

Editinga�le

...................................

25

7.3

Usingtheargumentlist..............................

26

7.4

Writingandquitting...............................

26

8

WindowsandBu�ersfunctions

27

8.1

Multi-windowfunctions,

............................

27

8.2

Bu�erlistfunctions................................

28

9

ScriptLanguage

28

9.1

Variables......................................

28

9.2

Expressionsyntax.................................

28

9.3

Functions.....................................

30

9.4

User-De�nedFunctions..............................

36

9.5

Commands

....................................

36

10GUI

37

10.1MouseControl

..................................

37

10.2WindowPosition

.................................

38

10.3Menus.......................................

39

10.4Miscellaneous...................................

40

11Syntaxhighlighting

41

11.1Syntax�les....................................

41

11.2De�ningasyntax.................................

41

11.3Syntaxarguments.................................

43

11.4Syntaxpatterns..................................

44

11.5Synchronizing...................................

44

11.6Highlightcommand................................

46

11.7Linkinggroups

..................................

48

12AutomaticCommands

48

12.1De�ningautocommands.............................

48

12.2Removingautocommands

............................

48

12.3Listingautocommands..............................

48

12.4Events.......................................

49

12.5Patterns......................................

50

12.6Filetypes......................................

51

12.7Groups.......................................

51

12.8Executingautocommands

............................

51

12.9Usingautocommands...............................

52

13Miscellany

53

13.1VIM

modes....................................

53

13.2VIM

registers...................................

54

Page 4: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

4

VIM

5.6ReferenceGuide

1

MovementCommands

1.1

Left-rightmotions

[n]h

left(also:CTRL-H,BS,or

key)

[n]lright(also:Space

or!

key)

0

to�rstcharacterintheline(also:Home

key)

b

to�rstnon-blankcharacterintheline

[n]$

tothelastcharacterintheline(n-1lineslower)(also:End

key)

[n]g0

to�rstcharacterinscreenline(di�ersfrom0whenlineswrap)

[n]gb

to�rstnon-blankcharacterinscreenline(di�ersfromb

whenlineswrap)

[n]g$

tolastcharacterinscreenline(di�ersfrom$whenlineswrap)

[n]gm

tomiddleofthescreenline

[n]jtocolumnn(default:1)

[n]fchar

tothen-thoccurrenceofchartotheright

[n]Fchar

tothen-thoccurrenceofchartotheleft

[n]tchar

tillbeforethen-thoccurrenceofchartotheright

[n]Tchar

tillbeforethen-thoccurrenceofchartotheleft

[n];repeatthelastf,F,t,orTntimes

[n],repeatthelastf,F,t,orTntimesinoppositedirection

1.2

Up-downmotions

[n]k

upnlines(also:CTRL-P

and")

[n]jdownnlines(also:CTRL-J,CTRL-N,NL,and#)

[n]{

upnlines,onthe�rstnon-blankcharacter

[n]+

downnlines,onthe�rstnon-blankcharacter(also:CTRL-M

andRet)

[n]

downn-1lines,onthe�rstnon-blankcharacter

[n]G

gotolinen(default:lastline),onthe�rstnon-blankcharacter

[n]gg

gotolinen(default:�rstline),onthe�rstnon-blankcharacter

n%

gotolinenpercentagedowninthe�le.nmustbegiven,otherwiseitisthe%

command

[n]gkorg"

upnscreenlines(di�ersfromkwhenlinewraps,andwhenusedwithan

operator,becauseit'snotlinewise.)

[n]gjorg#

downnscreenlines(di�ersfromjwhenlinewraps,andwhenusedwithan

operator,becauseit'snotlinewise.)

:[range]go[to][count]Gotocountbyteinthebu�er.Defaultcountiszero,startofthe

�le.Whengivingrange,thelastnumberinitused.End-of-linecharactersarecounted

dependingonthecurrent�leformatsetting.

1.3

Textobjectmotions

[n]w

nwords1

[n]W

nblank-separatedWORDSforward

[n]e

forwardtotheendofthen-thword

[n]E

forwardtotheendofthen-thblank-separatedWORD

[n]b

nwordsbackward

[n]B

nblank-separatedWORDSbackward

[n]ge

backwardtotheendofthen-thword

[n]gE

backwardtotheendofthen-thblank-separatedWORD

[n])nsentencesforward

[n](nsentencesbackward

1Forde�nitionofword,WORD,sentence,paragraphandsectionseeSection2.11

VIM

Distribution:

VIM

isCharityware.Please,readVIM

documentationfordetails.

VIM

Guidec

1997-2000,OlegRaisky<[email protected]>

VIM

Author,Bram

Moolenaar<[email protected]>

ProofreadbyJeanJordaan<[email protected]>

VIM

onWWW:http://www.vim.org/

Thisdocument:http://scisun.sci.ccny.cuny.edu/~olrcc/vim/

Page 5: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

56

VIM

5.6ReferenceGuide

NOTES

1

MOVEMENTCOMMANDS

5

[n]g

nparagraphsforward

[n]f

nparagraphsbackward

[n]]]nsectionsforward,atstartofsection

[n][[nsectionsbackward,atstartofsection

[n]][nsectionsforward,atendofsection

[n][]nsectionsbackward,atendofsection

[n][(ntimesbacktounclosed(

[n][f

ntimesbacktounclosedf

[n]])ntimesforwardtounclosed)

[n]]g

ntimesforwardtounclosedg

[n][#

ntimesbacktounclosed#ifor#else

[n]]#

ntimesforwardtounclosed#elseor#endif

[n][*

ntimesbacktostartofcomment/*

[n]]*

ntimesforwardtoendofcomment*/

1.4

Scrolling

[n]CTRL-E

windownlinesdownwards(default:1)

[n]CTRL-D

windownlinesDownwards(default:1/2window)

[n]CTRL-F

windownpagesForwards(downwards)

[n]CTRL-Y

windownlinesupwards(default:1)

[n]CTRL-U

windownlinesUpwards(default:1/2window)

[n]CTRL-B

windownpagesBackwards(upwards)

zRet

orztredraw,currentlineattopofwindow

z.orzz

redraw,currentlineatcenterofwindow

z{orzb

redraw,currentlineatbottomofwindow

[n]zh

scrollscreenncharacterstotheright

[n]zlscrollscreenncharacterstotheleft

[n]zH

scrollscreenhalfascreenwidthtotheright

[n]zL

scrollscreenhalfascreenwidthtotheleft

1.5

Variousmotions

%

�ndthenextbrace,bracket,comment,or#if/#else/#endif

inthislineandgotoitsmatch

[n]H

gotothen-thlineinthewindow,onthe�rstnon-blank

M

gotothemiddlelineinthewindow,onthe�rstnon-blank

[n]L

gotothen-thlinefromthebottom,onthe�rstnon-blank

[n]go

goton-thbyteinthebu�er

:[range]go[to][o�]goto[o�]setbyteinthebu�er

1.6

Marksandmotions

mfa-zA-Zg

markcurrentpositionwithmarkfa-zA-Zg

`fa-zg

gotomarkfa-zgwithincurrent�le

`fA-Zg

gotomarkfA-Zginany�le

`f0-9g

gotothepositionwhereVIM

waslastexited

\

gotothepositionbeforethelastjump

`"

gotothepositionwhenlasteditingthis�le

`[

gotothestartofthepreviouslyoperatedorputtext

`]

gototheendofthepreviouslyoperatedorputtext

`<

gotothestartofthe(previous)Visualarea

`>

gototheendofthe(previous)Visualarea

'fa-zA-Z0-9[]'"<

>

g

sameas`,butonthe�rstnon-blankintheline

:marksdisplaytheactivemarks

Page 6: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

6

VIM

5.6ReferenceGuide

[n]CTRL-O

goton-tholderpositioninjumplist

[n]CTRL-I

goton-thnewerpositioninjumplist

:ju[mps]displaythejumplist

1.7

Usingtags

:ta[g][!]tag

jumptotag

:[n]ta[g][!]jumpton-thnewertagintaglist

CTRL-]

jumptothetagundercursor,unlesschangeshavebeenmade

[n]CTRL-T

jumpbackfromn-tholdertagintaglist

:tj[ump][!][tag]Jumptotagtagorselectfromlistwhentherearemultiplematches

:ts[elect][!][tag]listmatchingtagsandselectonetojumpto

:[n]tn[ext][!]jumpton-thnextmatchingtag

:[n]tp[revious][!]jumpton-thpreviousmatchingtag

:[n]tr[ewind][!]jumpton-thmatchingtag

:[n]po[p][!]jumpbackfromn-tholdertagintaglist

:tagsprinttaglist

:pt[ag]tag

openapreviewwindowtoshowtagtag

CTRL-W

g

likeCTRL-]

butshowtaginpreviewwindow

:pts[elect]like:tselectbutshowtaginpreviewwindow

:ptj[ump]like:tjumpbutshowtaginpreviewwindow

:pc[lose]closetagpreviewwindow

CTRL-W

z

closetagpreviewwindow

2

EditingCommands

2.1

Insertingtext

[n]a

appendtextafterthecursor(ntimes)

[n]A

appendtextattheendoftheline(ntimes)

[n]iinserttextbeforethecursor(ntimes)(also:Ins)

[n]Iinserttextbeforethe�rstnon-blankintheline(ntimes)

[n]gIinserttextincolumn1(ntimes)

[n]o

openanewlinebelowthecurrentline,appendtext(ntimes)

[n]O

openanewlineabovethecurrentline,appendtext(ntimes)

2.2

KeysinInsertmode

char

actioninInsertmode2

Esc

endInsertmode,backtoNormalmode

CTRL-C

likeEsc,butdonotcompleteanabbreviationbegun

CTRL-A

insertpreviouslyinsertedtext

CTRL-@

insertpreviouslyinsertedtextandstopinsert

CTRL-O

command

executecommandandreturntoInsertmode

CTRL-R

f0-9a-z%#:.-="*g

insertthecontentsofaregister3

,

NL

orRet

orCTRL-M

orCTRL-J

beginnewline

CTRL-E

insertthecharacterfrombelowthecursor

CTRL-Y

insertthecharacterfromabovethecursor

CTRL-V

char

insertcharacterliterally,orenterdecimalbytevalue

CTRL-N

insertnextmatchofidenti�erbeforethecursor

CTRL-P

insertpreviousmatchofidenti�erbeforethecursor

CTRL-X

...

completethewordbeforethecursorinvariousways:

2SeeSection13.1fordescriptionofVIM

modes

3SeeSection13.2fordescriptionofVIM

registers

13

MISCELLANY

55

6.Expressionregister"=

Thisisnotreallyaregisterthatstorestext,butawaytouseanexpressionwherea

registercanbeused.Itisread-only,youcannotputtextintotheexpressionregister.

Afterthe\=",thecursormovestothecommandline,whereyoucanenteranyexpression.

Allnormalcommandlineeditingcommandsareavailable,includingaspecialhistoryfor

expressions.WhenyouendthecommandlinebytypinghCRi,theresultoftheexpressionis

computed.IfyouenditwithhEsci,theexpressionisabandoned.Iftheenteredcommand

lineisempty,thepreviousexpressionisused.

7.Selectionregister"*

ThisisusedforstoringandretrievingtheselectedtextfortheGUI.

Ifyouuseaputcommandwithoutspecifyingaregister,theregisterthatwaslastwritten

toisused(thisisalsothecontentoftheunnamedregister).Ifyouareconfused,usethe

\:dis"commandto�ndoutwhatwillbeput.

8.Blackholeregister"

Whenwritingtothisregister,nothinghappens.Thiscanbeusedtodeletetextwithout

a�ectingthenormalregisters.Whenreadingfromthisregister,nothingisreturned.

9.Lastsearchpatternregister"/

Containsthemostrecentsearch-pattern.Thisisusedfornandhlsearch.

Page 7: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

54

VIM

5.6ReferenceGuide

Switchingfrom

modetomode

Ifforanyreasonyoudonotknowwhichmodeyouarein,youcanalwaysgetbackto

NormalmodebytypingEsc

twice.

FROM#TO!

Normal

Visual

Select

Insert

Replace

Cmd-line

Ex

Normal

{

vVb

V

{

{

R

:/?!

Q

Visual

{

{

b

G

cC

{

:

{

Select

{

b

Ob

G

{

{

{

:

{

Insert

Esc

{

{

{

Ins

{

{

Replace

Esc

{

{

Ins

{

{

{

Cmd-line

{

{

{

:start

{

{

{

Ex

:vi

{

{

{

{

{

{

13.2

VIM

registers

ThereareninetypesofVIM

registers:

1.Unnamedregister""

Thisregisterisusedtoplacealltextdeletedwiththe\d",\c",\s",\x"commandsor

copiedwiththeyankcommand,regardlessofwhetherornotaspeci�cregisterwasused

(e.g."xdd).Anexceptionisthe

register:"dddoes-notstorethedeletedtextinany

register.Thecontentsofthisregisterareusedbyanyputcommand(porP)whichdoesnot

specifyaregister.Itcanbealsoaccessedbythename".

2.Numberedregisters"0{"9

Theseare�lledwithyankanddeletecommands.Register\0"is�lledwiththelastyank

command,unlessanotherregisterwasspeci�ed.Register\1"is�lledwiththetextthat

wasdeletedbyeachdeleteorchangecommand,unlessanotherregisterwasspeci�edorthe

textislessthanoneline(textdeletedwith\x"or\dw"willbeputinthesmalldelete

register).Thecontentsofregister\1"areputin\2",\2"!

\3",andsoforth.The

contentofregister\9"islost.

3.Smalldeleteregister"-

Thisoneis�lledwithdeletecommandsthatdeletelessthanoneline,exceptwhen

anotherregisterwasspeci�ed.

4.Namedregisters"a{"zand"A{"Z

Theseareonly�lledwhenyousayso.Theyarenamed\a"to\z"normally.Ifyouuse

anuppercaseletter,thesameregisteraswiththelowercaseletterisused,butthetextis

appendedtothepreviouscontent.Withalowercaseletterthepreviouscontentislost.

5.Read-onlyregisters":,".,"%and"#

Theycanonlybeusedwiththecommands\p",\P",\:put"andwithCTRL-R.

".Containsthelastinsertedtext(thesameaswhatisinsertedwiththeinsertmode

commandsCTRL-A

andCTRL-@).

Note:thisdoesn'tworkwithCTRL-R

onthecommandline.

"%

Containsthenameofthecurrent�le.

"#

Containsthenameofthealternate�le.

":Containsthelastcommandline.Itcanbeusedwith\@:",thisrepeatsthelastcommand

line.

2

EDITINGCOMMANDS

7

CTRL-X

CTRL-D

completethede�nitionormacro

CTRL-X

CTRL-F

completethe�lename

CTRL-X

CTRL-I

completethewordsearchingthecurrentandincluded�les.

CTRL-X

CTRL-K

completethewordusingdictionary�les.

CTRL-X

CTRL-L

completethewholelinesearchingthecurrent�le

CTRL-X

CTRL-N

completethewordsearchingthecurrent�le

CTRL-X

CTRL-]

completethetag

BS

orCTRL-H

deletethecharacterbeforethecursor

Del

deletethecharacterunderthecursor

CTRL-W

deletewordbeforethecursor

CTRL-U

deleteallenteredcharactersinthecurrentline

CTRL-T

insertoneshiftwidthofindentinfrontofthecurrentline

CTRL-D

deleteoneshiftwidthofindentinfrontofthecurrentline

0CTRL-D

deleteallindentinthecurrentline

b

CTRL-D

deleteallindentinthecurrentline,restoreindentinnextline

2.3

SpecialkeysinInsertmode

cursorkeysmovecursorleft/right/up/down

SHIFT-

/SHIFT-!

onewordleft/right

SHIFT-"/SHIFT-#

onescreenfulbackward/forward

CTRL-O

command

executecommand

End

cursorafterlastcharacterintheline

Home

cursorto�rstcharacterintheline

2.4

Digraphs,

Digraphsareusedtoentercharactersthatnormallycannotbeenteredbyanordinary

keyboard.Thesearemostlyaccentedcharacterswhichhavetheeighthbitset.

:dig[raphs]showcurrentlistofdigraphs

:dig[raphs]char1char2number...

adddigraph(s)tothelist

CTRL-K

char1[char2]enterdigraph

char1

BS

char2

enterdigraphifdigraphoptionset

2.5

Specialinserts

:r�le

insertthecontentsof�lebelowthecursor

:r!command

insertthestandardoutputofcommandbelowthecursor

2.6

Deletingtext

["x][n]x

deleten[intoregister"x]charactersunderandafterthecursor

["x][n]Del

deleten[intoregister"x]charactersunderandafterthecursor

["x][n]X

deleten[intoregister"x]charactersbeforethecursor

["x][n]dmotion

delete[intoregister"x]thetextthatismovedoverwithmotion

4

visual["x]d

delete[intoregister"x]thehighlightedtext

["x][n]dd

deleten[intoregister"x]lines

["x][n]D

delete[intoregister"x]tohEOLi(andn-1morelines)

[n]J

joinn-1lines(deletehEOLi)

[n]:j[oin][!]sameasJ,exceptwith[!]thejoindoesnotinsertordeleteanyspaces.

visualJ

jointhehighlightedlines

[n]gJ

likeJ,butwithoutinsertingspaces

4forde�nitionofmotionseeSection1.3

Page 8: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

8

VIM

5.6ReferenceGuide

visualgJ

likevisualJ,butwithoutinsertingspaces

:[range]d[x]deleterangelines[intoregisterx]

2.7

Copyingandmovingtext

:reg

showthecontentsofallregisters

:regarg

showthecontentsofregistersmentionedinarg

[n]["x]ymotion

yankthetextmovedoverwithmotionintoaregister["x]

visual["x]y

yankthehighlightedtextintoaregister["x]

["x][n]yy

yanknlinesintoaregister["x]

["x][n]Y

yanknlinesintoaregister["x]

["x][n]p

putaregister["x]afterthecursorposition(ntimes)

["x]gp

likepbutleavethecursorjustafterthenewtext.,thecursorposition(ntimes)

["x][n]P

putaregister["x]beforethecursorposition(ntimes)

["x]gP

likePbutleavethecursorjustafterthenewtext.,

["x]]MiddleMouse

likep,butadjustindenttocurrentline

["x][n]]p

likep,butadjustindenttocurrentline

["x][n][p

likeP,butadjustindenttocurrentline

2.8

Changingtext

[n]R

enterReplacemode(repeattheenteredtextntimes)

gREnterVirtualreplacemode:Eachcharacteryoutypereplacesexistingcharactersin

screenspace.

[n]cmotion

deletemotiontext[intoregister\x"]andstartinsert.

visualc

changethehighlightedtext

[n]cc

changenlines

[n]S

changenlines

[n]C

changetotheendoftheline(andn-1morelines)

[n]schangencharacters

grchar

replacethevirtualcharactersunderthecursorwithchar.Thisreplacesinscreen

space,not�lespace.

[n]rchar

replacencharacterswithchar

[n]grchar

replacencharacterswithcharwithouta�ectinglayout

[n]�

switchcaseforncharactersandadvancecursor

visual�

switchcaseforhighlightedtext

visualu

makehighlightedtextlowercase

visualU

makehighlightedtextuppercase

g�motion

switchcaseforthetextthatismovedoverwithmotion

[n]g��org�g�

switchcaseofcurrentline.,

gumotion

makethetextthatismovedoverwithmotionlowercase

gUmotion

makethetextthatismovedoverwithmotionuppercase

[n]guguorguu

makecurrentlineuppercase.,.

g?motion

Rot13encodemotiontext.,

visualg?

Rot13encodethehighlightedtext.,

g??

Rot13encodecurrentline.,

[n]gUUorgUgU

makecurrentlineuppercase.,

[n]CTRL-A

addntothenumberatorafterthecursor

[n]CTRL-X

subtractnfromthenumberatorafterthecursor

[n]<

motion

movethelinesthataremovedoverwithmotiononeshiftwidthleft

[n]<

<

movenlinesoneshiftwidthleft

[n]>

motion

movethelinesthataremovedoverwithmotiononeshiftwidthright

[n]>

>

movenlinesoneshiftwidthright

gqq

formatthecurrentline.,

13

MISCELLANY

53

SearchPatterns

Thesearchpatternsaresavedandrestored,sothattheautocommandsdonotchange

them.Whileexecutingautocommands,youcanusesearchpatternsnormally,e.g.withthe

ncommand.Aftertheautocommands�nish,thepatternsfrombeforetheautocommand

executionarerestored.Thismeansthatthestringshighlightedwiththehlsearchoptionare

nota�ectedbyautocommands.

13

Miscellany

13.1

VIM

modes

BASICmodes

VimhassixBASICmodes14:

Normalmode

InNormalmodeyoucanenterallthenormaleditorcommands.Ifyoustarttheeditor

youareinthismode.Thisisalsoknownascommandmode.

Visualmode

ThisislikeNormalmode,butthemovementcommandsextendahighlightedarea.

Whenanon-movementcommandisused,itisexecutedforthehighlightedarea.

Selectmode

ThislooksmostliketheMS-Windowsselectionmode.Typingaprintablecharacter

deletestheselectionandstartsInsertmode.

Insertmode

InInsertmodethetextyoutypeisinsertedintothebu�er.

Command-linemode

InCommand-linemode(alsocalledCmdlinemode)youcanenteronelineoftextatthe

bottomofthewindow.ThisisfortheExcommands,\:",thepatternsearchcommands,

\?"and\/",andthe�ltercommand,\!".

Exmode

LikeCommand-linemode,butafterenteringacommandyouremaininExmode.Very

limitededitingofthecommandline.

ADDITIONALmodes

Thereare�veADDITIONALmodes:

Operator-pendingmode

ThisislikeNormalmode,butafteranoperatorcommandhasstarted,andVim

is

waitingforamotiontospecifythetextthattheoperatorwillworkon.

Replacemode

ReplacemodeisaspecialcaseofInsertmode.YoucandothesamethingsasinInsert

mode,butforeachcharacteryouenter,onecharacteroftheexistingtextisdeleted.

InsertNormalmode

EnteredwhenCTRL-O

giveninInsertmode.ThisislikeNormalmode,butafter

executingonecommandVimreturnstoInsertmode.

InsertVisualmode

EnteredwhenstartingaVisualselectionfromInsertmode.WhentheVisualselection

ends,VimreturnstoInsertmode.

InsertSelectmode

EnteredwhenstartingSelectmodefromInsertmode.WhentheSelectmodeends,Vim

returnstoInsertmode.

14Thetypeofthemodeisshownonthestatuslineiftheshowmodeoptionisset

Page 9: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

52

VIM

5.6ReferenceGuide

12.9

Usingautocommands

Reading�les

Forreading�lestherearethreepossiblepairsofevents.VIM

usesonlyonepairata

time:

BufNewFilestarteditinganon-existentfile

BufReadPreBufReadPoststarteditinganexistingfile

FilterReadPreFilterReadPostreadthetempfilewithfilteroutput

FileReadPreFileReadPostanyotherfileread

Readingcompressed�les

Example

1

:autocmd!BufReadPre,FileReadPre*.gzsetbin

2

:autocmdBufReadPost,FileReadPost*.gz'[,']!gunzip

3

:autocmdBufReadPost,FileReadPost*.gzsetnobin

4

:autocmdBufReadPost,FileReadPost*.gzexecute":doautocmdBufReadPost".%:r

WritingFiles

Forwriting�lestherearefourpossiblepairsofevents.VIM

usesonlyonepairata

time:

BufWritePre

BufWritePost

writethewholebuffer

FilterWritePre

FilterWritePost

writetothetempfilewithfilterinput

FileAppendPre

FileAppendPost

appendtoafile

FileWritePre

FileWritePost

anyotherfilewrite

Writingcompressed�les

Example

1

:autocmd!BufWritePost,FileWritePost*.gz!mv<afile><afile>:r

2

:autocmdBufWritePost,FileWritePost*.gz!gzip<afile>:r

3

:autocmd!FileAppendPre*.gz!gunzip<afile>

4

:autocmdFileAppendPre*.gz!mv<afile>:r<afile>

5

:autocmd!FileAppendPost*.gz!mv<afile><afile>:r

6

:autocmdFileAppendPost*.gz!gzip<afile>:r

Nesting

Bydefault,autocommandsdonotnest.Ifyouuse:eor:winanautocommand,VIM

doesnotexecutetheBufReadandBufWriteautocommandsforthosecommands.Ifyoudo

wantthis,usethenested agforthosecommandsinwhichyouwantnesting.Thenesting

islimitedto10levelstogetoutofrecursiveloops.

Orderofexecution

Allmatchingautocommandswillbeexecutedintheorderthattheywerespeci�ed.It

isrecommendedthatyour�rstautocommandbeusedforall�lesbyusing\*"asthe�le

pattern.Thismeansthatyoucande�nedefaultsyoulikehereforanysettings,andifthere

isanothermatchingautocommanditwilloverridethese.Butifthereisnoothermatching

autocommand,thenatleastyourdefaultsettingsarerecovered(ifenteringthis�lefrom

anotherforwhichautocommandsdidmatch).Notethat\*"willalsomatch�lesstarting

with\.",unlikeUnixshells.

2

EDITINGCOMMANDS

9

[n]gqmotion

formatthelinesthataremovedoverwithmotiontotextwidthlength

:[range]ce[nter][width]centerthelinesinrange

:[range]le[ft][indent]left-alignthelinesinrangewithindent

:[range]ri[ght][width]right-alignthelinesinrange

2.9

Complexchanges

[n]!motioncommandRet

�lterthelinesthataremovedoverthroughcommand

[n]!!command

Ret

�lternlinesthroughcommand

visual!command

Ret

�lterthehighlightedlinesthroughcommand

:[range]!command

Ret

�lterrangelinesthroughcommand

[n]=motion

�lterthelinesthataremovedoverthroughindent

[n]==

�lternlinesthroughindent

visual=

�lterthehighlightedlinesthroughindent

:[range]s[ubstitute]/pattern/string/[cegpriI][n]substitutepatternbystringin

rangelines[ntimes];with

c

con�rmeachreplacement

e

whenthesearchpatternfails,donotissueanerrormessageand,inparticular,

continueinmapsasifnoerroroccurred

g

replacealloccurrencesofpattern

i

Ignorecaseforthepattern.

I

Don'tignorecaseforthepattern.

p

printthelinecontainingthelastsubstitute

r

Onlyusefulincombinationwith:&or:swithoutarguments.:&rworksthe

samewayas:�.

:[range]sno[magic]...

sameas:substitute,butalwaysusenomagic.

:[range]sm[agic]...

sameas:substitute,butalwaysusemagic.

Somecharactersinstringhaveaspecialmeaning:

magic

nomagic

action

&

n&

replacedwiththewholematchedpattern

n&

&

replacedwith&

n0

n0

replacedwiththewholematchedpattern

n1

n1

replacedwiththematchedpatterninthe�rstpairof()

n2

n2

replacedwiththematchedpatterninthesecondpairof()

. . .

. . .

n9

n9

replacedwiththematchedpatternintheninthpairof()

n�

replacedwiththestringoftheprevioussubstitute

n�

replacedwith�

nu

nu

nextcharactermadeuppercase

nU

nU

followingcharactersmadeuppercase

nl

nl

nextcharactermadelowercase

nL

nL

followingcharactersmadelowercase

ne

ne

endof/u,/U,/land/L(NOTE:nothEsci!)

nE

nE

endof/u,/U,/land/L

hCRi

hCRi

splitlineintwoatthispoint

nr

nr

idem

CTRL-V

hCRi

CTRL-V

hCRi

insertacarriage-returnhCTRL-Mi

nn

nn

hNLi

nb

nb

hBSi

nt

nt

hTabi

Page 10: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

10

VIM

5.6ReferenceGuide

:[range]&[cegriI][n]

:[range][range]s[ubstitute][cegriI][n]repeatprevious:s[ntimes]withnewrange

andoptions

:[range]�[cegriI][n]repeatlastsubstitute[ntimes]withsamesubstitutestringbut

withlastusedsearchpattern.

&

repeatprevious:soncurrentlinewithoutoptions

:[range]ret[ab][!][tabstop]settabstoptonewvalueandadjustwhitespaceaccordingly

2.10

Visualmode,

v

startorstophighlightingcharacters

V

startorstophighlightinglinewise

CTRL-V

startorstophighlightingblockwise

o

exchangecursorpositionwithstartofhighlighting

gvstarthighlightingonpreviousvisualarea

Blockwiseoperators

Istring

Withablockwiseselection,IstringESC

willinsertstringatthestartofblockon

everylineoftheblock,providedthatthelineextendsintotheblock.TABsaresplitto

retainvisualcolumns.

Astring

Withablockwiseselection,AstringESC

willappendstringtotheendofblockon

everylineoftheblock.Thereissomedi�eringbehaviorwheretheblockRHSisnot

straight,duetodi�erentlinelengths.

c

Allselectedtextintheblockwillbereplacedbythesametextstring.Whenusingc

theselectedtextisdeletedandInsertmodestarted.Youcanthenentertext(without

alinebreak).WhenyouhitEsc,thesamestringisinsertedinallpreviouslyselected

lines.

C

Likeusingc,buttheselectionisextendeduntiltheendofthelineforalllines.

>or<

Theblockisshiftedbyshiftwidth.TheRHSoftheblockisirrelevant.TheLHSof

theblockdeterminesthepointfromwhichtoapplyarightshift,andpaddingincludes

TABsoptimallyaccordingtotsandet.TheLHSoftheblockdeterminesthepoint

uptowhichtoshiftleft.

R

Everyscreencharinthehighlightedregionisreplacedwiththesamechar,i.e.TABs

aresplitandthevirtualwhitespaceisreplaced,maintainingscreenlayout.

VirtualReplacemode,

Virtualreplacemode(enteritwithgR)issimilartoReplacemode,butinsteadofre-

placingactualcharactersinthe�le,youarereplacingscreenrealestate,sothatcharacters

furtheroninthe�leneverappeartomove.

ThismodeisveryusefulforeditinghTabiseparatedcolumnsintables,forenteringnew

datawhilekeepingallthecolumnsaligned.

2.11

Textobjects,

(onlyinVisualmodeorafteranoperator)

word

awordconsistsofasequenceofletters,digitsandunderscores,orasequenceof

othernon-blankcharacters,separatedwithwhitespace(spaces,tabs,hEOLi).Thiscan

bechangedwiththeiskeywordoption.

WORD

aWORDconsistsofasequenceofnon-blankcharacters,separatedwithwhitespace.

AnemptylineisalsoconsideredtobeawordandaWORD.

sentence

asentenceisde�nedasendingata\.",\!"or\?"followedbyeithertheend

ofaline,orbyaspace.Anynumberofclosing\)",\]",\""and\'"charactersmay

appearafterthe\.",\!"or\?"beforethespacesorendofline.Aparagraphand

12

AUTOMATICCOMMANDS

51

Tomatchtherootdirectory,use\b/".

Forallsystemsthe\/"characterisusedforpathseparator(evenonMS-DOSand

OS/2).ThiswasdonebecausethebackslashisdiÆculttouseinapattern,andtomake

theautocommandsportableacrossdi�erentsystems.

Using\�"ina�lename(forhomedirectory)doesn'twork.Useapatternthatmatches

thefullpathname,forexample\*home/user/.cshrc".

12.6

Filetypes

Onsystemswhichsupport�letypesyoucanspecifythatacommandshouldonlybe

executedifthe�leisofacertaintype.Theactualtypecheckingdependsonwhichplatform

youarerunningVimon.Touse�letypecheckinginanautocommandyoushouldputalist

oftypestomatchinanglebracketsinplaceofapattern.

Toenable�letypedetection,usethiscommandinyourvimrc::�letypeon.

This

commandwillloadthe�le$VIMRUNTIME/�letype.vim,whichde�nesautocommands

fortheFileTypeevent.Ifthe�letypeisnotfoundbythename,the�le$VIMRUN-

TIME/scripts.vimisusedtodetectitfromthecontentsofthe�le.

12.7

Groups

:aug[roup]name

De�netheautocmdgroupnameforthefollowing:autocmdcommands.

Thename\end"or\END"selectsthedefaultgroup.

Whennospeci�cgroupisselected,VIM

usesthedefaultgroup.Thedefaultgroupdoes

nothaveaname.Youcannotexecutetheautocommandsfromthedefaultgroupseparately;

youcanexecutethemonlybyexecutingautocommandsforallgroups.

Normally,whenexecutingautocommandsautomatically,VIM

usestheautocommands

forallgroups.Thegrouponlymatterswhenexecutingautocommandswith:doautocmdor

:doautoall,orwhende�ningordeletingautocommands.

Thegroupnamecancontainanycharactersexceptwhitespace.Thegroupnameendis

reserved(alsoinuppercase).

12.8

Executingautocommands

Autocommandscanalsobeexecutedmanually.Thiscanbeusedafteradjustingthe

autocommands,orwhenthewrongautocommandshavebeenexecuted(�lepatternmatch

waswrong).

Note:thereiscurrentlynowaytodisabletheautocommands.

:do[autocmd][group]event[fname]Applytheautocommandsmatching[fname](de-

fault:current�lename)foreventtothecurrentbu�er.Thiscanbeusedwhenthe

current�lenamedoesnotmatchtherightpattern,afterchangingsettings,ortoexe-

cuteautocommandsforacertainevent.It'spossibletousethisinsideanautocommand

too,soyoucanbasetheautocommandsforoneextensiononanotherextension.

Whenthe[group]argumentisnotgiven,VIM

executestheautocommandsforallgroups.

Whenthe[group]argumentisincluded,VIM

executesonlythematchingautocommands

forthatgroup.

Note:ifyouuseanunde�nedgroupname,VIM

givesyouanerrormessage.

:doautoa[ll][group]event[fname]Like:doautocmd,butapplytheautocommandsto

eachloadedbu�er.

Careful:Don'tusethisforautocommandsthatdeleteabu�er,changetoanotherbu�er

orchangethecontentsofabu�er,theresultisunpredictable.Itisonlymeanttoperform

autocommandsthatsetoptions,changehighlighting,andsoon.

Page 11: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

50

VIM

5.6ReferenceGuide

FocusLostWhenVimlostinputfocus.OnlyfortheGUIversionandafewconsoleversions

wherethiscanbedetected.

CursorHold

Whentheuserdoesn'tpressakeyforthetimespeci�edwithupdatetime.Not

re-triggereduntiltheuserhaspressedakey(i.e.doesn't�reeveryupdatetimemsifyou

leaveVimtomakesomeco�ee.:)Note:Interactivecommandsand\:normal"cannot

beusedforthisevent.

BufEnterAfterenteringabu�er.Usefulforsettingoptionsfora�letype.Alsoexecuted

whenstartingtoeditabu�er,aftertheBufReadPostautocommands.

BufLeave

Beforeleavingtoanotherbu�er.Alsowhenleavingorclosingthecurrentwin-

dowandthenewcurrentwindowisnotforthesamebu�er.

BufUnload

Beforeunloadingabu�er.Thisiswhenthetextinthebu�erisgoingtobe

freed.ThismaybeafteraBufWritePostandbeforeaBufDelete.

BufHidden

Justafterabu�erhasbecomehidden.Thatis,whentherearenolonger

windowsthatshowthebu�er,butthebu�erisnotunloadedordeleted.NOTE:When

thisautocommandisexecuted,thecurrentbu�er\%"maybedi�erentfromthebu�er

beingunloadedhafilei.

BufCreate

Justaftercreatinganewbu�er.Alsousedjustafterabu�erhasbeenrenamed.

NOTE:Whenthisautocommandisexecuted,thecurrentbu�er\%"maybedi�erent

fromthebu�erbeingdeletedhafilei.

BufDelete

Beforedeletingabu�erfromthebu�erlist.TheBufUnloadmaybecalled�rst

(ifthebu�erwasloaded).

WinEnterAfterenteringanotherwindow.Notdoneforthe�rstwindow,whenVIM

hasbeenjuststarted.Usefulforsettingthewindowheight.Ifthewindowbelongs

toadi�erentbu�erfromtheonepreviouslybeingedited,VIM

executestheBufEnter

autocommandsaftertheWinEnterautocommands.

WinLeave

Beforeleavingawindow.Ifthewindowtobeenterednextisforadi�erent

bu�er,VIM

executestheBufLeaveautocommandsbeforetheWinLeaveautocommands.

GUIEnterAfterstartingtheGUIsuccesfully,andafteropeningthewindow.Itistriggered

beforeVimEnterwhenusinggvim.Canbeusedtopositionthewindowfroma.gvimrc

�le:

VimEnterAfterdoingallthestartupstu�,includingloading.vimrc�les,executingthe\-c

cmd"arguments,creatingallwindowsandloadingthebu�ersinthem.

VimLeavePre

BeforeexitingVim,justbeforewritingthe.viminfo�le.Thisisexecuted

onlyonce,ifthereisamatchwiththenameofwhathappenstobethecurrentbu�er

whenexiting.

VimLeave

BeforeexitingVIM

,justbeforewritingthe.viminfo�le.

UserNeverexecutedautomatically.Tobeusedforautocommandsthatareonlyexecuted

with:doautocmd.

FileEncoding

Fireso�whenyouchangethe�leencodingwith\:set�leencoding".Allows

youtosetupfontsorotherlanguagesensitivesettings.

TermChanged

Afterthevalueoftermwaschanged.Usefulforre-loadingthesyntax�le

toupdatethecolors,fontsandotherterminal-dependent.

12.5

Patterns

The�lepatternistestedforamatchagainstthe�lenameinoneoftwoways:

�Whenthereisno\/"inthepattern,VIM

checksforamatchagainstonlythetail

partofthe�lename(withoutitsleadingdirectorypath).

�Whenthereisa\/"inthepattern,VIM

checksforamatchagainsttheshort�lename

(asyoutypedit)andthefull�lename(afterexpandingittoafullpath,resolving

symboliclinks).

Thepatternisinterpretedlikemostlyusedin�lenames.Whenthepatternstartswith

\/",thisdoesnotmeanitmatchestherootdirectory.Itcanmatchany\/"inthe�lename.

2

EDITINGCOMMANDS

11

sectionboundaryisalsoasentenceboundary.Thede�nitionofasentencecannot

bechanged.

paragraph

aparagraphbeginsaftereachemptyline,andalsoateachofasetofparagraph

macros,speci�edbythepairsofcharactersintheparagraphsoption.Thedefaultis

\IPLPPPQPPLIpplpipbp",whichcorrespondstothemacros\.IP",\.LP",etc.(These

arenroffmacros,sothedotmustbeinthe�rstcolumn).Asectionboundaryisalsoa

paragraphboundary.Notethatthisdoesnotincludea\f"or\g"inthe�rstcolumn.

section

asectionbeginsafteraform-feed(hC-Li)inthe�rstcolumnandateachofaset

ofsectionmacros,speci�edbythepairsofcharactersinthesectionsoption.Thedefault

is\SHNHHHUnhsh",whichde�nesasectiontostartatthenroffmacros\.SH",\.NH",

\.H",\.HU",\.nh"and\.sh".

[n]aw

selectaword

[n]iw

selectinner

5

word

[n]aW

selectaWORD

[n]iW

selectinnerWORD

[n]asselectasentence

[n]isselectinnersentence

[n]ap

selectaparagraph

[n]ip

selectinnerparagraph

[n]a[ora]select[n]\["\]"blocks.

[n]i[ori]select[n]inner\["\]"blocks.

[n]a),a(orab

selectablock(from(to))

[n]i),i(orib

selectinnerblock(from(to))

[n]a<

ora>

select[n]<

>

blocks.

[n]i<ori>

select[n]<

>

innerblocks

[n]ag,aforaB

selectaBlock(fromftog)

[n]ig,iforiB

selectinnerBlock(fromftog)

2.12

RepeatingCommands

[n].repeatlastchange(withnreplacedwithn)

qfa-zg,

recordtypedcharactersintoregisterfa-zg

qfA-Zg,

recordtypedcharacters,appendedtoregisterfa-zg

q,

stoprecording

[n]@fa-zg

executethecontentsofregisterfa-zg(ntimes)

[n]@@,

repeatprevious@fa-zg(ntimes)

:@fa-zg,

executethecontentsofregisterfa-zgasanExcommand

:@@

repeatprevious:@fa-zg

:[range]g[lobal]/pattern/[cmd]executeExcommandcmd(default::p)onthelines

within[range]wherepatternmatches

:[range]g[lobal]!/pattern/[cmd]executeExcommandcmd(default::p)onthelines

within[range]wherepatterndoesNOTmatch

:so[urce]�le

readExcommandsfrom�le

:so[urce]!�le

readVIM

commandsfrom�le

:[n]sl[eep]n[m]don'tdoanythingfornseconds.Ifmisincluded,sleepfornmillisec-

onds.

[n]gsgotoSleepfornseconds

2.13

Undo/RedoCommands

[n]u,

undolastnchanges

[n]CTRL-R

,

redolastnundonechanges

U

restorelastchangedline

5\inner"meansthatwhitespacesbetweenwordsareincludedincountn

Page 12: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

12

VIM

5.6ReferenceGuide

2.14

Command-lineediting

Esc

abandoncommand-line(ifwildcharisEsc,typeittwice)

CTRL-V

char

insertcharliterally

CTRL-V

number

enterdecimalvalueofcharacter(uptothreedigits)

CTRL-K

char1char2,

enterdigraph

CTRL-R

f0-9a-z"%#:-=*g

insertthecontentsofaregister6

CTRL-R

CTRL-R

f0-9a-z"%#:-=*g

insertthecontentsofaregister.Workslikeusinga

singleCTRL-R,butthetextisinsertedliterally,notasiftyped.Thisdi�erswhenthe

registercontainscharacterslikehBSi.

/!

cursorleft/right

SHIFT-

/SHIFT-!

cursoronewordleft/right

CTRL-B/CTRL-E

cursortobeginning/endofcommand-line

BS

deletethecharacterinfrontofthecursor

Del

deletethecharacterunderthecursor

CTRL-W

deletethewordinfrontofthecursor

CTRL-U

removeallcharacters

"/#

recallolder/newercommand-linethatstartswithcurrentcommand

SHIFT-"/SHIFT-#

recallolder/newercommand-linefromhistory

:his[tory][name][�rst][,[last]Listthecontentsofhistorynamewhichcanbe:

c[md]

or

:

command-linehistory

s[earch]

or

/

searchstringhistory

e[xpr]

or

=

expressionregisterhistory

i[nput]

or

@

inputlinehistory

a[ll]

alloftheabove

Context-sensitivecompletiononthecommand-line:,

wildchar(default:Tab)docompletiononthepatterninfrontofthecursor.Ifthereare

multiplematches,beepandshowthe�rstone;furtherwildcharwillshowthenextones

CTRL-A

insertallnamesthatmatchpatterninfrontofcursor

CTRL-D

listallnamesthatmatchthepatterninfrontofthecursor

CTRL-L

insertlongestcommonpartofnamesthatmatchpattern

CTRL-N

afterwildcharwithmultiplematches:gotonextmatch

CTRL-P

afterwildcharwithmultiplematches:gotopreviousmatch

CTRL-R

...

inserttheobjectunderthecursor:

CTRL-F

the\�lename"underthecursor

CTRL-P

the\�lename"underthecursor,expandedwithpath

CTRL-W

the\word"underthecursor

CTRL-A

the\WORD"underthecursor

2.15

Encryption

Vimisabletowrite�lesencrypted,andreadthemback.Theencryptedtextcannot

bereadwithouttherightkey.Thenormalwaytoworkwithencryption,istousethe:X

command,whichwillaskyoutoenterakey.Afollowingwritecommandwillusethatkey

toencryptthe�le.Ifyoulatereditthesame�le,Vimwillaskyoutoenterakey.The

algorithmusedisbreakable.

Warning:Theswap�leandtextinmemoryarenotencrypted.Asystemadministrator

willbeabletoseeyourtextwhileyouareeditingit.Textyoucopyordeletegoestothe

numberedregisters.Theregisterscanbesavedinthe\.viminfo"�le,wheretheycouldbe

read.Changeyourviminfooptiontobesafe.Ifyoumakeatypowhenenteringthekeyand

thenwritethe�leandexit,thetextwillbelost!

6SeeSection13.2fordescriptionofVIM

registers

12

AUTOMATICCOMMANDS

49

:au[tocmd][group]Showallautocommands.

Ifyouprovidethegroupargument,VIM

listsonlytheautocommandsforgroup;other-

wise,VIM

liststheautocommandsforALLgroups.Notethatthisargumentbehaviordi�ers

fromthatforde�ningandremovingautocommands.

12.4

Events

Thefollowingeventsarerecognized.Caseisignored;forexample,BUFreadandbufread

canbeusedinsteadofBufRead.

BufFilePre

Beforechangingthenameofthecurrentbu�erwiththe\:�le"command.

BufFilePostAfterchangingthenameofthecurrentbu�erwiththe\:�le"command.

BufNewFile

Whenstartingtoedita�lethatdoesn'texist.Canbeusedtoreadina

skeleton�le.

BufReadPre

Whenstartingtoeditanewbu�er,beforereadingthe�leintothebu�er.

Notusedifthe�ledoesn'texist.

BufReadorBufReadPostWhenstartingtoeditanewbu�er,afterreadingthe�leinto

thebu�er,beforeexecutingthemodelines.ThisdoesNOTworkfor:r�le.Notused

whenthe�ledoesn'texist.Alsousedaftersuccessfullyrecoveringa�le.

FileReadPre

Beforereadinga�lewitha:readcommand.

FileReadPostAfterreadinga�lewitha:readcommand.NotethatVIM

setsthe'[and

']markstothe�rstandlastlinesoftheread.Thiscanbeusedtooperateonthelines

justread.

FilterReadPre

Beforereadinga�lefroma�ltercommand.VIM

checksthepatternagainst

thethenameofthecurrentbu�er,notthenameofthe,notthenameofthetemporary

�lethatistheoutputofthe�ltercommand.

FilterReadPostAfterreadinga�lefroma�ltercommand.VIM

checksthepatternagainst

thethenameofthecurrentbu�eraswithFilterReadPre.

FileType

Whenthe�letypeoptionhasbeenset.<a�le>canbeusedforthenameofthe

�lewherethisoptionwasset,and<amatch>forthenewvalueof�letype.

Syntax

Whenthesyntaxoptionhasbeenset.<a�le>canbeusedforthenameofthe�le

wherethisoptionwasset,and<amatch>forthenewvalueofsyntax.

StdinReadPre

Beforereadingfromstdinintothebu�er.Onlyusedwhenthe\-"argu-

mentwasusedwhenVIM

wasstarted.

StdinReadPostAfterreadingfromstdinintothebu�er,beforeexecutingthemodelines.

Onlyusedwhenthe\-"argumentwasusedwhenVIM

wasstarted.

BufWriteorBufWritePre

Beforewritingthewholebu�ertoa�le.

BufWritePostAfterwritingthewholebu�ertoa�le(shouldundothecommandsfor

BufWritePre).

FileWritePre

Beforewritingtoa�le,whennotwritingthewholebu�er.

FileWritePostAfterwritingtoa�le,whennotwritingthewholebu�er.

FileAppendPre

Beforeappendingtoa�le.

FileAppendPostAfterappendingtoa�le.

FilterWritePre

Beforewritinga�lefora�ltercommand.The�lenameofthecurrent

bu�erisusedtomatchwiththepattern,notthenameofthetemporary�lethatisthe

inputforthe�ltercommand.

FilterWritePostAfterwritinga�lefora�ltercommand.LikeFilterWritePre,the�lename

ofthecurrentbu�erisused.

FileChangedShellAfterVIM

runsashellcommandandnoticesthatthemodi�cation

timeofthecurrent�lehaschangedsinceeditingstarted.Runinplaceofthe\has

beenchanged"message.Seetimestamp.Usefulforreloadingrelatedbu�erswhichare

a�ectedbyasinglecommand.

FocusGained

WhenVimgotinputfocus.OnlyfortheGUIversionandafewconsole

versionswherethiscanbedetected.

Page 13: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

48

VIM

5.6ReferenceGuide

11.7

Linkinggroups

:hi[ghlight][!]linkfrom-groupto-group

Ifyouwanttousethesamehighlightingfor

severalsyntaxgroups,youcandothisbylinkingthesegroupsintoonecommonhighlight

group,andgivethecolorattributesonlyforthatgroup.

Notes:

�Ifthefrom-groupand/orto-groupdoesn'texist,itiscreated.Youdon'tgetanerror

messageforanon-existentgroup.

�Iftheto-groupisNONE,thelinkisremovedfromthefrom-group.

�Assoonasyouusea:highlightcommandforalinkedgroup,thelinkisremoved.

�Iftherearealreadyhighlightsettingsforthefrom-group,thelinkisnotmade,unless

the!isgiven.Fora:highlightlinkcommandinasourced�le,youdon'tgetanerror

message.Thiscanbeusedtoskiplinksforgroupsthatalreadyhavesettings.

12

AutomaticCommands,

Youcanspecifycommandstobeexecutedautomaticallyforwhenreadingorwritinga

�le,whenenteringorleavingabu�erorwindow,andwhenexitingVIM

.

12.1

De�ningautocommands

:au[tocmd][group]eventpat[nested]cmd

Addcmdtothelistofcommandsthatwill

beautomaticallyexecutedoneventfora�lematchingpat.VIM

alwaysaddsthecmd

afterexistingautocommands,sothattheautocommandsexecuteintheorderinwhich

theyweregiven.

The:autocmdcommandcannotbefollowedbyanothercommand,sinceany\j"isconsid-

eredpartofthecommand.Specialcharacters(e.g.%,<cword>)inthe:autocmdarguments

arenotexpandedwhentheautocommandisde�ned.Thesewillbeexpandedwhenthe

eventisrecognized,andthecmdisexecuted.Whenyour\.vimrc"�leissourcedtwice,

theautocommandswillappeartwice.Toavoidthis,put:autocmd!inyour\.vimrc"�le,

beforede�ningautocommands.

Whenthegroupargumentisnotgiven,VIM

usesthecurrentgroup(asde�nedwith

:augroup);otherwise,VIM

usesthegroupde�nedwith[group].

Note:whiletestingautocommands,itmightbeusefultosetverbose=9.Thiscausesthe

executedautocommandstobeechoed.

12.2

Removingautocommands

:au[tocmd]![group]eventpat[nested]cmd

Removeallautocommandsassociatedwith

eventandpat,andaddthecommandcmd.

:au[tocmd]![group]eventpat

Removeallautocommandsassociatedwitheventandpat.

:au[tocmd]![group]*pat

Removeallautocommandsassociatedwithpatforallevents.

:au[tocmd]![group]event

RemoveALLautocommandsforevent.

:au[tocmd]![group]RemoveALLautocommands.

Whenthegroupargumentisnotgiven,VIM

usesthecurrentgroup(asde�nedwith

:augroup);otherwise,VIM

usesthegroupde�nedwithgroup.

12.3

Listingautocommands

:au[tocmd][group]eventpat

Showtheautocommandsassociatedwitheventandpat.

:au[tocmd][group]*pat

Showtheautocommandsassociatedwithpatforallevents.

:au[tocmd][group]event

Showallautocommandsforevent.

3

KEYMAPPINGSABBREVIATIONS

13

:X

Promptforanencryptionkey.Thetypingisdonewithoutshowingtheactualtext,so

thatsomeonelookingatthedisplaywon'tseeit.Thetypedkeyisstoredinthekey

option,whichisusedtoencryptthe�lewhenitiswritten.

3

KeyMappingsAbbreviations

3.1

Keymapping

Thesecommandsareusedtomapakeyorkeysequencetoastringofcharacters.There

are�vesetsofmappings:

Normalmode:whentypingcommands.(e.g.:map<F3>o#include)

Visualmode:whentypingcommandswhiletheVisualareaishighlighted.

Operator-pendingmode:whenanoperatorispending(after\d",\y",\c",etc.).

Insertmode:thesearealsousedinReplacemode.

Command-linemode:whenenteringa\:"or\/"command.

Everythingfromthe�rstnon-blankafterlhsuptotheendofthelinehEOLi(or\j")is

consideredtobepartofrhs.Inclusionoflhsinrhsresultsinarecursivemapping.Recursion

depthiscontrolledbymaxmapdepthoption.Use\nore"versionsofmappingcommandsto

avoidrecursion.

:ma[p]lhsrhs

maplhstorhsinNormalandVisualmode

:ma[p]!lhsrhs

maplhstorhsinInsertandCommand-linemode

:no[remap][!]lhsrhs

sameas:map,noremappingforisrhs

:unm[ap]lhs

removethemappingoflhsforNormalandVisualmode

:unm[ap]!lhs

removethemappingoflhsforInsertandCommand-linemode

:ma[p][lhs]listmappings(startingwithlhs)forNormalandVisualmode

:ma[p]![lhs]listmappings(startingwithlhs)forInsertandCommand-linemode

:cmap/:cunmap/:cnoremap

like:map!/:unmap!/:noremap!butforCommand-linemode

only

:imap/:iunmap/:inoremap

like:map!/:unmap!/:noremap!butforInsertmodeonly

:nmap/:nunmap/:nnoremap

like:map/:unmap/:noremapbutforNormalmodeonly

:vmap/:vunmap/:vnoremap

like:map/:unmap/:noremapbutforVisualmodeonly

:omap/:ounmap/:onoremap

like:map/:unmap/:noremapbutonlyforwhenanoperatoris

pending

:mk[exrc][!]�le,

writecurrentmappings,abbreviations,andsettingsto�le

(default:.exrc;use!tooverwrite)

:mkv[imrc][!]�le,

sameas:mkexrc,butwithdefault.vimrc

:mks[ession][!][�le]like:mkvimrc,butstorecurrent�lesanddirectorytoo

:mapc[lear]removemappingsforNormalandVisualmode

:mapc[lear]!removemappingsforInsertandCmdlinemode

:imapc[lear]removemappingsforInsertmode

:vmapc[lear]removemappingsforVisualmode

:omapc[lear]removemappingsforOperator-pendingmode

:nmapc[lear]removemappingsforNormalmode

:cmapc[lear]removemappingsforCmdlinemode

3.2

Abbreviations

AbbreviationsareusedinInsert,ReplaceandCommand-linemodes.Abbreviationsare

neverrecursive.Therearethreetypesofabbreviations:

full-id

thistypeconsistsentirelyofkeywordcharacters(lettersandcharactersfromiskey-

wordoption).(e.g.foo,g3,-1)

Page 14: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

14

VIM

5.6ReferenceGuide

end-id

thistypeendsinakeywordcharacter,butalltheothercharactersarenotkeyword

characters.(e.g.#i,..f,$/7)

non-id,

thistypeendsinanon-keywordcharacter,theothercharactersmaybeofany

type,excludinghSpaceiandhTabi.(e.g.def#,4/7$)

:ab[breviate]lhsrhs

addabbreviationforlhstorhs

:ab[breviate]lhs

showabbreviationsthatstartwithlhs

:ab[breviate]showallabbreviations

:una[bbreviate]lhs

removeabbreviationforlhs

:norea[bbrev][lhs][rhs]like:ab,butdon'tremaprhs

:iab/:iunab/:inoreab

like:ab,butonlyforInsertmode

:cab/:cunab/:cnoreab

like:ab,butonlyforCommand-linemode

:abc[lear]removeallabbreviations

:cabc[lear]removeallabbreviationsforCmdlinemode

:iabc[lear]removeallabbreviationsforInsertmode

3.3

User-de�nedcommands,

Itispossibletode�neyourownExcommands.Auser-de�nedcommandcanactjust

likeabuilt-incommand,exceptthatwhenthecommandisexecuted,itistransformedinto

anormalExcommandandthenexecuted.Alluserde�nedcommandsmuststartwithan

uppercaseletter,toavoidconfusionwithbuiltincommands.User-de�nedcommandscan

havearguments,whicharesubjecttocompletionas�lenames,bu�ers,etc.Exactlyhow

thisworksdependsuponthecommand'sattributes,whicharespeci�edwhenthecommand

isde�ned.

:com[mand]listalluser-de�nedcommands.Whenlistingcommands,thecharactersin

the�rsttwocolumnsare

!

Commandhasthe-bangattribute

"

Commandhasthe-registerattribute

:com[mand]cmd

listtheuser-de�nedcommandsthatstartwithcmd

:com[mand][!][attr...]cmdrep

de�neausercommand.Thenameofthecommand

iscmdanditsreplacementtextisrep.Thecommand'sattributes(seebelow)areattr.

Ifthecommandalreadyexists,anerrorisreported,unlessa!isspeci�ed,whenthe

commandisrede�ned.

:delc[ommand]cmd

deletetheuser-de�nedcommandcmd.

:comc[lear]deletealluser-de�nedcommands.

Commandattributes

Commandattributessplitintofourcategories:

1.argumenthandling:-nargs=char,wherecharcanbe0,1,*,?or+

2.completionbehaviour:-complete=word,wherewordcanbeanyofthefollowing:

augroupbuffercommanddireventfilehelphighlightmenuoptiontag

3.rangehandling:-range=n,%or-count=n

4.specialcases:-bang{thecommandcantakea!modi�er,-register{the�rst

argumenttothecommandcanbeanoptionalregistername

Replacementtext

Thereplacementtextforauser-de�nedcommandisscannedforspecialescapesequences,

using<

...>

notation.Escapesequencesarereplacedwithvaluesfromtheenteredcommand

line,andallothertextiscopiedunchanged.TheresultingstringisexecutedasanEx

command.Thevalidescapesequencesare

11

SYNTAXHIGHLIGHTING

47

LineNrlinenumberfor\:number"and\:#"commands,andwhennumber

Normalnormaltext

Search

lastsearchpatternhighlighting(seehlsearch)

Highlightargumentsforcolorterminals(MS-DOSconsole,color-xterm)

cterm=attr-list

Thectermargumentislikelytobedi�erentfromterm,whencolorsare

used.Forexample,inanormalterminalcommentscouldbeunderlined,inacolor

terminaltheycanbemadeBlue.

Note:Manyterminals(e.g.,DOSconsole)can'tmixtheseattributeswithcoloring.Use

onlyoneofcterm=ORctermfg=ORctermbg=.

ctermfg=color-num,ctermbg=color-num

Thecolor-numargumentisacolornum-

ber.Itrangesfromzerotothenumbergivenbythetermcapentry\Co"(non-inclusive).

Theactualcolorwiththisnumberdependsonthetypeofterminalanditssettings.

Sometimesthecoloralsodependsonthesettingsofcterm.Forexample,onsome

systemscterm=boldctermfg=3givesanothercolor,onothersyoujustgetcolor3.

Thefollowingnamesarerecognized,withthecolornumberused:

NR-16

NR-8

ColorName

NR-16

NR-8

ColorName

0

0

Black

8

0*

DarkGray

1

4

DarkBlue

9

4*

Blue,LightBlue

2

2

DarkGreen

10

2*

Green,LightGreen

3

6

DarkCyan

11

6*

Cyan,LightCyan

4

1

DarkRed

12

1*

Red,LightRed

5

5

DarkMagenta

13

5*

Magenta,LightMagenta

6

3

Brown

14

3*

Yellow

7

7

LightGray13,Gray

15

7*

White

ThenumberunderNR-16isusedfor16-colorterminals(\tCo"greaterthanorequal

to16).ThenumberunderNR-8isusedfor8-colorterminals(\tCo"lessthan16).

The\*"indicatesthattheboldattributeissetforctermfg.Inmany8-colorterminals

(e.g.linux),thiscausesthebrightcolorstoappear.Thisdoesn'tworkforbackground

colors.Thecaseofthecolornamesisignored.

HighlightargumentsfortheGUI

gui=attr-list

ThesegivetheattributestouseintheGUImode.Notethatboldcanbe

alsosedhereandbyspecifyingaboldfont.Ithasthesamee�ect.

font=font-name

font-nameisthenameofafontasitisusedonthesystemVIM

runs

on.Thefont-nameNONEcanbeusedtoreverttothedefaultfont.Whensettingthe

fontfortheNormalgroup,thisbecomesthedefaultfont(untiltheguifontoptionis

changed;thelastonesetisused).

Note:allfontsusedshouldbeofthesamecharactersizeasthedefaultfont!

guifg=color-nameguibg=color-name

Thesegivetheforeground(guifg)andback-

ground(guibg)colortouseintheGUI.Thereareafewspecialnames:

NONE

nocolor(transparent)

background(bg)

usenormalbackgroundcolor

foreground(fg)

usenormalforegroundcolor

YoucanalsospecifyacolorintheRGBformat#rrggbb,whererristheRedvalue,bb

istheBluevalueandggistheGreenvalue.Allvaluesarehexadecimal,rangefrom00

toff.

13GraycanbespelledasGrey

Page 15: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

46

VIM

5.6ReferenceGuide

11.6

Highlightcommand

Therearetwotypesofhighlightgroups:

�Thegroupsusedforspeci�clanguages.Forthesethenamestartswiththenameof

thelanguage.Manyofthesedon'thaveanyattributes,butarelinkedtoagroupof

thesecondtype.

�Thegroupsusedforalllanguages.Thesearealsousedforthehighlightoption.

:hi[ghlight]listallthecurrenthighlightgroupsthathaveattributesset.

:hi[ghlight]group-name

listonehighlightgroup.

:hi[ghlight]cleargroup-name,:hi[ghlight]group-nameNONE

disablethehighlight-

ingforonehighlightgroup.

:hi[ghlight]group-namekey=arg...

addahighlightgroup,orchangethehighlight-

ingforanexistinggroup.

Highlightargumentsforblackandwhiteterminals(vt100,xterm)

term=attr-list

attr-listisacommaseparatedlist(withoutspaces)ofthefollowingitems

(inanyorder):NONE(noattributesused),bold,underline,reverse,inverse(same

asreverse),italic,standout.

start=term-list,stop=term-list

Theselistsofterminalcodescanbeusedtogetnon-

standardattributesonaterminal.

Theescapesequencespeci�edwiththestartargumentiswrittenbeforethecharacters

inthehighlightedarea.Itcanbeanythingthatyouwanttosendtotheterminalto

highlightthisarea.Theescapesequencespeci�edwiththestopargumentiswritten

afterthehighlightedarea.Thisshouldundothestartargument.

Theterm-listcanhavetwoforms:

�Astringwithescapesequences.Thisisanystringofcharacters,exceptthatit

can'tstartwithtandblanksarenotallowed.The<>notationisrecognizedhere,

soyoucanusethingslike<Esc>and<Space>.

�Alistofterminalcodes.Eachterminalcodehastheformtxx,wherexxisthe

nameofthetermcapentry.Thecodeshavetobeseparatedwithcommas.

Note:whitespaceisnotallowed.

Defaulthighlightgroup

Thesearethedefaulthighlightinggroups.Thesegroupsareusedbythehighlightoption

default.

Cursorthecharacterunderthecursor

Directory

directorynames(andotherspecialnamesinlistings)

ErrorMsg

errormessages

IncSearch

incsearchhighlighting

ModeMsg

showmodemessage

MoreMsg

more-prompt

NonText�andattheendofthewindowandcharactersfrom

Question

hit-returnpromptandyes/noquestions

SpecialKey

Metaandspecialkeyslistedwith\:map"

StatusLine

statuslineofcurrentwindow

StatusLineNC

statuslinesofnot-currentwindows

Title

titlesforoutputfrom:setall,\:autocmd"etc.

VisualVisualmodeselection

WarningMsg

warningmessages

4

OPTIONS

15

<line1>

Thestartinglineofthecommandrange

<line2>

The�nallineofthecommandrange

<count>

Anycountsupplied

<bang>

Expandstoa!,ifspeci�ed

<reg>

Theoptionalregister,ifspeci�ed

<args>

Thecommandarguments,exactlyassupplied

<lt>

Asingle<

character

Example

1

"Renamethecurrentbuffer

2

:com-nargs=1-bang-complete=fileRenf<args>|w<bang>

3

"Replacearangewiththecontentsofafile

4

"(Enterthisallasoneline)

5

:com-range-nargs=1-complete=file

6

Replace<line1>-pu_|<line1>,<line2>d|r<args>|<line1>d

4

Options

4.1

SettingOptions

:se[t]showallmodi�edoptions

:se[t]all,

showalloptions

:se[t]option

toggleoptionon,showstringornumberoption

:se[t]nooption

toggleoptiono�

:se[t]invoption,

invertoption

:se[t]option=value

setstringornumberoptiontovalue

:se[t]option?

showvalueofoption

:se[t]option+=value

Addthevaluetoanumberoption,orconcatenatethevaluetoa

stringoption.

:se[t]optionb

=value

Multiplythevaluetoanumberoption,orprependthevaluetoa

stringoption.

:se[t]option-=value

Subtractthevaluefromanumberoption,orremovethevaluefrom

astringoption,ifitisthere.

:se[t]option&

resetoptiontoitsdefaultvalue,

:�x[del],

setvalueof\tkD"accordingtovalueof\tkb"

4.2

Shortexplanationofeachoption:

in(){anabbreviatedversion

aleph(al),

ASCIIcodeoftheletterAleph(Hebrew)

allowrevins(ari),

AllowCTRL-inInsertandCommand-linemode.Seerevins

altkeymap(akm),

fordefaultsecondlanguage(Farsi/Hebrew)

autoindent(ai)takeindentfornewlinefrompreviousline

autowrite(aw)automaticallywrite�leifchanged

background(bg),

\dark"or\light",usedforhighlightcolors

backspace(bs),

howbackspaceworksatstartofline

backup(bk),

keepbackup�leafteroverwritinga�le

backupdir(bdir),

listofdirectoriesforthebackup�le

backupext(bex),

extensionusedforthebackup�le

binary(bin),

editbinary�lemode

bioskey(biosk),

MS-DOS:usebioscallsforinputcharacters

breakat(brk),

charactersthatmaycausealinebreak

browsedir(bsdir),

(onlyforGUI)whichdirectorytostartbrowsingin

Page 16: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

16

VIM

5.6ReferenceGuide

cindent(cin),

doCprogramindenting

cinkeys(cink),

keysthattriggerindentwhencindentisset

cinoptions(cino),

howtodoindentingwhencindentisset

cinwords(cinw),

wordswheresiandcinaddanindent

cmdheight(ch),

numberoflinestouseforthecommand-line

columns(co),

numberofcolumnsinthedisplay

comments(com),

patternsthatcanstartacommentline

compatible(cp),

behaveVi-compatibleasmuchaspossible

complete(cpt),

specifyhowInsertmodecompletionworks

con�rm

(cf),

con�rmcertainoperationsthatwouldnormallyfailbecauseofunsaved

changestoabu�er

conskey(consk),

getkeysdirectlyfromconsole(MS-DOSonly)

cpoptions(cpo),

agsforVi-compatiblebehaviour

cscopeprg(csprg),

commandtoexecutecscope

cscopetag(cst),

usecscopefortagcommands

cscopetagorder(csto),

determines:cstagsearchorder

cscopeverbose(csverb),

givemessageswhenaddingacscopedatabase

de�ne(def),

patterntobeusedto�ndamacrode�nition

dictionary(dict),

listof�lenamesusedforkeywordcompletion

digraph(dg),

enabletheenteringofdigraphsinInsertmode

directory(dir)listofdirectorynamesfortheswap�le

display(dy)listof agsforhowtodisplaytext

edcompatible(ed),

toggle agsof:substitutecommand

endo ine(eol),

writehEOLiforlastlinein�le

equalalways(ea),

windowsareautomaticallymadethesamesize

equalprg(ep),

externalprogramtousefor=command

errorbells(eb)ringthebellforerrormessages

error�le(ef),

nameofthe\error�le"fortheQuickFixmode

errorformat(efm),

descriptionofthelinesintheerror�le

esckeys(ek),

recognizefunctionkeysinInsertmode

eventignore(ei),

alistofautocommandeventnames,whicharetobeignored

expandtab(et),

usespaceswhenTab

isinserted

exrc(ex),

read.vimrcand.exrcinthecurrentdirectory

�leencoding(fe)�leencodingformulti-bytetext

�leformat(�),

�leformatusedfor�leI/O

�leformats(�s),

automaticallydetectedvaluesfor�leformat

�letype(ft),

typeof�le,usedforautocommands

fkmap(fk),

Farsikeyboardmapping

formatoptions(fo),

howautomaticformattingistobedone

formatprg(fp),

nameofexternalprogramusedwithgqcommand

gdefault(gd),

the:substitute aggisdefaulton

grepformat(gfm),

formatofgrepprgoutput

grepprg(gp),

programtousefor:grep

guicursor(gcr),

GUI:settingsforcursorshapeandblinking

guifont(gfn),

GUI:Name(s)offont(s)tobeused

guifontset(gfs),

GUI:Namesofmulti-bytefontstobeused

guiheadroom

(ghr),

GUI:pixelsroomforwindowdecorations

guioptions(go),

GUI:Whichcomponentsandoptionsareused

guipty,

GUI:trytouseapseudo-ttyfor:!commands

help�le(hf),

nameofthishelp�le

helpheight(hh),

minimumheightofanewhelpwindow

hidden(hid),

don'tunloadbu�erwhenitisabandoned

highlight(hl),

setshighlightingmodeforvariousoccasions

hlsearch(hls),

highlightmatcheswithlastsearchpattern

11

SYNTAXHIGHLIGHTING

45

Secondsyncingmethod:

Forthesecondmethod,onlytheminlines=N

argumentneedstobegiven.VIM

will

subtractNfromthelinenumberandstartparsingthere.ThismeansNextralinesneedto

beparsed,whichmakesthismethodabitslower.

Note:linesandminlinesareequivalent.

Thirdsyncingmethod:

Theideaistosynchronizeontheendofafewspeci�cregions,calledasyncpattern.The

searchstartsinthelinejustabovetheonewhereredrawingstarts.Fromtherethesearch

continuesbackwardsinthe�le.

Alinecontinuationpatterncanbegivenhere.Itisusedtodecidewhichgroupoflines

needtobesearchedasiftheywereasingleline.Thismeansthatthesearchforamatch

withthespeci�editemsstartsinthe�rstofthefollowingthatcontainsthecontinuation

pattern.

Whenamatchwithasyncpatternisfound,therestoftheline(orgroupofadjacent

lines)issearchedforanothermatch.Thelastmatchisused.Thisisusedwhenalinecan

containboththestartandtheendofaregion(e.g.,inaC-commentlike/*this*/,the

last*/isused).

Therearetwowayshowamatchwithasyncpatterncanbeused:

�Parsingforhighlightingstartswhereredrawingstarts(andwherethesearchforthe

syncpatternstarted).Thesyntaxgroupthatisexpectedtobevalidtheremustbe

speci�ed.Thisworkswellwhentheregionsthatcrosslinescannotcontainother

regions.

�Parsingforhighlightingcontinuesjustafterthematch.Thesyntaxgroupthatis

expectedtobepresentjustafterthematchmustbespeci�ed.Thiscanbeusedwhen

thepreviousmethoddoesn'tworkwell.It'smuchslower,becausemoretextneedsto

beparsed.

Bothtypesofsyncpatternscanbeusedatthesametime.Besidesthesyncpatterns,

othermatchesandregionscanbespeci�ed,toavoid�ndingunwantedmatches.

:sy[ntax]syncmatchgroup-namegroupheresync-group-name...

de�neamatch

thatisusedforsyncing.sync-group-nameisthenameofasyntaxgroupthatfollows

justafterthematch.Parsingofthetextforhighlightingstartsjustafterthematch.A

regionmustexistforthissync-group-name.The�rstonede�nedwillbeused.NONE

canbeusedforwhenthereisnosyntaxgroupafterthematch.

:sy[ntax]syncmatchgroup-namegrouptheresync-group-name...

likegrouphere,

butsync-group-nameisthenameofasyntaxgroupthatistobeusedatthestartofthe

linewheresearchingforthesyncpointstarted.Thetextbetweenthematchandthe

startofthesyncpatternsearchingisassumednottochangethesyntaxhighlighting.

:sy[ntax]syncmatch...,:sy[ntax]syncregion...

de�nearegionormatchthatis

skippedwhilesearchingforasyncpoint.

:sy[ntax]synclinecontpattern

whenpatternmatchesinaline,itisconsideredtocon-

tinueinthenextline.Thismeansthatthesearchforasyncpointwillconsiderthe

linestobeconcatenated.

Ifthemaxlines=N

argumentisgiventoo,thenumberoflinesthataresearchedfora

matchisrestrictedtoN.

Clearingsyntax

:sy[ntax]syncclearclearsallsyncsettings

:sy[ntax]synccleargroup-name...

clearsspeci�csyncpatterns

Page 17: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

44

VIM

5.6ReferenceGuide

11.4

Syntaxpatterns

Inthesyntaxcommands,apatternmustbesurroundedbytwoidenticalcharacters

(delimiters).Syntaxpatternsarealwaysinterpretedasifthemagicoptionissetandthe

\l" agisnotincludedincpoptions.Thepatterncanbefollowedbyacharactero�set,

whichcanbeusedtochangethehighlightedpartandtochangethetextareaincludedin

thematchorregion.Note:nowhitespaceisallowedbetweenthepatternandthecharacter

o�set(s).

Theo�settakestheformofwhat=offset,wherewhatcanbeoneofsixstrings:

ms

MatchStart

o�setforthestartofthematchedtext

me

MatchEnd

o�setfortheendofthematchedtext

hs

HighlightStart

o�setforwherethehighlightingstarts

he

HighlightEnd

o�setforwherethehighlightingends

rs

RegionStart

o�setforwherethebodyofaregionstarts

re

RegionEnd

o�setforwherethebodyofaregionends

lc

LeadingContext

o�setpast\leadingcontext"ofpattern

Theo�setcanbe:

s

startofthematchedpattern

s+num

startofthematchedpatternplusnumcharstotheright

s-num

startofthematchedpatternplusnumcharstotheleft

e

endofthematchedpattern

e+num

endofthematchedpatternplusnumcharstotheright

e-num

endofthematchedpatternplusnumcharstotheleft

num

(forlconly):startmatchingnumcharstotheleft

O�setscanbeconcatenated,separatedbycommas.

Leadingcontext

Thelco�setspeci�esaleadingcontext:apartofthepatternthatmustbepresent,

butisnotconsideredpartofthematch.Ano�setoflc=nwillcauseVIM

tostepbackn

columnsbeforeattemptingthepatternmatch,allowingcharacterswhichhavealreadybeen

matchedinpreviouspatternstoalsobeusedastheleadingcontextforthismatch.

Themso�setisautomaticallysettothesamevalueasthelco�set,unlessyousetms

explicitly.

11.5

Synchronizing

:sy[ntax]sync[ccomment[group-name]jminlines=N

j...]

Therearethreewaystosynchronize.Forallthreemethods,thelinerangewithinwhich

theparsingcanstartislimitedbyminlinesandmaxlines.

Iftheminlines=Nargumentisgiven,theparsingalwaysstartsatleastthatmanylines

backwards.Thiscanbeusediftheparsingmaytakeafewlinesbeforeit'scorrect,orwhen

it'snotpossibletousesyncing.

Ifthemaxlines=Nargumentisgiven,thenumberoflinesthataresearchedforacomment

orsyncingpatternisrestrictedtoNlinesbackwards(afteraddingminlines).Thisisuseful

ifyouhavefewthingstosynconandaslowmachine.

Firstsyncingmethod:

Forthe�rstmethod,onlytheccommentargumentneedstobegiven.WhenVIM

�nds

thatthelinewheredisplayingstartsisinsideaC-stylecomment,the�rstregionsyntaxitem

withthegroup-nameCommentwillbeused.

Themaxlinesargumentcanbeusedtorestrictthesearchtoanumberoflines.The

minlinesargumentcanbeusedtostartatleastanumberoflinesback(e.g.,forwhenthere

issomeconstructthatonlytakesafewlines,butishardtosyncon).

4

OPTIONS

17

history(hi),

numberofcommand-linesthatareremembered

hkmapp(hkp),

Hebrewkeyboardmapping

icon,

seticonofthewindowtothenameofthe�le

iconstring,

stringtousefortheVIM

icon

ignorecase(ic)ignorecaseinsearchpatterns

include(inc),

patterntobeusedto�ndaninclude�le

incsearch(is),

highlightmatchwhiletypingsearchpattern

infercase(inf),

adjustcaseofmatchforkeywordcompletion

insertmode(im),

starttheeditofa�leinInsertmode

isfname(isf),

charactersincludedin�lenamesandpathnames

isident(isi),

charactersincludedinidenti�ers

isprint(isp),

printablecharacters

iskeyword(isk),

charactersincludedinkeywords

joinspaces(js),

twospacesafteraperiodwithajoincommand

key,

encryptionkey

keymodel(km),

enablestarting/stoppingselectionwithkeys

keywordprg(kp),

programtousefortheKcommand

langmap(lmap),

alphabeticcharactersforotherlanguagemode

laststatus(ls),

tellswhenlastwindowhasstatuslines

lazyredraw

(lz),

don'tredrawwhileexecutingmacros

linebreak(lbr),

wraplonglinesatablank

lines

numberoflinesinthedisplay

lisp

automaticindentingforLisp

list

showTab

andhEOLi

listchars(lcs),

charactersfordisplayinginlistmode

magic

changesspecialcharactersinsearchpatterns

makeef(mef),

nameoftheerror�lefor:make

makeprg(mp),

programtouseforthe:makecommand

matchpairs(mps),

pairsofcharactersthat\%"canmatch

matchtime(mat),

tenthsofasecondtoshowthematchingparenthesis,

whenshowmatchisset

maxfuncdepth(mfd),

maximumrecursivedepthforuserfunctions

maxmapdepth(mmd),

maximumrecursivedepthformapping

maxmem

(mm),

maximummemory(inKbyte)usedforonebu�er

maxmemtot(mmt),

maximummemory(inKbyte)usedforallbu�ers

modeline(ml)recognizemodelinesatstartorendof�le

modelines(mls),

numberoflinescheckedformodelines

modi�ed(mod),

bu�erhasbeenmodi�ed

more,

pauselistingswhenthewholescreenis�lled

mouse,

enabletheuseofmouseclicks

mousefocus(mousef),

keyboardfocusfollowsthemouse

mousehide(mh),

hidemousepointerwhiletyping

mousemodel(mousem),

changesmeaningofmousebuttons

mousetime(mouset),

maxtimebetweenmousedouble-click

nrformats(nf),

numberformatsrecognizedforCTRL-A

command

number(nu)printthelinenumberinfrontofeachline

os�letype(oft),

operatingsystem-speci�c�letypeinformation

paragraphs(para)nro�macrosthatseparateparagraphs

paste,

allowpastingtext

pastetoggle(pt),

keycodethatcausespastetotoggle

patchmode(pm),

keeptheoldestversionofa�le

path(pa),

listofdirectoriessearchedwithgfetal

previewheight(pvh),

heightofthepreviewwindow

readonly(ro),

disallowwritingthebu�er

Page 18: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

18

VIM

5.6ReferenceGuide

remap

allowmappingstoworkrecursively

report

thresholdforreportingnumberoflineschanged

restorescreen(rs),

Win32:restorescreenwhenexiting

revins(ri),

insertingcharacterswillworkbackwards

rightleft(rl),

windowisright-to-leftoriented

ruler(ru),

showcursorlineandcolumninthestatusline

rulerformat(ruf),

customformatfortheruler

scroll(scr)linestoscrollwithCTRL-U

andCTRL-D

scrollbind(scb),

scrollinwindowasotherwindowsscroll

scrolljump(sj),

minimumnumberoflinestoscroll

scrollo�

(so),

minimumnumberoflinesaboveandbelowcursor

scrollopt(sbo),

howscrollbindshouldbehave

sections(sect)nro�macrosthatseparatesections

secure,

securemodeforreading.vimrcincurrentdir

selection(sel),

whattypeofselectiontouse

selectmode(slm),

whentouseSelectmodeinsteadofVisualmode

sessionoptions(ssop),

optionsfor:mksession

shell(sh)nameofshelltouseforexternalcommands

shellcmd ag(shcf),

agtoshelltoexecuteonecommand

shellpipe(sp),

stringtoputoutputof:makeinerror�le

shellquote(shq),

quotecharacter(s)foraroundshellcommand

shellredir(srr),

stringtoputoutputof�lterinatemp�le

shellslash(ssl),

useforwardslashforshell�lenames

shelltype(st),

Amiga:in uenceshowtouseashell

shellxquote(sxq),

likeshellquote,butincluderedirection

shiftround(sr),

roundindenttomultipleofshiftwidth

shiftwidth(sw)numberofspacestousefor(auto)indentstep

shortmess(shm),

listof ags,reducelengthofmessages

shortname(sn)

non-MS-DOS:Filenamesassumedtobe8.3chars

showbreak(sbr),

stringtouseatthestartofwrappedlines

showcmd(sc)show(partial)commandinstatusline

showfulltag(sft),

showfulltagpatternwhencompletingtag

showmatch(sm)brie yjumptomatchingbracketifinsertone

showmode(smd)messageonstatuslinetoshowcurrentmode

sidescroll(ss),

minimumnumberofcolumnstoscrollhorizontal

smartcase(scs),

noignorecasewhenpatternhasuppercase

smartindent(si),

smartautoindentingforCprograms

smarttab(sta),

useshiftwidthwheninsertingTab

softtabstop(sts),

numberofspacesthatTab

useswhileediting

splitbelow

(sb),

newwindowfromsplitisbelowthecurrentone

starto ine(sol),

commandsmovecursorto�rstblankinline

statusline(stl),

customformatforthestatusline

suÆxes(su),

suÆxesthatareignoredwithmultiplematch

swap�le(swf),

whethertouseaswap�leforabu�er

swapsync(sws),

howtosynctheswap�le

switchbuf(swb),

setsbehaviorwhenswitchingtoanotherbu�er

syntax(syn),

syntaxtobeloadedforcurrentbu�er

tabstop(ts)numberofspacesthatTab

in�leuses

tagbsearch(tbs),

usebinarysearchingintags�les

taglength(tl)numberofsigni�cantcharactersforatag

tagrelative(tr),

�lenamesintag�learerelative

tags(tag)listof�lenamesusedbythetagcommand

tagstack(tgst),

pushtagsontothetagstack

term

nameoftheterminal

11

SYNTAXHIGHLIGHTING

43

:sy[ntax]o�

disablessyntaxhighlightingforallbu�ers

:sy[ntax]clearsync-group-name...

removesallpatternsandkeywordsforgroup-

nameinthecurrentbu�er.

Listingsyntaxitems

:sy[ntax][list]listsallthesyntaxitems

:sy[ntax]listgroup-name

showsthesyntaxitemsforonesyntaxgroup

:sy[ntax]listgrouplist-name

showsthesyntaxgroupsforonegrouplist

11.3

Syntaxarguments

The:sy[ntax]commandsthatde�nesyntaxitemstakeanumberofarguments.The

commononesareexplainedhere.Theargumentsmaybegiveninanyorderandmaybe

mixedwiththepatterns.

contained

whenthecontainedargumentisgiven,thisitemwillnotberecognizedatthe

toplevel,butonlywhenitismentionedinthecontains�eldofanothermatch.

transparent

ifthetransparentargumentisgiven,thisitemwillnotbehighlighteditself,

butwilltakethehighlightingoftheitemitiscontainedin.Thisisusefulforsyntax

itemsthatdon'tneedanyhighlightingbutareusedonlytoskipoverapartofthetext.

Thesamegroupsastheitemitiscontainedinareused,unlessacontainsargumentis

giventoo.

oneline

theonelineargumentindicatesthattheregiondoesnotcrossalineboundary.It

mustmatchcompletelyinthecurrentline.However,whentheregionhasacontained

itemthatdoescrossalineboundary,itcontinuesonthenextlineanyway.Acontained

itemcanbeusedtorecognizealinecontinuationpattern.

contains=groupname,...

thecontainsargumentisfollowedbyalistofsyntaxgroup

names.Thesegroupswillbeallowedtobegininsidetheitem(theymayextendpast

thecontaininggroup'send).Thisallowsforrecursivenestingofmatchesandregions.

Ifthereisnocontainsargument,nogroupswillbecontainedinthisitem.Thegroup

namesdonotneedtobede�nedbeforetheycanbeusedhere.

contains=ALL

iftheonlyiteminthecontainslistisALL,thenallgroupswillbeaccepted

insidetheitem.

contains=ALLBUT,group-name,...

ifthe�rstiteminthecontainslistisALLBUT,

thenallgroupswillbeacceptedinsidetheitem,excepttheonesthatarelisted,andthe

containeditems.

Thegroup-nameinthecontainslistcanbeapattern.Allgroupnamesthatmatchthe

patternwillbeincluded(orexcluded,ifALLBUTisused).Thepatterncannotcontain

whitespaceoracomma.

nextgroup=groupname,...

thenextgroupargumentisfollowedbyalistofsyntax

groupnames,separatedbycommas(justlikewithcontains,soyoucanalsousepat-

terns).Ifthenextgroupargumentisgiven,thementionedsyntaxgroupswillbetried

foramatch,afterthematchorregionends.Ifnoneofthegroupsmatch,highlighting

continuesnormally.Ifthereisamatch,thisgroupwillbeused,evenwhenitisnot

mentionedinthecontains�eldofthecurrentgroup.Thisislikegivingthementioned

grouppriorityoverallothergroups

skipwhite

skipoverhSpaceiandhTabicharacters.Whenskipwhiteispresent,thewhite

spaceisonlyskippedifthereisnonextgroupthatmatchesthewhitespace.

skipnlskipovertheendofaline.Whenskipnlispresent,thematchwithnextgroupmay

befoundinthenextline.Thisonlyhappenswhenthecurrentitemendsattheendof

thecurrentline.Whenskipnlisnotpresent,thenextgroupwillonlybefoundafterthe

currentiteminthesameline.

skipempty

skipoveremptylines(impliesaskipnl)

Note:theskipwhite,skipnlandskipemptyareonlyusedincombinationwithnextgroup.

Page 19: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

42

VIM

5.6ReferenceGuide

match(therearenokeywordcharactersbeforeorafterthematch),e.g.ifwouldmatch

inif(a=b),butnotinifdefx.

match

amatchwithasingleregexppattern.Itmustbewithinoneline.

region

startsatamatchofthestartregexppatternandendswithamatchoftheend

regexppattern.Askipregexppatterncanbeusedtoavoidmatchingtheendpattern.

Severalsyntaxitemscanbeputintoonesyntaxgroup.Forasyntaxgroupyoucan

providehighlightingattributes.Youarefreetomakeahighlightgroupforonesyntaxitem,

ortoputallitemsintoonegroup.Incasewheremorethanoneitemmatchesatthesame

position,theonethatwasde�nedlastwins.Akeywordalwaysgoesbeforeamatchor

region.Akeywordwithmatchingcasealwaysgoesbeforeakeywordwithignoringcase.

:sy[ntax]case[matchjignore]de�neswhetherthefollowing:sy[ntax]commandswillwork

withmatchingcase,whenusingmatch,orwithignoringcase,whenusingignore.Note

thatanyitemsbeforethisarenota�ected,andallitemsuntilthenext:sy[ntax]case

commandarea�ected.

:sy[ntax]keywordgroup-name[options]keyword...[options]de�nesanumberof

keywords,where:

group-name{syntaxgroupname,e.g.Comment.

options{See\Syntaxarguments"below.

keyword...{listofkeywordswhichbelongtothisgroup.

Theoptionscanbegivenanywhereintheline.Theywillapplytoallkeywordsgiven,

alsoforoptionsthatcomeafterakeyword.Whenyouhaveakeywordwithanoptional

tail,likeExcommandsinVIM

,youcanputtheoptionalcharactersinside[],tode�ne

allthevariationsatonce.

Akeywordalwayshashigherprioritythanamatchorregion;thekeywordisusedifmore

thanoneitemmatches.Keywordsdonotnestandakeywordcan'tcontainanything

else.Themaximumlengthofakeywordis80characters.Thesamekeywordcanbe

de�nedmultipletimes,whenitscontainmentdi�ers.

:sy[ntax]matchgroup-name[options][excludenl]pattern[options]de�nesonematch,

wherepatternisthesearchpatternthatde�nesthematch.excludenl{don'tmakeapat-

ternwiththeend-of-line\$"extendacontainingmatchoritem.Onlyusefulforend

patterns.

:sy[ntax]regiongroup-name[options][matchgroup=groupname][keepend]start

=startpattern...[skip=skippattern]end=endpattern...[options]

de�nesoneregion,where:

[matchgroup=group-name]{thesyntaxgrouptouseforthefollowingstartorend

patternmatchesonly.Notusedforthetextinbetweenthematchedstartandend

patterns.UseNONEtoresettonotusingadi�erentgroupforthestartorendmatch.

keepend{doesn'tallowcontainedmatchestogopastamatchwiththeendpattern.

start=startpattern{thesearchpatternthatde�nesthestartoftheregion.

skip=skippattern{thesearchpatternthatde�nestextinsidetheregionwherenot

tolookfortheendpattern.

end=endpattern{thesearchpatternthatde�nestheendoftheregion.

Thestart/skip/endpatternsandtheoptionscanbegiveninanyorder.Therecanbe

zerooroneskippattern.Theremustbeoneormorestartandendpatterns.

Cleaningup

:sy[ntax]clear

switcheso�syntaxhighlighting.It'sagoodideatoincludethiscommand

atthebeginningofasyntax�le.

5

OTHERCOMMANDS

19

terse,

shortensomemessages

textauto(ta),

obsolete,use�leformats

textmode(tx),

obsolete,use�leformat

textwidth(tw),

maximumwidthoftextthatisbeinginserted

tildeop(top),

tildecommand�behaveslikeanoperator

timeout(to)time-outonmappingsandkeycodes

timeoutlen(tm)time-outtimeinmilliseconds

title,

settitleofwindowtothenameofthe�le

titlelen(tm),

givesthepercentageof\columns"touseforthelengthofthewindow

title

titleold,

oldtitle,restoredwhenexiting

titlestring,

titletousefortheVIM

window

toolbar(tb),

GUI:whichitemstoshowinthetoolbar

ttimeout,

time-outonmappings

ttimeoutlen(ttm),

time-outtimeforkeycodesinmilliseconds

ttybuiltin(tbi),

usebuilt-intermcapbeforeexternaltermcap

ttyfast(tf),

indicatesafastterminalconnection

ttymouse(ttym),

typeofmousecodesgenerated

ttyscroll(tsl)maximumnumberoflinesforascroll

ttytype(tty)aliasforterm

undolevels(ul),

maximumnumberofchangesthatcanbeundone

updatecount(uc),

afterthismanycharacters ushswap�le

updatetime(ut),

afterthismanymilliseconds ushswap�le

verbose(vbs),

giveinformativemessages

viminfo(vi),

use.viminfo�leuponstartupandexiting

visualbell(vb),

usevisualbellinsteadofbeeping

warn

warnforshellcommandwhenbu�erwaschanged

weirdinvert(wi),

forterminalsthathaveweirdinversionmethod

whichwrap(ww),

allowspeci�edkeystocrosslineboundaries

wildchar(wc),

command-linecharacterforwildcardexpansion

wildcharm

(wcm),

likewildcharbutalsoworkswhenmapped

winheight(wh),

minimumnumberoflinesfor

wildignore(wig),

�lesmatchingthesepatternsarenotcompleted

wildmenu(wmnu),

usemenuforcommandlinecompletion

wildmode(wim),

modeforwilcharcommand-lineexpansion

winaltkeys(wak),

whenthewindowssystemhandlesALTkeysthecurrentwindow

winminheight(wmh),

minimumnumberoflinesforanywindow

wrap,

longlineswrapandcontinueonthenextline

wrapmargin(wm)charsfromtherightwherewrappingstarts

wrapscan(ws)searcheswraparoundtheendofthe�le

write,

writingtoa�leisallowed

writeany(wa)writeto�lewithnoneedfor!override

writebackup(wb),

makeabackupbeforeoverwritinga�le

writedelay(wd),

delaythismanymsecforeachchar(fordebug)

5

OtherCommands

5.1

ShellCommands

:sh[ell]startashell

:!command

executecommandwithashell

K

lookupkeywordunderthecursorwithkeywordprgprogram(default:\man")

Page 20: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

20

VIM

5.6ReferenceGuide

5.2

QuickFixCommands,

VIM

hasaspecialmodetospeeduptheedit-compile-editcycle.Theideaistosavethe

errormessagesfromthecompilerina�leanduseVIM

tojumptotheerrorsonebyone.

Theerrorformatoptionshouldbesettomatchtheerrormessagesfromyourcompiler(see

below).

:cc[!][num]displayerrornum(defaultisthesameagain).Without\!"thisdoesn'twork

whenjumpingtoanotherbu�er,thecurrentbu�erhasbeenchanged,thereistheonly

windowforthebu�erandbothhiddenandautowriteareo�.Whenjumpingtoanother

bu�erwith\!"anychangestothecurrentbu�erarelost,unlesshiddenissetorthere

isanotherwindowforthisbu�er.

:[n]cn[ext][!]displaythennexterrorinthelistthatincludesa�lename.Ifthereareno

�lenamesatall,gotothennexterror.See:ccfor\!".

:[n]cp[revious][!]displaythenpreviouserrorinthelistthatincludesa�lename.Ifthere

areno�lenamesatall,gotothenpreviouserror.

:[n]cnf[ile][!]displaythe�rsterrorinthennext�leinthelistthatincludesa�lename.

Ifthereareno�lenamesatallorifthereisnonext�le,gotothennexterror.

:cl[ist][from][,[to]]listallerrorsthatincludea�lename

:cl[ist]!listallerrors

:cfreaderrorsfromthe�le\error�le"

:cr[ewind][!][nr]displayerror[nr].Ifnrisomitted,theFIRSTerrorisdisplayed.

:cla[st][!][nr]displayerror[nr].Ifnrisomitted,theLASTerrorisdisplayed.

:cq

quitwithoutwritingandreturnerrorcode(tothecompiler)

:make[args]startmake,readerrors,andjumpto�rsterror

:gr[ep][args]executegrepprgto�ndmatchesandjumptothe�rstone.

:col[der][n]gotooldererrorlist[ntimes].

:cnew[er][n]gotonewererrorlist[ntimes].

Errorformatoptionsyntax

Spec

Description

Spec

Description

%c

columnnumber(anumber)

%f

�lename(astring)

%l

linenumber(anumber)

%m

errormessage(astring)

%n

errornumber(anumber)

%r

matchestherestofasingle-

line�lemessage

%t

errortype(singlecharacter)

%*<conv>

any

scanf

non-assignable

conversion

%%

thesingle\%"character

5.3

ViminfoCommands,

Theviminfo�leisusedtostore:

�Thecommandlinehistory.

�Thesearchstringhistory.

�Theinput-linehistory.

�Contentsofregisters.

�Marksforseveral�les.

�Filemarks,pointingtolocationsin�les.

�Lastsearch/substitutepattern(for\n"and\&").

�Thebu�erlist.

�Globalvariables.

viminfo�le

readregisters,marks,historyatstartup,savewhenexiting

11

SYNTAXHIGHLIGHTING

41

11

Syntaxhighlighting,

Syntaxhighlightingprovidesthepossibilityofshowingpartsofthetextinanotherfont

orcolor.Tostartusingsyntaxhighlighting,typethiscommand::sy[ntax]on.Thiswill

enableautomaticsyntaxhighlighting.Thetypeofhighlightingwillbeselectedusingthe

�lenameextension,andsometimesusingthe�rstlineofthe�le.Thenameoftheacitve

syntaxisstoredinthe\currentsyntax"variable.

11.1

Syntax�les

Thesyntaxandhighlightingcommandsforonelanguagearenormallystoredinasyntax

�lenamed\name.vim",wherenameisthe[abbreviated]nameofthelanguage.Thesyntax

�lecancontainanyExcommands.

NamingConventions

Toalloweachusertopickhisfavoritesetofcolors,asetofpre-de�nednamesfor

highlightgroupscommonformanylanguageshasbeenchosen.Thesearethepreferred

namesfordi�erenthighlightgroups:

Name

Usedfor:

Name

Usedfor:

*Comment

anycomment

*Constant

anyconstant

*Error

anyerroneousconstruct

*Identi�er

anyvariablename

*Ignore

leftblank,hidden

*PreProc

genericPreprocessor

*Special

anyspecialsymbol

*Statement

anystatement

*Todo

anythingthatneedsextra

attention

*Type

int,long,char...

Boolean

abooleanconstant

Character

acharacterconstant

Conditional

if,then,else...

Debug

debuggingstatements

De�ne

#define

Delimiter

delimitingcharacter

Exception

try,catch,throw

Float

a oatingpointconstant

Function

functionandclassmethod

names

Include

#include

Keyword

anyotherkeyword

Label

case,default

Macro

sameasDe�ne

Number

anumberconstant

Operator

sizeof,+,*...

PreCondit

#if,#else...

Repeat

for,do,while...

SpecialChar

specialcharacterinacon-

stant

SpecialComment

specialthingsinsideacom-

ment

StorageClass

static,register...

String

astringconstant

Structure

struct,union,enum...

Tag

useCTRL-]

onthis

Typedef

atypedef

Thenamesmarkedwith\*"arethepreferredgroups,theotherareminorgroups.Forthe

preferredgroups,the\syntax.vim"�lecontainsdefaulthighlighting.Thehighlightgroup

namesarenotcasesensitive.Thefollowingnamesarereservedandcannotbeusedasa

groupname:NONEALLALLBUTcontainscontained.

11.2

De�ningasyntax

VIM

understandsthreetypesofsyntaxitems:

keyword

canonlycontainkeywordcharacters,de�nedbytotheiskeywordoption.Keyword

cannotcontainothersyntaxitems.Itwillonlyberecognizedwhenthereisacomplete

Page 21: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

40

VIM

5.6ReferenceGuide

ShowingWhatMenusAreMappedTo

Toseewhatanexistingmenuismappedto,usejustoneargumentafterthemenu

commands(similartothe:mapcommands).Ifthemenuspeci�edisasubmenu,thenall

menusinthathierarchywillbeshown.Ifnoargumentisgivenafter:menuatall,thenALL

menuitemsareshownfortheappropriatemode(e.g.Command-linemodefor:cmenu).

Note:whileenteringamenunameafteramenucommand,Tab

maybeusedtocomplete

thenameofthemenuitem.

DeletingMenus

:unme

:unmenu

:aun

:aunmenu

:nunme

:nunmenu

:ounme

:ounmenu

:vunme

:vunmenu

:iunme

:iunmenu

:cunme

:cunmenu

Todeleteamenuitemorawholesubmenu,usethe:unmenucommands,whichareanalogous

tothe:unmapcommands.Toremoveallmenususe:

:unmenun*"

removeallmenusinNormalandvisualmode

:unmenu!n*"

removeallmenusinInsertandCommand-linemode

10.4

Miscellaneous

ThissectiondescribesotherfeatureswhicharerelatedtotheGUI.

-Typingb

VfollowedbyaspecialkeyintheGUIwillinserthKeyi,sincetheinternal

stringusedismeaningless.Modi�ersmayalsobehelddowntogethModifiers-Keyi.

-IntheGUI,themodi�ershSHIFTi,hCTRLi,andhALTi(orhMETAi)maybeusedwithin

mappingsofspecialkeysandmouseevents

-IntheGUI,severalnormalkeysmayhavemodi�ersinmappingsetc,thesearehSpacei,

hTabi,hNLi,hCRi,hEsci.

-ExecutinganexternalcommandfromtheGUIwillnotalwayswork.\Normal"com-

mandslikels,grepandmakemostlywork�ne.Commandsthatrequireanintelligent

terminallikelessandispellwon'twork.Somemayevenhangandneedtobe

killedfromanotherterminal.FortheX11GUItheexternalcommandsareexecuted

insidethegvimwindow.FortheWin32GUItheexternalcommandsareexecutedin

aseparatewindow.

-Normally,VimtakescontrolofallhAlti-hKeyicombinations,toincreasethenumberof

possiblemappings.ThisclasheswiththestandarduseofAltinWin32asthekeyfor

accessingmenus.Thequickwayofgettingstandardbehavioristosetthewinaltkeys

optiontoyes.ThishoweverpreventsyoufrommappinghAltikeysatall.Another

wayistosetwinaltkeystomenu.Menushortcutkeysarethenhandledbywindows,

otherALTkeyscanbemapped.Thisdoesn'tallowadependencyonthecurrentstate

though.Togetroundthis,the:simaltkeycommandallowsVim(whenwinaltkeysis

notsettoyes)tofakeaWindows-stylehAltikeypress.

Thisexampleshowshowtoaddandremoveamenuitemforthekeywordunderthe

cursor.Theregisterzisused

Example

1

:nmenuWords.Add\Varwb"zye:menu!Words.<C-R>z<C-R>z<CR>

2

:nmenuWords.Remove\Varwb"zye:unmenu!Words.<C-R>z<CR>

3

:vmenuWords.Add\Var"zy:menu!Words.<C-R>z<C-R>z<CR>

4

:vmenuWords.Remove\Var"zy:unmenu!Words.<C-R><CR>

5

:imenuWords.Add\Var<Esc>wb"zye:menu!Words.<C-R>z<C-R>z<CR>a

6

:imenuWords.Remove\Var<Esc>wb"zye:unmenu!Words.<C-R>z<CR>a

5

OTHERCOMMANDS

21

:rv[iminfo]�le

readinfofromviminfo�le�le

:rv[iminfo]!�le

idem,overwriteexistinginfo

:wv[iminfo]�le

addinfotoviminfo�le�le

:wv[iminfo]!�le

writeinfotoviminfo�le�le

Viminfooptionsyntax

Theformatof\viminfo"string:charstringorcharnumber,wherecharcanbe:

'

{maximumnumberofpreviouslyedited�lesforwhichthemarksareremembered.

f

{whether�lemarksneedtobestored.Ifzero,�lemarks('0to'9,'Ato'Z)are

notstored.Whennotpresentorwhennon-zero,theyareallstored.

r

{removablemedia.Theargumentisastring(uptothenext\,").Thisparameter

canbegivenseveraltimes.Eachspeci�esthestartofapathforwhichnomarks

willbestored.Maximumlengthofeach\r"argumentis50characters.

{maximumnumberoflinessavedforeachregister.Ifzerothenregistersarenot

saved.Whennotincluded,alllinesaresaved.

:

{maximumnumberofitemsinthecommandlinehistorytobesaved.Whennot

included,thevalueofhistoryisused.

/

{maximumnumberofitemsinthesearchpatternhistorytobesaved.Ifnon-zero,

thentheprevioussearchandsubstitutepatternsarealsosaved.Whennotincluded,

thevalueofhistoryisused.

n

{nameoftheviminfo�le.Thenamemustimmediatelyfollowthe\n".Mustbe

thelastone!Ifthe\-i"argumentwasgivenwhenstartingVim,that�lename

overridestheonegivenherewithviminfo.Environmentvariablesareexpanded

whenopeningthe�le,notwhensettingtheoption.

%

{saveandrestorethebu�erlist.IfVimisstartedwitha�lenameargument,the

bu�erlistisnotrestored.IfVimisstartedwithouta�lenameargument,thebu�er

listisrestoredfromtheviminfo�le.Bu�erswithouta�lenameandbu�ersfor

help�lesarenotwrittentotheviminfo�le.

Automaticoptionsettingwheneditinga�le

vim:set-arg:..inthe�rstandlastlinesofthe�le(seemloption),set-argisgivenasan

argumentto:set

5.4

VariousCommands

:h[elp],

splitthewindowanddisplaythehelp�leinread-onlymode.Ifthereisahelp

windowopenalready,usethatone

:h[elp]subject

Like:help,additionallyjumptothetagsubject.subjectcanincludewild-

cardslike\*",\?"and\[a-z]"

CTRL-L

clearandredrawthescreen

CTRL-G

showcurrent�lename(withpath)andcursorposition

gashowASCIIvalueofcharacterundercursorindecimal,hex,andoctal

gCTRL-G

showcursorcolumn,line,andcharacterposition

CTRL-C

duringsearches:interruptthesearch

CTRL-B

breakMS-DOS:duringsearches:interruptthesearch

n

Del

whileenteringcountn:deletelastcharacter

:ve[rsion]showversioninformation

:moden

MS-DOS:setscreenmodeton(number,C80,C4350,etc.)

:norm[al][!]commands

executeNormalmodecommands

Q

switchtoExmode

:redir>

�le

redirectmessagesto�le

:redir>

>

�le

redirectmessagesto�le.Appendif�lealreadyexists

Page 22: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

22

VIM

5.6ReferenceGuide

:redi[r]@a-zA-Z

redirectmessagetoregistera-z.Appendtothecontentsoftheregister

ifitsnameisgivenuppercaseA-Z,

:redi[r]END

endredirectingmessages,

:[range]p[rint][n]printnlines,startingwithrange

:[range]l[ist][n]sameas:print,butdisplayunprintablecharacters

6

Ex

rangesandsearchpatterns

6.1

Ranges

,

separatestwolinenumbers

;

idem,setcursortothe�rstlinenumberbeforeinterpretingthesecondone

number

anabsolutelinenumber

.

thecurrentline

$

thelastlineinthe�le

%

equalto1,$(theentire�le)

*

equalto'<

,'>

(visualarea)

't

positionofmarkt

/pattern[/]thenextlinewherepatternmatches

?pattern[?]thepreviouslinewherepatternmatches

+[num]addnumtotheprecedinglinenumber(default:1)

-[num]subtractnumfromtheprecedinglinenumber(default:1)

6.2

SpecialEx

characters

j

separatestwocommands(notfor:globaland:!)

"

beginscomment

%

current�lename(onlywherea�lenameisexpected)

#[number]alternate�lenamenumber(onlywherea�lenameisexpected)

Note:Thenextsixaretypedliterally;thesearenotspecialkeys!

<cword>

wordunderthecursor(onlywherea�lenameisexpected)

<cWORD>

WORDunderthecursor(onlywherea�lenameisexpected)

<cfile>

filenameunderthecursor(onlywherea�lenameisexpected)

<afile>

filenameforautocommand(onlywherea�lenameisexpected)

<abuf>

whenexecutingautocommands,isreplacedwiththecurrentlye�ectivebu�ernum-

ber.

<amatch>

whenexecutingautocommands,isreplacedwiththematchforwhichthisauto-

commandwasexecuted.

<sfile>

filenameofa:source'd�le,withinthat�le(onlywherea�lenameisexpected)

After%,#,<cfile>,<sfile>or<afile>

:p

fullpath

:h

head(�lenameremoved)

:t

tail(�lenameonly)

:r

root(extensionremoved)

:e

extension

:.

reduce�lenametoberelative

tocurrentdirectory,ifpossible

:�

reduce�lenametoberelative

tothehomedirectory,ifpossi-

ble

:s/pat/sub/

substitutepatwithsub

6.3

Patternsearches

[n]/pattern[/o�set]Ret

searchforwardforthen-thoccurrenceofpattern

[n]?pattern[?o�set]Ret

searchbackwardforthen-thoccurrenceofpattern

[n]/Ret

repeatlastsearch,intheforwarddirection

10

GUI

39

10.3

Menus

Thedefaultmenusarereadfromthe�le\$VIMRUNTIME/menu.vim".MotifandWin32

GUIssupportTear-o�menus.

CreatingNewMenus

:me

:menu

:noreme

:noremenu

:am

:amenu

:an

:anoremenu

:nme

:nmenu

:nnoreme

:nnoremenu

:ome

:omenu

:onoreme

:onoremenu

:vme

:vmenu

:vnoreme

:vnoremenu

:ime

:imenu

:inoreme

:inoremenu

:cme

:cmenu

:cnoreme

:cnoremenu

Tocreateanewmenuitem,usethe:menucommands.Theyworkexactlylikethe:mapset

ofcommandsbutthe�rstargumentisamenuitemname,givenasapathofmenusand

sub-menuswitha\."betweenthem.

The:amenucommandcanbeusedtode�nemenuentriesforallmodesatonce.Tomake

thecommandworkcorrectly,acharacterisautomaticallyinsertedformodes:Normal)

nothing,Insert)

hCTRL-Oi,Cmdline)

hCTRL-Ci,Visual)

hEsci,Op-pending)

hEsci.

Careful:InInsertmodethisonlyworksforaSINGLENormalmodecommand,because

oftheCTRL-O.Ifyouhavetwoormorecommands,youwillneedtousethe:imenucommand.

Specialcharactersinamenuname:

&

Thenextcharacteristheshortcutkey.Makesureeachshortcutkeyisonlyusedonce

ina(sub)menu.

hTabiSeparatesthemenunamefromright-alignedtext.Thiscanbeusedtoshowthe

equivalenttypedcommand.

Menu-priority

Thepositionofamenuitem

onthemenubarisdeterminedbyits\priority".The

priorityisgivenasanumberbeforethe:menucommand.Menuswithahigherprioritygo

moretotheright.Whennopriorityisgiven,500isused.Thehighestpossiblepriorityis

about32000.Currently,youcanonlygiveapriorityforthelocationofthemenuinthe

menubar,notforthelocationofamenuiteminamenu.Thedefaultmenushavethese

priorities:File7!10;Edit7!20;Tools7!40;Syntax7!50;Bu�ers7!60;Window7!70;Help

7!9999;Thesamemechanismcanbeusedtopositionasubmenu.Thepriorityisthengiven

asadot-separatedlistofpriorities,beforethemenuname.

Toolbar

Currently,thetoolbarisonlyavailableintheWin32andgtk+GUI.Itshouldturnupin

otherGUIsinduecourse.Thedisplayofthetoolbariscontrolledbytheguioptionsletter

T.Thetoolbarisde�nedasaspecialmenucalledToolBar,whichonlyhasonelevel.

Tooltips&Menutips

ThesearecurrentlyonlysupportedfortheWin32GUI.

:tm[enu]menupathrhs

De�neatipforamenuortool.Whenatipisde�nedforamenu

item,itappearsinthecommand-lineareawhenthemouseisoverthatitem.Whena

tipisde�nedforatoolbaritem,itappearsasatooltipwhenthemousepausesover

thatbutton.

:tu[nmenu]menupath

Removeatipforamenuortool.

Page 23: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

38

VIM

5.6ReferenceGuide

X11vs.Win32GUI

X11GUI:InVisualmode,thehighlightedtextmaybepastedintootherwindows.Like-

wise,theselectedtextfromotherwindowsmaybepastedintoVIM

inNormalmode,

Insertmode,orontheCommandlinebyclickingthemiddlemousebutton.

Win32GUI:Visuallyselectedtextisonlycopiedtotheclipboardwhenusingaycom-

mand,oranotheroperatorwhenthe\*"registerisused.

OtherTextSelectionwithMouse

InCommand-linemode,atthehit-returnpromptorifthemouseoptionisturnedo�,

adi�erentkindofselectionisused:theleftbuttonselects,therightbuttonextendsthe

selectionandthemiddleonepastesthetextback.

VariousMouseClicks

Leftorrightclickonthestatuslinemakesthatwindowcurrent.Dragthestatuslineto

resizethewindowsaboveandbelow.

S-LeftMouse

Searchforwardforthewordunderthemouseclick.

S-RightMouse

Searchbackwardforthewordunderthemouseclick.

C-LeftMouse

Jumptothetagnameunderthemouseclick.

C-RightMouse

Jumpbacktopositionbeforetheprevioustagjump

GUISelections

Aspecialregister\*"isusedforstoringGUIselection.Nothingisputinthereunless

theinformationaboutwhattextisselectedisabouttochange,orwhenanotherapplication

wantstopastetheselectedtext.Similarly,whenwewanttopasteaselectionfromanother

application,theselectionisputinthe\*"register�rst,andthenputlikeanyotherregister.

Note:whenpastingtextfromoneVIM

intoanotherseparateVIM

,thetypeofselection

(character,line,orblock)willalsobecopied.

MouseMappings

Themouseevents,completewithmodi�ers,maybemapped.

Example

1

:map<S-LeftMouse><RightMouse>

2

:map<S-LeftDrag><RightDrag>

Note:Mousemappingwithmodi�ersdoesnotworkforxterm-likeselection.

10.2

WindowPosition

Vimtriestomakethewindow�tonthescreenwhenitstartsup.Thisavoidsthatyou

can'tseepartofit.Youcanchangetheheightthatisusedforthewindowtitleandatask

barwiththeguiheadroomoption.

:winp[os]DisplaycurrentpositionofthetopleftcorneroftheGUIvimwindowinpixels.

Doesnotworkinallversions.

:winp[os]X

Y

PuttheGUIvimwindowatthegivenXandYcoordinates.Thecoordi-

natesshouldspecifythepositioninpixelsofthetopleftcornerofthewindow.Does

notworkinallversions.

6

EX

RANGESANDSEARCHPATTERNS

23

[n]?Ret

repeatlastsearch,inthebackwarddirection

[n]n

repeatlastsearch

[n]N

repeatlastsearch,inoppositedirection

[n]*,

searchforwardfortheidenti�erunderthecursor

[n]#

,

searchbackwardfortheidenti�erunderthecursor

[n]g*,

like*,butalso�ndpartialmatches

[n]g#

,

like#,butalso�ndpartialmatches

gd,

gotolocaldeclarationofidenti�erunderthecursor

gD,

gotoglobaldeclarationofidenti�erunderthecursor

6.4

Specialcharactersinsearchpatterns

magic

7

nomagic

meaning

.

n.

matchesanysinglecharacter

b

b

atbeginningofpatternorafter\n|"or\n(",matchesstartof

line;atotherpositions,matchesliteral\b"

nb

nb

atanyposition,matchesliteral\b"

$

$

matcheshEOLi

n<

n<

matchesstartofword

n>

n>

matchesendofword

[a-z]

n[a-z]

matchesasinglecharfromtherange

[ba-z]

n[ba-z]

matchesasinglecharnotintherange

ni

ni

matchesanidenti�erchar,

nI

nI

idembutexcludingdigits,

nk

nk

matchesakeywordcharacter,

nK

nK

idembutexcludingdigits,

nf

nf

matchesa�lenamecharacter,

nF

nF

idembutexcludingdigits,

np

np

matchesaprintablecharacter,

nP

nP

idembutexcludingdigits,

ns

ns

matchesawhitespacecharacter,

nS

nS

matchesanon-whitespacecharacter,

nd

nd

digit:[0-9],

nD

nD

non-digit:[b0-9],

nx

nx

hexdigit:[0-9A-Fa-f],

nX

nX

non-hexdigit:[b0-9A-Fa-f],

no

no

octaldigit:[0-7],

nO

nO

non-octaldigit:[b0-7],

nw

nw

wordcharacter:[0-9A-Za-z],

nW

nW

non-wordcharacter:[b0-9A-Za-z],

nh

nh

head-of-wordcharacter:[A-Za-z],

nH

nH

non-head-of-wordcharacter:[bA-Za-z],

na

na

alphabeticcharacter:[A-Za-z],

nA

nA

non-alphabeticcharacter:[bA-Za-z],

nl

nl

lowercasecharacter:[a-z],

nL

nL

non-lowercasecharacter:[ba-z],

nu

nu

uppercasecharacter:[A-Z],

nU

nU

non-uppercasecharacter:[bA-Z],

Note:usingtheatomisfasterthanthe[]form

ne

ne

matcheshEsci

nt

nt

matcheshTabi

nr

nr

matcheshReti

Page 24: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

24

VIM

5.6ReferenceGuide

magic

nomagic

meaning

nb

nb

matcheshBSi

nj

nj

separatestwobranches

n(n)

n(n)

groupapatternintoanatom

n�

matchesthelastgivensubstitutestring

n1,n2,..,n9

n1,n2,..,n9

Matchesthesamestringthatwasmatchedbythe�rst,second..

ninthsub-expressioninn(andn).

Quanti�ers

*

n*

matches0ormoreoftheprecedingatom

n+

n+

matches1ormoreoftheprecedingatom,

n=

n=

matches0or1oftheprecedingatom,

nfn,mg

nfn,mg

matchesntomoftheprecedingatom,asmuchaspossible,

nfng

nfng

matchesnoftheprecedingatom,

nfn,g

nfn,g

matchesatleastnoftheprecedingatom,asmuchaspossible,

nf,mg

nf,mg

matches0tomoftheprecedingatom,asmuchaspossible,

nfg

nfg

thesameas*,

nf{n,mg

nf{n,mg

matchesntomoftheprecedingatom,asfewaspossible,

nf{ng

nf{ng

matchesnoftheprecedingatom,

nf{n,g

nf{n,g

matchesatleastnoftheprecedingatom,asfewaspossible,

nf{,mg

nf{,mg

matches0tomoftheprecedingatom,asfewaspossible,

nf{g

nf{g

matches0ormoreoftheprecedingatom,asfewaspossible,

Characterclassexpression

Acharacterclassexpressionisevaluatedtothesetofcharactersbelongingtothatcharac-

terclass.Thebracketsincharacterclassexpressionsareadditionaltothebracketsdelimiting

arange.Thefollowingcharacterclassesaresupported:

Name

Contents

Name

Contents

[:alnum:]

lettersanddigits

[:alpha:]

letters

[:ascii:]

ASCIIcharacters

[:blank:]

spaceandtabcharacters

[:cntrl:]

controlcharacters

[:digit:]

decimaldigits

[:graph:]

printablecharactersexcludingspace

[:lower:]

lowercaseletters

[:print:]

printablecharactersincludingspace

[:punct:]

punctuationcharacters

[:space:]

whitespacecharacters

[:upper:]

uppercaseletters

[:xdigit:]

hexadecimaldigits

6.5

O�setsallowedaftersearchcommand

[num]numlinesdownwards,incolumn1

+[num]numlinesdownwards,incolumn1

{[num]numlinesupwards,incolumn1

e[+num]numcharacterstotherightoftheendofthematch

e[{num]numcharacterstotheleftoftheendofthematch

s[+num]numcharacterstotherightofthestartofthematch

s[{num]numcharacterstotheleftofthestartofthematch

b[+num]numcharacterstotherightofthestart(begin)ofthematch

b[{num]numcharacterstotheleftofthestart(begin)ofthematch

;searchcommand

executesearchcommandnext

7seeoptionmagic,page17

10

GUI

37

:ifexpr...:en[dif]Executethecommandsuntilthenextmatching:elseor:endififexpr

evaluatestonon-zero.Note:from

VIM

version4.5until5.0,everyExcommandbe-

tweenthe:ifand:endifisignored.

:el[se]Executethecommandsuntilthenextmatching:elseor:endififtheywerenotalready

beingexecuted.

:elsei[f]expr

Shortfor:else:if,withtheadditionthatthereisnoextra:endif.

:wh[ile]expr...:endw[hile]Repeatthecommandsbetween:whileand:endwhile,aslong

asexprevaluatestonon-zero.Whenanerrorisdetectedfromacommandinsidethe

loop,executioncontinuesafterthe:endwhile.

Note:The:appendand:insertcommandsdon'tworkproperlyinsidea:whileloop.

:con[tinue]Whenusedinsidea:while,jumpsbacktothe:while.

:brea[k]Whenusedinsidea:while,skipstothecommandafterthematching:endwhile.

:ec[ho]expr...

Echoeseachexpr,withaspaceinbetweenandaterminatinghEOLi.See

also:comment.

:echonexpr...

Echoeseachexpr,withoutanythingadded.Alsosee:comment.

:echoh[l]name

Usethehighlightgroupnameforthefollowing:echo[n]commands.

:exe[cute]expr...

ExecutesthestringthatresultsfromtheevaluationofexprasanEx

command.Multipleargumentsareconcatenated,withaspaceinbetween.

Note::execute,:echoand:echoncannotbefollowedbyacommentdirectly,becausetheysee

the"asthestartofastring.But,you,however,canuse\j"followedbyacomment.

10

GUI,

10.1

MouseControl

Themouseonlyworksiftheappropriate aginthemouseoptionisset.WhentheGUI

isswitchedon,themouseoptionissettoa,enablingitforallmodesexceptforthe\hit

returntocontinue"message.Thiscanbechangedfromthegvimrc�le.Aquickwayto

settheseiswiththe":behave"command.

:be[have]modelsetbehaviorformouseandselection.Validargumentsare:mswin(MS-

Windowsbehavior)andxterm(Xtermbehavior)

Using\:behave"changestheseoptions:

option

mswin

xterm

option

mswin

xterm

selectmode

mouse,key

{

mousemodel

popup

extend

keymodel

startsel,stopsel

{

selection

exclusive

inclusive

VisualSelectionwithMouse

Themousecanbeusedtostartaselection.Howdependsonthemousemodeloption:

Ifselectmodecontainsmouse,thentheselectionwillbeinSelectmode.Thismeansthat

typingnormaltextwillreplacetheselection.Otherwise,theselectionwillbeinVisual

mode.

Rightbutton:Clicktherightbuttontoextendthevisualselectiontothepositionpointed

towiththemouse.InVisualmodetheclosestendwillbeextended,otherwiseVisual

modeisstartedandextendsfromtheoldcursorpositiontothenewone.

Leftbutton:Doubleclickingmaybedonetomaketheselectionword-wise,tripleclicking

makesitline-wise,andquadrupleclickingmakesitrectangularblock-wise.

Page 25: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

36

VIM

5.6ReferenceGuide

Feature

Description

xfontset

Xfontsetsupport.

xtermclipboard

supportforxtermclipboard.

xtermsave

supportforsavingandrestoringthextermscreen.

x11

X11support.

9.4

User-De�nedFunctions

Newfunctionscanbede�ned.Theycanbecalledwith\Name()",justlikebuilt-in

functions.Thenamemuststartwithanuppercaseletter,toavoidconfusionwithbuiltin

functions.

:fu[nction]Listallfunctionsandtheirarguments.

:fu[nction]name

Listfunctionname.

:fu[nction][!]name([arguments])[range][abort]De�neanewfunctionbythename

name.Thenamemustbemadeofalphanumericcharactersandunderscore,andmust

startwithacapital.Anargumentcanbede�nedbygivingitsname.Inthefunction

thiscanthenbeusedas\a:name"(\a:"forargument).Upto20argumentscanbe

given,separatedbycommas.Anargument\..."canbespeci�ed,whichmeansthat

moreargumentsmaybefollowing.Inthefunctiontheycanbeusedas\a:1",\a:2",

etc.\a:0"issettothenumberofextraarguments(whichcanbe0).Whennotusing

\...",thenumberofargumentsinafunctioncallmustbeequalthenumberofnamed

arguments.Whenusing\...",thenumberofargumentsmaybelarger.Thebodyofthe

functionfollowsinthenextlines,until\:endfunction".Whenafunctionbythisname

alreadyexistsand[!]isnotusedanerrormessageisgiven.When[!]isused,an

existingfunctionissilentlyreplaced.Whentherangeargumentisadded,thefunction

isexpectedtotakecareofarangeitself.Therangeispassedas\a:firstline"and

\a:lastline".Ifrangeisexcluded,a\:call"witharangewillcallthefunctionfor

eachline,withthecursoronthestartofeachline.Whenthe[abort]argumentis

added,thefunctionwillabortassoonasanerrorisdetected.

:endf[unction]Theendofafunctionde�nition.

:delf[unction]name

Deletefunctionname.

:retu[rn][expr]Returnfromafunction.Whenexprisgiven,itisevaluatedandreturned

astheresultofthefunction.Ifexprisnotgiven,thenumber0isreturned.Whena

functionendswithoutanexplicit\:return",thenumber0isreturned.

Insideafunctionvariablescanbeused.Thesearelocalvariables,whichwilldisappear

whenthefunctionreturns.Globalvariablesneedtobeaccessedwithg:.

9.5

Commands

:letvar-name=expr

Setinternalvariablevar-nametotheresultoftheexpressionexpr.

Thevariablewillgetthetypefromtheexpr.Ifvar-namedidn'texistyet,itiscreated.

:let$env-name=expr

Setenvironmentvariableenv-nametotheresultoftheexpres-

sionexpr.ThetypeisalwaysString.

:let@reg-name=expr

Writetheresultoftheexpressionexprinregisterreg-name.reg-

namemustbeasingleletter,andmustbethenameofawritableregister.\@@"canbe

usedfortheunnamedregister.IftheresultofexprendsinahCRiorhNLi,theregister

willbelinewise,otherwiseitwillbesettocharacterwise.

:let&option-name=expr

Setoptionoption-nametotheresultoftheexpressionexpr.

Thetypeoftheoptionisalwaysused.

:unl[et][!]var-name

Removetheinternalvariablevar-name.Severalvariablenamescan

begiven,theyareallremoved.With[!]noerrormessageisgivenfornon-existing

variables.

7

STARTING,WRITINGANDQUITTINGCOMMANDS

25

7

Starting,WritingandQuittingCommands

7.1

StartingVIM

vimoptions

starteditingwithanemptybu�er

vimoptions�le...

starteditingoneormore�les

vimoptions{

read�lefromstdin

vimoptions{ttag

editthe�leassociatedwithtag

vimoptions{q[�le]starteditinginQuickFixmode,displaythe�rsterror

VIM

arguments:

+/pattern�le...,

putthecursoratthe�rstoccurrenceofpattern

+command

executecommandafterloadingthe�le

+[num]putthecursoratline[num](default:lastline)

{{

endofoptions,otherargumentsare�lenames

{b,

binarymode

{C,

compatible,setthecompatibleoption

{ddevice,

Amiga:opendevicetobeusedasaconsole

{e,

Exmode,startVIM

inExmode

{F,

Farsimode(fkmapandrightleftareset)

{f,

GUI:foregroundprocess,don'tfork;Amiga:donotrestartVIM

toopenawindow

{g,

startGUI(alsoallowsotheroptions)

{H,

Hebrewmode(hkmapandrightleftareset)

{iviminfo,

readinfofromviminfoinsteadofother�les

{lLispmode

{m

modi�cationsnotallowed

{n,

donotcreateaswap�le

{N,

nocompatible,resetthecompatibleoption

{on,

opennwindows(default:oneforeach�le)

{r�le..

recoverabortededitsession

{rgivelistofswap�les

{R,

read-onlymode,implies-n

{sscriptin,

�rstreadcommandsfromthe�lescriptin

{Tterminal,

setterminalname

{Ugvimrc,

idem,forwhenstartingtheGUI

{uvimrc,

readinitsfromvimrcinsteadofotherinits

{V,

verbose,giveinformativemessages

{vVimode,startExinNormalmode

{wscriptout,

writetypedcharsto�lescriptout(append)

{W

scriptout,

writetypedcharsto�lescriptout(overwrite)

{xuseencryptiontoread/write�les.Willpromptforakey,whichisthenstoredinthe

keyoption.

{

read�lefromstdin

7.2

Editinga�le

:e[dit]editthecurrent�le,unlesschangeshavebeenmade

:e[dit]!editthecurrent�lealways.Discardanychanges

:e[dit]�le

edit�le,unlesschangeshavebeenmade

:e[dit]!�le

edit�lealways.Discardanychanges

:ex[+cmd][�le]sameas:edit,butalsoswitchtoExmode.

:�n[d][!][+cmd][�le],

Find�lein\$path"andthen:editit.notinVi

:vi[sual][!][+cmd][�le]whenenteredinExmode:LeaveExmode,gobacktoNormal

mode.

:vie[w][+cmd]�le

whenenteredinExmode:LeaveExmode,gobacktoNormalmode.

Page 26: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

26

VIM

5.6ReferenceGuide

[n]CTRL-b

editalternate�len(equivalentto:en)

gfor]feditthe�lewhosenameisunderthecursor

:pwd

printthecurrentdirectoryname

:cd[path]changethecurrentdirectorytopath

:cd-backtopreviouscurrentdirectory.

:f[ile]printthecurrent�lenameandthecursorposition

:f[ile]name

setthecurrent�lenametoname

:�lesshowalternate�lenames

7.3

Usingtheargumentlist

:ar[gs]printtheargumentlist,withthecurrent�lein[]

:allor:sallopenawindowforevery�leinthearglist

:wn[ext][!]write�leandeditnext�le

:wn[ext][!]�le

writeto�leandeditnext�le,unless�leexists.With!,overwriteexisting

�le

:wN[ext][!]�le

write�leandeditprevious�le

incurrentwindow:

innewwindow:

description

:argu[ment][n]

:sar[gument]n

edit�len

:n[ext]

:sn[ext]

editnext�le

:n[ext]arglist

:sn[ext]arglist

de�nenewarglistandedit�rst�le

:N[ext]

:sN[ext]

editprevious�le

:rew[ind][!]

:srew[ind]

edit�rst�le

:last

:slast

editlast�le

7.4

Writingandquitting

:[range]w[rite][!]writetothecurrent�le

:[range]w[rite]�le

writeto�le,unlessitalreadyexists

:[range]w[rite]!�le

writeto�le.Overwriteanexisting�le

:[range]w[rite][!]>

>

appendtothecurrent�le

:[range]w[rite][!]>

>

�le

appendto�le

:[range]w[rite]!cmd

executecmdwithrangelinesasstandardinput

:[range]up[date][!]writetocurrent�leifmodi�ed

:wall[!]writeallchangedbu�ers

:q[uit]quitcurrentbu�er,unlesschangeshavebeenmade.ExitVIM

whenthereareno

othernon-helpbu�ers

:q[uit]!quitcurrentbu�eralways,discardanychanges.ExitVIM

whentherearenoother

non-helpbu�ers

:conf[irm]qa[ll]exitVim.Bringupapromptwhensomebu�ershavebeenchanged.

:qa[ll]exitVIM

,unlesschangeshavebeenmade

:qa[ll]!exitVIM

always,discardanychanges

:cq

quitwithoutwritingandreturnerrorcode

:wq[!]writethecurrent�leandexit

:wq[!]�le

writeto�leandexit

:x[it][!]�le

like:wqbutwriteonlywhenchangeshavebeenmade

ZZ

sameas:x

ZQ

sameas:q!

:conf[irm]wqa[ll]or:conf[irm]xa[ll]writeallchangedbu�ersandexitVim.Bringupa

promptwhensomebu�ersarereadonlyorcannotbewrittenforanotherreason.

:xa[ll][!]or:wqa[ll][!]writeallchangedbu�ersandexit

9

SCRIPTLANGUAGE

35

Feature

Description

langmap

langmapsupport.

linebreak

linebreak,breakatandshowbreak

support.lispindent

supportforlispindenting.

mac

MacintoshversionofVIM

.

menu

supportfor:menu.

mksession

supportfor:mksession.

modifyfname

�lenamemodi�ers.

mouse

supportmouse.

mousedec

supportforDecterminalmouse.

mousegpm

supportforgpm(Linuxconsolemouse)

mousenetterm

supportfornettermmouse.

mousexterm

supportforxtermmouse.

multibyte

supportforKoreanetal.

multibyteime

supportforIMEinputmethod

ole

OLEautomationsupportforWin32.

os2

OS/2versionofVim.

os�letype

supportforos�letypes.

perl

Perlinterface.

python

Pythoninterface.

quick�x

quick�xsupport.

rightleft

rightleftsupport.

scrollbind

scrollbindsupport.

smartindent

smartindentsupport.

sni�

SniFFinterfacesupport.

statusline

supportforstatusline,rulerformatandspecialformatsofti-

tlestringandiconstring.

syntax

syntaxhighlightingsupport.

syntaxitems

Thereareactivesyntaxhighlightingitemsforthecurrentbu�er.

system

Compiledtousesystem()insteadoffork()/exec().

tagbinary

binarysearchingintags�les.

tagoldstatic

supportforoldstatictags.

taganywhite

supportforanywhitecharactersintags�les.

tcl

Tclinterface.

terminfo

terminfoinsteadoftermcap.

textobjects

supportfortext-objects.

tgetent

tgetentsupport,abletouseatermcaporterminfo�le.

title

windowtitlesupporttitle.

unix

UnixversionofVIM

.

user-commands

User-de�nedcommands.

viminfo

viminfosupport.

vimstarting

Truewhileinitialsource'ingtakesplace.

visualextra

extraVisualmodecommands.

vms

VMSversionofVim.

wildignore

wildignoreoption.

win32

Win32versionofVIM

(Windows95/NT).

wildmenu

wildmenuoption.

wildignore

wildignoreoption.

winaltkeys

winaltkeysoption.

win16

Win16versionofVim(Windows3.1).

win32

Win32versionofVim(Windows95/NT).

writebackup

writebackupdefaulton.

xim

Xinputmethodsupport.

Page 27: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

34

VIM

5.6ReferenceGuide

windown.Whenniszero,thenumberofthebu�erinthecurrentwindowisreturned.

Whenwindowndoesn'texist,-1isreturned.

winheight(n)TheresultisaNumber,whichistheheightofwindownr.Whenniszero,the

heightofthecurrentwindowisreturned.Whenwindowndoesn'texist,-1isreturned.

Anexistingwindowalwayshasaheightofzeroormore.

winnr()TheresultisaNumber,whichisthenumberofthecurrentwindow.Thetop

windowhasnumber1.

Feature-list:

Feature

Description

allbuiltinterms

allbuiltinterminalsenabled.

amiga

AmigaversionofVIM

.

arp

ARPsupport(Amiga).

autocmd

autocommandssupport.

beos

BeOSversionofVIM

.

browse

:browsesupport,andbrowse()willwork.

builtinterms

somebuiltinterminals.

byteo�set

supportfor\o"instatusline

cindent

cindentsupport.

clipboard

clipboardsupport.

cmdlinecompl

cmdline-completionsupport.

cmdlineinfo

showcmdandrulersupport.

comments

commentssupport.

cryptv

encryptionsupportencryption.

cscope

:cscopesupport.

compatible

CompiledtobeveryVicompatible.

debug

DEBUGde�ned.

dialogcon

consoledialogsupport.

dialoggui

GUIdialogsupport.

digraphs

supportfordigraphs.

dos32

32bitsDOS(DJGPP)versionofVIM

.

dos16

16bitsDOSversionofVIM

.

emacs-tags

supportforEmacstags.

eval

expressionevaluationsupport.

exextra

extraExcommands.

extrasearch

supportforincsearchandhlsearch

farsi

Farsisupport(farsi).

�leinpath

supportforgfand<cfile>

�ndinpath

supportforinclude�lesearches

fnamecase

Casein�lenamesmatters(Unixonly).

fork

Compiledtousefork()/exec()insteadofsystem().

gui

GUIenabled.

guiathena

AthenaGUI.

guibeos

BeOsGUI.

guigtk

GTK+GUI.

guimac

MacintoshGUI.

guimotif

MotifGUI.

guiwin32

MSWindowsWin32GUI.

guiwin32s

ibid,andWin32ssystembeingused(Windows3.1)

guirunning

VIM

isrunningintheGUI,oritwillstartsoon.

hangulinput

Hangulinputsupport.

insertexpand

supportforCTRL-XexpansioncommandsinInsertmode.

8

WINDOWSANDBUFFERSFUNCTIONS

27

:st[op][!]suspendVIM

orstartnewshell.Ifawoptionissetand[!]notgivenwritethe

bu�er

CTRL-Z

sameas:stop!

8

W

indowsandBu�ersfunctions

8.1

Multi-windowfunctions,

CTRL-W

sor:splitsplitwindowintotwoparts

:[n]sp[lit]ornew[+cmd]�le

splitwindowandedit�leinoneofthem.Executethe

command+cmdwhenthe�lehasbeenloaded.Makenewwindownhigh.

:[n]sv[iew][+cmd]�le

Sameas:split,butsetreadonlyoptionforthisbu�er.

:[n]sf[ind][+cmd]�le

Sameas:split,butsearchfor�lein\$path".Doesn'tsplitif�le

isnotfound.

CTRL-W

]splitwindowandjumptotagundercursor

:pta[g][!][tagname]Does:tag[!][tagname]andshowsthefoundtagina\Preview"

windowwithoutchangingthecurrentbu�erorcursorposition.Ifa\Preview"window

alreadyexists,itisre-used(likeahelpwindowis).Ifanewoneisopened,previewheight

isusedfortheheightofthewindow.

CTRL-W

zor:pc[lose][!]Closeany\Preview"windowscurrentlyopen.Whenthehidden

optionisset,orwhenthebu�erwaschangedandthe[!]isused,thebu�erbecomes

hidden(unlessthereisanotherwindoweditingit).Thecommandfailsifany\Preview"

bu�ercannotbeclosed.

:[n]pp[op][!]Does:[n]pop[!]inthepreviewwindow.

CTRL-W

g

Useidenti�erundercursorasatagandperforma:ptagonit.Makethenew

\Preview"window(ifrequired)Nhigh.IfNisnotgiven,previewheightisused.

CTRL-W

gg

Useidenti�erundercursorasatagandperforma:ptjumponit.Makethe

newPreviewwindow(ifrequired)Nhigh.IfNisnotgiven,previewheightisused.

CTRL-W

g]splitcurrentwindowintwo.Useidenti�erundercursorasatagandperform

:tselectonitinthenewupperwindow.MakenewwindowNhigh.

CTRL-W

gCTRL-]

splitcurrentwindowintwo.Useidenti�erundercursorasatagand

perform:tjumponitinthenewupperwindow.MakenewwindowNhigh.

CTRL-W

fsplitwindowandedit�lenameunderthecursor

CTRL-W

CTRL-b

splitwindowandeditalternate�le

CTRL-W

nor:new

createnewemptywindow

CTRL-W

qor:q[uit]quiteditingandclosewindow

CTRL-W

cor:cl[ose]makebu�erhiddenandclosewindow

CTRL-W

oor:on[ly][!]makecurrentwindowonlyoneonthescreen

CTRL-W

jmovecursortowindowbelow

CTRL-W

k

movecursortowindowabove

CTRL-W

CTRL-W

movecursortowindowbelow(wrap)

CTRL-W

W

movecursortowindowabove(wrap)

CTRL-W

tmovecursortotopwindow

CTRL-W

b

movecursortobottomwindow

CTRL-W

p

movecursortopreviousactivewindow

CTRL-W

rrotatewindowsdownwards

CTRL-W

R

rotatewindowsupwards

CTRL-W

x

exchangecurrentwindowwithnextone

CTRL-W

=

makeallwindowsequalheight

CTRL-W

{

decreasecurrentwindowheight

CTRL-W

+or:res[ize]+n

increasecurrentwindowheight[byn]

CTRL-W

setcurrentwindowheight(default:veryhigh)

Page 28: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

28

VIM

5.6ReferenceGuide

8.2

Bu�erlistfunctions

:bu�ersor:�leslistallknownbu�erand�lenames

:ballor:sballeditallargs/bu�ers

:unhideor:sunhide

editallloadedbu�ers

:bad[d][+lnum]fname

add�lenamefnametothelist,withoutloadingit.Iflnumis

speci�ed,thecursorwillbepositionedatthatlinewhenthebu�eris�rstentered.

:bunload[!][n]unloadbu�ernfrommemory

:bd[elete][!][n]or:[n]bd[delete]unloadbu�ernanddeleteitfromthebu�erlist

incurrentwindow:

innewwindow:

description

:[n]bu�er[n]

:[n]sbu�er[n]

toarg/bufn

:[n]bnext[n]

:[n]sbnext[n]

ton-thnextarg/buf

:[n]bNext[n]

:[n]sbNext[n]

ton-thpreviousarg/buf

:[n]bprevious[n]

:[n]sbprevious[n]

ton-thpreviousarg/buf

:brewind

:sbrewind

to�rstarg/buf

:blast

:sblast

tolastarg/buf

:[n]bmod[n]

:[n]sbmod[n]

ton-thmodi�edbuf

9

ScriptLanguage,

9.1

Variables

VIM

supportstwotypesofvariables:Number{a32bitsignednumberandString{a

NULLterminatedstringof8-bitunsignedcharacters.Theyareconvertedautomatically,

dependingonhowtheyareused.ForbooleanoperatorsNumbersareused.ZeroisFALSE,

non-zeroisTRUE.

AVIM

variablenamecanbemadeupofletters,digitsandunderscore(\"),butit

cannotstartwithadigit.Aninternalvariableiscreatedwiththe:letanddestroyedwith

the:unletcommand.Avariablenamethatisprecededwithb:andw:islocaltothecurrent

bu�erandwindow,respectively.Insidefunctionsglobalvariablesareaccessedwithg:.

Built-invariables

v:countThecountgivenforthelastNormalmodecommand.Canbeusedtogetthecount

beforeamapping.Read-only.

v:count1

Justlike\v:count",butdefaultstoonewhennocountisused.

v:errmsg

Lastgivenerrormessage.Thisvariablemaybeset.

v:warningmsg

Lastgivenwarningmessage.It'sallowedtosetthisvariable.

v:statusmsg

Lastgivenstatusmessage.It'sallowedtosetthisvariable.

v:shellerrorResultofthelastshellcommand.Whennon-zero,thelastshellcommand

hadanerror.Whenzero,therewasnoproblem.

v:thissession

Full�lenameofthelastloadedorsavedsession�le.See:mksession.

v:version

VersionnumberofVIM

.Majorversionnumbertimes100plusminorversion

number.Version5.01is501.Read-only.

9.2

Expressionsyntax

Operators:8

8numberedinorderofincreasingprecedence

9

SCRIPTLANGUAGE

33

nr2char(expr)ReturnastringconsistingofasinglecharacterwiththeASCIIvalueexpr.

rename(from,to)

Renamethe�lebythenamefromtothenameto.Thisshouldalso

worktomove�lesacross�lesystems.TheresultisaNumber,whichis0ifthe�lewas

renamedsuccessfully,andnon-zerowhentherenamingfailed.

setline(lnum,line)Setlinelnum

ofthecurrentbu�ertoline.Ifthissucceeds,0is

returned.Ifthisfails(mostlikelylnumisinvalid)1isreturned.

strftime(format[,time])TheresultisaString,whichisthecurrentdateandtime,as

speci�edbytheformatstring.SeethemanualpageoftheCfunctionstrftime()for

theformat.Themaximumlengthoftheresultis80characters.

strlen(expr)TheresultisaNumber,whichisthelengthoftheStringexpr.

strpart(src,start,len)TheresultisaString,whichispartofsrc,startingfromchar-

acterstart,withthelengthlen.Whencharactersbeyondthelengthofthestringare

implied,thisdoesn'tresultinanerror,thecharactersaresimplyomitted.

strtrans(expr)TheresultisaString,whichisexprwithallunprintablecharacterstrans-

latedintoprintablecharacters.

substitute(expr,pat,sub, ags)TheresultisaString,whichisacopyofexpr,inwhich

the�rstmatchofpatisreplacedwithsub.Thisworkslikethe:substitutecommand

(withoutany ags).Butthemagicoptionisignored,thepatisalwaysprocessedasif

magicisset.Whenpatdoesnotmatchinexpr,exprisreturnedunmodi�ed.When

agsisg,allmatchesofpatinexprarereplaced.Otherwise agsshouldbe"".

synID(line,col,trans)TheresultisaNumber,whichisthesyntaxIDattheposition

lineandcolinthecurrentwindow.ThesyntaxIDcanbeusedwithsynIDattr()and

synIDtrans()toobtainsyntaxinformationabouttext.colis1fortheleftmostcolumn,

lineis1forthe�rstline.

Whentransisnon-zero,transparentitemsarereducedtotheitem

thattheyre-

veal.Thisisusefulwhenwantingtoknowthee�ectivecolor.Whentransiszero,

thetransparentitemisreturned.Thisisusefulwhenwantingtoknowwhichsyntax

itemise�ective(e.g.insideparentheses).

synIDattr(synID,what)[,mode]TheresultisaString,whichisthewhatattributeof

syntaxIDsynID.Thiscanbeusedtoobtaininformationaboutasyntaxitem.mode

canbegui,ctermorterm,togettheattributesforthatmode.

synIDtrans(synID)TheresultisaNumber,whichisthetranslatedsyntaxIDofsynID.

ThisisthesyntaxgroupIDofwhatisbeingusedtohighlightthecharacter.Highlight

linksarefollowed.

system(expr)Gettheoutputoftheshellcommandexpr.Note:newlinesinexprmay

causethecommandtofail.Thisisnottobeusedforinteractivecommands.Theresult

isaString.Tomaketheresultmoresystem-independent,theshelloutputis�lteredto

replacehCRiwithhNLiforMacintosh,andhCRihNLiwithhNLiforDOS-likesystems.

tempname()TheresultisaString,whichisthenameofa�lethatdoesn'texist.Itcan

beusedforatemporary�le.Thenameisdi�erentforeachleast26consecutivecalls.a

unique�le.

visualmode()TheresultisaString,whichdescribesthelastVisualmodeused.Initially

itreturnsanemptystring,butonceVisualmodehasbeenused,itreturns\v",\V",

or\CTRL-V"(asingleCTRL-Vcharacter)forcharacter-wise,line-wise,orblock-wise

Visualmoderespecively.

virtcol(expr)TheresultisaNumber,whichisthescreencolumnofthe�lepositiongiven

byexpr.Thecolumnnumberisreturnasifthescreenwereofin�nitewidth.Ifthere

isahTabiatthatposition,thereturnedNumberisthelastcolumnoccupiedbythe

hTabi.Forexample,forahTabiincolumn1,withtssetto8,itreturns8;Theaccepted

positionsare:

.

thecursorposition

'x

positionofmark\x"(ifthemarkisnotset,0isreturned)

Onlymarksinthecurrent�lecanbeused.

winbufnr(n)TheresultisaNumber,whichisthenumberofthebu�erassociatedwith

Page 29: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

32

VIM

5.6ReferenceGuide

histget(history[,index])TheresultisaString,theentrywithNumberindexfromhis-

tory.Seehist-namesforthepossiblevaluesofhistory,and:history-indexingforindex.If

thereisnosuchentry,anemptyStringisreturned.Whenindexisomitted,themost

recentitemfromthehistoryisused.

histnr(history)TheresultistheNumberofthecurrententryinhistory.Seehist-names

forthepossiblevaluesofhistory.Ifanerroroccurred,-1isreturned.

hlexists(name)TheresultisaNumber,whichisnon-zeroifahighlightgroupcalledname

exists.Thegroupmayhavebeende�nedasahighlightgrouporasasyntaxitemor

both.Notnecessarilywhenhighlightinghasbeende�nedforit,itmayalsohavebeen

usedforasyntaxitem.

hlID(name)TheresultisaNumber,whichistheIDofthehighlightgroupwithname

name.Whenthehighlightgroupdoesn'texist,zeroisreturned.

input(prompt)TheresultisaString,whichiswhatevertheusertypedonthecommand-

line.Theparameteriseitherapromptstring,orablankstring(fornoprompt).A

ncanbeusedintheprompttostartanewline.

isdirectory(directory)TheresultisaNumber,whichisTRUEwhenadirectorywiththe

namedirectoryexists.Ifdirectorydoesn'texist,orisn'tadirectory,theresultisFALSE.

directoryisanyexpressionusedasaString.

libcall(libname,funcname,argument)

Callfunctionfuncnameintherun-timelibrary

libnamewithargumentargument.TheresultistheStringreturned.Ifargumentis

anumber,itispassedtothefunctionasanint;ifparamisastring,itispassedas

anull-terminatedstring.IfthefunctionreturnsNULL,thiswillappearasanempty

stringtoVim.WARNING:Ifthefunctionreturnsanon-validpointer,Vimwillcrash!

Thisalsohappensifthefunctionreturnsanumber.ForWin32systems,libnameshould

bethe�lenameoftheDLLwithoutthe\.dll"suÆx.Afullpathisonlyrequiredifthe

DLLisnotintheusualplaces.

line(expr)TheresultisaNumber,whichisthelinenumberofthe�lepositiongivenwith

expr.Theacceptedpositionsare:

.

thecursorposition

$

thelastlineinthecurrentbu�er

'x

positionofmark\x"(ifthemarkisnotset,0isreturned)

Onlymarksinthecurrent�lecanbeused.

line2byte(lnum)Returnthebytecountfromthestartofthebu�erforlinelnum.This

includestheend-of-linecharacter,dependingonthe'�leformat'optionforthecurrent

bu�er.The�rstlinereturns1.Whenlnumisinvalid-1isreturned.

localtime()Returnthecurrenttime,measuredassecondssince1stJan1970.

maparg(name[,mode])Returntherhsofmappingnameinmodemode.Whenthereis

nomappingforname,anemptyStringisreturned.Thesecharacterscanbeusedfor

mode:

\n"

Normal

\v"

Visual

\o"

Operator-pending

\i"

Insert

\c"

Cmd-line

""

Normal,VisualandOperator-pending

Whenmodeisomitted,themodesfrom""areused.Thenamecanhavespecialkey

names,likeinthe\:map"command.ThereturnedStringhasspecialcharacterstrans-

latedlikeintheoutputofthe\:map"commandlisting.

mapcheck(name[,mode])Checkifthereisamappingthatmatcheswithnameinmode

mode.Whenthereisnomappingthatmatcheswithname,andemptyStringisreturned.

Ifthereisone,therhsofthatmappingisreturned.Ifthereareseveralmatches,the

rhsofoneofthemisreturned.Thisfunctioncanbeusedtocheckifamappingcanbe

addedwithoutbeingambiguous.

match(expr,pat)TheresultisaNumber,whichgivestheindexinexprwherepatmatches.

Ifthereisnomatch,-1isreturned.Seepatternforthepatternsthatareaccepted.

matchend(expr,pat)Sameasmatch(),butreturntheindexof�rstcharacterafterthe

match.

matchstr(expr,pat)Sameasmatch(),butreturnthematchedstring.

9

SCRIPTLANGUAGE

29

#

Operator

Description

#

Operator

Description

1

jj[...]9

logicalOR

9

=�

regexpmatches

2

&&[...]

logicalAND

10

!�

regexpdoesn'tmatch

3

==

equal

11

+[...]

numberaddition

4

!=

notequal

12

{[...]

numbersubtraction

5

>

greaterthan

13

.[...]

stringconcatenation

6

>

=

greaterthanorequal

14

*[...]

numbermultiplication

7

<

smallerthan

15

/[...]

numberdivision

8

<

=

smallerthanorequal

16

%[...]

numbermodulo

17

!expr

logicalNOT

18

{expr

unaryminus

Description:

-Allexpressionswithinonelevelareparsedfromlefttoright.

-Comparisonoperatorscanbeappendedwith#{to\matchcase"or?{to\ignore

case"ofcomparedexpressions.

-Theargumentsof*,+,{,%,/,jjand&&operationsare(convertedto)Numbers.

WhencomparingaStringwithaNumber,theStringisconvertedtoaNumber,and

thecomparisonisdoneonNumbers.

-ComparingtwoStringsisdonewithstrcmp().Thisresultsinthemathematical

di�erence,notnecessarilythealphabeticaldi�erenceinthelocallanguage.

-The=�and!�operatorsmatchthelefthandargumentwiththerighthandargument,

whichisusedasapattern.Thismatchingisalwaysdonelikemagicwasset,nomatter

whattheactualvalueofmagicis.Thevalueofignorecasedoesmatterthough.To

avoidbackslashesintheregexppatterntobedoubled,useasingle-quotestring.

Operands:

Operand

Description

Operand

Description

expr1[expr2]

indexinString

number

numberconstant

"string"

stringconstant

'string'

literalstringconstant

&option

optionvalue

(expr1)

nestedexpression

variable

internalvariable

$VAR

environmentvariable

@r

contentsofregister\r"

function(expr1,...)

functioncall

Description:

expr1[expr2]ThisresultsinaStringthatcontainstheexpr2'thsinglecharacterfrom

expr1.expr1isusedasaString,expr2asaNumber.Theindexstartswith0(likein

C).

Careful:columnnumbersstartwithone!

IfthelengthoftheStringislessthantheindex,theresultisanemptyString.

"string"

Astringconstantmaycontainthesespecialcharacters:

Character

Description

Character

Description

n...

3-digitoctalnumber

n..

2-digitoctalnumber

10

9[...]indicatesthattheoperationsinthislevelcanbeconcatenated.

10mustbefollowedbynon-digit

Page 30: Bram Moolenaar &OlegRaiskydatabase.sarang.net/study/vim/vimguide-0.7-bkl.a4.pdfCommands 48 12.1 De ning auto commands 12.2 Remo ving auto commands 12.3 Listing auto commands 12.4 Ev

30

VIM

5.6ReferenceGuide

Character

Description

Character

Description

n.

1-digitoctalnumber11

nx..

2-characterhexnumber

nx.

1-characterhexnumber12

nX..

sameasnx..

nX.

sameasnx.

nb

backspace

ne

escape

nf

formfeed

nn

newline

nr

return

nt

tab

nn

backslash

n"

doublequote

n<xxx>

Specialkeyname\xxx"

Notethatn000andnx00forcetheendofthestring.

'string'Thisstringistakenliterally.Nobackslashesareremovedorhaveaspecialmean-

ing.Aliteralstringcannotcontainasinglequote.Useanormalstringforthat.

@r

Theresultisthecontentsofthenamedregister,asasinglestring.Newlinesareinserted

whererequired.Togetthecontentsoftheunnamedregisteruse\@@".The\="register

cannotbeusedhere.

9.3

Functions

argc()Theresultisthenumberof�lesintheargumentlist.Seearglist.

argv(n)Theresultisthen-th�leintheargumentlist.

browse(save,title,initdir,default)Putupa�lerequester.Thisonlyworksonlyin

someGUIversions.Theinput�eldsare:

save

whennon-zero,select�letowrite

title

titlefortherequester

initdir

directorytostartbrowsingin

default

default�lename

append(lnum,string)

Appendthetextstringafterlinelnuminthecurrentbu�er.lnum

canbezero,toinsertalinebeforethe�rstone.Returns1forfailure(lnumoutof

range)or0forsuccess.

bufexists(var)TheresultisaNumber,whichisnon-zeroifabu�ercalledvarexists.If

thevarargumentisastring,itmustmatchabu�ernameexactly.Ifthevarargument

isanumber,bu�ernumbersareused.Usebu�erexists(0)totestfortheexistenceofan

alternate�lename.

bu oaded(expr)TheresultisaNumber,whichisnon-zeroifabu�ercalledexprexists

andisloaded(showninawindoworhidden).Theexprargumentisusedlikewith

bufexists().

bufname(expr)Theresultisthenameofabu�er,asitisdisplayedbythe:lscommand.

IfexprisaNumber,thatbu�ernumber'snameisgiven.IfexprisaString,itisused

asaregexppatterntomatchwiththebu�ernames.

bufnr(expr)Theresultisthenumberofabu�er,asitisdisplayedbythe:lscommand.

bufwinnr(expr)TheresultisaNumber,whichisthenumberofthe�rstwindowassociated

withbu�erexpr.Fortheuseofexpr,seebufname()above.Ifbu�erexprdoesn'texist

orthereisnosuchwindow,-1isreturned.

byte2line(byte)Returnthelinenumberthatcontainsthecharacteratbytecountbytein

thecurrentbu�er.Thisincludestheend-of-linecharacter,dependingonthe'�leformat'

optionforthecurrentbu�er.The�rstcharacterhasbytecountone.

char2nr(expr)ReturnASCIIvalueofthe�rstcharinexpr.

col(expr)TheresultisaNumber,whichisthecolumnofthe�lepositiongivenwithexpr.

Theacceptedpositionsare:

.

thecursorposition

'x

positionofmark\x"(ifthemarkisnotset,0isreturned).

Onlymarksinthecurrent�lecanbeused.The�rstcolumnis1.0isreturnedforan

error.

12mustbefollowedbynon-hex

9

SCRIPTLANGUAGE

31

con�rm(msg,choices[,default[,type

])]msgisdisplayedinadialogwithchoicesas

thealternatives.defaultisthenumberofthechoicethatismadeiftheuserhitsCR.

Ifdefaultisomitted,0isused.Theoptionaltypeargumentgivesthetypeofdialog.

delete(fname)Deletesthe�lebythenamefname.TheresultisaNumber,whichis0if

the�lewasdeletedsuccessfully,andnon-zerowhenthedeletionfailed.

did�letype()Returnsnon-zerowhenautocommandsarebeingexecutedandtheFileType

eventhasbeentriggeredatleastonce.CanbeusedtoavoidtriggeringtheFileType

eventagaininthescriptsthatdetectthe�letype.

escape(string,chars)Escapethecharactersincharsthatoccurinstringwithaback-

slash.

exists(expr)TheresultisaNumber,whichis1ifvarisde�ned,zerootherwise.Theexpr

argumentisastring,whichcontainsoneofthese:

&option-name

VIM

option

$ENVNAME

environmentvariable

varname

internalvariable.

expand(expr,[, ag])Expandthe�lewildcardsinexpr.TheresultisaString.When

theresultofexprstartswith%,#or<

,theexpansionisdonelikeforthecmdline-special

variableswiththeirassociatedmodi�ers.Therecannotbeawhitespacebetweenthe

variablesandthefollowingmodi�er.Whenthecurrentoralternate�lenameisnot

de�ned,%or#useanemptystring.Using%:pinabu�erwithnonameresultsinthe

currentdirectory,witha\/"added.

�lereadable(fname)

TheresultisaNumber,whichisTRUEwhena�lewiththename

fnameexists,andcanberead.Iffnamedoesn'texist,orisadirectory,theresultis

FALSE.fnameisanyexpression,whichisusedasaString.

fnamemodify(fname,mods)Modify�lenamefnameaccordingtomods.modsisastring

ofcharacterslikeitisusedfor�lenamesonthecommandline.

getcwd()TheresultisaString,whichisthenameofthecurrentworkingdirectory.

getftime(fname)TheresultisaNumber,whichisthelastmodi�cationtimeofthegiven

�lefname.Thevalueismeasuredassecondssince1stJan1970,andmaybepassedto

strftime().

getline(lnum)TheresultisaString,whichislinelnumfromthecurrentbu�er.

getwinposx()TheresultisaNumber,whichistheXcoordinateinpixelsofthelefthand

sideoftheGUIvimwindow.Theresultwillbe-1iftheinformationisnotavailable.

getwinposy()TheresultisaNumber,whichistheYcoordinateinpixelsofthetopofthe

GUIvimwindow.Theresultwillbe-1iftheinformationisnotavailable.

glob(expr)Expandthe�lewildcardsinexpr.TheresultisaString.Whenthereare

severalmatches,theyareseparatedbyNL

characters.Iftheexpansionfails,theresult

isanemptystring.

has(feature)TheresultisaNumber,whichis1ifthefeatureissupported,zerootherwise.

Thefeatureargumentisastring.SeeFeature-listbelow.

hostname()TheresultisaString,whichisthenameofthemachineonwhichVIM

is

currentlyrunning.Machinenamesgreaterthan256characterslongaretruncated.

histadd(history,item)

AddtheStringitemtothehistoryhistorywhichcanbeoneof:

cmd

or

:

commandlinehistory

search

or

/

searchpatternhistory

expr

or

=

typedexpressionhistory

input

or

@

inputlinehistory

Ifitemdoesalreadyexistinthehistory,itwillbeshiftedtobecomethenewestentry.

TheresultisaNumber:1iftheoperationwassuccessful,otherwise0isreturned.

histdel(history[,item])

Clearhistory,i.e.deleteallitsentries.Iftheparameteritemis

givenasString,thisisseenasregularexpression.Allentriesmatchingthatexpression

willberemovedfromthehistory(ifthereareany).IfitemisaNumber,itwillbe

interpretedasindex.Therespectiveentrywillberemovedifitexists.Theresultisa

Number:1forasuccessfuloperation,otherwise0isreturned.