1*usr_30.txt* For Vim version 7.3. Last change: 2007 Nov 10 2 3 VIM USER MANUAL - by Bram Moolenaar 4 5 Editing programs 6 7 8Vim has various commands that aid in writing computer programs. Compile a 9program and directly jump to reported errors. Automatically set the indent 10for many languages and format comments. 11 12|30.1| Compiling 13|30.2| Indenting C files 14|30.3| Automatic indenting 15|30.4| Other indenting 16|30.5| Tabs and spaces 17|30.6| Formatting comments 18 19 Next chapter: |usr_31.txt| Exploiting the GUI 20 Previous chapter: |usr_29.txt| Moving through programs 21Table of contents: |usr_toc.txt| 22 23============================================================================== 24*30.1* Compiling 25 26Vim has a set of so called "quickfix" commands. They enable you to compile a 27program from within Vim and then go through the errors generated and fix them 28(hopefully). You can then recompile and fix any new errors that are found 29until finally your program compiles without any error. 30 31The following command runs the program "make" (supplying it with any argument 32you give) and captures the results: > 33 34 :make {arguments} 35 36If errors were generated, they are captured and the editor positions you where 37the first error occurred. 38 Take a look at an example ":make" session. (Typical :make sessions generate 39far more errors and fewer stupid ones.) After typing ":make" the screen looks 40like this: 41 42 :!make | &tee /tmp/vim215953.err ~ 43 gcc -g -Wall -o prog main.c sub.c ~ 44 main.c: In function 'main': ~ 45 main.c:6: too many arguments to function 'do_sub' ~ 46 main.c: At top level: ~ 47 main.c:10: parse error before '}' ~ 48 make: *** [prog] Error 1 ~ 49 50 2 returned ~ 51 "main.c" 11L, 111C ~ 52 (3 of 6): too many arguments to function 'do_sub' ~ 53 Press ENTER or type command to continue ~ 54 55From this you can see that you have errors in the file "main.c". When you 56press <Enter>, Vim displays the file "main.c", with the cursor positioned on 57line 6, the first line with an error. You did not need to specify the file or 58the line number, Vim knew where to go by looking in the error messages. 59 60 +---------------------------------------------------+ 61 |int main() | 62 |{ | 63 | int i=3; | 64 cursor -> | do_sub("foo"); | 65 | ++i; | 66 | return (0); | 67 |} | 68 |} | 69 | ~ | 70 |(3 of 12): too many arguments to function 'do_sub' | 71 +---------------------------------------------------+ 72 73The following command goes to where the next error occurs: > 74 75 :cnext 76 77Vim jumps to line 10, the last line in the file, where there is an extra '}'. 78 When there is not enough room, Vim will shorten the error message. To see 79the whole message use: > 80 81 :cc 82 83You can get an overview of all the error messages with the ":clist" command. 84The output looks like this: > 85 86 :clist 87< 3 main.c: 6:too many arguments to function 'do_sub' ~ 88 5 main.c: 10:parse error before '}' ~ 89 90Only the lines where Vim recognized a file name and line number are listed 91here. It assumes those are the interesting lines and the rest is just boring 92messages. However, sometimes unrecognized lines do contain something you want 93to see. Output from the linker, for example, about an undefined function. 94To see all the messages add a "!" to the command: > 95 96 :clist! 97< 1 gcc -g -Wall -o prog main.c sub.c ~ 98 2 main.c: In function 'main': ~ 99 3 main.c:6: too many arguments to function 'do_sub' ~ 100 4 main.c: At top level: ~ 101 5 main.c:10: parse error before '}' ~ 102 6 make: *** [prog] Error 1 ~ 103 104Vim will highlight the current error. To go back to the previous error, use: 105> 106 :cprevious 107 108Other commands to move around in the error list: 109 110 :cfirst to first error 111 :clast to last error 112 :cc 3 to error nr 3 113 114 115USING ANOTHER COMPILER 116 117The name of the program to run when the ":make" command is executed is defined 118by the 'makeprg' option. Usually this is set to "make", but Visual C++ users 119should set this to "nmake" by executing the following command: > 120 121 :set makeprg=nmake 122 123You can also include arguments in this option. Special characters need to 124be escaped with a backslash. Example: > 125 126 :set makeprg=nmake\ -f\ project.mak 127 128You can include special Vim keywords in the command specification. The % 129character expands to the name of the current file. So if you execute the 130command: > 131 :set makeprg=make\ % 132 133When you are editing main.c, then ":make" executes the following command: > 134 135 make main.c 136 137This is not too useful, so you will refine the command a little and use the :r 138(root) modifier: > 139 140 :set makeprg=make\ %:r.o 141 142Now the command executed is as follows: > 143 144 make main.o 145 146More about these modifiers here: |filename-modifiers|. 147 148 149OLD ERROR LISTS 150 151Suppose you ":make" a program. There is a warning message in one file and an 152error message in another. You fix the error and use ":make" again to check if 153it was really fixed. Now you want to look at the warning message. It doesn't 154show up in the last error list, since the file with the warning wasn't 155compiled again. You can go back to the previous error list with: > 156 157 :colder 158 159Then use ":clist" and ":cc {nr}" to jump to the place with the warning. 160 To go forward to the next error list: > 161 162 :cnewer 163 164Vim remembers ten error lists. 165 166 167SWITCHING COMPILERS 168 169You have to tell Vim what format the error messages are that your compiler 170produces. This is done with the 'errorformat' option. The syntax of this 171option is quite complicated and it can be made to fit almost any compiler. 172You can find the explanation here: |errorformat|. 173 174You might be using various different compilers. Setting the 'makeprg' option, 175and especially the 'errorformat' each time is not easy. Vim offers a simple 176method for this. For example, to switch to using the Microsoft Visual C++ 177compiler: > 178 179 :compiler msvc 180 181This will find the Vim script for the "msvc" compiler and set the appropriate 182options. 183 You can write your own compiler files. See |write-compiler-plugin|. 184 185 186OUTPUT REDIRECTION 187 188The ":make" command redirects the output of the executed program to an error 189file. How this works depends on various things, such as the 'shell'. If your 190":make" command doesn't capture the output, check the 'makeef' and 191'shellpipe' options. The 'shellquote' and 'shellxquote' options might also 192matter. 193 194In case you can't get ":make" to redirect the file for you, an alternative is 195to compile the program in another window and redirect the output into a file. 196Then have Vim read this file with: > 197 198 :cfile {filename} 199 200Jumping to errors will work like with the ":make" command. 201 202============================================================================== 203*30.2* Indenting C style text 204 205A program is much easier to understand when the lines have been properly 206indented. Vim offers various ways to make this less work. For C or C style 207programs like Java or C++, set the 'cindent' option. Vim knows a lot about C 208programs and will try very hard to automatically set the indent for you. Set 209the 'shiftwidth' option to the amount of spaces you want for a deeper level. 210Four spaces will work fine. One ":set" command will do it: > 211 212 :set cindent shiftwidth=4 213 214With this option enabled, when you type something such as "if (x)", the next 215line will automatically be indented an additional level. 216 217 if (flag) 218 Automatic indent ---> do_the_work(); 219 Automatic unindent <-- if (other_flag) { 220 Automatic indent ---> do_file(); 221 keep indent do_some_more(); 222 Automatic unindent <-- } 223 224When you type something in curly braces ({}), the text will be indented at the 225start and unindented at the end. The unindenting will happen after typing the 226'}', since Vim can't guess what you are going to type. 227 228One side effect of automatic indentation is that it helps you catch errors in 229your code early. When you type a } to finish a function, only to find that 230the automatic indentation gives it more indent than what you expected, there 231is probably a } missing. Use the "%" command to find out which { matches the 232} you typed. 233 A missing ) and ; also cause extra indent. Thus if you get more white 234space than you would expect, check the preceding lines. 235 236When you have code that is badly formatted, or you inserted and deleted lines, 237you need to re-indent the lines. The "=" operator does this. The simplest 238form is: > 239 240 == 241 242This indents the current line. Like with all operators, there are three ways 243to use it. In Visual mode "=" indents the selected lines. A useful text 244object is "a{". This selects the current {} block. Thus, to re-indent the 245code block the cursor is in: > 246 247 =a{ 248 249I you have really badly indented code, you can re-indent the whole file with: 250> 251 gg=G 252 253However, don't do this in files that have been carefully indented manually. 254The automatic indenting does a good job, but in some situations you might want 255to overrule it. 256 257 258SETTING INDENT STYLE 259 260Different people have different styles of indentation. By default Vim does a 261pretty good job of indenting in a way that 90% of programmers do. There are 262different styles, however; so if you want to, you can customize the 263indentation style with the 'cinoptions' option. 264 By default 'cinoptions' is empty and Vim uses the default style. You can 265add various items where you want something different. For example, to make 266curly braces be placed like this: 267 268 if (flag) ~ 269 { ~ 270 i = 8; ~ 271 j = 0; ~ 272 } ~ 273 274Use this command: > 275 276 :set cinoptions+={2 277 278There are many of these items. See |cinoptions-values|. 279 280============================================================================== 281*30.3* Automatic indenting 282 283You don't want to switch on the 'cindent' option manually every time you edit 284a C file. This is how you make it work automatically: > 285 286 :filetype indent on 287 288Actually, this does a lot more than switching on 'cindent' for C files. First 289of all, it enables detecting the type of a file. That's the same as what is 290used for syntax highlighting. 291 When the filetype is known, Vim will search for an indent file for this 292type of file. The Vim distribution includes a number of these for various 293programming languages. This indent file will then prepare for automatic 294indenting specifically for this file. 295 296If you don't like the automatic indenting, you can switch it off again: > 297 298 :filetype indent off 299 300If you don't like the indenting for one specific type of file, this is how you 301avoid it. Create a file with just this one line: > 302 303 :let b:did_indent = 1 304 305Now you need to write this in a file with a specific name: 306 307 {directory}/indent/{filetype}.vim 308 309The {filetype} is the name of the file type, such as "cpp" or "java". You can 310see the exact name that Vim detected with this command: > 311 312 :set filetype 313 314In this file the output is: 315 316 filetype=help ~ 317 318Thus you would use "help" for {filetype}. 319 For the {directory} part you need to use your runtime directory. Look at 320the output of this command: > 321 322 set runtimepath 323 324Now use the first item, the name before the first comma. Thus if the output 325looks like this: 326 327 runtimepath=~/.vim,/usr/local/share/vim/vim60/runtime,~/.vim/after ~ 328 329You use "~/.vim" for {directory}. Then the resulting file name is: 330 331 ~/.vim/indent/help.vim ~ 332 333Instead of switching the indenting off, you could write your own indent file. 334How to do that is explained here: |indent-expression|. 335 336============================================================================== 337*30.4* Other indenting 338 339The most simple form of automatic indenting is with the 'autoindent' option. 340It uses the indent from the previous line. A bit smarter is the 'smartindent' 341option. This is useful for languages where no indent file is available. 342'smartindent' is not as smart as 'cindent', but smarter than 'autoindent'. 343 With 'smartindent' set, an extra level of indentation is added for each { 344and removed for each }. An extra level of indentation will also be added for 345any of the words in the 'cinwords' option. Lines that begin with # are 346treated specially: all indentation is removed. This is done so that 347preprocessor directives will all start in column 1. The indentation is 348restored for the next line. 349 350 351CORRECTING INDENTS 352 353When you are using 'autoindent' or 'smartindent' to get the indent of the 354previous line, there will be many times when you need to add or remove one 355'shiftwidth' worth of indent. A quick way to do this is using the CTRL-D and 356CTRL-T commands in Insert mode. 357 For example, you are typing a shell script that is supposed to look like 358this: 359 360 if test -n a; then ~ 361 echo a ~ 362 echo "-------" ~ 363 fi ~ 364 365Start off by setting these options: > 366 367 :set autoindent shiftwidth=3 368 369You start by typing the first line, <Enter> and the start of the second line: 370 371 if test -n a; then ~ 372 echo ~ 373 374Now you see that you need an extra indent. Type CTRL-T. The result: 375 376 if test -n a; then ~ 377 echo ~ 378 379The CTRL-T command, in Insert mode, adds one 'shiftwidth' to the indent, no 380matter where in the line you are. 381 You continue typing the second line, <Enter> and the third line. This time 382the indent is OK. Then <Enter> and the last line. Now you have this: 383 384 if test -n a; then ~ 385 echo a ~ 386 echo "-------" ~ 387 fi ~ 388 389To remove the superfluous indent in the last line press CTRL-D. This deletes 390one 'shiftwidth' worth of indent, no matter where you are in the line. 391 When you are in Normal mode, you can use the ">>" and "<<" commands to 392shift lines. ">" and "<" are operators, thus you have the usual three ways to 393specify the lines you want to indent. A useful combination is: > 394 395 >i{ 396 397This adds one indent to the current block of lines, inside {}. The { and } 398lines themselves are left unmodified. ">a{" includes them. In this example 399the cursor is on "printf": 400 401 original text after ">i{" after ">a{" 402 403 if (flag) if (flag) if (flag) ~ 404 { { { ~ 405 printf("yes"); printf("yes"); printf("yes"); ~ 406 flag = 0; flag = 0; flag = 0; ~ 407 } } } ~ 408 409============================================================================== 410*30.5* Tabs and spaces 411 412'tabstop' is set to eight by default. Although you can change it, you quickly 413run into trouble later. Other programs won't know what tabstop value you 414used. They probably use the default value of eight, and your text suddenly 415looks very different. Also, most printers use a fixed tabstop value of eight. 416Thus it's best to keep 'tabstop' alone. (If you edit a file which was written 417with a different tabstop setting, see |25.3| for how to fix that.) 418 For indenting lines in a program, using a multiple of eight spaces makes 419you quickly run into the right border of the window. Using a single space 420doesn't provide enough visual difference. Many people prefer to use four 421spaces, a good compromise. 422 Since a <Tab> is eight spaces and you want to use an indent of four spaces, 423you can't use a <Tab> character to make your indent. There are two ways to 424handle this: 425 4261. Use a mix of <Tab> and space characters. Since a <Tab> takes the place of 427 eight spaces, you have fewer characters in your file. Inserting a <Tab> 428 is quicker than eight spaces. Backspacing works faster as well. 429 4302. Use spaces only. This avoids the trouble with programs that use a 431 different tabstop value. 432 433Fortunately, Vim supports both methods quite well. 434 435 436SPACES AND TABS 437 438If you are using a combination of tabs and spaces, you just edit normally. 439The Vim defaults do a fine job of handling things. 440 You can make life a little easier by setting the 'softtabstop' option. 441This option tells Vim to make the <Tab> key look and feel as if tabs were set 442at the value of 'softtabstop', but actually use a combination of tabs and 443spaces. 444 After you execute the following command, every time you press the <Tab> key 445the cursor moves to the next 4-column boundary: > 446 447 :set softtabstop=4 448 449When you start in the first column and press <Tab>, you get 4 spaces inserted 450in your text. The second time, Vim takes out the 4 spaces and puts in a <Tab> 451(thus taking you to column 8). Thus Vim uses as many <Tab>s as possible, and 452then fills up with spaces. 453 When backspacing it works the other way around. A <BS> will always delete 454the amount specified with 'softtabstop'. Then <Tab>s are used as many as 455possible and spaces to fill the gap. 456 The following shows what happens pressing <Tab> a few times, and then using 457<BS>. A "." stands for a space and "------->" for a <Tab>. 458 459 type result ~ 460 <Tab> .... 461 <Tab><Tab> -------> 462 <Tab><Tab><Tab> ------->.... 463 <Tab><Tab><Tab><BS> -------> 464 <Tab><Tab><Tab><BS><BS> .... 465 466An alternative is to use the 'smarttab' option. When it's set, Vim uses 467'shiftwidth' for a <Tab> typed in the indent of a line, and a real <Tab> when 468typed after the first non-blank character. However, <BS> doesn't work like 469with 'softtabstop'. 470 471 472JUST SPACES 473 474If you want absolutely no tabs in your file, you can set the 'expandtab' 475option: > 476 477 :set expandtab 478 479When this option is set, the <Tab> key inserts a series of spaces. Thus you 480get the same amount of white space as if a <Tab> character was inserted, but 481there isn't a real <Tab> character in your file. 482 The backspace key will delete each space by itself. Thus after typing one 483<Tab> you have to press the <BS> key up to eight times to undo it. If you are 484in the indent, pressing CTRL-D will be a lot quicker. 485 486 487CHANGING TABS IN SPACES (AND BACK) 488 489Setting 'expandtab' does not affect any existing tabs. In other words, any 490tabs in the document remain tabs. If you want to convert tabs to spaces, use 491the ":retab" command. Use these commands: > 492 493 :set expandtab 494 :%retab 495 496Now Vim will have changed all indents to use spaces instead of tabs. However, 497all tabs that come after a non-blank character are kept. If you want these to 498be converted as well, add a !: > 499 500 :%retab! 501 502This is a little bit dangerous, because it can also change tabs inside a 503string. To check if these exist, you could use this: > 504 505 /"[^"\t]*\t[^"]*" 506 507It's recommended not to use hard tabs inside a string. Replace them with 508"\t" to avoid trouble. 509 510The other way around works just as well: > 511 512 :set noexpandtab 513 :%retab! 514 515============================================================================== 516*30.6* Formatting comments 517 518One of the great things about Vim is that it understands comments. You can 519ask Vim to format a comment and it will do the right thing. 520 Suppose, for example, that you have the following comment: 521 522 /* ~ 523 * This is a test ~ 524 * of the text formatting. ~ 525 */ ~ 526 527You then ask Vim to format it by positioning the cursor at the start of the 528comment and type: > 529 530 gq]/ 531 532"gq" is the operator to format text. "]/" is the motion that takes you to the 533end of a comment. The result is: 534 535 /* ~ 536 * This is a test of the text formatting. ~ 537 */ ~ 538 539Notice that Vim properly handled the beginning of each line. 540 An alternative is to select the text that is to be formatted in Visual mode 541and type "gq". 542 543To add a new line to the comment, position the cursor on the middle line and 544press "o". The result looks like this: 545 546 /* ~ 547 * This is a test of the text formatting. ~ 548 * ~ 549 */ ~ 550 551Vim has automatically inserted a star and a space for you. Now you can type 552the comment text. When it gets longer than 'textwidth', Vim will break the 553line. Again, the star is inserted automatically: 554 555 /* ~ 556 * This is a test of the text formatting. ~ 557 * Typing a lot of text here will make Vim ~ 558 * break ~ 559 */ ~ 560 561For this to work some flags must be present in 'formatoptions': 562 563 r insert the star when typing <Enter> in Insert mode 564 o insert the star when using "o" or "O" in Normal mode 565 c break comment text according to 'textwidth' 566 567See |fo-table| for more flags. 568 569 570DEFINING A COMMENT 571 572The 'comments' option defines what a comment looks like. Vim distinguishes 573between a single-line comment and a comment that has a different start, end 574and middle part. 575 Many single-line comments start with a specific character. In C++ // is 576used, in Makefiles #, in Vim scripts ". For example, to make Vim understand 577C++ comments: > 578 579 :set comments=:// 580 581The colon separates the flags of an item from the text by which the comment is 582recognized. The general form of an item in 'comments' is: 583 584 {flags}:{text} 585 586The {flags} part can be empty, as in this case. 587 Several of these items can be concatenated, separated by commas. This 588allows recognizing different types of comments at the same time. For example, 589let's edit an e-mail message. When replying, the text that others wrote is 590preceded with ">" and "!" characters. This command would work: > 591 592 :set comments=n:>,n:! 593 594There are two items, one for comments starting with ">" and one for comments 595that start with "!". Both use the flag "n". This means that these comments 596nest. Thus a line starting with ">" may have another comment after the ">". 597This allows formatting a message like this: 598 599 > ! Did you see that site? ~ 600 > ! It looks really great. ~ 601 > I don't like it. The ~ 602 > colors are terrible. ~ 603 What is the URL of that ~ 604 site? ~ 605 606Try setting 'textwidth' to a different value, e.g., 80, and format the text by 607Visually selecting it and typing "gq". The result is: 608 609 > ! Did you see that site? It looks really great. ~ 610 > I don't like it. The colors are terrible. ~ 611 What is the URL of that site? ~ 612 613You will notice that Vim did not move text from one type of comment to 614another. The "I" in the second line would have fit at the end of the first 615line, but since that line starts with "> !" and the second line with ">", Vim 616knows that this is a different kind of comment. 617 618 619A THREE PART COMMENT 620 621A C comment starts with "/*", has "*" in the middle and "*/" at the end. The 622entry in 'comments' for this looks like this: > 623 624 :set comments=s1:/*,mb:*,ex:*/ 625 626The start is defined with "s1:/*". The "s" indicates the start of a 627three-piece comment. The colon separates the flags from the text by which the 628comment is recognized: "/*". There is one flag: "1". This tells Vim that the 629middle part has an offset of one space. 630 The middle part "mb:*" starts with "m", which indicates it is a middle 631part. The "b" flag means that a blank must follow the text. Otherwise Vim 632would consider text like "*pointer" also to be the middle of a comment. 633 The end part "ex:*/" has the "e" for identification. The "x" flag has a 634special meaning. It means that after Vim automatically inserted a star, 635typing / will remove the extra space. 636 637For more details see |format-comments|. 638 639============================================================================== 640 641Next chapter: |usr_31.txt| Exploiting the GUI 642 643Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl: 644