· 6 years ago · Sep 04, 2019, 05:52 PM
1" nvim file: ~/.config/nvim/init.vim
2" Last Change: set 04 2019 08:24
3" vim: ff=unix ai et ts=4
4" Author: Sérgio Luiz Araújo Silva
5"
6" ( O O )
7" +-----------oOO--(_)--OOo--------------+
8" | |
9" | °v° Sergio Luiz Araujo Silva |
10" | /(_)\ Linux User #423493 |
11" | ^ ^ voyeg3r ✉ gmail.com |
12" +--------------------------------------+
13"
14" _ _ _
15" | \ | | ___ _____ _(_)_ __ ___
16" | \| |/ _ \/ _ \ \ / / | '_ ` _ \
17" | |\ | __/ (_) \ V /| | | | | | |
18" |_| \_|\___|\___/ \_/ |_|_| |_| |_|
19"
20"
21" TODO: fix some indentation issuies
22"
23" As you type a substitution the results will immediately be
24" visible in the edit window. This feature is best highlighted
25" in this video: http://www.youtube.com/watch?v=sA3z6gsqOuw
26if has("nvim")
27 set inccommand=nosplit
28 tnoremap <Esc> <c-\><c-n>
29 if executable('nvr')
30 let $VISUAL="nvr -cc split --remote-wait +'set bufhidden=wipe'"
31 endif
32endif
33
34" Required:
35let mapleader = ','
36set shada=!,'500,<50,s10,h
37set nospell
38
39set nomodeline
40
41"set spelllang=en,pt
42"set complete+=kspell
43"set sps=8 " Quantidade de sugestões do spell
44" i_Ctrl-g_u allows us to have a better undo
45inoremap <C-s> <c-g>u<Esc>[s1z=gi<c-g>u
46
47" Toggles paste to insert clipboard content
48"inoremap <S-Insert> <ESC>:setl paste<CR>gi<C-R>+<ESC>:setl nopaste<CR>gi
49inoremap <S-Insert> <ESC>"+p`]a
50
51" Auto install vim plug
52if empty(glob('~/.dotfiles/nvim/autoload/plug.vim'))
53 if !executable("curl")
54 echoerr "You have to install curl or first install vim-plug yourself!"
55 execute "q!"
56 endif
57 silent !curl -fLo ~/.dotfiles/nvim/autoload/plug.vim --create-dirs
58 \ https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
59 autocmd VimEnter * PlugInstall --sync | source $MYVIMRC
60endif
61
62call plug#begin(expand(glob('~/.config/nvim/plugged')))
63"Plug 'lervag/vimtex'
64"Plug 'voldikss/vim-translate-me'
65"Plug 'mhinz/vim-startify'
66"Plug 'henrik/vim-indexed-search'
67"Plug 'coderifous/textobj-word-column.vim'
68"Plug 'mhinz/neovim-remote'
69Plug 'junegunn/limelight.vim'
70Plug 'bilalq/lite-dfm'
71Plug 'PeterRincker/vim-searchlight'
72Plug 'Yggdroot/indentLine'
73Plug 'ap/vim-buftabline'
74"Plug 'voyeg3r/vim-neatstatus'
75Plug 'nelstrom/vim-visual-star-search'
76Plug 'w0rp/ale' , { 'on': ['ALEToggle'] }
77Plug 'rking/ag.vim', { 'on': ['Ag'] }
78"Plug 'wellle/targets.vim'
79Plug 'mattn/emmet-vim' , { 'for': ['html', 'htmldjango', 'javascript.jsx', 'css'] }
80Plug 'tpope/vim-abolish', { 'on': [] } "Advanced regex Substitution
81"Plug 'tpope/vim-surround', { 'on': [] }
82Plug 'tpope/vim-surround',
83 \ { 'on': ['<Plug>Dsurround', '<Plug>Csurround', '<Plug>CSurround',
84 \ '<Plug>Ysurround', '<Plug>YSurround', '<Plug>Yssurround',
85 \ '<Plug>YSsurround', '<Plug>VSurround', '<Plug>VgSurround'] }
86"Plug 'tpope/vim-unimpaired'
87"Plug 'godlygeek/tabular', { 'on': ['Tabularize'] }
88"Plug 'jezcope/vim-align', { 'on' : 'Align' }
89Plug 'tommcdo/vim-exchange'
90"Plug 'nelstrom/vim-visual-star-search'
91"Plug 'nelstrom/vim-markdown-folding'
92"Plug 'haya14busa/incsearch.vim'
93Plug 'timakro/vim-searchant'
94"Plug 'inside/vim-search-pulse'
95Plug 'machakann/vim-highlightedyank'
96Plug 'vim-scripts/VisIncr', { 'on': [] }
97Plug 'Shougo/deoplete.nvim', { 'do': ':UpdateRemotePlugins' }
98Plug 'zchee/deoplete-jedi'
99Plug 'kshenoy/vim-signature', { 'on': [] }
100Plug 'vimwiki/vimwiki', { 'for': ['markdown', 'vimwiki'] }
101"Plug 'vimwiki/vimwiki', { 'for': [] }
102Plug 'sjl/gundo.vim', { 'on': ['GundoToggle'] }
103"Plug 'chrisbra/NrrwRgn', { 'on': ['NR', 'NrrwRgn'] }
104Plug 'chrisbra/NrrwRgn'
105Plug 'tpope/vim-speeddating'
106Plug 'jiangmiao/auto-pairs'
107"Plug 'rstacruz/vim-closer'
108Plug 'tpope/vim-commentary'
109"Plug 'tpope/vim-fugitive'
110"Plug 'tommcdo/vim-lion', { 'on': [] }
111Plug 'vim-airline/vim-airline'
112Plug 'vim-airline/vim-airline-themes'
113"Plug 'airblade/vim-gitgutter'
114Plug 'vim-scripts/grep.vim', { 'on': [] }
115Plug 'vim-scripts/CSApprox', { 'on': [] }
116"Plug 'majutsushi/tagbar'
117"Plug 'scrooloose/syntastic'
118"Plug 'Yggdroot/indentLine'
119
120if isdirectory('/usr/local/opt/fzf')
121 Plug '/usr/local/opt/fzf' | Plug 'junegunn/fzf.vim'
122else
123 Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
124 Plug 'junegunn/fzf.vim'
125 "Plug 'junegunn/fzf', { 'on': ['FZF', 'History', 'Files' ], 'dir': '~/.fzf', 'do': './install --bin' }
126 "Plug 'junegunn/fzf.vim', { 'on': ['FZF', 'History', 'Files' ] }
127endif
128
129Plug 'scrooloose/nerdtree', { 'on': 'NERDTreeToggle' }
130"Plug 'SirVer/ultisnips', {'on': '#InsertEnter' } | Plug 'honza/vim-snippets', {'on': [] }
131"Plug 'SirVer/ultisnips', { 'on': [] }
132Plug 'SirVer/ultisnips'
133Plug 'honza/vim-snippets'
134
135" Color
136Plug 'sainnhe/vim-color-forest-night'
137Plug 'axvr/photon.vim'
138Plug 'morhetz/gruvbox'
139Plug 'reedes/vim-colors-pencil'
140Plug 'trevordmiller/nova-vim'
141Plug 'crusoexia/vim-monokai', { 'on': [] }
142Plug 'ayu-theme/ayu-vim'
143Plug 'drewtempelmeyer/palenight.vim'
144Plug 'endel/vim-github-colorscheme'
145Plug 'NLKNguyen/papercolor-theme'
146Plug 'icymind/NeoSolarized'
147Plug 'lifepillar/vim-solarized8'
148Plug 'tomasr/molokai'
149Plug 'nanotech/jellybeans.vim'
150Plug 'mhartington/oceanic-next'
151Plug 'sainnhe/vim-color-vanilla-cake'
152" statusline
153"Plug 'vim-scripts/Obvious-Mode'
154" Color picker
155Plug 'lilydjwg/colorizer', { 'on': [] }
156call plug#end()
157
158" Recover from accidental Ctrl-U
159" http://vim.wikia.com/wiki/Recover_from_accidental_Ctrl-U
160" use Ctrl-r . to get your text back
161"inoremap <c-u> <c-g>u<c-u>
162"inoremap <c-w> <c-g>u<c-w>
163"inoremap <c-y> <c-o>u
164inoremap <silent> <c-w> <c-\><c-o>db
165inoremap <silent> <c-u> <c-\><c-o>d0
166"inoremap <silent> <C-S-Y> <C-R>"
167
168" https://github.com/ryangrose/easy-pandoc-templates
169" https://vi.stackexchange.com/questions/17549/
170if !exists('*PandocMappings')
171 function! PandocMappings()
172 " NOTE: <F16> equals to Shift-F4
173 noremap <F4> :! pandoc '%:p' -o /tmp/'%:p:t'.html --template=easy_template.html --toc && firefox /tmp/'%:p:t'.html &<CR><CR>
174 noremap <F16> :! pandoc '%:p' -o /tmp/'%:p:t'.pdf --pdf-engine=pdflatex --toc && evince /tmp/'%:p:t'.pdf &<CR><CR>
175 endfun
176endif
177
178augroup every
179 autocmd!
180 au InsertEnter * set norelativenumber
181 au InsertLeave * set relativenumber
182augroup END
183
184" inserts a line below without commenting if file is modifiable &ma?
185" nnoremap <silent> <cr> :set paste<cr>o<esc>:set nopaste<cr>
186nnoremap <expr> <Enter> &ma?":set paste\<cr>\<esc>o\<esc>:set nopaste\<cr>":"\<cr>"
187
188" show registers
189nnoremap <Leader>r :registers<CR>
190
191" save with <F9> if file was modified
192nnoremap <F9> :update<cr>
193inoremap <F9> <c-o>:update<cr>
194vnoremap <F9> :<c-u>update<cr><bar>gv
195
196nnoremap Q :normal .<CR>
197
198nnoremap '. `.
199nnoremap - $
200
201nnoremap n nzzzv
202nnoremap N Nzzzv
203nnoremap } }zzzv
204nnoremap { {zzzv
205"nnoremap <C-M-l> :set cursorline!<CR>
206nnoremap <C-M-l> :<c-u>setlocal list! list?<CR>
207
208" spelling
209" nnoremap <C-s> [s1z=<C-o>
210" nnoremap <Leader>s ]s1z=<C-o>
211" nnoremap <Leader>g ]szg<C-o>
212" See more about <C-x>s
213" Below mappings allows you to toggle spelling
214" nnoremap <F7> :setlocal spell!<CR>
215" inoremap <F7> <C-o>:setlocal spell!<CR>
216
217" allows me to use a smarter cgn
218"nnoremap * :keepjumps normal *``<cr>
219nnoremap c* *<c-o>cgn
220nnoremap c# #<C-o>cgn
221
222" avoid clipboard hacking security issue
223" http://thejh.net/misc/website-terminal-copy-paste
224inoremap <C-R>+ <C-R><C-R>+
225" Auto reindent pasted text (from hacking vim p.138)
226" nnoremap p p=`]
227" cool
228
229"command! -nargs=0 CopyFile :%y+<CR>
230command! CloneBuffer new | 0put =getbufline('#',1,'$')
231
232command! WipeReg for i in range(34,122) | silent! call setreg(nr2char(i), []) | endfor
233
234function! s:Registers( arguments )
235 redir => l:registersOutput
236 silent! execute 'registers' a:arguments
237 redir END
238 for l:line in split(l:registersOutput, "\n")
239 if l:line !~# '^"\S\s*$'
240 echo l:line
241 endif
242 endfor
243endfunction
244command! -nargs=? Registers call <SID>Registers(<q-args>)
245
246" Spell mistakes color
247"highlight SpellBad cterm=bold ctermfg=white ctermbg=red
248"highlight SpellCap cterm=bold ctermfg=red ctermbg=white
249if has("multi_byte")
250 if &termencoding == ""
251 let &termencoding = &encoding
252 endif
253 set encoding=utf-8
254 setglobal fileencoding=utf-8
255 set fileencodings=ucs-bom,utf-8,latin1
256endif
257
258set guicursor=n-v-c:block,i-ci-ve:ver25,r-cr:hor20,o:hor50
259 \,a:blinkwait300-blinkoff200-blinkon150-Cursor/lCursor
260 \,sm:block-blinkwait175-blinkoff150-blinkon175
261
262set laststatus=2
263set guicursor+=n:blinkon1 " not blinking cursor in normal mode
264"set guicursor+=i:blinkon1 " cursor blinkin in insert mode
265"
266"set dictionary+=~/.dotfiles/nvim/words.txt " C-x C-k C-n
267"set nrformats+=alpha " Increases/Decreases numbers with Ctrl-a/Ctrl-x correctrly
268set lazyredraw " speed up macros
269set mouse=a " enable mouse click
270set path+=.,**
271set scrolloff=1 " keep 1 line visible when scrolling
272set sidescrolloff=5
273set ai " set auto-indenting on for programming (nvim default)
274set hidden " Switch buffers without saving them
275"set autowrite
276"set autowriteall
277set display+=lastline
278"set nobackup " do not keep a backup file
279set number " show line numbers
280set showmatch " jump to matches when entering regexp
281set ignorecase " ignore case when searching
282set infercase " case inferred by default
283set smartcase " no ignorecase if Uppercase char present
284set visualbell " turn off error beep/flash
285set novisualbell " turn off visual bell
286set title " shows filename at the top
287set formatoptions=tcqj
288set expandtab " Converts tab into spaces
289set tabstop=4 " Number of spaces that a <Tab> in the file counts for
290set softtabstop=4 " number of spaces in tab when editing
291set shiftwidth=4 " indented with the reindent operations with >> and <<
292set nojoinspaces " Prevents inserting two spaces after punctuation on a join (J)
293set shiftround " when at 3 spaces, and I hit > go to 4, not 5
294"set t_RV=
295
296let &fillchars = "vert:\u2502,diff: "
297let &listchars = "tab:\u25b8 ,extends:\u00bb,precedes:\u00ab,space:\u00b7,nbsp:\u2334,eol:\u21b2"
298let &showbreak = "\u21aa "
299
300set wildignore+=*.o,*.obj,.git,*.rbc,*.pyc,__pycache__,*.swp,*.bak
301set wildignore+=*.so,*.pdf,*.swp,*.zip,*.pyc,*.db,*.sqlite,*.jpg,*.png,*.gif
302set wildmenu
303"set wildmode=list:longest,full
304"set wildmode=longest:full,list:full
305set wildmode=longest,list
306" making <tab> work properly on vim command line
307"set whichwrap +=<,>
308set nopaste
309set pastetoggle=<F8>
310set linebreak " Keep whole words during wrapping
311set noshowmode
312set noerrorbells visualbell
313
314"You can get case-insensitivity for the filename completion in Vim with the following.
315set wildignorecase
316
317" jump to next/previous comment
318" https://vimtricks.com/viml/2017/05/26/jump-to-next-commented-line/
319nnoremap ]c :call search('^\s*'.substitute(escape(&cms, '\.*[]^$'), '%s', '.*', '').'\s*$')<CR>
320nnoremap [c :call search('^\s*'.substitute(escape(&cms, '\.*[]^$'), '%s', '.*', '').'\s*$', 'b')<CR>
321
322" nvim default undodir: ~/.local/share/nvim/undo (|xdg|), auto-created
323set undofile " Maintain undo history between sessions
324
325let g:indentLine_char = '▏'
326
327" Enable airline symbols
328let g:airline_powerline_fonts = 1
329let g:airline_highlighting_cache = 1
330
331" if is there more than one buffer it will appear on buftabline
332let g:buftabline_show = 1
333let g:buftabline_numbers = 1
334
335" function! RunningInsideGit()
336" let result = system('env | grep ^GIT_')
337" if result == ""
338" return 0
339" else
340" return 1
341" endif
342" endfunction
343
344" many plugins are disabled by default and called by
345" this function for example: call LoadPluginFunction('vim-lion')
346" and the command LoadPlugin plugin-name (whithout quotes)
347" list unloaded plugins
348" \v^Plug[^/]*\/\zs([^']*)\ze',\s+\{\s+'on':\s+[]
349if !exists('*LoadPluginFunction')
350 fun! LoadPluginFunction(pluginname)
351 let l:curpos = getcurpos()
352 execute plug#load(a:pluginname)
353 call cursor(l:curpos[1], l:curpos[2])
354 return ''
355 endfun
356endif
357command! -nargs=1 LoadPlugin :call LoadPluginFunction(<q-args>)
358
359" augroup help_start
360" autocmd!
361" autocmd FileType help,markdown call SetHelpFiletype()
362" augroup end
363"
364" if !exists('*SetHelpFiletype')
365" fun! SetHelpFiletype()
366" augroup help_insert
367" autocmd!
368" autocmd InsertEnter <buffer> setlocal conceallevel=0 | highlight clear Ignore
369" autocmd InsertLeave <buffer> setlocal conceallevel=2
370" augroup end
371" endfun
372" endif
373
374" Toggle *conceallevel*
375nnoremap <Leader>c :let &l:cole=(&cole == 3) ? 0 : 3 <bar> echo 'conceallevel ' . &cole <CR>
376syntax match arrow "->" conceal cchar=→
377syntax match rcomp ">>" conceal cchar=»
378syntax match lcom "<<" conceal cchar=«
379set concealcursor=n
380set conceallevel=3
381
382" lazy load for ultisnips
383" https://medium.com/@saaguero/improving-performance-in-vim-9b33598c8eaf
384inoremap <silent> <C-j> <C-r>=LoadUltiSnips()<CR>
385nnoremap <silent> <C-M-u> :call LoadUltiSnips()<CR>
386" This function only runs when UltiSnips is not loaded
387if !exists('*LoadUltiSnips')
388 function! LoadUltiSnips()
389 call Preserve(":execute plug#load('vim-snippets')")
390 call Preserve(":execute plug#load('ultisnips')")
391 call UltiSnips#ExpandSnippet()
392 echo "Ultisnips loaded!"
393 return ""
394 endfunction
395endif
396
397nnoremap <Leader>z :LiteDFMToggle<CR>
398
399nnoremap <F2> :NERDTreeToggle<cr>
400" hide old “Press ? for help”
401let NERDTreeMinimalUI = 1
402let NERDTreeDirArrows = 1
403" close nerdthree when it opens a file
404let NERDTreeQuitOnOpen = 1
405" Automatically delete the buffer of the file you just deleted with NerdTree:
406let NERDTreeAutoDeleteBuffer = 1
407
408inoremap <expr> <TAB> pumvisible() ? "\<C-y>" : "\<TAB>"
409let g:deoplete#sources = {}
410let g:deoplete#sources._=['omni', 'buffer', 'member', 'tag', 'ultisnips', 'file']
411let g:deoplete#enable_at_startup = 1
412let g:deoplete#enable_refresh_always = 1
413let g:deoplete#enable_ignore_case = 1
414let g:deoplete#enable_smart_case = 1
415let g:deoplete#enable_camel_case = 1
416let g:deoplete#file#enable_buffer_path = 1
417let g:deoplete#sources#jedi#python_path = '/usr/bin/python3'
418
419" <CR>: close popup and save indent.
420" Now each Enter creates a undo point ":h i_Ctrl-g_u"
421" inoremap <silent> <CR> <C-r>=<SID>my_cr_function()<CR>
422"if !exists('*s:my_cr_function')
423" function! s:my_cr_function()
424" "return deoplete#mappings#smart_close_popup() . "\<C-g>u\<CR>"
425" return deoplete#mappings#smart_close_popup() . "\<CR>"
426" endfunction
427"endif
428
429" Trying to fix deoplete
430"set runtimepath+=~/path/to/deoplete.nvim/
431set runtimepath+=~/.config/nvim/plugged/deoplete.nvim/
432let g:deoplete#enable_at_startup = 1
433
434call deoplete#custom#source('_', 'matchers', ['matcher_full_fuzzy'])
435set omnifunc=syntaxcomplete#Complete
436"set completeopt=longest,menuone,preview,noinsert
437set completeopt=menuone,longest,preview
438
439" copy until the end of line using
440nnoremap Y y$
441
442" Jump outside '"({
443if !exists('g:AutoPairsShortcutJump')
444 let g:AutoPairsShortcutJump = '<A-l>'
445endif
446
447if exists('$SHELL')
448 set shell=$SHELL
449else
450 set shell=/bin/sh
451endif
452
453" Use whole "words" when opening URLs.
454" This avoids cutting off parameters (after '?') and anchors (after '#').
455" See http://vi.stackexchange.com/q/2801/1631
456let g:netrw_gx="<cWORD>"
457let g:netrw_liststyle = 3
458let g:netrw_browsex_viewer= "opera"
459
460" pencil is another great colorscheme
461"colo PaperColor
462"silent! colo gruvbox
463" gruvbox has a great light colorscheme, just press <Shift><F7>
464let colorscheme="PaperColor"
465if findfile("colors/" .colorscheme .".vim", &rtp) != ""
466 execute "colorscheme " . colorscheme
467endif
468
469" https://stackoverflow.com/a/7589970/2571881
470" if strftime("%H") < 17
471" set background=light
472" else
473" set background=dark
474" endif
475
476" source: http://tilvim.com/2013/07/31/swapping-bg.html <F19> = Shif-F7
477" nmap <F19> :let &background = ( &background == "dark"? "light" : "dark" )<CR>
478
479" removed ifs because it must be used with neovim
480let $NVIM_TUI_ENABLE_TRUE_COLOR=1
481set termguicolors
482
483" When double click a word vim will hightlight all other ocurences
484" see CountWordFunction()
485" [I shows lines with word under the cursor
486nnoremap <silent> <2-LeftMouse> :let @/='\V\<'.escape(expand('<cword>'), '\').'\>'<cr>:set hls<cr>:CountWord<cr>
487nnoremap <Leader>* :let @/='\V\<'.escape(expand('<cword>'), '\').'\>'<cr>:set hls<cr>:CountWord<cr>
488
489nnoremap <F5> :GundoToggle<CR>
490let g:gundo_prefer_python3 = 1
491
492nnoremap <Left> :vertical resize +2<CR>
493nnoremap <Right> :vertical resize -2<CR>
494"nnoremap <Up> :resize -2<CR>
495"nnoremap <Down> :resize +2<CR>
496
497set wildchar=<Tab> wildmenu wildmode=full
498set wildcharm=<C-Z>
499nnoremap <F10> :b <C-Z><S-TAB>
500" list buffers and jump to a chosen one
501nnoremap <Leader>b :ls<CR>:b<Space>
502
503" sometimes you need to know how many opened buffers you have
504" source: https://superuser.com/a/1221514/45032
505if !exists('*CountBuffers')
506 fun! CountBuffers() abort
507 "let l:total = len(filter(range(1, bufnr('$')), 'buflisted(v:val)'))
508 let l:total = len(getbufinfo({'buflisted':1}))
509 echom "you have " . l:total . " opened buffers!"
510 endfun
511endif
512command! -nargs=0 Nbufs :call CountBuffers()
513
514if !exists('*CloseAllBuffersButCurrent')
515 function! CloseAllBuffersButCurrent()
516 let curr = bufnr("%")
517 let last = bufnr("$")
518 if curr > 1 | silent! execute "1,".(curr-1)."bd" | endif
519 if curr < last | silent! execute (curr+1).",".last."bd" | endif
520 echom "All other buffers unloaded!"
521 endfunction
522endif
523command! -nargs=0 Bonly :call CloseAllBuffersButCurrent()
524command! -nargs=0 Bo :call CloseAllBuffersButCurrent()
525
526" close the buffer
527nnoremap <C-M-d> :bd!<CR>
528nnoremap <C-M-w> :bw!<CR>
529nnoremap <C-M-o> :Bonly<CR>
530
531" substitute word under cursor - This map is used for spell
532" nnoremap <Leader>s :call Preserve('%s/\<<C-r><C-w>\>//g\<left><left>')
533
534" Scroll split window
535nnoremap <C-M-k> <c-w>w<c-y><c-w>w
536nnoremap <C-M-j> <c-w>w<c-e><c-w>w
537
538" resise windows
539nnoremap <M-=> <C-w>+
540nnoremap <M--> <C-w>-
541filetype on " detect type of file
542"filetype plugin indent on " neovim default (don't bother with this)
543" My font is fira mono regular stled on gnome-shell
544
545" line text-objects
546" vnoremap <silent> al :<c-u>norm!0v$h<cr>
547vnoremap <silent> al :<c-u>norm!0v$<cr>
548vnoremap <silent> il :<c-u>norm!_vg_<cr>
549onoremap <silent> al :norm val<cr>
550onoremap <silent> il :norm vil<cr>
551
552" more text objects
553for char in [ '_', '.', ':', ',', ';', '<bar>', '/', '<bslash>', '*', '+', '%', '`' ]
554 execute 'xnoremap i' . char . ' :<C-u>normal! T' . char . 'vt' . char . '<CR>'
555 execute 'onoremap i' . char . ' :normal vi' . char . '<CR>'
556 execute 'xnoremap a' . char . ' :<C-u>normal! F' . char . 'vf' . char . '<CR>'
557 execute 'onoremap a' . char . ' :normal va' . char . '<CR>'
558endfor
559
560" buffer text-object
561"xnoremap i% GoggV
562"omap i% :<C-u>normal vi%<CR>
563
564command! -nargs=0 Reindent :call Preserve('exec "normal! gg=G"')
565command! MakeTags !ctags -R .
566
567" create a scratch window - rascunho
568command! Scratch new | setlocal bt=nofile bh=wipe nobl noswapfile nu
569cnoreabbrev SC Scratch
570
571" Now this allows me to open a scratch buffer with various options, like I could
572" call :Sedit ft=javascript and that would open a scratch buffer with filetype
573" javascript (and hence show the right syntax highlighting).
574" https://dhruvasagar.com/2014/03/11/creating-custom-scratch-buffers-in-vim
575
576if !exists('*ScratchEdit')
577 function! ScratchEdit(cmd, options)
578 exe a:cmd tempname()
579 setl buftype=nofile bufhidden=wipe nobuflisted
580 if !empty(a:options) | exe 'setl' a:options | endif
581 endfunction
582endif
583
584command! -bar -nargs=* Sedit call ScratchEdit('edit', <q-args>)
585command! -bar -nargs=* Ssplit call ScratchEdit('split', <q-args>)
586command! -bar -nargs=* Svsplit call ScratchEdit('vsplit', <q-args>)
587command! -bar -nargs=* Stabedit call ScratchEdit('tabe', <q-args>)
588
589" select last paste in visual mode
590" https://vim.fandom.com/wiki/Selecting_your_pasted_text
591" nnoremap gp `[v`]
592nnoremap <expr> gp '`[' . strpart(getregtype(), 0, 1) . '`]'
593
594if !exists('*s:setupWrapping')
595 function s:setupWrapping()
596 set wrap
597 set wm=2
598 set textwidth=78
599 set formatoptions+=t
600 endfunction
601endif
602
603" join lines keeping cursor position
604nnoremap J :call Preserve(':join')<CR>
605nnoremap <Leader>J :call Preserve(':join!')<CR>
606"noremap <silent> <expr> j (v:count == 0 ? 'gj' : 'j')
607"noremap <silent> <expr> k (v:count == 0 ? 'gk' : 'k')
608" It adds motions like 25j and 30k to the jump list, so you can cycle
609" through them with control-o and control-i.
610" source: https://www.vi-improved.org/vim-tips/
611nnoremap <expr> j v:count ? (v:count > 5 ? "m'" . v:count : '') . 'j' : 'gj'
612nnoremap <expr> k v:count ? (v:count > 5 ? "m'" . v:count : '') . 'k' : 'gk'
613
614" to insert this result: --> :put =Randnum(1000)
615if !exists('*Randnumber')
616 function! Randnumber(max) abort
617 return str2nr(matchstr(reltimestr(reltime()), '\v\.@<=\d+')[1:]) % a:max
618 endfunction
619endif
620
621if !exists('*CountWordFunction')
622 fun! CountWordFunction()
623 try
624 let l:win_view = winsaveview()
625 exec "%s/" . expand("<cword>") . "//gn"
626 finally
627 call winrestview(l:win_view)
628 endtry
629 endfun
630endif
631
632command! -nargs=0 CountWord :call CountWordFunction()
633cnoreabbrev cw CountWord
634nnoremap <F3> :CountWord<CR>
635
636" Reloads vimrc after saving but keep cursor position
637if !exists('*ReloadVimrcFunction')
638 function! ReloadVimrcFunction()
639 call Preserve(':source $MYVIMRC')
640 hi Normal guibg=NONE ctermbg=NONE
641 windo redraw
642 echom "Reloaded init.vim"
643 endfunction
644endif
645noremap <silent> <Leader>v :e $MYVIMRC<cr>
646command! -nargs=0 ReloadVimrc :call ReloadVimrcFunction()
647
648" Reference: https://stackoverflow.com/posts/30552423/revisions
649augroup vimrc_todo
650 autocmd!
651 autocmd BufEnter * syntax match MyTodo /\v<(FIXME|NOTE|OBS|TODO|OPTIMIZE)>:/ containedin=.*Comment.*
652 autocmd BufEnter * silent! syntax clear cTodo
653 autocmd BufEnter * silent! syntax clear vimTodo
654augroup END
655"highlight link MyTodo Todo
656highlight def link MyTodo Todo
657
658augroup Reload
659 autocmd!
660 autocmd BufWritePost init.vim call ReloadVimrcFunction()
661augroup END
662
663" The PC is fast enough, do syntax highlight syncing from start unless 200 lines
664augroup vimrc-sync-fromstart
665 autocmd!
666 "autocmd BufEnter * syntax sync maxlines=200
667 autocmd BufWinEnter,Syntax * syn sync minlines=500 maxlines=500
668augroup END
669
670"" Remember cursor position
671augroup vimrc-remember-cursor-position
672 autocmd!
673 autocmd BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g`\"" | endif
674augroup END
675
676augroup lcd-folder
677 au!
678 autocmd BufEnter * silent! lcd %:p:h
679augroup END
680
681augroup sh
682 au!
683 au! BufWritePost *.sh,*.zsh :silent !chmod a+x <afile>
684augroup END
685
686" trying to fix fzf behavior with <esc>
687augroup fixFzf
688 au!
689 autocmd! FileType fzf tnoremap <buffer> <esc> <c-c>
690augroup END
691
692if !exists('*SetPythonOptions')
693 function! SetPythonOptions()
694 set keywordprg=pydoc
695 filetype plugin indent on
696 set smartindent et sts=4 sw=4 tw=80 fo=croq
697 let python_highlight_builtins=1
698 let python_highlight_all=1
699 let python_highlight_exceptions=1
700 let python_highlight_numbers=1
701 let python_highlight_space_errors=1
702 let g:_uspy=":python3"
703 let g:ultisnipsusepythonversion = 3
704 let g:loaded_python_provider = 0
705 let g:loaded_python3_provider = 0
706 "let g:python_host_skip_check=1
707 "let g:python3_host_skip_check=1
708 endfunction
709endif
710
711let g:python_host_prog = '/usr/bin/python'
712let g:python3_host_prog = '/usr/bin/python3'
713
714"" txt
715augroup vimrc-wrapping
716 autocmd!
717 autocmd BufRead,BufNewFile *.txt,*.md,*.tex call s:setupWrapping()
718augroup END
719
720"" make/cmake
721augroup vimrc-make-cmake
722 autocmd!
723 autocmd FileType make setlocal noexpandtab
724 autocmd BufNewFile,BufRead CMakeLists.txt setlocal filetype=cmake
725augroup END
726
727"augroup markdown
728"" autocmd FileType markdown,vimwiki setlocal textwidth=78 formatprg=par\ -w78
729" autocmd BufNewFile,BufRead *.{md,mdwn,mkd,mkdn,mark*} setlocal ft=markdown
730"augroup END
731
732"augroup spellcheck_documentation
733" autocmd BufNewFile,BufRead *.{md,mdwn,mkd,mkdn,mark*,txt} setlocal spell
734" " Don't mark URL-like and acronyms things as spelling errors
735" syn match UrlNoSpell "\v(https?|ftp):[^[:space:]]*" contains=@NoSpell
736" syn match AcronymNoSpell '\v\u{2,}(\d+)?' contains=@NoSpell
737" syn match myExCapitalWords '+\<[A-Z]\w*\>+' contains=@NoSpell
738"augroup END
739
740" autoformat html files on opening or saving them
741" this function it called only if the filetype is html
742" and pandoc is present in the system
743"function! SetHtml()
744" if executable('pandoc')
745" let pandoc_pipeline = "pandoc --from=html --to=markdown"
746" let pandoc_pipeline .= " | pandoc --from=markdown --to=html"
747" let &l:formatprg=pandoc_pipeline
748" endif
749"endfunction
750
751"" Set working directory
752nnoremap <Leader>. :lcd %:p:h<CR>
753" Change in next bracket
754nnoremap cinb cib
755nnoremap cinB ciB
756"" fzf.vim
757let $FZF_DEFAULT_COMMAND = "find * -path '*/\.*' -prune -o -path 'node_modules/**' -prune -o -path 'target/**' -prune -o -path 'dist/**' -prune -o -type f -print -o -type l -print 2> /dev/null"
758" The Silver Searcher
759if executable('ag')
760 let $FZF_DEFAULT_COMMAND = 'ag --hidden --ignore .git -g ""'
761 set grepprg=ag\ --nogroup\ --nocolor\ --ignore-case\ --column
762 set grepformat=%f:%l:%c:%m,%f:%l:%m
763endif
764
765" nnoremap <silent> <Leader>b :Buffers<CR>
766nnoremap <silent> <Leader>h :History<cr>
767nnoremap <silent> <c-p> :FZF -m ~/.dotfiles<CR>
768
769" " hide fzf statusline
770" if has('nvim') || has('gui_running')
771" autocmd! FileType fzf
772" autocmd FileType fzf set laststatus=0 noshowmode noruler
773" autocmd BufLeave <buffer> set laststatus=2 showmode ruler
774" endif
775
776" Most recent used files
777command! FZFMru call fzf#run({
778\ 'source': v:oldfiles,
779\ 'sink': 'e',
780\ 'options': '-m -x +s',
781\ 'down': '40%'})
782nnoremap <leader>m :FZFMru<cr>
783
784" Files command with preview window
785command! -bang -nargs=? -complete=dir Files
786 \ call fzf#vim#files(<q-args>, fzf#vim#with_preview(), <bang>0)
787
788nnoremap <leader>f :Files<CR>
789
790" snippets
791let g:UltiSnipsExpandTrigger="<C-j>"
792let g:UltiSnipsJumpForwardTrigger="<C-j>"
793let g:UltiSnipsJumpBackwardTrigger="<C-k>"
794let g:UltiSnipsEditSplit="vertical"
795let g:UltiSnipsListSnippets="<C-Space>"
796" syntastic
797let g:syntastic_always_populate_loc_list=1
798let g:syntastic_error_symbol='✗'
799let g:syntastic_warning_symbol='⚠'
800let g:syntastic_style_error_symbol = '✗'
801let g:syntastic_style_warning_symbol = '⚠'
802let g:syntastic_auto_loc_list=1
803let g:syntastic_aggregate_errors = 1
804
805" Tagbar
806"nnoremap <silent> <F4> :TagbarToggle<CR>
807"let g:tagbar_autofocus = 1
808
809"" Vmap for maintain Visual Mode after shifting > and <
810vnoremap < <gv
811vnoremap > >gv
812
813" Move lines
814vnoremap <silent><C-Up> :m-2<CR>gv
815nnoremap <silent><C-Up> <Esc>:m-2<CR>
816nnoremap <silent> <C-Down> <Esc>:m+<CR>
817inoremap <silent> <C-Down> <Esc>:m+<CR>a
818inoremap <silent> <C-Up> <Esc>:m-2<CR>a
819xnoremap <C-Up> :move '<-2<cr>gv
820xnoremap <C-Down> :move '>+<cr>gv
821
822" delete current till the end of line
823inoremap <C-k> <C-o>C
824nnoremap <C-k> _D
825
826" Interpret .md files, etc. as .markdown
827let g:vimwiki_ext2syntax = {'.Rmd': 'markdown', '.rmd': 'markdown','.md': 'markdown', '.markdown': 'markdown', '.mdown': 'markdown'}
828
829" vimwiki/vimwiki
830let g:vimwiki_list = [{'path': '~/.dotfiles/nvim/wiki', 'syntax': 'markdown', 'ext': '.md'}]
831
832"*:VimwikiSearch* /pattern/
833"*:VWS* /pattern/
834" Search for /pattern/ in all files of current wiki.
835" To display all matches use |:lopen| command.
836" To display next match use |:lnext| command.
837" To display previous match use |:lprevious| command.
838let g:vimwiki_table_mappings = 0
839
840" Highlight redundant whitespace and tabs.
841" This has the advantage of not highlighting each space you type at
842" the end of the line, only when you open a file or leave insert
843" mode. Very neat."
844" http://vim.wikia.com/wiki/Highlight_unwanted_spaces
845"match ExtraWhitespace /\s\+$/
846highlight ExtraWhitespace ctermbg=red guibg=red
847match ExtraWhitespace /\s\+$/
848
849augroup redundant-whitespaces
850 au!
851 autocmd BufWinEnter * match ExtraWhitespace /\s\+$/
852 autocmd InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
853 autocmd InsertLeave * match ExtraWhitespace /\s\+$/
854 autocmd BufWinLeave * call clearmatches()
855 "autocmd BufWinLeave <buffer> call clearmatches()
856 "autocmd BufWinLeave * call StripTrailingWhitespace()
857 " source: https://www.vi-improved.org/recommendations/
858augroup END
859
860" there is a discussion here where I have commented:
861" https://vi.stackexchange.com/a/19353/7339
862" see more about range :h <line1>
863" command! -range=% Cls <line1>,<line2>call StripTrailingWhitespace()
864" if !exists('*StripTrailingWhitespace')
865" function! StripTrailingWhitespace()
866" if !&binary && &filetype != 'diff'
867" call Preserve(":%s,\\s\\+$,,e")
868" endif
869" endfunction
870" endif
871"command! Cls call StripTrailingWhitespace()
872command! Cls :call Preserve(':%s/\v\s+$//e')
873cnoreabbrev cls Cls
874cnoreabbrev StripTrailingSpace Cls
875" com! StripTrailingSpace :call StripTrailingWhitespace()
876" cnoreabbrev cls StripTrailingSpace
877
878" Align text by a chosen char
879" https://stackoverflow.com/questions/57093175/
880" :Align =
881" :8,$ Align =
882" if !exists('*AlignText')
883" function! AlignText(param) range
884" execute a:firstline . ',' . a:lastline . '!column -t -s' . a:param . ' -o' . a:param
885" endfunction
886" endif
887" command! -range=% -nargs=1 Align <line1>,<line2>call AlignText(<q-args>)
888
889" https://stackoverflow.com/questions/57093175/
890" https://vi.stackexchange.com/questions/2410/
891if !exists('*AlignText')
892 function! AlignText(...) range
893 if a:0 < 1
894 execute a:firstline . ',' . a:lastline . '!column -t'
895
896 else
897 execute a:firstline . ',' . a:lastline . '!column -t -s' . a:1 . ' -o' . a:1
898 endif
899 endfunction
900endif
901command! -range=% -nargs=? Align <line1>,<line2>call AlignText(<f-args>)
902
903augroup removetrailingspaces
904 au!
905 "au! BufwritePre *.md,*.py,*.sh,*.zsh,*.txt Preserve :%s/\v\s+$//e
906 au! BufwritePre *.md,*.py,*.sh,*.zsh,*.txt :call Preserve(':%s/\v\s+$//e')
907augroup END
908
909command! -nargs=* Wrap set wrap linebreak nolist
910cnoreabbrev wrap set wrap
911cnoreabbrev nowrap set nowrap
912
913" Make the 81st column stand out
914highlight ColorColumn ctermbg=magenta
915call matchadd('ColorColumn', '\%81v', 100)
916" Esta função insere um change log
917" se nelas não houver "Last Change" ele passa batido
918" ou seja não insere o cabeçalho
919" usr_41.txt
920
921if !exists('*InsertChangeLog')
922 fun! InsertChangeLog() abort
923 let l:flag=0
924 for i in range(1,7)
925 if getline(i) !~ '.*Last Change.*'
926 let l:flag = l:flag + 1
927 endif
928 endfor
929 if l:flag >= 5
930 normal(1G)
931 call append(0, "Arquivo:")
932 call append(1, "Created: " . strftime("%Y %B %d hs %H:%M"))
933 call append(2, "Last Change: " . strftime("%b %d %Y hs %H:%M"))
934 call append(3, "autor: <+digite seu nome+>")
935 call append(4, "site: <+digite o endereço de seu site+>")
936 call append(5, "twitter: <+your twitter here+>")
937 call append(6, "email: <+seu email+>")
938 normal gg
939 endif
940 endfun
941endif
942
943" This functions clears the last search from history
944if !exists('*UndoUndoSearch')
945 fun! UndoUndoSearch()
946 call histdel("search", -1)
947 let @/ = histget("search", -1)
948 endfun
949endif
950
951if !exists('*ChangeHeader')
952 fun! ChangeHeader() abort
953 if line('$')>=7
954 call Preserve(':1,7s/Last \(Change\|Modified\):\s\+\zs.*/\=strftime("%b %d %Y %H:%M")/ei')
955 endif
956 endfun
957endif
958
959command! -nargs=0 CH :call ChangeHeader()
960augroup change_header
961 au!
962 au! BufWritePre * :silent call ChangeHeader()
963augroup END
964
965" jump to next place holder
966if !exists('*JumpToNextPlaceholder')
967 function! JumpToNextPlaceholder() abort
968 let old_query = getreg('/')
969 echo search("<+.\\++>")
970 exec "norm! c/+>/e\<CR>"
971 call setreg('/', old_query)
972 endfunction
973endif
974
975nnoremap <Leader>p :keepjumps call JumpToNextPlaceholder()<CR>a
976inoremap <Leader>p <ESC>:keepjumps call JumpToNextPlaceholder()<CR>a
977
978noremap <F12> <Esc>:syntax sync fromstart<CR>
979inoremap <F12> <C-o>:syntax sync fromstart<CR>
980
981highlight ColorColumn ctermbg=magenta
982call matchadd('ColorColumn', '\%81v', 100)
983
984" dos2unix ^M
985if !exists('*func_name')
986 fun! Dos2unixFunction() abort
987 "call Preserve('%s/ $//ge')
988 call Preserve(":%s/\x0D$//e")
989 set ff=unix
990 set bomb
991 set encoding=utf-8
992 set fileencoding=utf-8
993 endfun
994endif
995com! Dos2Unix :call Dos2unixFunction()
996cnoreabbrev dos2unix Dos2unix
997cnoreabbrev d2u Dos2Unix
998" one liner rename file
999" source: http://stackoverflow.com/questions/1205286/renaming-the-current-file-in-vim
1000command! -nargs=1 Rename try | saveas <args> | call delete(expand('#')) | bd # | endtry
1001
1002" Utility function that save last search and cursor position
1003" http://technotales.wordpress.com/2010/03/31/preserve-a-vim-function-that-keeps-your-state/
1004" video from vimcasts.org: http://vimcasts.org/episodes/tidying-whitespace
1005" using 'execute' command doesn't overwrite the last search pattern, so I
1006" don't need to store and restore it.
1007" preserve function
1008if !exists('*Preserve')
1009 function! Preserve(command)
1010 try
1011 let l:win_view = winsaveview()
1012 "silent! keepjumps keeppatterns execute a:command
1013 silent! execute 'keeppatterns keepjumps ' . a:command
1014 finally
1015 call winrestview(l:win_view)
1016 endtry
1017 endfunction
1018endif
1019
1020command! -nargs=1 Keep call Preserve(<q-args>)
1021cnoreabbrev pre Keep
1022
1023" remove consecutive blank lines
1024" see Preserve function definition
1025" another way to remove blank lines :g/^$/,/./-j
1026call Preserve(':g/^$/,/./-j')
1027if !exists('*DelBlankLines')
1028 fun! DelBlankLines() range
1029 if !&binary && &filetype != 'diff'
1030 call Preserve(':%s/\s\+$//e')
1031 call Preserve(':%s/^\n\{2,}/\r/ge')
1032 endif
1033 endfun
1034endif
1035
1036command! -nargs=0 DelBlank :call DelBlankLines()
1037nnoremap <Leader>d :call DelBlankLines()<cr>
1038
1039" Sudo to write
1040" cnoremap w!! w !sudo tee % >/dev/null
1041cnoremap w!! execute 'silent! write !sudo tee % >/dev/null' <bar> edit!
1042command! SaveAsRoot w !sudo tee %
1043cnoreabbrev sudow SaveAsRoot
1044
1045" bash/emacs keybindings
1046imap <C-a> <C-o>0
1047imap <C-e> <C-o>$
1048cnoremap <c-a> <home>
1049cnoremap <c-e> <end>
1050
1051" " toggles hightlight search and list with Ctrl-l
1052" nnoremap <C-l> :let [&hls, &list] = [!&list, &hls+&list==1]<CR>
1053" inoremap <C-l> <C-o>:let [&hls, &list] = [!&list, &hls+&list==1]<CR>
1054" vnoremap <C-l> <ESC>:let [&hls, &list] = [!&list, &hls+&list==1]<CR> <bar> gv
1055
1056nnoremap <c-l> <ESC>:set hls! hls?<cr><c-l>
1057inoremap <c-l> <C-o>:set hls! hls?<cr><c-l>
1058vnoremap <c-l> <ESC>:set hls! hls?<cr><c-l> <bar> gv
1059
1060" undo inserting
1061" https://vi.stackexchange.com/a/15246/7339
1062let g=0
1063inoremap <expr> <C-_> "\<C-o>".(g == 0 ? ':undo' : ':redo'). "\<CR>"
1064
1065" alternate between relative number, number and no number
1066set nu rnu
1067" toggles number and relative number with Ctrl-n
1068nnoremap <C-n> :let [&nu, &rnu] = [!&rnu, &nu+&rnu==1]<cr>
1069
1070" a barra de espaços -- zR abre todos os folders
1071nnoremap <Leader><space> @=((foldclosed(line('.')) < 0) ? 'zc' : 'zo')<CR>
1072" https://superuser.com/a/170026/45032
1073set foldlevelstart=99
1074
1075nnoremap <space> /
1076" the below mapping conficts with ultisnis
1077"nnoremap <c-space> :
1078
1079hi Folded ctermbg=black
1080
1081let g:UltiSnipsSnippetsDir = expand("~/.dotfiles/nvim/snips/")
1082let g:UltiSnipsSnippetDirectories=["snips", "UltiSnips"]
1083map <Leader>u :UltiSnipsEdit<cr>
1084" Snippets variables
1085let g:snips_author='Sergio Araujo'
1086let g:snips_site='http://vivaotux.blogspot.com'
1087let g:snips_email='<voyeg3r ✉ gmail.com>'
1088let g:snips_github='https://github.com/voyeg3r'
1089let g:snips_twitter='@voyeg3r'
1090let g:UltiSnipsEditSplit="horizontal"
1091
1092inoreabbrev fname <C-R>=expand("%:t")<CR>
1093inoreabbrev Fname <C-R>=expand("%:p")<CR>
1094inoreabbrev idate <C-R>=strftime("%b %d %Y %H:%M")<CR>
1095inoreabbrev hdate <C-R>=strftime("%Y %B %d")<CR>
1096"inoreabbrev -> →
1097inoreabbrev mymail <voyeg3r ✉ gmail.com>
1098inoreabbrev slas Sérgio Luiz Araújo Silva
1099inoreabbrev tuiter http://www.twitter.com/voyeg3r
1100inoreabbrev vivaotux http://vivaotux.blogspot.com
1101cnoreabbrev ag Ag
1102
1103" Fot transparency on terminal it needs to be at the end of init.vim
1104" transparency on the background
1105hi Normal guibg=NONE ctermbg=NONE