Some versions of vi
and ex
have a modeline
or
modelines
option.
When that option is set in your
.exrc
file (30.6
)
,
you can store setup commands at the top or bottom of any file you edit.
When you start the editor, it will read the setup commands and run them.
This is a lot like having a separate
.exrc
for each file you edit.
CAUTION:
Modelines can be a security problem.
If any troublemakers should edit your files and change your modelines, think
about the difficulties they can cause you.
Most newer versions of vi
disable modelines by default.
Here's a sample file - a
shell script (44.1
)
with a modeline on the second line:
#! /bin/sh
# vi:set number wrapmargin=0 autoindent showmatch:
while read line
do
...
The modeline has #
, the shell's comment character, at the start
of it - so, the shell will ignore the line but vi
will still read it.
This is only necessary in a shell script, but it demonstrates that the
modeline need not start in column 1. The modeline itself
consists of a space or tab, the string vi:
or ex:
, the
commands to be executed, and a closing colon. Both the space or tab
before the modeline, and the closing colon are important - they
tell the editor where the modeline begins and ends. You
can put modelines on the first five or last five lines of a file
(or both).
When you start vi
on the file shown in the example above,
it sets the options number,
wrapmargin=0
, autoindent
, and showmatch
.
NOTE:
Any time you open a file with a modeline, vi
changes the file
status to "modified"-even if you haven't actually made any changes.
To leave the file without writing it, you have to use the :q!
command.
This is a hassle when you use UNIX tools that depend on a file's
modification time, like
make
(28.13
)
,
especially if you also have the autowrite
option set.
To find out whether your version of vi
supports modelines - and
whether the option is called modeline
or modelines
-get
a list of all options with the command :set
all
.
If the option is available, but not set, you'll see nomodeline
(or nomodelines
)
as one of the options. Put the command
set modeline(s)
in your .exrc
file to enable the option.
Unfortunately, some versions list the option but don't support it!