Write shorter scripts for the Vim editor by not including statements such as endif
, endfunction
, and endwhile
to mark the end of code blocks.
This utility inserts end statements; It looks at indentation to determine where code blocks end.
Some of my own scripts had >15% fewer lines after deleting end statements.
To build ~/bin/add_vim_script_end_statements run:
./build
on Linux. Run build.cmd
on MS-Windows.
The program reads stdin and writes to stdout. An example invocation:
add_vim_script_end_statements <my_script.vim+ >.my_script.vim
-
Tabs shouldn't be used for indenting the start of a line; Presently the program only counts spaces at the start of a line.
-
Be careful with having multiple statements on one line; This program only looks for keywords that introduce a code block immediately after any spaces at the start of a line. With
let c = Condition() | if c
moveif c
onto it's own line to have the program add a correspondingendif
statement. -
Keywords that prefix a code block need to be written in full, e.g.
while
notwh
, andfunction
notfunc
. -
If an exception is thrown by a script generated by this program
v:throwpoint
will refer to the generated file not the file it was generated from; It'd be nice to provide a function that returns the throwpoint in the source file givenv:throwpoint
for the generated file. -
I'd like Vim to be able to execute scripts without end statements (and then there'd be no need for this program other than for backporting scripts to run on a Vim that requires end statements).
-
augroup end
is inserted at the end of an augroup block. (Indent theautocmd
s within an augroup block.) -
Use
:source util/delete_end_statements.vim
to convert an existing script.
Programmers commonly use indentation to show code blocks - it makes it easy to see what statements are part of what. To see why, consider the following script which does not use indentation:
function X()
if flag1
call Fn()
if flag2
call Fn2()
call Fn3()
endif
call Fn4()
endif
endfunction
The "structure" of this code is hard to see. Which statements are skipped when function X is called and flag1 is false?
Indenting blocks helps!
function X()
if flag1
call Fn()
if flag2
call Fn2()
call Fn3()
call Fn4()
Now if asked which statements are skipped when X is called and flag1 is false we can immediately see that the remainder of the function body will be skipped as the remaining lines are all indented more than if flag1
.
(As well as adding indentation above I also removed the end statements resulting in 7 lines instead of 10.)