tags:

views:

116

answers:

5

Someplace I saw a snippet of code which told vi to use soft tabs and set the size of a tab. If you put this snippet at the bottom of a source file, then vi would magically use those settings for that file.

What is the syntax and rules for including that snippet in a source file? Can emacs be made to use these settings as well?

+1  A: 

As far as I know, vi didn't have this capability. You're likely thinking of the modeline feature of Vim. There is similar functionality in emacs, where you can put local variables in the file.

Note that, at least in Vim, modelines have had a history of vulnerabilities. This is primarily due to problematic options being specifically blacklisted instead of only allowing a certain subset of variables to be set in modelines. I'd suggest using a plugin like securemodelines.

jamessan
+1  A: 

Put this in your C++ source file:

// vim: set ft=cpp

The modeline feature looks for the string "vim: " and then executes what follows. Note: this could open up potential exploits if you don't trust the files you are opening, so think twice before enabling this feature.

Ether
+2  A: 

Check out :h modeline.

Example:

/* vim: ai set sw=4 ts=4 */

See :h modelines for how many lines into a file Vim will check for modeline info. The default is to check the first 5 lines.

overthink
'modelines' is the number of lines to check at the beginning AND end of the file.
jamessan
You missed my favorite 'et'. Let the indentation wars begin!
Ewan Todd
@jamessan - thanks, good info@Ewan - no comment :)
overthink
+1  A: 

You can put this in a comment in your source file:

ex: set softtabstop=4 shiftwidth=4 tabstop=4 expandtab:

The comment syntax depends on the type of the source file.

For C/C++/Java, this would be:

// ex: set softtabstop=4 shiftwidth=4 tabstop=4 expandtab:

For JSP, this would be:

<%-- ex: set softtabstop=4 shiftwidth=4 tabstop=4 expandtab: --%>

This works if it is placed at the beginning of the source file, but I'm not sure that this'll work if placed at the end of it too.

This will not work for emacs. There might be a different way of achieving the same for emacs.

Siddhartha Reddy
A: 

Okay, first of all, in real vi you do this in the .exrc file.

Second, use

set autoindent tabstop=8 shiftwidth=4

because otherwise vi will insert tabs it thinks are only 4 characters wide. The resulting text file will not look like it makes sense in any other editor.

Charlie Martin