xref: /vim-8.2.3635/runtime/doc/repeat.txt (revision fb094e14)
1*repeat.txt*    For Vim version 8.0.  Last change: 2017 Jun 10
2
3
4		  VIM REFERENCE MANUAL    by Bram Moolenaar
5
6
7Repeating commands, Vim scripts and debugging			*repeating*
8
9Chapter 26 of the user manual introduces repeating |usr_26.txt|.
10
111. Single repeats		|single-repeat|
122. Multiple repeats		|multi-repeat|
133. Complex repeats		|complex-repeat|
144. Using Vim scripts		|using-scripts|
155. Using Vim packages		|packages|
166. Creating Vim packages	|package-create|
177. Debugging scripts		|debug-scripts|
188. Profiling			|profiling|
19
20==============================================================================
211. Single repeats					*single-repeat*
22
23							*.*
24.			Repeat last change, with count replaced with [count].
25			Also repeat a yank command, when the 'y' flag is
26			included in 'cpoptions'.  Does not repeat a
27			command-line command.
28
29Simple changes can be repeated with the "." command.  Without a count, the
30count of the last change is used.  If you enter a count, it will replace the
31last one.  |v:count| and |v:count1| will be set.
32
33If the last change included a specification of a numbered register, the
34register number will be incremented.  See |redo-register| for an example how
35to use this.
36
37Note that when repeating a command that used a Visual selection, the same SIZE
38of area is used, see |visual-repeat|.
39
40							*@:*
41@:			Repeat last command-line [count] times.
42			{not available when compiled without the
43			|+cmdline_hist| feature}
44
45
46==============================================================================
472. Multiple repeats					*multi-repeat*
48
49						*:g* *:global* *E148*
50:[range]g[lobal]/{pattern}/[cmd]
51			Execute the Ex command [cmd] (default ":p") on the
52			lines within [range] where {pattern} matches.
53
54:[range]g[lobal]!/{pattern}/[cmd]
55			Execute the Ex command [cmd] (default ":p") on the
56			lines within [range] where {pattern} does NOT match.
57
58							*:v* *:vglobal*
59:[range]v[global]/{pattern}/[cmd]
60			Same as :g!.
61
62Instead of the '/' which surrounds the {pattern}, you can use any other
63single byte character, but not an alphabetic character, '\', '"' or '|'.
64This is useful if you want to include a '/' in the search pattern or
65replacement string.
66
67For the definition of a pattern, see |pattern|.
68
69NOTE [cmd] may contain a range; see |collapse| and |edit-paragraph-join| for
70examples.
71
72The global commands work by first scanning through the [range] lines and
73marking each line where a match occurs (for a multi-line pattern, only the
74start of the match matters).
75In a second scan the [cmd] is executed for each marked line, as if the cursor
76was in that line.  For ":v" and ":g!" the command is executed for each not
77marked line.  If a line is deleted its mark disappears.
78The default for [range] is the whole buffer (1,$).  Use "CTRL-C" to interrupt
79the command.  If an error message is given for a line, the command for that
80line is aborted and the global command continues with the next marked or
81unmarked line.
82								*E147*
83When the command is used recursively, it only works on one line.  Giving a
84range is then not allowed. This is useful to find all lines that match a
85pattern and do not match another pattern: >
86	:g/found/v/notfound/{cmd}
87This first finds all lines containing "found", but only executes {cmd} when
88there is no match for "notfound".
89
90To execute a non-Ex command, you can use the `:normal` command: >
91	:g/pat/normal {commands}
92Make sure that {commands} ends with a whole command, otherwise Vim will wait
93for you to type the rest of the command for each match.  The screen will not
94have been updated, so you don't know what you are doing.  See |:normal|.
95
96The undo/redo command will undo/redo the whole global command at once.
97The previous context mark will only be set once (with "''" you go back to
98where the cursor was before the global command).
99
100The global command sets both the last used search pattern and the last used
101substitute pattern (this is vi compatible).  This makes it easy to globally
102replace a string:
103	:g/pat/s//PAT/g
104This replaces all occurrences of "pat" with "PAT".  The same can be done with:
105	:%s/pat/PAT/g
106Which is two characters shorter!
107
108When using "global" in Ex mode, a special case is using ":visual" as a
109command.  This will move to a matching line, go to Normal mode to let you
110execute commands there until you use |Q| to return to Ex mode.  This will be
111repeated for each matching line.  While doing this you cannot use ":global".
112To abort this type CTRL-C twice.
113
114==============================================================================
1153. Complex repeats					*complex-repeat*
116
117							*q* *recording*
118q{0-9a-zA-Z"}		Record typed characters into register {0-9a-zA-Z"}
119			(uppercase to append).  The 'q' command is disabled
120			while executing a register, and it doesn't work inside
121			a mapping and |:normal|.
122
123			Note: If the register being used for recording is also
124			used for |y| and |p| the result is most likely not
125			what is expected, because the put will paste the
126			recorded macro and the yank will overwrite the
127			recorded macro. {Vi: no recording}
128
129q			Stops recording.  (Implementation note: The 'q' that
130			stops recording is not stored in the register, unless
131			it was the result of a mapping)  {Vi: no recording}
132
133							*@*
134@{0-9a-z".=*+}		Execute the contents of register {0-9a-z".=*+} [count]
135			times.  Note that register '%' (name of the current
136			file) and '#' (name of the alternate file) cannot be
137			used.
138			The register is executed like a mapping, that means
139			that the difference between 'wildchar' and 'wildcharm'
140			applies.
141			For "@=" you are prompted to enter an expression.  The
142			result of the expression is then executed.
143			See also |@:|.  {Vi: only named registers}
144
145							*@@* *E748*
146@@			Repeat the previous @{0-9a-z":*} [count] times.
147
148:[addr]*{0-9a-z".=+}						*:@* *:star*
149:[addr]@{0-9a-z".=*+}	Execute the contents of register {0-9a-z".=*+} as an Ex
150			command.  First set cursor at line [addr] (default is
151			current line).  When the last line in the register does
152			not have a <CR> it will be added automatically when
153			the 'e' flag is present in 'cpoptions'.
154			Note that the ":*" command is only recognized when the
155			'*' flag is present in 'cpoptions'.  This is NOT the
156			default when 'nocompatible' is used.
157			For ":@=" the last used expression is used.  The
158			result of evaluating the expression is executed as an
159			Ex command.
160			Mappings are not recognized in these commands.
161			{Vi: only in some versions} Future: Will execute the
162			register for each line in the address range.
163
164							*:@:*
165:[addr]@:		Repeat last command-line.  First set cursor at line
166			[addr] (default is current line).  {not in Vi}
167
168:[addr]@							*:@@*
169:[addr]@@		Repeat the previous :@{0-9a-z"}.  First set cursor at
170			line [addr] (default is current line).  {Vi: only in
171			some versions}
172
173==============================================================================
1744. Using Vim scripts					*using-scripts*
175
176For writing a Vim script, see chapter 41 of the user manual |usr_41.txt|.
177
178					*:so* *:source* *load-vim-script*
179:so[urce] {file}	Read Ex commands from {file}.  These are commands that
180			start with a ":".
181			Triggers the |SourcePre| autocommand.
182
183:so[urce]! {file}	Read Vim commands from {file}.  These are commands
184			that are executed from Normal mode, like you type
185			them.
186			When used after |:global|, |:argdo|, |:windo|,
187			|:bufdo|, in a loop or when another command follows
188			the display won't be updated while executing the
189			commands.
190			{not in Vi}
191
192							*:ru* *:runtime*
193:ru[ntime][!] [where] {file} ..
194			Read Ex commands from {file} in each directory given
195			by 'runtimepath' and/or 'packpath'.  There is no error
196			for non-existing files.
197
198			Example: >
199				:runtime syntax/c.vim
200
201<			There can be multiple {file} arguments, separated by
202			spaces.  Each {file} is searched for in the first
203			directory from 'runtimepath', then in the second
204			directory, etc.  Use a backslash to include a space
205			inside {file} (although it's better not to use spaces
206			in file names, it causes trouble).
207
208			When [!] is included, all found files are sourced.
209			When it is not included only the first found file is
210			sourced.
211
212			When [where] is omitted only 'runtimepath' is used.
213			Other values:
214				START	search under "start" in 'packpath'
215				OPT 	search under "opt" in 'packpath'
216				PACK	search under "start" and "opt" in
217					'packpath'
218				ALL	first use 'runtimepath', then search
219					under "start" and "opt" in 'packpath'
220
221			When {file} contains wildcards it is expanded to all
222			matching files.  Example: >
223				:runtime! plugin/*.vim
224<			This is what Vim uses to load the plugin files when
225			starting up.  This similar command: >
226				:runtime plugin/*.vim
227<			would source the first file only.
228
229			When 'verbose' is one or higher, there is a message
230			when no file could be found.
231			When 'verbose' is two or higher, there is a message
232			about each searched file.
233			{not in Vi}
234
235							*:pa* *:packadd* *E919*
236:pa[ckadd][!] {name}	Search for an optional plugin directory in 'packpath'
237			and source any plugin files found.  The directory must
238			match:
239				pack/*/opt/{name} ~
240			The directory is added to 'runtimepath' if it wasn't
241			there yet.
242			If the directory pack/*/opt/{name}/after exists it is
243			added at the end of 'runtimepath'.
244
245			Note that {name} is the directory name, not the name
246			of the .vim file.  All the files matching the pattern
247				pack/*/opt/{name}/plugin/**/*.vim ~
248			will be sourced.  This allows for using subdirectories
249			below "plugin", just like with plugins in
250			'runtimepath'.
251
252			If the filetype detection was not enabled yet (this
253			is usually done with a "syntax enable" or "filetype
254			on" command in your .vimrc file), this will also look
255			for "{name}/ftdetect/*.vim" files.
256
257			When the optional ! is added no plugin files or
258			ftdetect scripts are loaded, only the matching
259			directories are added to 'runtimepath'.  This is
260			useful in your .vimrc.  The plugins will then be
261			loaded during initialization, see |load-plugins|.
262
263			Also see |pack-add|.
264
265						*:packl* *:packloadall*
266:packl[oadall][!]	Load all packages in the "start" directory under each
267			entry in 'packpath'.
268
269			First all the directories found are added to
270			'runtimepath', then the plugins found in the
271			directories are sourced.  This allows for a plugin to
272			depend on something of another plugin, e.g. an
273			"autoload" directory.  See |packload-two-steps| for
274			how this can be useful.
275
276			This is normally done automatically during startup,
277			after loading your .vimrc file.  With this command it
278			can be done earlier.
279
280			Packages will be loaded only once.  After this command
281			it won't happen again.  When the optional ! is added
282			this command will load packages even when done before.
283
284			An error only causes sourcing the script where it
285			happens to be aborted, further plugins will be loaded.
286			See |packages|.
287
288:scripte[ncoding] [encoding]		*:scripte* *:scriptencoding* *E167*
289			Specify the character encoding used in the script.
290			The following lines will be converted from [encoding]
291			to the value of the 'encoding' option, if they are
292			different.  Examples: >
293				scriptencoding iso-8859-5
294				scriptencoding cp932
295<
296			When [encoding] is empty, no conversion is done.  This
297			can be used to restrict conversion to a sequence of
298			lines: >
299				scriptencoding euc-jp
300				... lines to be converted ...
301				scriptencoding
302				... not converted ...
303
304<			When conversion isn't supported by the system, there
305			is no error message and no conversion is done.  When a
306			line can't be converted there is no error and the
307			original line is kept.
308
309			Don't use "ucs-2" or "ucs-4", scripts cannot be in
310			these encodings (they would contain NUL bytes).
311			When a sourced script starts with a BOM (Byte Order
312			Mark) in utf-8 format Vim will recognize it, no need
313			to use ":scriptencoding utf-8" then.
314
315			If you set the 'encoding' option in your |.vimrc|,
316			`:scriptencoding` must be placed after that. E.g.: >
317				set encoding=utf-8
318				scriptencoding utf-8
319<
320			When compiled without the |+multi_byte| feature this
321			command is ignored.
322			{not in Vi}
323
324						*:scr* *:scriptnames*
325:scr[iptnames]		List all sourced script names, in the order they were
326			first sourced.  The number is used for the script ID
327			|<SID>|.
328			{not in Vi} {not available when compiled without the
329			|+eval| feature}
330
331						*:fini* *:finish* *E168*
332:fini[sh]		Stop sourcing a script.  Can only be used in a Vim
333			script file.  This is a quick way to skip the rest of
334			the file.  If it is used after a |:try| but before the
335			matching |:finally| (if present), the commands
336			following the ":finally" up to the matching |:endtry|
337			are executed first.  This process applies to all
338			nested ":try"s in the script.  The outermost ":endtry"
339			then stops sourcing the script.  {not in Vi}
340
341All commands and command sequences can be repeated by putting them in a named
342register and then executing it.  There are two ways to get the commands in the
343register:
344- Use the record command "q".  You type the commands once, and while they are
345  being executed they are stored in a register.  Easy, because you can see
346  what you are doing.  If you make a mistake, "p"ut the register into the
347  file, edit the command sequence, and then delete it into the register
348  again.  You can continue recording by appending to the register (use an
349  uppercase letter).
350- Delete or yank the command sequence into the register.
351
352Often used command sequences can be put under a function key with the ':map'
353command.
354
355An alternative is to put the commands in a file, and execute them with the
356':source!' command.  Useful for long command sequences.  Can be combined with
357the ':map' command to put complicated commands under a function key.
358
359The ':source' command reads Ex commands from a file line by line.  You will
360have to type any needed keyboard input.  The ':source!' command reads from a
361script file character by character, interpreting each character as if you
362typed it.
363
364Example: When you give the ":!ls" command you get the |hit-enter| prompt.  If
365you ':source' a file with the line "!ls" in it, you will have to type the
366<Enter> yourself.  But if you ':source!' a file with the line ":!ls" in it,
367the next characters from that file are read until a <CR> is found.  You will
368not have to type <CR> yourself, unless ":!ls" was the last line in the file.
369
370It is possible to put ':source[!]' commands in the script file, so you can
371make a top-down hierarchy of script files.  The ':source' command can be
372nested as deep as the number of files that can be opened at one time (about
37315).  The ':source!' command can be nested up to 15 levels deep.
374
375You can use the "<sfile>" string (literally, this is not a special key) inside
376of the sourced file, in places where a file name is expected.  It will be
377replaced by the file name of the sourced file.  For example, if you have a
378"other.vimrc" file in the same directory as your ".vimrc" file, you can source
379it from your ".vimrc" file with this command: >
380	:source <sfile>:h/other.vimrc
381
382In script files terminal-dependent key codes are represented by
383terminal-independent two character codes.  This means that they can be used
384in the same way on different kinds of terminals.  The first character of a
385key code is 0x80 or 128, shown on the screen as "~@".  The second one can be
386found in the list |key-notation|.  Any of these codes can also be entered
387with CTRL-V followed by the three digit decimal code.  This does NOT work for
388the <t_xx> termcap codes, these can only be used in mappings.
389
390							*:source_crnl* *W15*
391MS-DOS, Win32 and OS/2: Files that are read with ":source" normally have
392<CR><NL> <EOL>s.  These always work.  If you are using a file with <NL> <EOL>s
393(for example, a file made on Unix), this will be recognized if 'fileformats'
394is not empty and the first line does not end in a <CR>.  This fails if the
395first line has something like ":map <F1> :help^M", where "^M" is a <CR>.  If
396the first line ends in a <CR>, but following ones don't, you will get an error
397message, because the <CR> from the first lines will be lost.
398
399Mac Classic: Files that are read with ":source" normally have <CR> <EOL>s.
400These always work.  If you are using a file with <NL> <EOL>s (for example, a
401file made on Unix), this will be recognized if 'fileformats' is not empty and
402the first line does not end in a <CR>.  Be careful not to use a file with <NL>
403linebreaks which has a <CR> in first line.
404
405On other systems, Vim expects ":source"ed files to end in a <NL>.  These
406always work.  If you are using a file with <CR><NL> <EOL>s (for example, a
407file made on MS-DOS), all lines will have a trailing <CR>.  This may cause
408problems for some commands (e.g., mappings).  There is no automatic <EOL>
409detection, because it's common to start with a line that defines a mapping
410that ends in a <CR>, which will confuse the automaton.
411
412							*line-continuation*
413Long lines in a ":source"d Ex command script file can be split by inserting
414a line continuation symbol "\" (backslash) at the start of the next line.
415There can be white space before the backslash, which is ignored.
416
417Example: the lines >
418	:set comments=sr:/*,mb:*,el:*/,
419		     \://,
420		     \b:#,
421		     \:%,
422		     \n:>,
423		     \fb:-
424are interpreted as if they were given in one line:
425	:set comments=sr:/*,mb:*,el:*/,://,b:#,:%,n:>,fb:-
426
427All leading whitespace characters in the line before a backslash are ignored.
428Note however that trailing whitespace in the line before it cannot be
429inserted freely; it depends on the position where a command is split up
430whether additional whitespace is allowed or not.
431
432When a space is required it's best to put it right after the backslash.  A
433space at the end of a line is hard to see and may be accidentally deleted. >
434	:syn match Comment
435		\ "very long regexp"
436		\ keepend
437
438There is a problem with the ":append" and ":insert" commands: >
439   :1append
440   \asdf
441   .
442The backslash is seen as a line-continuation symbol, thus this results in the
443command: >
444   :1appendasdf
445   .
446To avoid this, add the 'C' flag to the 'cpoptions' option: >
447   :set cpo+=C
448   :1append
449   \asdf
450   .
451   :set cpo-=C
452
453Note that when the commands are inside a function, you need to add the 'C'
454flag when defining the function, it is not relevant when executing it. >
455   :set cpo+=C
456   :function Foo()
457   :1append
458   \asdf
459   .
460   :endfunction
461   :set cpo-=C
462
463Rationale:
464	Most programs work with a trailing backslash to indicate line
465	continuation.  Using this in Vim would cause incompatibility with Vi.
466	For example for this Vi mapping: >
467		:map xx  asdf\
468<	Therefore the unusual leading backslash is used.
469
470==============================================================================
4715. Using Vim packages					*packages*
472
473A Vim package is a directory that contains one or more plugins.  The
474advantages over normal plugins:
475- A package can be downloaded as an archive and unpacked in its own directory.
476  Thus the files are not mixed with files of other plugins.  That makes it
477  easy to update and remove.
478- A package can be a git, mercurial, etc. repository.  That makes it really
479  easy to update.
480- A package can contain multiple plugins that depend on each other.
481- A package can contain plugins that are automatically loaded on startup and
482  ones that are only loaded when needed with `:packadd`.
483
484
485Using a package and loading automatically ~
486
487Let's assume your Vim files are in the "~/.vim" directory and you want to add a
488package from a zip archive "/tmp/foopack.zip":
489	% mkdir -p ~/.vim/pack/foo
490	% cd ~/.vim/pack/foo
491	% unzip /tmp/foopack.zip
492
493The directory name "foo" is arbitrary, you can pick anything you like.
494
495You would now have these files under ~/.vim:
496	pack/foo/README.txt
497	pack/foo/start/foobar/plugin/foo.vim
498	pack/foo/start/foobar/syntax/some.vim
499	pack/foo/opt/foodebug/plugin/debugger.vim
500
501When Vim starts up, after processing your .vimrc, it scans all directories in
502'packpath' for plugins under the "pack/*/start" directory.  First all those
503directories are added to 'runtimepath'.  Then all the plugins are loaded.
504See |packload-two-steps| for how these two steps can be useful.
505
506In the example Vim will find "pack/foo/start/foobar/plugin/foo.vim" and adds
507"~/.vim/pack/foo/start/foobar" to 'runtimepath'.
508
509If the "foobar" plugin kicks in and sets the 'filetype' to "some", Vim will
510find the syntax/some.vim file, because its directory is in 'runtimepath'.
511
512Vim will also load ftdetect files, if there are any.
513
514Note that the files under "pack/foo/opt" are not loaded automatically, only the
515ones under "pack/foo/start".  See |pack-add| below for how the "opt" directory
516is used.
517
518Loading packages automatically will not happen if loading plugins is disabled,
519see |load-plugins|.
520
521To load packages earlier, so that 'runtimepath' gets updated: >
522	:packloadall
523This also works when loading plugins is disabled.  The automatic loading will
524only happen once.
525
526If the package has an "after" directory, that directory is added to the end of
527'runtimepath', so that anything there will be loaded later.
528
529
530Using a single plugin and loading it automatically ~
531
532If you don't have a package but a single plugin, you need to create the extra
533directory level:
534	% mkdir -p ~/.vim/pack/foo/start/foobar
535	% cd ~/.vim/pack/foo/start/foobar
536	% unzip /tmp/someplugin.zip
537
538You would now have these files:
539	pack/foo/start/foobar/plugin/foo.vim
540	pack/foo/start/foobar/syntax/some.vim
541
542From here it works like above.
543
544
545Optional plugins ~
546							*pack-add*
547To load an optional plugin from a pack use the `:packadd` command: >
548	:packadd foodebug
549This searches for "pack/*/opt/foodebug" in 'packpath' and will find
550~/.vim/pack/foo/opt/foodebug/plugin/debugger.vim and source it.
551
552This could be done if some conditions are met.  For example, depending on
553whether Vim supports a feature or a dependency is missing.
554
555You can also load an optional plugin at startup, by putting this command in
556your |.vimrc|: >
557	:packadd! foodebug
558The extra "!" is so that the plugin isn't loaded if Vim was started with
559|--noplugin|.
560
561It is perfectly normal for a package to only have files in the "opt"
562directory.  You then need to load each plugin when you want to use it.
563
564
565Where to put what ~
566
567Since color schemes, loaded with `:colorscheme`, are found below
568"pack/*/start" and "pack/*/opt", you could put them anywhere.  We recommend
569you put them below "pack/*/opt", for example
570".vim/pack/mycolors/opt/dark/colors/very_dark.vim".
571
572Filetype plugins should go under "pack/*/start", so that they are always
573found.  Unless you have more than one plugin for a file type and want to
574select which one to load with `:packadd`.  E.g. depending on the compiler
575version: >
576	if foo_compiler_version > 34
577	  packadd foo_new
578	else
579	  packadd foo_old
580	endif
581
582The "after" directory is most likely not useful in a package.  It's not
583disallowed though.
584
585==============================================================================
5866. Creating Vim packages				*package-create*
587
588This assumes you write one or more plugins that you distribute as a package.
589
590If you have two unrelated plugins you would use two packages, so that Vim
591users can chose what they include or not.  Or you can decide to use one
592package with optional plugins, and tell the user to add the ones he wants with
593`:packadd`.
594
595Decide how you want to distribute the package.  You can create an archive or
596you could use a repository.  An archive can be used by more users, but is a
597bit harder to update to a new version.  A repository can usually be kept
598up-to-date easily, but it requires a program like "git" to be available.
599You can do both, github can automatically create an archive for a release.
600
601Your directory layout would be like this:
602   start/foobar/plugin/foo.vim    	" always loaded, defines commands
603   start/foobar/plugin/bar.vim    	" always loaded, defines commands
604   start/foobar/autoload/foo.vim  	" loaded when foo command used
605   start/foobar/doc/foo.txt       	" help for foo.vim
606   start/foobar/doc/tags          	" help tags
607   opt/fooextra/plugin/extra.vim  	" optional plugin, defines commands
608   opt/fooextra/autoload/extra.vim  	" loaded when extra command used
609   opt/fooextra/doc/extra.txt  	        " help for extra.vim
610   opt/fooextra/doc/tags  	        " help tags
611
612This allows for the user to do: >
613	mkdir ~/.vim/pack/myfoobar
614	cd ~/.vim/pack/myfoobar
615	git clone https://github.com/you/foobar.git
616
617Here "myfoobar" is a name that the user can choose, the only condition is that
618it differs from other packages.
619
620In your documentation you explain what the plugins do, and tell the user how
621to load the optional plugin: >
622	:packadd! fooextra
623
624You could add this packadd command in one of your plugins, to be executed when
625the optional plugin is needed.
626
627Run the `:helptags` command to generate the doc/tags file.  Including this
628generated file in the package means that the user can drop the package in his
629pack directory and the help command works right away.  Don't forget to re-run
630the command after changing the plugin help: >
631	:helptags path/start/foobar/doc
632	:helptags path/opt/fooextra/doc
633
634
635Dependencies between plugins ~
636							*packload-two-steps*
637Suppose you have two plugins that depend on the same functionality. You can
638put the common functionality in an autoload directory, so that it will be
639found automatically.  Your package would have these files:
640
641	pack/foo/start/one/plugin/one.vim  >
642		call foolib#getit()
643<	pack/foo/start/two/plugin/two.vim >
644		call foolib#getit()
645<	pack/foo/start/lib/autoload/foolib.vim >
646		func foolib#getit()
647
648This works, because loading packages will first add all found directories to
649'runtimepath' before sourcing the plugins.
650
651==============================================================================
6527. Debugging scripts					*debug-scripts*
653
654Besides the obvious messages that you can add to your scripts to find out what
655they are doing, Vim offers a debug mode.  This allows you to step through a
656sourced file or user function and set breakpoints.
657
658NOTE: The debugging mode is far from perfect.  Debugging will have side
659effects on how Vim works.  You cannot use it to debug everything.  For
660example, the display is messed up by the debugging messages.
661{Vi does not have a debug mode}
662
663An alternative to debug mode is setting the 'verbose' option.  With a bigger
664number it will give more verbose messages about what Vim is doing.
665
666
667STARTING DEBUG MODE						*debug-mode*
668
669To enter debugging mode use one of these methods:
6701. Start Vim with the |-D| argument: >
671	vim -D file.txt
672<  Debugging will start as soon as the first vimrc file is sourced.  This is
673   useful to find out what is happening when Vim is starting up.  A side
674   effect is that Vim will switch the terminal mode before initialisations
675   have finished, with unpredictable results.
676   For a GUI-only version (Windows, Macintosh) the debugging will start as
677   soon as the GUI window has been opened.  To make this happen early, add a
678   ":gui" command in the vimrc file.
679								*:debug*
6802. Run a command with ":debug" prepended.  Debugging will only be done while
681   this command executes.  Useful for debugging a specific script or user
682   function.  And for scripts and functions used by autocommands.  Example: >
683	:debug edit test.txt.gz
684
6853. Set a breakpoint in a sourced file or user function.  You could do this in
686   the command line: >
687	vim -c "breakadd file */explorer.vim" .
688<  This will run Vim and stop in the first line of the "explorer.vim" script.
689   Breakpoints can also be set while in debugging mode.
690
691In debugging mode every executed command is displayed before it is executed.
692Comment lines, empty lines and lines that are not executed are skipped.  When
693a line contains two commands, separated by "|", each command will be displayed
694separately.
695
696
697DEBUG MODE
698
699Once in debugging mode, the usual Ex commands can be used.  For example, to
700inspect the value of a variable: >
701	echo idx
702When inside a user function, this will print the value of the local variable
703"idx".  Prepend "g:" to get the value of a global variable: >
704	echo g:idx
705All commands are executed in the context of the current function or script.
706You can also set options, for example setting or resetting 'verbose' will show
707what happens, but you might want to set it just before executing the lines you
708are interested in: >
709	:set verbose=20
710
711Commands that require updating the screen should be avoided, because their
712effect won't be noticed until after leaving debug mode.  For example: >
713	:help
714won't be very helpful.
715
716There is a separate command-line history for debug mode.
717
718The line number for a function line is relative to the start of the function.
719If you have trouble figuring out where you are, edit the file that defines
720the function in another Vim, search for the start of the function and do
721"99j".  Replace "99" with the line number.
722
723Additionally, these commands can be used:
724							*>cont*
725	cont		Continue execution until the next breakpoint is hit.
726							*>quit*
727	quit		Abort execution.  This is like using CTRL-C, some
728			things might still be executed, doesn't abort
729			everything.  Still stops at the next breakpoint.
730							*>next*
731	next		Execute the command and come back to debug mode when
732			it's finished.  This steps over user function calls
733			and sourced files.
734							*>step*
735	step		Execute the command and come back to debug mode for
736			the next command.  This steps into called user
737			functions and sourced files.
738							*>interrupt*
739	interrupt	This is like using CTRL-C, but unlike ">quit" comes
740			back to debug mode for the next command that is
741			executed.  Useful for testing |:finally| and |:catch|
742			on interrupt exceptions.
743							*>finish*
744	finish		Finish the current script or user function and come
745			back to debug mode for the command after the one that
746			sourced or called it.
747							*>bt*
748							*>backtrace*
749							*>where*
750	backtrace	Show the call stacktrace for current debugging session.
751	bt
752	where
753							*>frame*
754	frame N		Goes to N backtrace level. + and - signs make movement
755			relative.  E.g., ":frame +3" goes three frames up.
756							*>up*
757	up		Goes one level up from call stacktrace.
758							*>down*
759	down		Goes one level down from call stacktrace.
760
761About the additional commands in debug mode:
762- There is no command-line completion for them, you get the completion for the
763  normal Ex commands only.
764- You can shorten them, up to a single character, unless more than one command
765  starts with the same letter.  "f" stands for "finish", use "fr" for "frame".
766- Hitting <CR> will repeat the previous one.  When doing another command, this
767  is reset (because it's not clear what you want to repeat).
768- When you want to use the Ex command with the same name, prepend a colon:
769  ":cont", ":next", ":finish" (or shorter).
770
771The backtrace shows the hierarchy of function calls, e.g.:
772	>bt ~
773	  3 function One[3] ~
774	  2 Two[3] ~
775	->1 Three[3] ~
776	  0 Four ~
777	line 1: let four = 4 ~
778
779The "->" points to the current frame.  Use "up", "down" and "frame N" to
780select another frame.
781
782In the current frame you can evaluate the local function variables.  There is
783no way to see the command at the current line yet.
784
785
786DEFINING BREAKPOINTS
787							*:breaka* *:breakadd*
788:breaka[dd] func [lnum] {name}
789		Set a breakpoint in a function.  Example: >
790			:breakadd func Explore
791<		Doesn't check for a valid function name, thus the breakpoint
792		can be set before the function is defined.
793
794:breaka[dd] file [lnum] {name}
795		Set a breakpoint in a sourced file.  Example: >
796			:breakadd file 43 .vimrc
797
798:breaka[dd] here
799		Set a breakpoint in the current line of the current file.
800		Like doing: >
801			:breakadd file <cursor-line> <current-file>
802<		Note that this only works for commands that are executed when
803		sourcing the file, not for a function defined in that file.
804
805The [lnum] is the line number of the breakpoint.  Vim will stop at or after
806this line.  When omitted line 1 is used.
807
808							*:debug-name*
809{name} is a pattern that is matched with the file or function name.  The
810pattern is like what is used for autocommands.  There must be a full match (as
811if the pattern starts with "^" and ends in "$").  A "*" matches any sequence
812of characters.  'ignorecase' is not used, but "\c" can be used in the pattern
813to ignore case |/\c|.  Don't include the () for the function name!
814
815The match for sourced scripts is done against the full file name.  If no path
816is specified the current directory is used.  Examples: >
817	breakadd file explorer.vim
818matches "explorer.vim" in the current directory. >
819	breakadd file *explorer.vim
820matches ".../plugin/explorer.vim", ".../plugin/iexplorer.vim", etc. >
821	breakadd file */explorer.vim
822matches ".../plugin/explorer.vim" and "explorer.vim" in any other directory.
823
824The match for functions is done against the name as it's shown in the output
825of ":function".  For local functions this means that something like "<SNR>99_"
826is prepended.
827
828Note that functions are first loaded and later executed.  When they are loaded
829the "file" breakpoints are checked, when they are executed the "func"
830breakpoints.
831
832
833DELETING BREAKPOINTS
834						*:breakd* *:breakdel* *E161*
835:breakd[el] {nr}
836		Delete breakpoint {nr}.  Use |:breaklist| to see the number of
837		each breakpoint.
838
839:breakd[el] *
840		Delete all breakpoints.
841
842:breakd[el] func [lnum] {name}
843		Delete a breakpoint in a function.
844
845:breakd[el] file [lnum] {name}
846		Delete a breakpoint in a sourced file.
847
848:breakd[el] here
849		Delete a breakpoint at the current line of the current file.
850
851When [lnum] is omitted, the first breakpoint in the function or file is
852deleted.
853The {name} must be exactly the same as what was typed for the ":breakadd"
854command.  "explorer", "*explorer.vim" and "*explorer*" are different.
855
856
857LISTING BREAKPOINTS
858							*:breakl* *:breaklist*
859:breakl[ist]
860		List all breakpoints.
861
862
863OBSCURE
864
865						*:debugg* *:debuggreedy*
866:debugg[reedy]
867		Read debug mode commands from the normal input stream, instead
868		of getting them directly from the user.  Only useful for test
869		scripts.  Example: >
870		  echo 'q^Mq' | vim -e -s -c debuggreedy -c 'breakadd file script.vim' -S script.vim
871
872:0debugg[reedy]
873		Undo ":debuggreedy": get debug mode commands directly from the
874		user, don't use typeahead for debug commands.
875
876==============================================================================
8778. Profiling						*profile* *profiling*
878
879Profiling means that Vim measures the time that is spent on executing
880functions and/or scripts.  The |+profile| feature is required for this.
881It is only included when Vim was compiled with "huge" features.
882{Vi does not have profiling}
883
884You can also use the |reltime()| function to measure time.  This only requires
885the |+reltime| feature, which is present more often.
886
887For profiling syntax highlighting see |:syntime|.
888
889For example, to profile the one_script.vim script file: >
890	:profile start /tmp/one_script_profile
891	:profile file one_script.vim
892	:source one_script.vim
893	:exit
894
895
896:prof[ile] start {fname}			*:prof* *:profile* *E750*
897		Start profiling, write the output in {fname} upon exit.
898		"~/" and environment variables in {fname} will be expanded.
899		If {fname} already exists it will be silently overwritten.
900		The variable |v:profiling| is set to one.
901
902:prof[ile] pause
903		Don't profile until the following ":profile continue".  Can be
904		used when doing something that should not be counted (e.g., an
905		external command).  Does not nest.
906
907:prof[ile] continue
908		Continue profiling after ":profile pause".
909
910:prof[ile] func {pattern}
911		Profile function that matches the pattern {pattern}.
912		See |:debug-name| for how {pattern} is used.
913
914:prof[ile][!] file {pattern}
915		Profile script file that matches the pattern {pattern}.
916		See |:debug-name| for how {pattern} is used.
917		This only profiles the script itself, not the functions
918		defined in it.
919		When the [!] is added then all functions defined in the script
920		will also be profiled.
921		Note that profiling only starts when the script is loaded
922		after this command.  A :profile command in the script itself
923		won't work.
924
925
926:profd[el] ...						*:profd* *:profdel*
927		Stop profiling for the arguments specified. See |:breakdel|
928		for the arguments.
929
930
931You must always start with a ":profile start fname" command.  The resulting
932file is written when Vim exits.  Here is an example of the output, with line
933numbers prepended for the explanation:
934
935  1 FUNCTION  Test2() ~
936  2 Called 1 time ~
937  3 Total time:   0.155251 ~
938  4  Self time:   0.002006 ~
939  5  ~
940  6 count  total (s)   self (s) ~
941  7	9	       0.000096   for i in range(8) ~
942  8	8   0.153655   0.000410     call Test3() ~
943  9	8	       0.000070   endfor ~
944 10				  " Ask a question ~
945 11	1	       0.001341   echo input("give me an answer: ") ~
946
947The header (lines 1-4) gives the time for the whole function.  The "Total"
948time is the time passed while the function was executing.  The "Self" time is
949the "Total" time reduced by time spent in:
950- other user defined functions
951- sourced scripts
952- executed autocommands
953- external (shell) commands
954
955Lines 7-11 show the time spent in each executed line.  Lines that are not
956executed do not count.  Thus a comment line is never counted.
957
958The Count column shows how many times a line was executed.  Note that the
959"for" command in line 7 is executed one more time as the following lines.
960That is because the line is also executed to detect the end of the loop.
961
962The time Vim spends waiting for user input isn't counted at all.  Thus how
963long you take to respond to the input() prompt is irrelevant.
964
965Profiling should give a good indication of where time is spent, but keep in
966mind there are various things that may clobber the results:
967
968- The accuracy of the time measured depends on the gettimeofday() system
969  function.  It may only be as accurate as 1/100 second, even though the times
970  are displayed in micro seconds.
971
972- Real elapsed time is measured, if other processes are busy they may cause
973  delays at unpredictable moments.  You may want to run the profiling several
974  times and use the lowest results.
975
976- If you have several commands in one line you only get one time.  Split the
977  line to see the time for the individual commands.
978
979- The time of the lines added up is mostly less than the time of the whole
980  function.  There is some overhead in between.
981
982- Functions that are deleted before Vim exits will not produce profiling
983  information.  You can check the |v:profiling| variable if needed: >
984	:if !v:profiling
985	:   delfunc MyFunc
986	:endif
987<
988- Profiling may give weird results on multi-processor systems, when sleep
989  mode kicks in or the processor frequency is reduced to save power.
990
991- The "self" time is wrong when a function is used recursively.
992
993
994 vim:tw=78:ts=8:ft=help:norl:
995