问题
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:
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.
回答2:
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.
回答3:
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.
回答4:
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.
回答5:
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.
来源:https://stackoverflow.com/questions/1662799/whats-the-syntax-for-telling-vi-to-read-write-a-source-file-with-soft-tabs-and