Internals

keynames:

  • <c-d> is control Ctrl + d, in help it can be written as CTRL-D
  • <esc> is escape key
  • <space> space
  • <cr> sometimes it is <Enter>
  • <bs> backspace
  • <left> left arrow
  • <s-left> shift left
  • <c-left> control left
  • ^I is when we insert <tab>
  • <nl> new line. If you use echom "a\nb" you will see a^@b (CTRL-v + CTRL-j)
  • <tab> tab

If you press c-s ctrl+s than terminal will freeze all output and looks like vim hangs and stop working, but you need to run c-q ctrl+q to exit from that.

special variables

  • <leader> by default is \ but I use <space>. To check current value use: :echo mapleader, to set use :let mapleader=" "
  • <localleader>
  • <non-keyword-character> maps all non keyword chars: :set iskeyword? returns [email protected],48-57,_,192-255,- ie alphabetic ascii, digits 0-9, _ , and some special chars
  • <nop> no operation, usefull when you want to disable some keys

My Vimrc

Good starting poing for .vimrc is http://vim.wikia.com/wiki/Example_vimrc You can find my .vimrc

Note that control key can be written as caret ^ so instead Ctrl + n it can be written as ^n.

Use vim help, with:

  • :help
  • :helpgrep windows
  • :help ctrl-i what Ctrl + i do in normal mode (normal is by default searched) we could also write :help ^i
  • :help i_^i what ctrl+i do in insert mode
  • :help v_^i what ctrl+i do in visual mode
  • :help c_^i what ctrl+i do in command mode

other help commands can be found :help usr_02.txt. Follow link with ctrl+] and jump back with ctrl+o

Instead of ^o I would write ctrl-o.

Some keys:

  • <c-o> is ctrl-o, take to normal mode for just ONE command, so if you want to go up in insert mode <c-o> k, or to reformat paragraph <c-o> gqip

    Other usefull commands in insert mode:

    • <c-o> <c-t> <c-o> <c-d> indent deindent in insert mode
    • <c-o> d delete everything to the right of cursor
    • <c-u> delete everything to the left
    • <c-w> delete word to the left of cursor
    • <c-h> backspace
    • <c-j> return
  • <c-o><s-o> (i don’t know exactly but it stays in insert mode and run s-o)

Command line mode :help usr_20.txt is when using : or search /,?.

  • You can press <Enter> anywhere inside line
  • Navigation with cursors <Left>, <S-Left> (one word left) and CTRL+B/CTRL+E begin/end of line (only difference with bash is that CTRL+B is char left and CTRL+F enters Replace mode in comand line window)
  • Delete with <BS> or CTRL-W delete whole word, CTRL+U delete all before text

  • tab completetion works and you can see all matches with CTRL-D (match is when command starts or short name starts with that)
  • command line history can be used when you type start of command and :se<UP> CTRL-P ignore what is already typed.

  • Command line window q: or CTRL-F is used to edit long commands. <CR> to execute comand end exit. Exit with :q or CTRL-C.

You can join multiple commands with | or <NR> (more help with cmdline-lines)

Update to vim 8 use

sudo add-apt-repository ppa:jonathonf/vim
sudo apt-get update
sudo apt-get install vim

Plugins

Pathogen is no longer needed since you can install packages to .vim/pack/my-packages/start.

Install pathogen and other interesting plugins:

mkdir -p ~/.vim/autoload ~/.vim/bundle && \
curl -LSso ~/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim

cd ~/.vim/bundle
git clone git://github.com/tpope/vim-rails.git # example: Rview

You can find my list of plugins

  • rails-vim is nice
    • if you want to use rspec instead of minitest, you need to remove tests folder so :Espec works
    • run <leader>s to run nearest spec (also t,l,a for file, last and all specs)
    • there are mappings for minitests: Efunctionaltest are controller tests, Eunittest are model tests, Eintegrationtest are integration between controllers. Do not know how to jump system tests.
    • use projections to add custom commands, for example app/services
    let g:rails_projections = {
        \ "app/services/*.rb": {
        \   "command": "service",
        \   "template":
        \     ["class {camelcase|capitalize|colons}", "end"],
        \   "test": [
        \     "test/services/{}_test.rb",
        \     "spec/models/{}_spec.rb"
        \   ],
        \ }}
    
  • ctrlp ctrl+p
    • to seach already opened buffers, hit <c-p> and than <c-f>
    • to open in horizontal sprit use <c-p> and <c-x>
    • to open in current buffer, instead of patching autoload/ctrlp.vim:1309 to use let md = 'r' instead of let md = argmaps you can configure different prompt mappings for <c-o> to immediatelly replace buffer.
    " make ctrl-o immediatelly replace buffer so we don't need to answer OpenMulti prompt
    " Open Selected: [t]ab/[v]ertical/[h]orizontal/[r]eplace/h[i]dden? 
    let g:ctrlp_prompt_mappings = {
    \ 'PrtSelectMove("j")':   ['<down>'],
    \ 'AcceptSelection("r")': ['<c-j>'],
    \ }
    
  • splitjoin for inline ruby blocks { } to convert do multiline do\n end.

Some not used anymore

  • You complete me: its too much visualisation

    # http://vimawesome.com/plugin/vim-rspec-sad-beautiful-tragic # :RunSpec
    git clone [email protected]:Valloric/YouCompleteMe.git && cd YouCompleteMe && ./install.sh && cd -
    
  • vim-markdown: issue with syntax highlight for * inside code block

  • vim-autoclose: annoying O char waiting next input

Running ruby in vim and show in separate window

link Press F7 to run selected or all code. Shift + F7 close the window.

"save code, run ruby, show output in preview window
function! Ruby_eval_vsplit() range
  let src = tempname()
  let dst = tempname()
  execute ": " . a:firstline . "," . a:lastline . "w " . src
  execute ":silent ! ruby " . src . " > " . dst . " 2>&1 "
  execute ":pclose!"
  execute ":redraw!"
  execute ":vsplit"
  execute "normal \<C-W>l"
  execute ":e! " . dst
  execute ":set pvw"
  execute "normal \<C-W>h"
endfunction
vmap <silent> <F7> :call Ruby_eval_vsplit()<CR>
nmap <silent> <F7> mzggVG<F7>`z
imap <silent> <F7> <Esc><F7>a
map <silent> <S-F7> <C-W>l:bw<CR>
imap <silent> <S-F7> <Esc><S-F7>a

Seeing is believing

Show ruby return values on each line in vim. Install seeing_is_believing with gem install seeing_is_believing --version 3.0.0.beta.7 and add plugin cd ~/.vim/bundle && git clone https://github.com/hwartig/vim-seeing-is-believing and add mappins: F4 mark, F5 run (not in visual) and enter mark and run (not in insert mode)

" .vimrc Enable seeing-is-believing mappings only for Ruby
augroup seeingIsBelievingSettings
  autocmd!

  autocmd FileType ruby nmap <buffer> <Enter> <Plug>(seeing-is-believing-mark-and-run)
  autocmd FileType ruby xmap <buffer> <Enter> <Plug>(seeing-is-believing-mark-and-run)

  autocmd FileType ruby nmap <buffer> <F4> <Plug>(seeing-is-believing-mark)
  autocmd FileType ruby xmap <buffer> <F4> <Plug>(seeing-is-believing-mark)
  autocmd FileType ruby imap <buffer> <F4> <Plug>(seeing-is-believing-mark)

  autocmd FileType ruby nmap <buffer> <F5> <Plug>(seeing-is-believing-run)
  autocmd FileType ruby imap <buffer> <F5> <Plug>(seeing-is-believing-run)
augroup END

Theory

  • quick reference card
  • tutorial
  • nnoremap ,html :asd first letter n means that this applies only in normal mode, no remap means do not reinvoke if those commands ,html are used for something else, map means simply when I type ,html please type :asd Other modes are: cmap control.
  • cabbrev E e can be used to replace E with e on command line.
  • normal! (with bang) means execute this exactly as I write (normal will not ignore mappings that user could have written and destroy your commands)
  • functions can be used to wrap some commands and give it a name. Use function! so you can overwrite it without error. Undo will undo whole function at once.

    function! MyFuction()
      normal! mmu`m
    endfunction
    nnoremap <leader>sp :call MyFuction()<cr>
    
  • source current file nnoremap <leader>sop :source %<cr> is used to source .vimrc so you do not need to exit and start vim again. You can reload any .vim file, for example :source ~/config/vim/syntastic.vim
  • conditionals

    function! MF(level)
      if a:level == 1
        normal! yy
      elseif a:level == 2
        " ....
      endif
    endfunction
    

Movements and Navigation

  • gj gk for long lines that are wrapped to multiple lines, it will go up and down
  • $ end of line, 0 start of line (or ^), use _ to select end of line before new line character
  • + and - move line up or down on the first letter
  • { and } move on paragraph (empty line)
  • ^B(^U) or ^F (^D) scroll up (half) or down (half) page
  • H M L move to the top/middle/bottom of the window, so you can scroll
  • mA then 'A jump there (downcase letter a can jump only on current buffer), :marks gives the jump location, two ‘ '' is jump back, '. jump to last change
  • ^o and ^i will jump to previos and next location. ^] to jump to section under cursor - hyperlink - ctags
  • % jump closing brackets or other matching brace
  • 5G or :5 goes to the line 5
  • gg goes top, G goes bottom
  • g, and g; jump to next/prev change on current buffer
  • :set scrollbind in two buffers will make them scroll simultaneously. toggle scrolling with :set scb!
  • show line numbers :set number or relative numbers :set relativenumber (or shorter :set rnu. To disable you can :set norelativenumber
  • show approx position in text ^G
  • gf follow that file

Motions and selections

  • ciw change inner word, caw including spaces that follows the word
    • ca] change all inside brackets including both [ ]
  • daw removes the inner word
  • dt delete until the space, df delete until the space including space
  • dap}p switch two paragraph
  • dE removes to the End of the string
  • vit inner or vat outer visual select (including html tag) :h tag-blocks
    • repeat at to select wraped tag
    • jump to closing (Oposite) html tag with o in visual mode. more on :help visual-operators :help v_it
    • vap select paragraph (until next empty line, including that empty line)
    • dst delete surround tag with vim surround plugin.
    • cil change inner line with line text object plugin
    • vii select same indent level with indent text object
  • va' visually select all inside ‘ including ‘
  • cgn change visually selected text using previous search
  • recording macro to q with qq, exit with q, run with @q
  • paste commands in insert mode with ^Rq
  • ^T indent ^D dedent in insert mode. In normal mode you can select and indent with = To indent whole file you can jump to begging and indent to last line gg=G. In visual mode gq will format text to 80 char lines (good for markdown) Sort selection with :sort u

HTML indent works fine but note when to avoid erb tags. It detects %> as closed tag except when line starts with <%. Do not use comment in the middle of erb since that line somehow is not indented. Better is to add another comment tag inline <%# if condition? %>

Instead
<div>
  text node <%= name %>
</div>

Use
<div>
  text node
  <%= name %>
</div>

For if else anotation use separated tag
<% if b %>
<% else %><%# if b %>
<% end %><%# if b %>

For multiline ruby there is a problems so use single line erb
<% one %>
<% two %>

For case switch there is a problem since it is not recognized as valid ruby
    <fieldset>
      <% case searchable %>
      <% when Book %>
        <legend>Book</legend>
        <%= searchable.title %>
      <% when User %>
      <% end %>
only solution is to merge two line into one
    <fieldset>
      <% case searchable when Book %>
        <legend>Book</legend>
        <%= searchable.title %>
      <% when User %>
      <% end %>

Motion in visual mode

  • '< to the first line of last selected visual area. Note that you need to exit current visual area and than jump to first or last line/char
  • gv to select previous selected visual area

ragtag plugin in insert mode:

  • <c-x>/ close last html tag
  • <c-x>= append <%= %>, use <c-x>+ to wrap around last line
  • <c-x>- append <% %>, use <c-x>_ to wrap around last line
  • <c-x>@ insert stylesheet or <c-x>$ javascript tags

Copy paste

  • "+y copy visual selection to system clipboard, ubuntu should run sudo apt-get install vim-gtk. or vim-gnome. On ubuntu 18 that package is outdated so I need to compile from source https://stackoverflow.com/questions/37079424/ubuntu-16-04-lts-cant-enable-xterm-clipboard-in-vim/37079474#37079474
    sudo apt-get build-dep vim
    git clone https://github.com/vim/vim.git vim_source
    cd vim_source/
    ./configure \
      --enable-perlinterp=dynamic \
      --enable-pythoninterp=dynamic \
      --enable-rubyinterp=dynamic \
      --enable-cscope \
      --enable-gui=auto \
      --enable-gtk2-check \
      --enable-gnome-check \
      --with-features=normal \
      --with-x \
      --with-compiledby="DevNull <[email protected]/dev/null>" \
      --with-python-config-dir=/usr/lib/python2.7/config-$(uname -m)-linux-gnu
    make -j8
    sudo checkinstall
    
  • select which register to use with (use character not number) for example: yank link to register a and paste: "add "ap". When deleting or changing it will override default register, so you need to select some other register, like black hole register "_ if you want to paste same stuff multiple times, for example "_d or "_c will keep default register untouched.
  • %y+ copy all lines to clipboard
  • to move a line to buffer on the left you can record macro (something like yy ^wh p ^wl)
  • to paste with proper indend use vim-unimpaired ]p , also from plugin :help unimpaired
  • [l ]l ale errors
  • ]b buffers
  • ]q go next [q prev Quick fix, Alss next error or warning with :lnext or :lpr or using [l ]l. More are in :help unimpaired-next
  • ]ow to enable wrap, toggle with yow, more :help unimpaired-toggling

To close error window you need to :lcl. I use map for quickfix to :.cc

  • insert text from external command is with :read !date

Exploring

  • :edit . (short :e.) opens (:vsp) splits netrw of folder,

Tips

  • open file on specific line vi +10 README

Netrw

netrw.vim is native exprorer. :Explore(short :E) :Vex of current editing file To change current folder just press c on folder line help :netrw-c. That’s better than cd ../path which change in all tabs. It will not affect already opened windows, so it should be done on the first window in the tab.

Inside netrw:

  • % create new file, more info :help netrw-%
  • d create new directory
  • R rename file/directory under cursor
  • D delete file/directory under cursor

NERD tree

  • to change current directory to selected folder, type in normal mode cd. It will change directory only in current buffer.
  • refresh with r (selected dir) or R (all)

Searching

  • / for searching, to search in oposite direction ? (n and N for next and previous result). If search string is all lowercased than it will search ignore case, but if you have at leat on uppercased letter than case is important
  • :grep subject -R * --exclude-dir={log,spec,public,features,tmp,vendor,assets,db} -I. Instead of :grep I use :Ack (which uses ag)

https://github.com/ggreer/the_silver_searcher. It will ignore all from .gitignore so no need to exclude dir. Here are some ack.vim helpers:

  • ? quick summary of keys, h open in horizontal split
  • ag pattern -G show will search only filenames like show.html.erb (-G is short for --file-search-regex patter), -i ignore case, -l show only filenames. --ignore-dir=lib will ignore specific folders (regex not supported). Filter only specific file type ag --list-file-types| less you can use ag MyClass --ruby.

  • grep end of the word /usan\> help with :h /\>
  • :%s/old/new/gc
  • q: shows history of commands
  • q/ shows history of searches
  • :argdo %s/foo/bar/ge | update replace (substitute) in all arg
  • :set nowrapscan is usefull when you want to stop search when you hit bottom of a file. With gg you can jump to begging. :set wrapscan when you want to back to wrapped search
  • clear highlights until nex search :noh, to clear completely set nohlsearch or toggle nnoremap <F3> :set hlsearch!<CR>
  • vim my_string **/*.md | copen search only md files for my_string and show results
  • beggining and end of line marks like /^asd and /asd$ works fine (not in the middle /asd^qwe. For multiline search you can use: \n new line, \_s space,tab or newline, \_. any char including new line, \_^ and \_$ are beggining and end of line. You can use minimum matcher \{-} to stop as soon as possible (instead of * which will stop at last occurrence).
    • /asd\_.\{-}qwe find asd followed with any character (including new line) and stop at qwe. You can use S and S! snippet

:Ack can be used to find in files. In vim it uses ag instead of grep or Ack. To search specific types use option -G and regexp like: :Ack montserrat -G 'css$' For two line search you can use: :Ack 'destroy\n.*authorize' app/controllers/ For multiline (dot not matter how many lines are in between) :Ack 'destroy(\n.*)*flash.now..notice' app/controllers/

Windows buffers and tabs

terminology

  • :tabe file open file in new tab, gt switch between tabs
  • :help Ctrl-W_T move current buffer in new tab, Disable default Terminal -> Preferences -> Shortcuts
  • gx open link under cursor with gnome-open. Issue #1386
  • :vsp #1 vertically split window with file #1
  • :on or Ctrl+W+o closes all windord except current
  • :buffers, :b1, :bun closes the buffer
  • CTRL+^ (shift+6) jump to previous buffer
  • retab this will actually reformat all source
  • ctrl+w+f is the same as gf but opens in new vertical split window
  • b substring_of_filename open buffer that matches substring (press tab in case of multiple mathces)

Quickfix window can be opened with :copen

Completion

  • ^n or ^p in insert mode to autocomplete strings and get next/previous item
  • ^x^o to autocomplete using omni completion :set omnifunc=csscomplete#CompleteCSS
  • ^x^n only strings from current file
  • ^x^l complete whole lines
  • ^x^f to complete filename (keep ^x^f when you navigate subfolders)
  • ^x^] for tags find other shortcuts with :help ins-completion
  • ^a and ^x to increment and decrement numbers speeddating if you want to increment dates
  • for commands you can use ^d to show all completion and <tab> to use it

Tips

  • Repeat last colon command @:, repeat last command @@
  • :args app/*/* to add all files to arg list
  • :nnoremap _ f_x~ find next _, remove and uppercase link for moving underscore to CamelCase
  • using vim inside irb or rails console with gem interactive_editor. Its usefull since you can paste only limited number of chars to irb line. Now you can write your input data in file/ruby code and insert byebug/debugger/pry in rails code, and start hunting for bugs
  • set showcmd enable showing all keys that I’m typing in bottom right corner, very usefull when explaining to someone
  • snippet nnoremap ,html :-1read $HOME/.vim/.skeleton.html<CR>3jwf>a my snippets
  • K in normal mode opens documentation for that keyword, for example image_tag or select will open documentation for all gems which defines that keyword
  • black screen is caused to silent command https://github.com/vim/vim/issues/1253 use :redraw!
is good if you are having mappings launch ex commands. # Books, videos tutorials * vim begginer tutorial `:help vimtutor` or run in shell `vimtutor` * [vim theory]( /2017/06/05/vim-theory/) * <https://www.youtube.com/watch?v=5r6yzFEXajQ> * start vim without plugin , no plugins [--noplugin](https://www.youtube.com/watch?v=XA2WjJbmmoM) or start vanila vim without vimrc initialization `vim -u NONE` ~~~ # fuzzy finder set path+=** find *-vim # ~~~ # CTAGS You need to generate tags file with `ctags -R .`. You can use default params. ~~~ # ~/.ctags --recurse=yes --exclude=.git --exclude=log --languages=ruby ~~~ Some vim keys: ~~~ ^] # ctrl + ] : jump to tag under cursos ^t # jump back in tags stack (stack is when you go into definition with ^]) ^o ^i # similar move back and forward, but all jumps (not just tags) ^x^] # autocomplete tags g] # list all ambiguous tags: same method could be defined in multiple classes :ts my_met # select tags for this search, also ctrp tags ~~~ To generate tags for all gems install <https://github.com/tpope/gem-ctags> ~~~ gem install gem-ctags gem ctags ~~~ Create template to git hook <http://tbaggery.com/2011/08/08/effortless-ctags-with-git.html> ~~~ ~~~ Also use CtrlPTag so you can navigate to tag # Syntastic checker Instead of synstastic I use ALE <https://github.com/w0rp/ale> Results are put in location list so you can navigate with `] l`. ~~~ " config/vim/ale.vim " change message let g:ale_echo_msg_format = '[%linter%] %s [%severity%]' " disable linter on change let g:ale_lint_on_text_changed = 'never' " use only erubylint let g:ale_linters = {'eruby': ['erubylint']} " enable airline let g:airline#extensions#ale#enabled = 1 " use less invansive color for warnings highlight ALEWarning ctermbg=DarkMagenta " disable ale for all subrepositories under real-world-rails let g:ale_pattern_options = { \ '.*real-world-rails.*': { 'ale_enabled': 0}, \} ~~~ You can disable ALE with `ALEToggle`. You can see error message `ALEDetail`. Yo see all configuration options `ALEInfo`. There was issue with erb <https://github.com/w0rp/ale/issues/580> but this erubylint was recently removed from ale linters. ## Syntastic (deprecated, use ALE instead) [syntastic](https://github.com/scrooloose/syntastic) vim plugin is great to write your code. Just need to install external syntac checkers and they will be eabled. `SyntasticInfo` can give you current checkers and `help syntastic-checkers` will show you all available checkers. To check if some checker is installed you can try with system command (here we show current path): ~~~ :echo syntastic#util#system('echo "$PATH"') ~~~ You need to activate checkers for specific **filetype** and you can customise speific **checker** ~~~ let g:syntastic__checkers = [''] let g:syntastic___args = "--my --args --here" ~~~ Here is my configuration for syntastic and vim <https://github.com/duleorlovic/config/blob/master/vim/syntastic.vim> You need to install this tools: * Markdown `gem install mdl` * Ruby, Rails `gem install rubocop`. You can automatically fix some errors with `rubocop --auto-correct Gemfile`. Configuration is in .rubocop.yml in $HOME or project root. You can disable all ~~~ # .rubocop.yml AllCops: DisabledByDefault: true ~~~ My preferred configuration is https://github.com/duleorlovic/config/blob/master/.rubocop.yml * inline in comment `# rubocop:disable Metrics/AbcSize, Metrics/MethodLength` * gem 'rubocop-rspec' is nice linter for rspec. You can run manually with `-D` param to see cop names. To disable some errors define quiet messages in `syntastic.vim` (`:help syntastic_quiet_messages`) [g:syntastic_eruby_ruby_quiet_message](https://github.com/duleorlovic/config/blob/master/vim/syntastic.vim#L21) * fix `possibly useless use of a constant in void context` in erb is with `<%= CONST.to_s %>`, when is problem with + than fix with assign `<%= total = a + b; total %>` * for js I use `jshint` with es6 and disabled semicolons * semicolons also disabled in `eslint` (which extends from airbnb-base) * for styleles I use `stylelint` and local `.stylelintrc` since version 9.10 does not pick my home configuration * Javascript `npm install -g jscs jscs-angular` and create files [.jscs]( * json `npm install -g jsonlint` [link to issue](https://github.com/jaxbot/syntastic-react/issues/4) ~~~ " .vimrc au BufRead,BufNewFile *.json set filetype=json let g:syntastic_json_checkers=['jsonlint'] ~~~ * coffeescript `npm install -g coffeelint` # Vimium chrome extension https://github.com/philc/vimium Normal mode: * `j` and `k` down and up on a page * `f` follow links `F` follow in new tab * `H` and `L` back and forward in history * `J` and `K` prev and next tab * `o` search and open history links * `T` search open tabs * `r` reload the page * `gg` top or `G` bottom of the page * `gi` go to first input element Additional navigation commands: * `yy` copy current url to clipboard * `gu` go up one level in URL path * `gU` go to root of domain Find mode, enter with `/`: * `n` and `N` next and prev search match Insert mode, enter with `i`. So if you notice that `x` closes tab even you are inside input, jump into insert mode first... Since gmail has own `j` `k` prev and next email, I added rule to ignore all (`*`) keys Do not know https://stackoverflow.com/questions/53918093/why-is-class-demo-button-so-special-in-vimium?noredirect=1#comment94679088_53918093 # Vimum VimFx [VimFx](https://addons.mozilla.org/ru/firefox/addon/vimfx/) [source](https://github.com/akhodakivskiy/VimFx) is vimium for firefox. `f` for navigation and clicks, `/` for search (n N), `x` `X` for close and reopen tab, `J` `K` switch, `space` `shift+space` page down up. [Hints mode](https://github.com/akhodakivskiy/VimFx/blob/master/documentation/commands.md): * `f` anything clicable `F` opens in new tab (or press Ctrl) `ew` new window * by default lowercase letter will filter hint strings, but you can use uppercase letter to filter by text (you can see what is entered in lower right corner) * `yf` copy text and links # Rails vim Some todos: Pluralize * When I type `:Rcontroller customer` it should go to `:Rcontroller customers` instead of error: `No such controller customer`. This usually happens when I have a lot of models `customer_invoices`, `customer_payments` and `customers`. Localize * When I'm in `index.html.erb` and I type `:Rcontroller` than I jump to controller, but if I'm on `index.in.html.erb` than there is an error `Argument required`. Also problem with `:Eview another_` Jump to system tests # Create scripts for vim `help usr_41.txt` is Write a vim script in user manual. <https://en.wikibooks.org/wiki/Learning_the_vi_Editor/Vim/VimL_Script_language> Detect if some features are enabled, for example only on macOS `:help feature-list`: ~~~ " copy to clipboard on macOS need to use pbcopy if has('macunix') vnoremap "+y :w !pbcopy endif ~~~ ## Vim scripts in ruby: https://subvisual.co/blog/posts/139-how-to-program-vim-using-ruby/ ## Vim ruby support `:help ruby` Some integrated stuff in vim https://github.com/vim-ruby/vim-ruby/blob/master/doc/vim-ruby.txt https://github.com/vim-ruby/vim-ruby/wiki/VimRubySupport # WHEREAMI my plugin to show dedented lines When looking at large files in small window (I have 4 vim windows in my single terminal window) than I want to see to which block current line belongs. In schema.rb, current line in which table ? ~~~ ActiveRecord::Schema.define(version: 20170124131420) do create_table "projects", force: :cascade do |t| ... long ... t.integer title ~~~ In ability.rb, current ability to which user ? When I'm in long spec file, I want to see setup block for current example and all outer example groups (maybe to group all descriptions in one sentence). ~~~ RSpec.describe Project do let(:project) { Project.new } before ... long ... describe "create task" do ... long ... it "order by date" do project ~~~ Also in view, I want to be able where current element belongs, so list all wrapped elements. And when I'm in scss I want to see all parent selector, classes and media queries. Solution is to use similar row as in https://github.com/chrisbra/csv.vim `:Header` # RubocopFix vim plugin rubocop Fix current rubocop error, by adding `rubocop:disable` # Graph visualization in markdown <https://markvis-editor.js.org/> # Debug profile startup time * if vim does not show properly, blank or empty screen, try `:redraw!` <https://github.com/bchretien/vim-profiler> * <https://github.com/vim-scripts/Decho> # Undo <https://github.com/mbbill/undotree> and remaped to F5 so you can easilly revert back to some earlier file. # Vim test https://8thlight.com/blog/chris-jordan/2016/06/13/running-tests-in-vim.html ~~~ " run single rspec test example for current line nnoremap rs :execute "!rspec %:" . line(".") " set compiler :compiler rspec :make % ~~~ Place language specific (file type) plugins inside `~/.vim/ftplugin/ruby.vim` so they are automatically loaded when you open ruby file. Use https://github.com/janko-m/vim-test * `t` test nearest spec to the line (if not inside example, whole file will be run) `:TestNearest` * `T` test whole file `:TestFile` * `a` test whole suite `:TestSuite` * `l` test last, usefull if you navigate to the code and see if test pass `:TestLast` * `g` visit test, jump back to the test to write more tests `:TestVisit` I use strategy `let test#strategy = "dispatch"`. Asyncrun will not correctly parse errors: ~~~ # instead of one error # AsyncRun show two expected `#<User id: 1061, email: "[email protected]", created_at: "2017-09-23 09|19| 48", updated_at: "2017-09-23 09:19:48">.confirmed?` to return true, got false spec/features/user_confirmation_spec.rb|25| in `block (2 levels) in <top (required)>' ~~~ I prefer to use xdotool and send command to actual window ~~~ " config/vim/ftplugin/ruby.vim function! EchoStrategy(cmd) let current_window = system('xdotool getactivewindow | tr -d "\n"') let target_window = system('xdotool search --classname vp_3_class_slash | tr -d "\n"') execute 'Dispatch! xdotool windowactivate --sync '.target_window.' type "'.a:cmd.'"; xdotool key --delay 50 space Return windowactivate '.current_window endfunction let g:test#custom_strategies = {'echo': function('EchoStrategy')} let g:test#strategy = 'echo' ~~~ # Vim plugin <https://github.com/junegunn/vim-plug> vim plugin manager is installed with one command `curl -fLo ~/.vim/autoload/plug.vim --create-dirs https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim` and setup in .vimrc ~~~ call plug#begin('~/.vim/plugged') " Make sure you use single quotes " Shorthand notation; fetches https://github.com/junegunn/vim-easy-align Plug 'junegunn/vim-easy-align' call plug#end() ~~~ And install with `PlugInstall` # Vim Color Scheme <https://github.com/nightsense/vimspectr> is installed using vim-plug ~~~ Plug 'nightsense/vimspectr' colorscheme vimspectr60flat-dark ~~~ but I prefer to tweek one by one color ~~~ highlight Comment cterm=underline ctermbg=Blue ctermfg=White ~~~ `cterm` accepts `bold` `underline` `reverse` `italic` but no colors. `ctermfg` and `ctermbg` accepts colors, list of all on `:help cterm-color` Highlight groups can be found on [highlight-groups](http://vimdoc.sourceforge.net/htmldoc/syntax.html#highlight-groups) To see where the color is defined use `verbose`, for example ~~~ verbose hi Comment ~~~ Using ALE I see `:help g:ale_set_highlights` that groups are `ALEError`, `ALEWarning` ... so I use less invasive color: ~~~ hi ALEWarning m ~~~ # Folding In visual mode you can select and run `:fold` collapse expand You can hide copy right sections of other comments. ~~~ " .vimrc " https://stackoverflow.com/questions/2250011/can-i-have-vim-ignore-a-license-block-at-the-top-of-a-file function! FoldCopyright() if !exists( "b:foldedCopyright" ) let b:foldedCopyright = 1 silent! 1,/# Copyright/;/USA\.$/fold endif endfunction autocmd BufNewFile,BufRead *.rb call FoldCopyright() ~~~ If you use `autocmd FileType vim setlocal foldmethod=marker` marker method than any lines that starts and ends with *{ { { .... }}}* can be toggled with `za` # Database Use https://github.com/tpope/vim-db and access with ~~~ :DB mysql://username:[email protected]/my_db_test ~~~ # Tmux Not using for now * strange characters instead of single quote I see `<91>` and `<92>` in vim. https://superuser.com/questions/199799/vim-shows-strange-characters-91-92 run `:%s/[\x91\x92]/'/g` to replace them https://handbook.infinum.co/books/rails/Editors/Vim https://emily.st/2018/11/13/vim-in-the-future/