Как настроить vim для редактирования файлов Makefile и обычного кода?


22

Я использую Mac OSX 10.7.5, содержимое .vimrc выглядит следующим образом:

set tabstop=4
set shiftwidth=4
set softtabstop=4
set expandtab
set shiftround  
set smarttab    
set autoindent  
set copyindent  

autocmd FileType make setlocal noexpandtab

То, что я пытаюсь сделать, - это когда я редактирую обычные файлы, такие как .js, .html, я хочу, чтобы на моих вкладках имелось 4 пробела вместо обычной вкладки.

Но когда я редактирую Makefile, мне нужно, чтобы он был обычной вкладкой вместо 4 пробелов для отступов.

Я думал, что приведенная выше настройка в .vimrc даст мне это, но не работает для меня, так как, когда я редактирую Makefile, я все еще получаю 4 пробела для отступа.

Не уверен, что я здесь делаю не так?

Ответы:


26

Это раздел моего .vimrc:

" enable filetype detection:
filetype on
filetype plugin on
filetype indent on " file type based indentation

" recognize anything in my .Postponed directory as a news article, and anything
" at all with a .txt extension as being human-language text [this clobbers the
" `help' filetype, but that doesn't seem to prevent help from working
" properly]:
augroup filetype
  autocmd BufNewFile,BufRead */.Postponed/* set filetype=mail
  autocmd BufNewFile,BufRead *.txt set filetype=human
augroup END

autocmd FileType mail set formatoptions+=t textwidth=72 " enable wrapping in mail
autocmd FileType human set formatoptions-=t textwidth=0 " disable wrapping in txt

" for C-like  programming where comments have explicit end
" characters, if starting a new line in the middle of a comment automatically
" insert the comment leader characters:
autocmd FileType c,cpp,java set formatoptions+=ro
autocmd FileType c set omnifunc=ccomplete#Complete

" fixed indentation should be OK for XML and CSS. People have fast internet
" anyway. Indentation set to 2.
autocmd FileType html,xhtml,css,xml,xslt set shiftwidth=2 softtabstop=2

" two space indentation for some files
autocmd FileType vim,lua,nginx set shiftwidth=2 softtabstop=2

" for CSS, also have things in braces indented:
autocmd FileType css set omnifunc=csscomplete#CompleteCSS

" add completion for xHTML
autocmd FileType xhtml,html set omnifunc=htmlcomplete#CompleteTags

" add completion for XML
autocmd FileType xml set omnifunc=xmlcomplete#CompleteTags

" in makefiles, don't expand tabs to spaces, since actual tab characters are
" needed, and have indentation at 8 chars to be sure that all indents are tabs
" (despite the mappings later):
autocmd FileType make set noexpandtab shiftwidth=8 softtabstop=0

" ensure normal tabs in assembly files
" and set to NASM syntax highlighting
autocmd FileType asm set noexpandtab shiftwidth=8 softtabstop=0 syntax=nasm

Раздел должен быть понятен, но я предлагаю вам прочитать справку vim на filetypeи autocmd.

Вероятно, самая важная строка для вас:

autocmd FileType make set noexpandtab shiftwidth=8 softtabstop=0

убедитесь, что обнаружение типа файла включено, хотя.


Спасибо за отличные автокоманды! Я заметил в этом уроке, когда узнал от вас, .vimrcчто если вы не заключите свои разделы autocmdв augroupразделы, Vim прочитает их и продублирует. Это верно?
Джошуа

6

Вместо того, чтобы делать это с помощью autocmds, вы можете создать свой собственный плагин для файловых типов для каждого типа файлов и разместить его там ~/.vim/ftplugin/<filetype>.vim, где <filetype>вы хотите указать фактический тип файла. Например:

mkdir -p ~/.vim/ftplugin
echo "setlocal noexpandtab" > ~/.vim/ftplugin/make.vim

Вам необходимо убедиться, что в вашем файле включены подключаемые модули ~/.vimrcс помощью следующей команды:

filetype plugin on

Этот ответ имеет больше смысла, если вы хотите, чтобы ваши каталоги .vimrc и .vim были аккуратными.
Флоби

0

Проще настроить vim так, чтобы он всегда расширял вкладки, что нужно для всех файлов, кроме make-файлов. В make-файлах вы можете использовать вкладку, где хотите. Это не будет расширено.

Используя наш сайт, вы подтверждаете, что прочитали и поняли нашу Политику в отношении файлов cookie и Политику конфиденциальности.
Licensed under cc by-sa 3.0 with attribution required.