vim/vimrc

595 lines
19 KiB
VimL
Raw Normal View History

2019-05-29 08:13:03 +00:00
" vim: fdm=marker
"{{{ Клавиши Leader и LocalLeader
let mapleader="\<Space>"
let maplocalleader=","
" Таймауты для ввода комбинаций, использующих клавиши Leader и LocalLeader
set timeout timeoutlen=5000 ttimeoutlen=100
"}}}
" https://github.com/tpope/vim-pathogen
call pathogen#infect()
" https://github.com/junegunn/vim-plug
" Менеджер плагинов "
call plug#begin('~/.vim/plugged')
" https://github.com/lyokha/vim-xkbswitch
" Автоматическое переключение раскладки клавиатуры в режиме вставки "
Plug 'lyokha/vim-xkbswitch'
" https://github.com/itchyny/lightline.vim
" Настраиваемая строка состояния "
" https://github.com/taohexxx/lightline-buffer
" Строка с названиями буферов "
Plug 'itchyny/lightline.vim' | Plug 'taohexxx/lightline-buffer'
" https://github.com/oblitum/rainbow
" Разноцветные скобки "
Plug 'oblitum/rainbow'
" https://github.com/ntpeters/vim-better-whitespace
" Подсветка лишних пробельных символов "
Plug 'ntpeters/vim-better-whitespace'
" https://github.com/wincent/terminus
" Улучшенная поддержка терминала "
Plug 'wincent/terminus'
" https://www.vim.org/scripts/script.php?script_id=231
" Tab для логической разметки, Space для выравнивания "
Plug 'dpc/vim-smarttabs'
" https://github.com/ctrlpvim/ctrlp.vim
" Поиск файлов и буферов "
Plug 'ctrlpvim/ctrlp.vim'
" https://github.com/easymotion/vim-easymotion
" Быстрая навигация "
Plug 'easymotion/vim-easymotion'
" https://github.com/haya14busa/incsearch.vim
" Поиск "
Plug 'haya14busa/incsearch.vim' | Plug 'haya14busa/incsearch-easymotion.vim'
" https://github.com/moll/vim-bbye
" Удаление буферов с сохранением расположения окон "
Plug 'moll/vim-bbye'
" https://github.com/sstallion/vim-wildignore
" Чтение масок файлов из файлов wildignore и suffixes "
Plug 'sstallion/vim-wildignore'
" https://github.com/tpope/vim-fugitive
" Git "
" Plug 'tpope/vim-fugitive'
" https://github.com/airblade/vim-gitgutter
" Отличия от Git в левой колонке "
Plug 'airblade/vim-gitgutter'
" https://github.com/neomake/neomake
" Проверка синтаксиса в фоновом режиме "
Plug 'neomake/neomake'
" https://github.com/stephpy/vim-yaml
" YAML "
Plug 'stephpy/vim-yaml'
" https://github.com/plasticboy/vim-markdown
" Markdown "
Plug 'plasticboy/vim-markdown'
" https://github.com/SirVer/ultisnips
" Вставка фрагментов кода "
Plug 'sirver/ultisnips'
" https://github.com/honza/vim-snippets
" Библиотека фрагментов кода "
Plug 'honza/vim-snippets'
" https://github.com/aklt/plantuml-syntax
" Plantuml "
Plug 'aklt/plantuml-syntax'
" https://github.com/dhruvasagar/vim-table-mode
" Создание таблиц "
Plug 'dhruvasagar/vim-table-mode'
" https://github.com/junegunn/vim-easy-align
" Выравнивание строк "
Plug 'junegunn/vim-easy-align'
" Перечисление плагинов заканчивается здесь "
call plug#end()
"{{{ Базовые настройки
" Включена подсветка синтаксиса "
syntax on
filetype plugin indent on
" Отключен режим совместимости "
set nocompatible
" Проверка изменения файла другой программой "
set autoread
" Автоматическая запись перед make, внешними командами и т.п. "
set autowrite
" Показывать парные скобки "
set showmatch
" Размер табуляции "
set tabstop=4
" Размер сдвига при нажатии на клавиши << и >> "
set shiftwidth=4
" Количество пробелов, на которое будет заменена табуляция "
set softtabstop=4
" Не заменять <TAB> на пробелы "
set noexpandtab
" Визуальный перенос строк "
set wrap
" Визуальный перенос строк по словам, а не по буквам "
set linebreak
" Визуальный перенос строки с учётом отступов "
set breakindent
" Подсветка выражения, которое ищется в тексте "
set hlsearch
" Переход на найденный текст в процессе набора строки "
set incsearch
" Не останавливать поиск при достижении конца файла "
set wrapscan
" Игнорировать регистр букв при поиске, если в шаблоне нет заглавных букв "
set smartcase
" Копирует отступ от предыдущей строки "
set autoindent
" Автоматическая расстановка отступов "
set smartindent
" Кодировка внутри Vim "
set encoding=utf-8
" Кодировка терминала "
set termencoding=utf-8
" Кодировка для сохраняемого файла "
set fileencoding=utf-8
" Список предполагаемых кодировок в порядке предпочтения "
set fileencodings=utf8,koi8r,cp1251,cp866,latin1,ucs-2le
" Включаем мышку даже в текстовом режиме "
" (без этого символы табуляции раскладываются в кучу пробелов) "
set mouse=a
" Модель поведения правой кнопки мыши "
set mousemodel=popup
" Тип переноса строк "
set fileformat=unix
" В графическом режиме: убрать меню "
set guioptions-=m
" В графическом режиме: убрать панель инструментов "
set guioptions-=T
" В графическом режиме: убрать прокрутку справа "
set guioptions-=r
" В графическом режиме: убрать прокрутку слева "
set guioptions-=L
" В графическом режиме: отключить графические вкладки "
set guioptions-=e
" Шрифт в графическом режиме "
set guifont=PragmataPro\ 10
" Количество отображаемых строк над/под курсором "
set scrolloff=6
" Количество отображаемых колонок слева/справа от курсора "
set sidescrolloff=5
" Нумерация строк включена "
set number
" Нумерация строк абсолютная "
set nornu
" Использовать меню в статусной строке "
set wildmenu
" Клавиша для переключения между пунктами меню "
set wildcharm=<Tab>
" Всегда отображать статусную строку для каждого окна "
set laststatus=2
" Отображение набираемой в данный момент команды в правом нижнем углу экрана "
set showcmd
" Пробельные символы "
set listchars=tab:>·,trail:~,extends:>,precedes:<,space:␣
" Включение отображения пробельных символов "
set list
" Копирование выравнивания от предыдущей строки "
set copyindent
"}}}
"{{{ Раскладки клавиатуры
let g:XkbSwitchEnabled = 1
let g:XkbSwitchNLayout = 'us'
let g:XkbSwitchIMappings = ['ru']
let g:XkbSwitchIMappingsTr = {
\ 'ru':
\ {'<': 'qwertyuiop[]asdfghjkl;''zxcvbnm,.`/'.
\ 'QWERTYUIOP{}ASDFGHJKL:"ZXCVBNM<>?~@#$^&|',
\ '>': 'йцукенгшщзхъфывапролджэячсмитьбюё.'.
\ 'ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ,Ё"№;:?/'}
\ }
let g:XkbSwitchSkipIMappings = {
\ 'c' : ['.', '>', ':', '{<CR>', '/*', '/*<CR>'],
\ 'cpp' : ['.', '>', ':', '{<CR>', '/*', '/*<CR>'],
\ 'markdown' : ['[', ']', '{', '}', "'", '"', '`', '~']
\ }
"}}}
"{{{ Цветовая схема kolor https://github.com/zeis/vim-kolor/
" Enable italic. Default: 1
let g:kolor_italic=0
" Enable bold. Default: 1
let g:kolor_bold=1
" Enable underline. Default: 0
let g:kolor_underlined=0
" Gray 'MatchParen' color. Default: 0
let g:kolor_alternative_matchparen=0
" White foreground 'MatchParen' color that might work better with some terminals. Default: 0
let g:kolor_inverted_matchparen=0
colorscheme kolor
highlight SpecialKey guifg=#585858 guibg=NONE gui=none
highlight NonText guifg=#585858 guibg=#2e2d2b gui=none
if &t_Co > 255
highlight SpecialKey ctermfg=240 ctermbg=none cterm=none
highlight NonText ctermfg=240 ctermbg=235 cterm=none
endif
" Разноцветные скобки для определённых типов файлов
autocmd FileType bash,python,vim,html,c,cpp,objc,objcpp call rainbow#load()
"}}}
"{{{ Подсветка лишних пробельных символов
let g:better_whitespace_enabled=1
let g:strip_whitelines_at_eof=1
let g:strip_whitespace_on_save=0
autocmd FileType javascript,c,cpp,java,html,ruby,vim,python EnableStripWhitespaceOnSave
"}}}
"{{{1 Статусная строка
" Всегда отображать статусную строку для каждого окна "
set laststatus=2
" Всегда отображать перечень буферов "
set showtabline=2
" \ [ 'fugitive', 'readonly', 'filename', 'modified' ] ],
" \ 'fugitive': '%{exists("*fugitive#head")?fugitive#head():""}',
" \ 'fugitive': '(exists("*fugitive#head") && ""!=fugitive#head())',
" Lightline
let g:lightline = {
\ 'colorscheme': 'wombat',
\ 'active': {
\ 'left': [ [ 'filetype' ],
\ [ 'mode', 'paste' ],
\ [ 'readonly', 'filename', 'modified' ] ],
\ 'right': [ [ 'character', 'lineinfo', 'percent' ], [ 'fileformat', 'fileencoding' ], [ 'neomake_errors', 'neomake_warnings' ] ]
\ },
\ 'tabline': {
\ 'left': [ [ 'bufferinfo' ],
\ [ 'separator' ],
\ [ 'bufferbefore', 'buffercurrent', 'bufferafter' ], ],
\ 'right': [ [ 'close' ], ],
\ 'separator': { 'left': '|', 'right': '|' },
\ },
\ 'component': {
\ 'readonly': '%{&filetype=="help"?"":&readonly?"⭤":""}',
\ 'modified': '%{&filetype=="help"?"":&modified?"+":&modifiable?"":"-"}',
\ 'character': '%04B',
\ 'separator': '|',
\ },
\ 'component_function': {
\ 'mode': 'LightlineMode',
\ 'bufferinfo': 'lightline#buffer#bufferinfo',
\ },
\ 'component_visible_condition': {
\ 'readonly': '(&filetype!="help"&& &readonly)',
\ 'modified': '(&filetype!="help"&&(&modified||!&modifiable))',
\ 'neomake_errors': '(exists(":Neomake") && ((get(neomake#statusline#QflistCounts(), "E", 0) + get(neomake#statusline#LoclistCounts(), "E", 0)) > 0)',
\ 'neomake_warnings': '(exists(":Neomake") && ((get(neomake#statusline#QflistCounts(), "W", 0) + get(neomake#statusline#LoclistCounts(), "W", 0)) > 0)',
\ 'character': '1'
\ },
\ 'component_expand': {
\ 'buffercurrent': 'lightline#buffer#buffercurrent',
\ 'bufferbefore': 'lightline#buffer#bufferbefore',
\ 'bufferafter': 'lightline#buffer#bufferafter',
\ 'neomake_errors': 'LightLineNeomakeErrors',
\ 'neomake_warnings': 'LightLineNeomakeWarnings',
\ },
\ 'component_type': {
\ 'buffercurrent': 'tabsel',
\ 'bufferbefore': 'raw',
\ 'bufferafter': 'raw',
\ },
\ 'separator': { 'left': '', 'right': '' },
\ 'subseparator': { 'left': '|', 'right': '|' },
\ 'tabline_separator': { 'left': '', 'right': '' },
\ 'tabline_subseparator': { 'left': '|', 'right': '|' },
\ }
function! LightlineMode()
return expand('%:t') ==# '__Tagbar__' ? 'Tagbar':
\ expand('%:t') ==# 'ControlP' ? 'CtrlP' :
\ &filetype ==# 'unite' ? 'Unite' :
\ &filetype ==# 'vimfiler' ? 'VimFiler' :
\ &filetype ==# 'vimshell' ? 'VimShell' :
\ winwidth(0) > 60 ? lightline#mode()[0:2] : ''
endfunction
function! LightLineNeomakeErrors()
if !exists(":Neomake") || ((get(neomake#statusline#QflistCounts(), "E", 0) + get(neomake#statusline#LoclistCounts(), "E", 0)) == 0)
return ''
endif
return 'E:'.(get(neomake#statusline#LoclistCounts(), 'E', 0) + get(neomake#statusline#QflistCounts(), 'E', 0))
endfunction
function! LightLineNeomakeWarnings()
if !exists(":Neomake") || ((get(neomake#statusline#QflistCounts(), "W", 0) + get(neomake#statusline#LoclistCounts(), "W", 0)) == 0)
return ''
endif
return 'W:'.(get(neomake#statusline#LoclistCounts(), 'W', 0) + get(neomake#statusline#QflistCounts(), 'W', 0))
endfunction
"1}}}
"{{{ Настройка CtrlP
let g:ctrlp_custom_ignore = {
\ 'dir': '\v[\/](\.(git|hg|svn)|\_site)$',
\ 'file': '\v\.(exe|so|dll|class|png|jpg|jpeg)$',
\ 'link': 'some_bad_symbolic_links',
\ }
let g:ctrlp_follow_symlinks = 1
if executable('ag')
" Use ag over grep
set grepprg=ag\ --nogroup\ --nocolor
" Use ag in CtrlP for listing files. Lightning fast and respects .gitignore
let g:ctrlp_user_command = 'ag %s -l --nocolor -g ""'
" ag is fast enough that CtrlP doesn't need to cache
let g:ctrlp_use_caching = 0
endif
" Use a leader instead of the actual named binding
nmap <leader>p :CtrlP<cr>
" Easy bindings for its various modes
nmap <leader>bb :CtrlPBuffer<cr>
nmap <leader>bm :CtrlPMixed<cr>
nmap <leader>bs :CtrlPMRU<cr>"
"1}}}
"{{{1 Перемещение по буферам
nmap <Leader>bc :Bdelete<CR>
nmap <Leader>bn :bnext!<CR>
nmap <Leader>bp :bprev!<CR>
" map <Leader>b<c> to navigate through tabs
for c in range('1', '9')
exec "nmap <Leader>b".c." :b!".c."<CR>"
endfor
"1}}}
" Переход к последней позиции при открытии файла "
if has("autocmd")
au BufReadPost * if line("'\"") > 0 && line("'\"") <= line("$") | exe "normal g'\"" | endif
endif
" Открыть файл настроек "
nmap <silent> <leader>vie :e $MYVIMRC<CR>
" Перезагрузить файл настроек "
nmap <silent> <leader>vis :so $MYVIMRC<CR>
augroup reload_vimrc
autocmd!
autocmd BufWritePost $MYVIMRC nested source $MYVIMRC
augroup END
"{{{ Neomake
" Запускать после записи или чтения файла
call neomake#configure#automake('rw', 1000)
function! LocationNext()
try
lnext
catch
try | lfirst | catch | endtry
endtry
endfunction
" <leader>e для перехода к следующей ошибке или предупреждению "
nnoremap <leader>ee :call LocationNext()<cr>
let g:neomake_make_maker = {
\ 'exe': 'make',
\ 'args': ['-j', 'auto'],
\ 'errorformat': '%f:%l:%c: %m',
\ }
"}}}
" Отмена автоматического комментирования кода при вставке из буфера "
autocmd FileType * setlocal formatoptions-=cro
" Запрет TAB для markdown "
autocmd FileType markdown set expandtab
autocmd FileType cmake setlocal ts=2 sts=2 sw=2 et
"{{{ Проверка орфографии для русского и английского
setlocal spell spelllang=ru,en
set spellsuggest=9
function! ChangeSpellLang()
if &spelllang == "ru,en"
setlocal spell spelllang=en
echo "spelllang: en"
elseif &spelllang == "en"
setlocal spell spelllang=ru
echo "spelllang: ru"
elseif &spelllang == "ru"
setlocal nospell spelllang=
echo "spelllang: off"
else
setlocal spell spelllang=ru,en
echo "spelllang: ru,en"
endif
endfunc
" Выбор набора языков для проверки орфографии "
map <C-F7> :call ChangeSpellLang()<CR>
imap <C-F7> <Esc>:call ChangeSpellLang()<CR>
" Выбор альтернатив для исправления "
imap <F7> <C-X>s
map <F7> z=
"}}}
"{{{ Переключение варианта нумерации строк
function! ChangeNumbering()
if &number
if &rnu
set nornu
else
set nonumber
endif
else
set number
set rnu
endif
endfunc
map <LocalLeader># <Esc>:call ChangeNumbering()<CR>
"}}}
"{{{ Меню для выбора кодировки файла
menu Encoding.Open\ as\ KOI8-R :e ++enc=koi8-r<CR>
menu Encoding.Open\ as\ CP1251 :e ++enc=cp1251<CR>
menu Encoding.Open\ as\ CP866 :e ++enc=cp866<CR>
menu Encoding.Open\ as\ LATIN1 :e ++enc=latin1<CR>
menu Encoding.Open\ as\ UCS-2LE :e ++enc=ucs-2le<CR>
menu Encoding.Open\ as\ UTF-8 :e ++enc=utf-8<CR>
menu Encoding.Convert\ to\ UTF-8 :set fenc=utf-8<CR>
map <F12> :emenu Encoding.<Tab>
"}}}
"{{{ Easymotion
" Не включать команды по умолчанию "
let g:EasyMotion_do_mapping = 0
" Умный регистр "
let g:EasyMotion_smartcase = 1
" <Leader>ec{char} для перехода к {char} "
map <Leader>ec <Plug>(easymotion-bd-f)
nmap <Leader>ec <Plug>(easymotion-overwin-f)
" s{char}{char} для перехода к {char}{char} "
nmap s <Plug>(easymotion-overwin-f2)
" Переход к строке "
map <Leader>eg <Plug>(easymotion-bd-jk)
nmap <Leader>eg <Plug>(easymotion-overwin-line)
" Переход к слову "
map <Leader>ew <Plug>(easymotion-bd-w)
nmap <Leader>ew <Plug>(easymotion-overwin-w)
" Навигация по строкам "
map <Leader>el <Plug>(easymotion-lineforward)
map <Leader>ej <Plug>(easymotion-j)
map <Leader>ek <Plug>(easymotion-k)
map <Leader>eh <Plug>(easymotion-linebackward)
" Повторить последний переход
map <Leader>er <Plug>(easymotion-repeat)
" Замена стандартного поиска по тексту
" map / <Plug>(easymotion-sn)
" omap / <Plug>(easymotion-tn)
" These `n` & `N` mappings are options. You do not have to map `n` & `N` to EasyMotion.
" Without these mappings, `n` & `N` works fine. (These mappings just provide
" different highlight method and have some other features )
" map n <Plug>(easymotion-next)
" map N <Plug>(easymotion-prev)
"}}}
"{{{ Incsearch
map / <Plug>(incsearch-forward)
map ? <Plug>(incsearch-backward)
map g/ <Plug>(incsearch-stay)
map z/ <Plug>(incsearch-easymotion-/)
map z? <Plug>(incsearch-easymotion-?)
map zg/ <Plug>(incsearch-easymotion-stay)
"}}}
"{{{ UltiSnips
let g:UltiSnipsExpandTrigger="<tab>"
let g:UltiSnipsJumpForwardTrigger="<c-b>"
let g:UltiSnipsJumpBackwardTrigger="<c-z>"
let g:UltiSnipsEditSplit="vertical"
"}}}
"{{{ Table Mode
let g:table_mode_corner='|'
let g:table_mode_corner_corner='+'
let g:table_mode_header_fillchar='='
"}}}
"{{{ Easy align
" Start interactive EasyAlign in visual mode (e.g. vipga)
xmap ga <Plug>(EasyAlign)
" Start interactive EasyAlign for a motion/text object (e.g. gaip)
nmap ga <Plug>(EasyAlign)
"}}}