Text Editor

In progressively less "real" order :)


a few ed commands, in case you are somehow stuck in this archaic world...
1d      =       delete 1 line
w       = write (save) file
q       = quit

in shell scripts, can do edits like:


echo "1d
q" | ed FILE


echo abc    | sed 's/abc/123/'		# s for search and replace abc -> 123
echo abcabc | sed 's/abc/123/g'		#   g suffix = globally.
echo a/b/c  | sed 's:/:-:g'		# use : instead of /, so that / is not matched.
echo abc    | sed 's:.*::'		# . = any char, * = any repeat
					# .* matches everything, 
					# replaced with empty string

echo a b c  | sed 's:\(.*\) \(.*\) \(.*\):\2 \1 \3:'	# \1 for first (.*), \2 for second one, etc.  
							# () need to be escaped thus the ugly \( \) syntax.

sed -i "s/#Protocol 2,1/Protocol 2/" /etc/ssh/sshd_config
# -i = inline replace.    but it still create a temp file and copy over, so will break hard links.

sed -i.bak 's/\tkernel.*/& elevator=deadline/' /boot/grub/grub.conf
# add 'elevator=deadline' to the end of the kernel line
# & stands for all pattern that matched in the search
# -i.bak  save orig file with .bak extension

sed '1d'    file.txt	# for line #N (1),   Delete it.  ie, delete first line
sed '3d'    file.txt	# for line #N (3),   Delete it.  ie, delete the third line only.  it is NOT deleting 3 lines!!
sed '2,4d'  file.txt	# for line #2 to #4, Delete them
sed -i '$d' file.txt	# delete the last line, saving the data to same filename (and no output to std out)

sed -i '/mnt\/cchome[124]/d' /etc/fstab # remove lines matching reg exp pattern from the fstab file
sed '/^ *$/d'        file.txt	# remove lines that are blank or have white space only. regexp delimted by // 

sed -e 's/,/\n/g' -e "s/'/ '/g"		# run two substitution at the same time, think of tr below 
					# sed can deal with multi-character match substitution, tr can't
tr  ",'" "\n "				# replace (,) with newline.  (') with space
More complex sed string matching:

expression in parenthesis are the tagged ones, and refered to as \1, \2, etc.
Note that w/in the sed 'cmd', the parenthesis has to be quoted with \ or will
get error from sed.  Also, it seems sed reg exp repeat is only *, no +

(note in perl it is $1 $2 etc)

Not sure in awk, but it is not $1 cuz that's input file field 1, did not like
\1 either.

eg string matching:
switch add vm1-nsw1 -type alpine -loadBalancer vm1-nlb1 -ulink 4:1 -slink 4:2 -glink 9:9 -mlink 1:1-1:16,2:1-2:4,3:1-3:4 -vp
n -vpnPort 80 -conServer -conPort 2029 -vipSubnet -dummyVIP -vlan -vlanName vm

sed 's/.*-vipSubnet \(192.168[^ ]*\)\.0\/.*/\1/'`

will reduce the above whole line to just 192.168.15 (nuber after the -vipSubnet).

Other sed edit command, incl delete matching line + line after/before, etc:


keyboar arrow keys, good for my sgi drug-adic keyboard! (or laptop with tiny arrow keys!!)

   h   j   k   l  
   lf  dn  up  rt

      |  k |
  | h | j  | l |
vimdiff file1.txt file2.txt # character-based side-by-side diff, handle up to 4 files. # ^w J = vertical split (toggle) # ^w H = horizontal split other vimdiff method, note small vs big o: vim -o A.txt B.txt C.txt will open three horizontal splits for each file. vim -O A.txt B.txt C.txt will open three vertical splits for each file (other diff tools, see linux.html#difftools)

Basic VI editing commands

Note: meta-x means ESC, then x, M-C-x means ESC, then C-x (bash man page)

core commands

q! = quit vi no matter what, get me out of this hell hole!
w  = write, save file.
i  = insert at cursor
A  = add at end of line
o  = add line below current
J  = join lines (current and one below)
dd = delete whole {n} line (each invocation clear the anon. buffer)
Y  = yank current line to anonymous buffer (used by y and d)
P  = paste before cursor  (linewise if buffer contain whole line) 

other oft use commands

a = add after current char
I = insert at beginning of line
O = add line above current and edit it
{n}J  = join lines (current and one below)
   D  = delete from cursor till end of line 
{n}dd = delete whole {n} line (each invocation clear the anon. buffer)
   dw = delete word
{n}Y  = yank current line to anonymous buffer (used by y and d)
    p = paste after  cursor  (from anonymous buffer)
    P = paste before cursor  (linewise if buffer contain whole line) 
 {n}x = delete the character {n chars, default = 1}
 {n}X = backspace
r = replace char ( {n}r = replaces next n char with a new single char )
R = infinite replacement
C = change remaining of the line
cc= change the whole line (ie rewrite the line)
cw= change word
u = undo
:x  = exit and save
:q! = quit w/o save
:w FILENAME  = write  (note, vi continue work on current file)
/   = serch

Navigation control while in INSERT mode

^F = scroll fwd (down)  1 screen
^B =        back        1
^D = scroll down        1/2
^U =        up          1/2
^E =        down  	1 line
^Y =        up    	1 line
H = go to top     of screen
M =       middle
L =       bottom
G =       end of file
w = move to next word
b = move back 1 word
) = next sentence    ( = previous sentence
} = next paragraph   { = previous paragraph

(most usable in bash interactive cli too)
^W	= previous word erase
^U	= erase from cursor till begin of line
^E	= go to end       of line
^A  = go to beginning of line
^D	= undo 1 level of auto indent

Search and Replace

/findme		serch for word "findme"
n		find next hit

search PATTERN1 and replace it with PATTERN2
  this only replace 1 instance
  g= global.  ie replace all instance on the current line
  c = confirm each replacement

from line 1 till last line ($)
substitute PATTERN1 with PATTERN2
globally (all apperearance in the line)

NOTE: can use %s instead of 1,$ for entire file search and replace

vim flags:
g= global
c= confirm (interactive prompt)
I= case sensitive (even if ignore case flag is set)

environment settings

:set nu		enable line numbering
:set nonu	turn off line numbering
:set ic		   = insenstive case, for case insenstive searching
:set showmode | noshowmode = show mode or not in status bar
:set beautify      = remove some ugly control char
:set noerrorbell   = no beeps
:set tabstop=4     = set tab to 4 spaces (default = 8)
:set ai | noai	   = auto indent   ^D = back one indent
				  O^D = cancel all indent
				hat^D = tmp suspend indent
settings can be in .vimrc or modeline

slightly more advanced commands

:syntax on	= (VIM only), use color highlight syntax
:set list	= show all control char, tab as ^I. newline as $, etc

:r FILE	= read FILE into current doc (after current cursor pos)
:r !CMD	= run unix CMD and write the output after current cursor pos
		  eg ':r !date' will write the current date into the document

press control-v, then the control char to save a control char in doc
^G (in command mode) = show status of file


troubleshooting the stupid ai

indent has become notoriously difficult. vim tries to be smart, but at least for my use, needing constant change between "tab mode" and "space mode", writting code vs rst vs pasting, the ai is really annoying :(
newer vi ai also tries to force an indent style. my old version html without ending </LI> tags drive the ai to indent wrongly for my stuff. either i get this ai turned off or a divorce is in order :(
*sigh* brc vim is the problem child. lrc vim is okay with the updated .vimrc that check for file type.

:set nosmartindent
:set nocindent
:set noai
:setlocal nosi
:setlocal nocin

vim -u NONE -U NONE -N		# start vim with default settings
# -N : No-compatible mode, less vi compatible 

vim --noplugin 
vim -D 			  			# -D : debug mode

:verbose set modeline?		# 

:messages					# show warnings, errors

:source %					# reload .vimrc

ref: https://vi.stackexchange.com/questions/2003/how-do-i-debug-my-vimrc-file

vim debug mode

vim --noplugin -D # -D : debug mode
n				: next line
ENTER			: repeat next line

cont			: continue, back to vim interface
q				: continue, back to vim interface

vim vs vi

vim is vi clone, more features: vim -g or gvim = X based vim 5.3
^R = redo, after some undo  (in command mode)
^T = go Back in help, etc.  ^O = go forward.  bookmark stuff.
^] = get into help topic.

:set compatible
compatible = vi compatible mode (only 1 level undo, etc)
 default on unless there is .vimrc file
:help  (or :h) online help

-X : no X server connection, always text mode (vim 6 only?)

:e  = (Edit) open a new file in the current window (closing current file)
:sp = (SPlit) open a new file in a separate (new) window (:q in the window to close it)
:vs = (Vertical Split)  vim 6.0 only.  

^W+arrow = jumpt to next window

:syntax on = to get syntax highlight (those that come with distribution)
		source external syntax hightlight definition file:
   		source ~/perl.vim

** Features of vim **
- multi level undo
- supposedly better keyboard map!!
- ctrl+arrow works as meta word moving in edit mode!!
- HOME, END, PgUp, PgDn, INS and DEL key all works too!!
- one anonying feature of vim 4.2, it is like pico, auto cr at end of line
  (don't think it is true in vim 5.3, or else find way to disable this!)
- wider terminal support.  vi can handle only up to 163 columns (inclusive).

VIM Split Windows commands

:sp		= SPlit open file in new window frame
^W ArrowKey	= move cursor to window Up, Down
^W s	= split into two horizontal windows
^W _	= maximize current windwow frame
^W +  	= make current window frame bigger
^W v    = split into two vertical windows  (vim 6.0)
^W <    = reduce number of columns in current window
^W >    = increate columns

VIM visual mode (cut-n-paste)

v = enter visual mode
	use arrow to highlight blocks
	y = copy block to memory (subsequent paste with p)
	x = cut block  (remove from text and place into memory)

	> = indent (shift) block 1 "tab"
	< = back indent block 1 "tab"

Turning off grandiose mode

some sort of smartindent is doing a lot of wring thing and driving me nut.
  • wsl using VIM 8.0, which does NOT support the keyword smartindent.
  • Zorin vim seems to be suffering from this grandiose character too :(
    Don't really have a solution to this yet, not sure what's going on. :set smartindent does NOT turn grandiose mode off :(
    Drop me a line if you can help!! Thx!

    Dealing with Python

    .vimrc: set tabstop=8 shiftwidth=8 expandtab :retab " will convert tab to spaces :set list " see ^I for tab instead cat dictionary_dump.txt | sed -e 's/,/\n/g' -e "s/u'/ '/g"

    Dealing with Yaml

    Yaml is even messier to deal with than Python, due to indents requirements of lines with '-' and those without. May as well forget tab ever existed and just use space. alias vis="\vim -c 'set shiftwidth=2 tabstop=4 formatoptions-=cro list nu expandtab syntax-=on'"


    Embed vim directives in the first/last (5) lines of a file. see source of this file for eg.
    # space, eg for python, yaml :: 
    # vim: filetype=python shiftwidth=2 tabstop=4 formatoptions-=cro list nu expandtab 
    # note that filetype=... set shiftwidth, settings are parsed left to right, last one stays.
    # so if have things like shiftwidth=8 tabstop=8 filetype=ruby
    # the filetype setting will reset tabstop back to 2 spaces
    # tab, eg for .sh, .html ::
    # vim: shiftwidth=4 tabstop=4 formatoptions-=cro list nu
    # haven't been able to force "syntax on" in modeline, so have to have it in .vimrc , but it should largely be on by default
    # cuz syntax is a command and not a set option?
    # sometime ago had alias vit="vim -c 'set syntax-=on'"  # not sure where it worked, but no longer work on zorin
    # Debian/Mint has modeline disabled by default.  Query it by:
    :verbose set modeline?		# 
    # reenable via .vimrc:: set modelines=5
    # yaml/python and tabs are enemies.
    # nosmarttab noautoindent nosmartindent  dont seems to reliably get rid of the "ai" in vim
    # :set paste  to get into paste mode is easiest
    # but paste mode is mutually exclusive (ie overwrite) expandtab :-/
    # tab and yaml, cant live with them, cant live without them :-//
    Ref: kuperman vim guide it has a number of advance commands I have to learn! :)


    Actually see geerlingguy's .vimrc
    " eg of .vimrc:
    " (quote) is used to delimiter comment.
    " can use 
    :set ignorecase
    " or 
    set ignorecase
    " ie, : in front don't matter.  
    set tabstap=4 shiftwidth=4 expandtab
    " above is pretty much a necessity for python
    " thanksfully old solaris vfstab and other that insist on seeing a tab is no longer present
    " .tsv, ie, tab delimited file would be screwed with this setting :(
    " :retab will convert tab to space on existing file
    set tw:0
    :set textwidth=0
    " # textwidth=0 = don't break long lines automatically, good for coding
    " # but somehow the god damened textwidth is ignored, 
    " # and vim always default to 78. :(
    " # so that probably need to be done manually
    :set wrap
    " set wrap-off  = use horizontal scroll to see long line
    " gqG 
    " will format / fold rest of doc to 80 columns max width 
    " http://stackoverflow.com/questions/3033423/vim-command-to-restructure-force-text-to-80-columns
    :set ignorecase
    " # case insensitive search
    :set wrapscan
    " # search wrap around EOF
    :set number
    " display line numbering
    " set nonu 
    " will turn off line numbering
    syntax on
    " use color syntax highlight
    command ref: 
    vim 6.0 has a vimdiff program to do diff.
    also a evim thing that behave more like notepad (no cmd/edit mode).
    Also see vi reference (don't remember where I got the cache from)

    [Doc URL: http://tin6150.github.io/psg/vi.html ]
    Last Updated: 2008-03-22
    (cc) Tin Ho. See main page for copyright info.