VIM

Save file with sudo

:w !sudo tee %

Vim Tip: Fix plugin loading error “Not an editor command: ^M”

E492: Not an editor command: ^M
line    9:
E182: Invalid command name
line   10:
E492: Not an editor command: ^M
line   12:
E182: Invalid command name
line   13:
E492: Not an editor command: ^M
line   15:
E182: Invalid command name
line   16:
E492: Not an editor command: ^M
line   18:
E182: Invalid command name
$ git config --global core.autocrlf input

https://web.archive.org/web/20201026005959/https://jjafuller.com/2017/06/2624/

print numbers

:for i in range(0, 2023) | put =i | endfor

E353: Nothing in register +

A workaround. In Vim, when you yank (copy) a piece of text, it is automatically placed into the unnamed register "" and the yank register "0.

remapping the y

There's no built-in way to do this in Vim, but you could accomplish it by remapping the y keystroke in your .vimrc file:

nnoremap y "ay
vnoremap y "ay

Comment all the lines under dependencies

name: Commerce Order
type: module
description: 'Defines the Order entity and associated features.'
package: Commerce
core_version_requirement: ^9.2 || ^10
configure: commerce_order.configuration
dependencies:
  - commerce:commerce
  - commerce:commerce_price
  - commerce:commerce_store
  - commerce:commerce_number_pattern
:g/dependencies/,/^\s*$/-1s/^/# / 
name: Commerce Order
type: module
description: 'Defines the Order entity and associated features.'
package: Commerce
core_version_requirement: ^9.2 || ^10
configure: commerce_order.configuration
#dependencies:
#  - commerce:commerce
#  - commerce:commerce_price
#  - commerce:commerce_store
#  - commerce:commerce_number_pattern

Extract Drupal machine name modules

root@1aecfb78797a:/var/www/html# drush pml | grep commerce
  Commerce                          Commerce (commerce)                                                                 Enabled    8.x-2.29
  Commerce                          Commerce Cart (commerce_cart)                                                       Enabled    8.x-2.29
  Commerce                          Commerce Checkout (commerce_checkout)                                               Disabled   8.x-2.29
  Commerce                          Commerce Log (commerce_log)                                                         Disabled   8.x-2.29
  Commerce                          Commerce Number Pattern (commerce_number_pattern)                                   Enabled    8.x-2.29
root@1aecfb78797a:/var/www/html# drush pml | grep commerce | grep -oP '\(\K[^\)]+'
commerce
commerce_cart
commerce_checkout
commerce_log
commerce_number_pattern


clean text with vim and tr when this error is triggered " Bad character '

:%!tr -d '\r' | tr -d '\200-\377'

in vim, I have a file where each line has 3 columns separated by "|", how to sort the second column usando awk

:%s/\(\S\+\)\s\+\(\S\+\)\s\+\(\S.*\S\)\s*\./\1 | \2 | \3 \./
:%EasyAlign1|
:%EasyAlign2|
:%!awk -F'|' '{print $1 "|" $2 "|" $3}' | sort -t'|' -k2 | awk -F'|' '{print $1 "|" $2 "|" $3}'
:%!awk -F'|' '{print $1 "|" $2 "|" $3}' | sort -t'|' -k1 | awk -F'|' '{print $1 "|" $2 "|" $3}'

how to add a separator character between subject, predicate and object in each triple using vim

:%s/\(\S\+\)\s\+\(\S\+\)\s\+\(\S.*\S\)\s*\./\1 SEP \2 SEP \3 \./

Sort numerically in VI editor [duplicate]

:1,794:sort n

Remove RDF triples where the object is datatype property

:g!/<http[^>]*> <http[^>]*> <http[^>]*>/d

Create a new buffer with a copy of the content of current file

:vnew | r #1

Remove all arbitrary spaces before a line in Vim

:left

How do I open files from my oldfiles list in vim?

:bro[wse] ol[dfiles][!]

https://stackoverflow.com/questions/29688188/how-do-i-open-files-from-my-oldfiles-list-in-vim

In Vim, what is the simplest way to join all lines in a file into a single line?

J

ggVGJ

https://stackoverflow.com/questions/391710/in-vim-what-is-the-simplest-way-to-join-all-lines-in-a-file-into-a-single-line

In VIM, how do I break one really long line into multiple lines?

:set tw=80
:set fo+=t
gq{motion} % format the line that {motion} moves over
{Visual}gq % format the visually selected area
gqq        % format the current line

https://stackoverflow.com/questions/1272173/in-vim-how-do-i-break-one-really-long-line-into-multiple-lines

formatting on the entire file, and don’t want the smaller lines to be joined.

:g/./ normal gqq

https://www.programmerhat.com/vim-gq/

Replacing characters in SPARQL queries

:'<,'>s!\\newline!!ge|'<,'>s!\\!!ge|'<,'>s!begin{flushleft}!\\begin{lstlisting}[style=construct]!ge|'<,'>s!end{flushleft}!\\end{lstlisting}!ge|'<,'>s!\$<\$!<!ge|'<,'>s!\$>\$!>!ge|'<,'>s!{}!!g

"The 'e' flag tells ":substitute" that not finding a match is not an error." —usr_12.txt,

example:

%s/from1/to1/ge | %s/from2/to2/ge | %s/from3/to3/ge

https://vim.fandom.com/wiki/Multiple_commands_at_once

Changing text selection color in visual mode in vim

set background=dark

https://stackoverflow.com/questions/31950035/changing-text-selection-color-in-visual-mode-in-vim

Setting up Vim for YAML editing

autocmd FileType yaml setlocal ts=2 sts=2 sw=2 expandtab
let g:indentLine_char = '⦙'

https://www.arthurkoziel.com/setting-up-vim-for-yaml/

How do I fix the indentation of an entire file in Vim?

gg=G

https://stackoverflow.com/questions/506075/how-do-i-fix-the-indentation-of-an-entire-file-in-vi

Hide comments with Vim folding

autocmd FileType ruby,eruby
      \ set foldmethod=expr |
      \ set foldexpr=getline(v:lnum)=~'^\\s*#'
zM closes all folds in the current file;
zR opens all folds in the current file;
zc closes the fold under the cursor;
zo opens the fold under the cursor.

cursors invisible after changing colorscheme

:hi clear

Vim: Pipe selected text to shell cmd and receive output on vim info/command line

https://stackoverflow.com/questions/2575545/vim-pipe-selected-text-to-shell-cmd-and-receive-output-on-vim-info-command-line

"dump selected lines
function! DumpLines() range
  echo system('sed -n '.a:firstline.','.a:lastline.'p '.expand('%'))
endfunction

com! -range=% -nargs=0 Dump :<line1>,<line2>call DumpLines()

VIM: change default behavior of delete

" shortcut to delete in the black hole register
nnoremap <leader>d "_d
vnoremap <leader>d "_d
" shortcut to paste but keeping the current register
vnoremap <leader>p "_dP

Show current key setting?

:let mapleader

https://vi.stackexchange.com/questions/5462/how-can-i-source-a-visual-selection-of-vimscript

https://superuser.com/questions/608170/vim-yank-multiple-non-continous-chunks-of-text-into-a-registers?rq=1

Support for ghost-text in regular vim

https://github.com/pandysong/ghost-text.vim https://ghosttext.fregante.com/troubleshooting/

EasyAlign

'<,'>EasyAlign /string_separator/

zzapper 16 Years of Vi + 15+ years of Vim and still learning

http://zzapper.co.uk/vimtips.html

Search and Replace on odd/even numbered lines using g

:g/^/s/foo/bar/|+t+|-d
:%!sed 'n;s/foo/bar/'
:%!sed 's/foo/bar/;n'

https://vi.stackexchange.com/questions/34785/search-and-replace-on-odd-even-numbered-lines-using-g

Vim + sed

%! sed 's/\(.*\)<a href="\(.*\)" title\(.*\)/\2/g'

Vim pasting -- scroll through previously yanked text

https://stackoverflow.com/questions/17013750/vim-pasting-scroll-through-previously-yanked-text https://vim.fandom.com/wiki/Comfortable_handling_of_registers

Tmux buffer

# to write the current line into the tmux buffer:
:.w !tmux load-buffer -

# to write all *lines* within the visual selection into the tmux buffer:
:'<,'>w !tmux load-buffer -
:'<,'>:w !tmux load-buffer -
:'<,'>:w !xclip -sel clip

# to pipe the content of a register (e.g. from a previous selection) into the buffer:
# @" being the unnamed register, @0 - @9 the numbered registers, and so on
:call system('tmux load-buffer -', @")
vnoremap <leader>tc y<cr>:call system("tmux load-buffer -", @0)<cr>gv
nnoremap <leader>tp :let @0 = system("tmux save-buffer -")<cr>"0p<cr>g;

Create a new page and paste all the content from opened buffer

%y+
vnew|put

two ways to copy

%y+     vs      "+y

Special characters

https://stackoverflow.com/questions/1585449/insert-the-carriage-return-character-in-vim

https://blog.sanctum.geek.nz/special-characters-in-vim/

:%!fold -w 60

Ex commands

delete all text

:%d

copy all text

:%y+

paste all text

:put+

Pipe shell

https://superuser.com/questions/157987/pipe-output-of-shell-command-into-a-new-buffer-in-vim

Print context

%g/rule.*count/z#.3

Get the name of the current file

https://vim.fandom.com/wiki/Get_the_name_of_the_current_file

Search and replace

https://vim.fandom.com/wiki/Search_and_replace

Append output of an external command

https://vim.fandom.com/wiki/Append_output_of_an_external_command

https://www.youtube.com/watch?v=PUsHbsLqI00

What does `` mean?

https://vi.stackexchange.com/questions/2286/what-does-bar-mean

https://unix.stackexchange.com/questions/282366/how-to-invoke-vim-editor-and-pipe-output-to-bash

nmap r :w !ls  mvim -
nmap r :w !ls \| mvim -

Redirect g search output

command! -nargs=? Filter let @a='' | execute 'g//y A' | new | setlocal bt=nofile | put! a

https://vim.fandom.com/wiki/Redirect_g_search_output

https://renenyffenegger.ch/notes/development/vim/registers/index

http://zzapper.co.uk/vimtips.html

open new file

vim -c enew

process content in another buffer

vnew | r #1 | % ! sort -u
vnew | r #

read output from command

tabnew | r ! docker ps -a 2&gt;&amp;1

Vim: Close All Buffers But This One

:w | %bd | e#

pipeline

:w ! sort | uniq | tee %
:w ! docker ps -a 2&gt;&amp;1 | tee %

load tmux buffer in a new window

vnew|r!tmux capture-pane -pS -32768 -t 2

How to delete all lines matching a pattern and a line after in Vim?

:g/word/normal 2dd
:g/word/,+1d

How to run a series of vim commands from command prompt

vim -c "source script.vim" A.txt

https://stackoverflow.com/questions/23235112/how-to-run-a-series-of-vim-commands-from-command-prompt

Concatenate vim commands

execute("%!cat -s")|1,24d|g/mappin/d|g/target/d|%s/source /select count(*) from (/g|%s/^$/) as t;/g|$d|norm!$a) as t;
  • It uses execute at the beginning to return implicitly and pass the result to next step in the pipeline since the command was external cat
  • the command $d has to executed almost at the end because otherwise the cursor does not come back to the beginning.
  • the last command of the pipeline insert a string ) as t

regular expressions

%s/mappingId \(.*\)/select '\1' as t;/g

Using Your Buffer as Input to a Command

:[range]write !{cmd}
'&lt;,'&gt;write !python

https://www.linux.com/training-tutorials/vim-tips-working-external-commands/

https://vimways.org/2019/vim-and-the-shell/

How to replace only selected visual block not the line in Vim

https://stackoverflow.com/questions/48145696/how-to-replace-only-selected-visual-block-not-the-line-in-vim https://vim.fandom.com/wiki/Applying_substitutes_to_a_visual_block

:'&lt;,'&gt;s/data/backup/g.
:'&lt;,'&gt;s/\%Vdata\%V/backup/g

\%V only matches within the current visual area.


Execute selection from script in Vim

https://stackoverflow.com/questions/40289706/execute-selection-from-script-in-vim

More Vim page up and page down keys

[Control][b] - Move back one full screen
[Control][f] - Move forward one full screen
[Control][d] - Move forward 1/2 screen
[Control][u] - Move back (up) 1/2 screen

redo next command

first ex command (can be tabn)

:bnext

run, last ex command

@:

repeat, last ex command

@@

https://vim.fandom.com/wiki/Repeat_last_change

Modifiers

Examples, when the file name is "src/version.c", current dir
"/home/mool/vim":
  :p            /home/mool/vim/src/version.c
  :p:.                     src/version.c
  :p:~               ~/vim/src/version.c
  :h                       src
  :p:h          /home/mool/vim/src
  :p:h:h        /home/mool/vim
  :t                       version.c
  :p:t                     version.c
  :r                       src/version
  :p:r          /home/mool/vim/src/version
  :t:r                     version
  :e                           c
  :s?version?main?             src/main.c
  :s?version?main?:p    /home/mool/vim/src/main.c
  :p:gs?/?\\?       \home\mool\vim\src\version.c

    %       current file name
    %&lt;       current file name without extension
    #       alternate file name for current window
    #&lt;       idem, without extension

Open buffer in a new tab

  • list buffers
:ls
  1 #h   "geographicAreaM49Code.py"     line 16
  3 %a   "~/PycharmProjects/caterina/geographicAreaM49Label.py" line 1
  • using command sb (split and show buffer)with the id number chosen from ls (autocomplete also works)
sb 1
tab sb 1
  • using command sp with the id number from ls (the symbol # has to be prepended to the id number)
sp #1
tab sp #1

https://vi.stackexchange.com/questions/6746/how-can-i-open-a-buffer-in-a-new-tab-leaving-the-current-window-and-buffer-intac

Comment and uncomment lines with //

45,67s#^#//
45,67s#^//#

Display output of a command

: vnew | r! git status
: r! git push gh --all
: r! git --no-pager log --oneline

Get result of find command up in a quickfix

:cexpr system('find . -name 'foo.txt' -print')

Open a buffer as a vertical split in VIM

:vsp | b1

display hidden characters

:set listchars=eol:$,tab:&gt;-,trail:~,extends:&gt;,precedes:&lt;
:set list

Remove unwanted spaces

%s/\s\+$//e

Setting up Vim to yank to clipboard on Mac OS X

http://www.markcampbell.me/2016/04/12/setting-up-yank-to-clipboard-on-a-mac-with-vim.html

Here's what I did:

brew install reattach-to-user-namespace

Ensure the following is set in .tmux.conf:

set -g default-shell $SHELL 
set -g default-command "reattach-to-user-namespace -l ${SHELL}"

In .vimrc

set clipboard=unnamed

https://github.com/tmux/tmux/issues/543

How do I insert text at beginning of a multi-line selection in vi/Vim?

Press Esc to enter 'command mode'
Use Ctrl+V to enter visual block mode
Move Up/Downto select the columns of text in the lines you want to comment.
Then hit Shift+i and type the text you want to insert.
Then hit Esc, wait 1 second and the inserted text will appear on every line.

https://stackoverflow.com/questions/253380/how-do-i-insert-text-at-beginning-of-a-multi-line-selection-in-vi-vim

how do I apply a macro to a set of lines?

11,30norm! @a

https://stackoverflow.com/questions/390174/in-vim-how-do-i-apply-a-macro-to-a-set-of-lines

Highlight number of occurrences for selected text

Shift #

Multiple commands at once

%s/htm/html/c | %s/JPEG/jpg/c | %s/GIF/gif/c

http://vim.wikia.com/wiki/Multiple_commands_at_once

Macros

qx
@x

where x is a register identifier to callback the recorded macro

http://vim.wikia.com/wiki/Macros

Open a new Tab with netrw and a right side windows

tabe /home/asanchez75/docker/docker-elk-sides/ | vsp | vertical resize 40

Cheat sheet

http://www.viemu.com/a_vi_vim_graphical_cheat_sheet_tutorial.html

File explorer

https://shapeshed.com/vim-netrw/

let g:netrw_banner = 0
let g:netrw_liststyle = 3
let g:netrw_browse_split = 4
let g:netrw_altv = 1
let g:netrw_winsize = 25
augroup ProjectDrawer
  autocmd!
  autocmd VimEnter * :Vexplore
augroup END

https://www.youtube.com/watch?v=XA2WjJbmmoM&t=2070s

Save sessions

https://bocoup.com/blog/sessions-the-vim-feature-you-probably-arent-using

:mks ~/.vim/sessions/rooster.vim
:source ~/.vim/sessions/rooster.vim

Set working directory to the current file

To change to the directory of the currently open file (this sets the current directory for all windows in Vim):

:cd %:p:h

You can also change the directory only for the current window (each window has a local current directory that can be different from Vim's global current directory):

:lcd %:p:h

In these commands, % gives the name of the current file, %:p gives its full path, and %:p:h gives its directory (the "head" of the full path).

Windows management

split horizontal

ctrl + w + s

split vertical

ctrl + w + v

close windows

ctrl + w + c
:q
:bd

keep open Only this window

ctrl + w + o

Switch between windows

ctrl + w + w

Tabs management

commands

:tabs         list all tabs including their displayed windows
:tabm 0       move current tab to first
:tabm         move current tab to last
:tabm {i}     move current tab to position i+1

:tabn         go to next tab
:tabn {i}     go to the tab number {i}
:tabp         go to previous tab
:tabfirst     go to first tab
:tablast      go to last tab
:tabnew filename  new tab
:q              close tab

Current windows directory (horizontal windows)

Sex = sp

Vertical windows

vsp

Explorer

Ex: /Library/Webserver/

To return to the explorer window, press

Ctrl-^ 

See old commands

q:
 :e filename      - edit another file
 :split filename  - split window and load another file
 ctrl-w up arrow  - move cursor up a window
 ctrl-w ctrl-w    - move cursor to another window (cycle)
 ctrl-w_          - maximize current window
 ctrl-w=          - make all equal size
 10 ctrl-w+       - increase window size by 10 lines
 :vsplit file     - vertical split
 :sview file      - same as split, but readonly
 :hide            - close current window
 :only            - keep only this window open
 :ls              - show current buffers
 :b 2             - open buffer #2 in this window

https://www.cs.oberlin.edu/~kuperman/help/vim/windows.html

https://chromatichq.com/blog/working-vim-never-leave-your-terminal

http://vim.wikia.com/wiki/Using_tab_pages

https://sanctum.geek.nz/arabesque/buffers-windows-tabs/

https://www.sourceallies.com/2009/11/vim-splits-an-introduction/

http://vim.wikia.com/wiki/Set_working_directory_to_the_current_file

Tags