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

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
  - 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
#  - 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[^\)]+'

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 \./
:%!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


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

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

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

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

:g/./ normal gqq

Replacing characters in SPARQL queries


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


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

Changing text selection color in visual mode in vim

set background=dark

Setting up Vim for YAML editing

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

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


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

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

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

Support for ghost-text in regular vim


'<,'>EasyAlign /string_separator/

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

Search and Replace on odd/even numbered lines using g

:%!sed 'n;s/foo/bar/'
:%!sed 's/foo/bar/;n'

Vim + sed

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

Vim pasting -- scroll through previously yanked text

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


two ways to copy

%y+     vs      "+y

Special characters

:%!fold -w 60

Ex commands

delete all text


copy all text


paste all text


Pipe shell

Print context


Get the name of the current file

Search and replace

Append output of an external command

What does `` mean?

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

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#


: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

How to run a series of vim commands from command prompt

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

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

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


\%V only matches within the current visual area.

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)


run, last ex command


repeat, last ex command



Examples, when the file name is "src/version.c", current dir
  :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
  1 #h   ""     line 16
  3 %a   "~/PycharmProjects/caterina/" 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

Comment and uncomment lines with //


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


Setting up Vim to yank to clipboard on Mac OS X

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

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.

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

11,30norm! @a

Highlight number of occurrences for selected text

Shift #

Multiple commands at once

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



where x is a register identifier to callback the recorded macro

Open a new Tab with netrw and a right side windows

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

Cheat sheet

File explorer

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 VimEnter * :Vexplore
augroup END

Save sessions

: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

keep open Only this window

ctrl + w + o

Switch between windows

ctrl + w + w

Tabs management


: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



Ex: /Library/Webserver/

To return to the explorer window, press


See old commands

 :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