How to run the last n commands in Vim

I got my answer from here: Using command line history in vim

Here is a summary to execute your command of choice from command history:

  • q: (opens the command history window)
  • use vim browsing keys to go to the command you want to execute. Alternately :n where n is line number of the command to execute, will place you on the line.
  • CR -> (Carriage return) Press enter to execute the command.

If you want to run the last n commands for example:

  • q:
  • yank the number of commands you want to run
  • Press ctrlc twice
  • :@"

How to increase the history limit:

put this line in your vim.rc file: set history 100 (100 will be the history limit)

If this history limit is not taking effect, please read here: How to increase cmdline history size

How to run vim command on multiple files

Vim: Find and replace text across files

Programmers almost always need the ability to find and replace certain text across multiple files in their projects. Most IDEs provide find and replace functionality. And there are many free tools onlineto just find and replace text across multiple files. Because I am using Vim as my favorite editor for over 15 years now, it came natural to choose Vim for such job, and not depend on another tool.

For a real life example, in one Rails project, I used caching in my view templates. I used a plugin to set an expiration time for the cache. I needed the cache function to look like:

<% cache(“sidebox_latest_news”, :expire => 15.minutes.from_now) do %>

<% end %>

I used this technique in about 25 of my templates. Then i decided not to use timed expiration of the cache. So I needed to remove the expire argument of the cache method. I needed to remove it from all of my 25 templates. I used Vim to find the needed piece of text to be removed.

In Vim, when we need to replace text in a file, we use the substitute command.


This should replace the first occurrence of “old_text” with “new_text” for the current cursor line. To substitute all matching occurrences in the line, just add the flag ‘g’ which refers to global. And to substitute all the file occurrences of the pattern, add the ‘%’ before the substitute command.


Vim alerts if it didn’t find the pattern, to disable the alert just append the flag ‘e’.


For a complete documentation for the substitute Vim command, use vim help.

:help substitute

Now, after we knew how to substitute text in Vim, we need to substitute the expire argument. we cannot do without using regular expressions. That’s because the argument is not the same in all the files, it carries different time values, and may differ in spacing.

<% cache(“sidebox_related_reports”, :expire => 1.hour.from_now) do %>

<% end %>

So we need to match the whole argument from the comma at the start till the right parentheses and replace it with empty text. the regular expression we should use to match the argument is;

/, *:expire.+)/

I will quickly explain the pattern above, but please refer to any of the many tutorials online about Regular expression for more details. The pattern starts with a comma which is the start of the text we need to remove. Followed by a space and a ‘*’ which means a comma followed by zero or more spaces then ‘:expire’ followed by “one or more” “character”. And finally the pattern ended with a right parentheses. So our pattern starts with a comma and ends with a right parentheses. Any text matching this pattern in all templates files should be replaced with empty text, or to be specific, with a right parentheses, as the parentheses is already part of the text to be removed.

To apply Vim command to all the templates files, I will use the ‘args’ command. I will pass all the templates files in the app/views folder to ‘args’ using wildcards, and because Rails store the templates files grouped in folders named after their controllers I will use double wildcard ‘app/views/*/*’ to list the files 2 levels deep under app/views folder.

After I passed the required files to ‘args’, I can apply whatever command I like to all these files using the command ‘argdo’. First I will apply the substitute ‘s’ command and then ‘update’ which will only save the modified files.

:args app/views/*/*
:argdo %s/, :expire.*)/)/ge | update

Finally, another neat option is adding the flag ‘c’ which will ask confirmation before each substitution.

:argdo %s/, :expire.*)/)/gec | update

Setting the backspace key functionality in VIM

Vi Back space does not work ??

Setting the Backspace Key

For the backspace key, it isn’t quite as easy. The problem here is that there are two common backspace codes: backspace and delete. One is ^H, the other is ^?. If you are having problems it is because your terminal program choose the one the system didn’t. The default cluster login scripts set it to ^H. One solution is to change the setting in the local terminal emulator. However there are many possible emulators and we can’t support them all. So, to fix this on the UNIX side, you have to type the following at the shell prompt:

stty erase ^v<press backspace key right after typing ^v>

The ^v (control – v ) is the “quote character.” It keeps the shell from interpreting the next keystroke. This is necessary because some shells are smart enough to realize that either ^H or ^? should be treated as the backspace character, but some programs don’t (like mail, vi…).

If the problem persists try one of the following:

put the following lines into your .vimrc or type them in the vi commnad mode

set nocompatible bs=2

set backspace=start,eol,indent

set backspace=2

How to set the tab spacing in vi

set tabstop=x

x is the number of spaces that tab should introduce

How to highlight multiple words in VIM:

The above link provides an excellent way to highlight multiple words in vim. It is easy to setup, use and to extend the functionality provided.

How to use / without \ in a search string

Are you sick of using escape character “\” while searching-replacing a long string with ‘/’ in them? Then here is the solution

suppose you want to replace all ‘/’ with “.” in a long string like “soc_tb/smca/par_glm1/pcs_cdu_glm1/pcs_cdu_glm1_plm/plm/mux_body/all_disable”

Instead of doing the following


do this


VIM does not require you to use “/” for search and replace. So instead of this


you can use any other character. I prefer “#”. So this is what I do


The advantage is that now you can freely use “/” in your string without worrying about escape character “\” madness

How to highlight multiple words in vim

Vim provides a simple way to highlight all occurrences matching your last search, but it doesn’t provide an easy way to highlight more than one search. This tip provides a script to make it easy to highlight multiple words in different colors. In addition, you can search for the next highlighted word.




The script uses matchadd() which requires Vim 7.2 (actually version 7.1.040 or later). You will probably need gvim to display the colors specified in the script. In addition, the script assumes you have a numeric keypad and a system that allows you to map keys on that keypad (for example, the command :map <k0> :echo 'Hello'<CR> would display Hello when you press 0 on the numeric keypad).

You need the script (highlights.vim) and the file that defines the highlight groups (highlights.csv); these are given below.



The script defines highlight groups named hl1, hl2, … hl9 (and more). Once enabled, pressing one of the keys 1, 2, … 9 on the numeric keypad will highlight the word under the cursor with the colors defined in the corresponding highlight group (for example, press 4 on the keypad to highlight the current word with the hl4 group).

Type \m (assuming the default backslash leader key) to toggle mapping of the keypad on/off. At startup, the numeric keypad operates normally because only \mis mapped.

After typing \m to enable the mappings, you could use the keypad to:

  • Press 1 to highlight the current visually selected text, or the current word (if nothing is selected). Highlight group hl1 is used.
  • Press 2 for highlight hl2, 3 for highlight hl3, etc.
  • Press 0 to remove all highlights from the current visually selected text, or the current word.

For example, if you place the cursor on the word “rain” and press 4 on the keypad, all occurrences of “rain” will be highlighted (use :hi hl4 to show the colors). No highlighting will occur in words like “rainbow”.

Alternatively, place the cursor on “rain” and press viw to select the word, then 4. All occurrences of the visually selected text will be highlighted, including the “rain” in “rainbow”.

Each window has its own set of highlights: if you use :split to show two windows, you can have one set of highlights in the top window, and a different set in the other window.

With the mappings enabled, you could use the keypad to:

  • Press - to remove all highlights in the current window.
  • Press + to restore the highlighting when - was last used in the current window.
  • Press * to restore the highlighting when - was last used in any window.

For example, suppose you are displaying two windows and you want the same highlighting in each window. In the first window, apply the wanted highlighting. Then (using the numeric keypad keys):

  • Press - to remove all highlights in the first window.
  • Press + to restore them.
  • Switch to the other window and press * to apply the highlights from the first window.


After using \m to enable mappings, you can search for the next or previous occurrence of highlighted text. Patterns highlighted with the :match or :2matchcommands are also found.

Type \f to find the next match, or \F to find backwards. This has no effect on search highlighting or history.

Alternatively, type \n or \N to search forwards or backwards. Now you can press the normal search keys n or N to find the next or previous occurrence.

Highlight commandEdit

The script defines a :Highlight n pattern command where n is a number (1..99) and pattern is the text you want highlighted. Depending on your system, you may be able to use the abbreviation :Hi rather than :Highlight.

The following examples use different colors to highlight various patterns:

:Highlight 4 hello
:Highlight 5 \<hello\>
:Highlight 6 Hello World
:Highlight 7 \c\<th

The second example is the same as placing the cursor on “hello” then pressing 5 on the numeric keypad. The last example highlights th occurring at the beginning of a word, not case sensitive.

The following command will list all active highlights (group names and patterns):


Other commandsEdit

After using \m to enable the keypad mappings, you can press 1..9 on the keypad to highlight the visual selection (if any), or the current word. For example, pressing 4 on the keypad will highlight using the hl4 group.

In addition, you can press a digit 1..9 on the main keyboard before pressing 1..9 on the keypad. For example, if you press 2 on the main keyboard before 4on the keypad, the hl24 highlight group will be used.

The :Hclear command can clear highlights. After typing :Hclear, you can enter an argument, or you can press Space then Tab for command completion (highlighted patterns). Examples:

" Remove highlight for visual selection (if any), or current word.
" Remove highlight 24.
:Hclear 24
" Remove all highlights for pattern '\c\<th'.
:Hclear \c\<th
" Remove all highlights.
:Hclear *

The following command will create a scratch buffer showing all the defined highlights:


The following commands can be used to save or restore the current highlights:

:Hsave anyname
:Hrestore anyname

Replace anyname with any name you would like to use. These commands use uppercase global variables (anyname is converted to uppercase), which Vim will save providing you have the ! flag in the 'viminfo' option (:set viminfo^=!).

After typing :Hsave or :Hrestore, you can press Space then Tab for command completion.


Copy this text into Vim to test word highlighting:

777  888  999   111 222 333 444 555 666 777 888 999
444  555  666   999 111 222 333 444 555 666 777 888
111  222  333   888 999 111 222 333 444 555 666 777
111222 333444 555666 777888999 111222 333444 555666

Use :sp to split the window and view the above text in both windows. Use \m to enable mappings, then apply some matches in the top window. Switch to the bottom window and apply some different matches: each window maintains a separate list of highlight matches.

In the next step, you must use the -+* keys on the numeric keypad. While in the bottom window, press - to clear highlighting in that window. If wanted, press+ to restore highlighting. In the top window, press * to apply the highlighting from the bottom window.


Create file ~/.vim/plugin/highlights.vim (Unix) or $HOME/vimfiles/plugin/highlights.vim (Windows) containing the script below, then restart Vim.

" Plugin to highlight multiple words in different colors.
" Version 2008-11-19 from
" File highlights.csv (in same directory as script) defines the highlights.
" Type '\m' to toggle mapping of keypad on/off (assuming \ leader).
" Type '\f' to find the next match; '\F' to find backwards.
" Can also type '\n' or '\N' for search; then n or N will find next.
" On the numeric keypad, press:
"   1 to highlight visually selected text or current word
"     using highlight group hl1 (defined below)
"   2 for highlight hl2, 3 for highlight hl3, etc
"     (can press 1 to 9 on keypad for highlights hl1 to hl9)
"   0 to remove highlight from current word
"   - to remove all highlights in current window
"   + to restore highlights cleared with '-' in current window
"   * to restore highlights (possibly from another window)
" Can press 1 or 2 on main keyboard before keypad 1..9 for more highlights.
" Commands:
"   ':Highlight' list all highlights.
"   ':Highlight [n [pattern]]' set highlight.
"   ':Hsample' display all highlights in a scratch buffer.
"   ':Hclear [hlnum|pattern|*]' clear highlights.
"   ':Hsave x', ':Hrestore x' save/restore highlights (x any name).
" Saving current highlights requires '!' in 'viminfo' option.
if v:version < 702 || exists('loaded_highlightmultiple') || &cp
let loaded_highlightmultiple = 1
" On first call, read file highlights.csv in same directory as script.
" For example, line "5,white,blue,black,green" executes:
" highlight hl5 ctermfg=white ctermbg=blue guifg=black guibg=green
let s:data_file = expand('<sfile>:p:r').'.csv'
let s:loaded_data = 0
function! LoadHighlights()
  if !s:loaded_data
    if filereadable(s:data_file)
      let names = ['hl', 'ctermfg=', 'ctermbg=', 'guifg=', 'guibg=']
      for line in readfile(s:data_file)
        let fields = split(line, ',', 1)
        if len(fields) == 5 && fields[0] =~ '^\d\+$'
          let cmd = range(5)
          call map(cmd, 'names[v:val].fields[v:val]')
          call filter(cmd, 'v:val!~''=$''')
          execute 'silent highlight '.join(cmd)
      let s:loaded_data = 1
    if !s:loaded_data
      echo 'Error: Could not read highlight data from '.s:data_file
" Return last visually selected text or '\<cword\>'.
" what = 1 (selection), or 2 (cword), or 0 (guess if 1 or 2 is wanted).
function! s:Pattern(what)
  if a:what == 2 || (a:what == 0 && histget(':', -1) =~# '^H')
    let result = expand("<cword>")
    if !empty(result)
      let result = '\<'.result.'\>'
    let old_reg = getreg('"')
    let old_regtype = getregtype('"')
    normal! gvy
    let result = substitute(escape(@@, '\.*$^~['), '\_s\+', '\\_s\\+', 'g')
    normal! gV
    call setreg('"', old_reg, old_regtype)
  return result
" Remove any highlighting for hlnum then highlight pattern (if not empty).
" If pat is numeric, use current word or visual selection and
" increase hlnum by count*10 (if count [1..9] is given).
function! s:DoHighlight(hlnum, pat, decade)
  call LoadHighlights()
  let hltotal = a:hlnum
  if 0 < a:decade && a:decade < 10
    let hltotal += a:decade * 10
  if type(a:pat) == type(0)
    let pattern = s:Pattern(a:pat)
    let pattern = a:pat
  let id = hltotal + 100
  silent! call matchdelete(id)
  if !empty(pattern)
      call matchadd('hl'.hltotal, pattern, -1, id)
    catch /E28:/
      echo 'Highlight hl'.hltotal.' is not defined'
" Remove all matches for pattern.
function! s:UndoHighlight(pat)
  if type(a:pat) == type(0)
    let pattern = s:Pattern(a:pat)
    let pattern = a:pat
  for m in getmatches()
    if m.pattern ==# pattern
      call matchdelete(
" Return pattern to search for next match, and do search.
function! s:Search(backward)
  let patterns = []
  for m in getmatches()
    call add(patterns, m.pattern)
  if empty(patterns)
    let pat = ''
    let pat = join(patterns, '\|')
    call search(pat, a:backward ? 'b' : '')
  return pat
" Enable or disable mappings and any current matches.
function! s:MatchToggle()
  if exists('g:match_maps') && g:match_maps
    let g:match_maps = 0
    for i in range(0, 9)
      execute 'unmap <k'.i.'>'
    nunmap <kMinus>
    nunmap <kPlus>
    nunmap <kMultiply>
    nunmap <Leader>f
    nunmap <Leader>F
    nunmap <Leader>n
    nunmap <Leader>N
    let g:match_maps = 1
    for i in range(1, 9)
      execute 'vnoremap <silent> <k'.i.'> :<C-U>call <SID>DoHighlight('.i.', 1, v:count)<CR>'
      execute 'nnoremap <silent> <k'.i.'> :<C-U>call <SID>DoHighlight('.i.', 2, v:count)<CR>'
    vnoremap <silent> <k0> :<C-U>call <SID>UndoHighlight(1)<CR>
    nnoremap <silent> <k0> :<C-U>call <SID>UndoHighlight(2)<CR>
    nnoremap <silent> <kMinus> :call <SID>WindowMatches(0)<CR>
    nnoremap <silent> <kPlus> :call <SID>WindowMatches(1)<CR>
    nnoremap <silent> <kMultiply> :call <SID>WindowMatches(2)<CR>
    nnoremap <silent> <Leader>f :call <SID>Search(0)<CR>
    nnoremap <silent> <Leader>F :call <SID>Search(1)<CR>
    nnoremap <silent> <Leader>n :let @/=<SID>Search(0)<CR>
    nnoremap <silent> <Leader>N :let @/=<SID>Search(1)<CR>
  call s:WindowMatches(g:match_maps)
  echo 'Mappings for matching:' g:match_maps ? 'ON' : 'off'
nnoremap <silent> <Leader>m :call <SID>MatchToggle()<CR>
" Remove and save current matches, or restore them.
function! s:WindowMatches(action)
  call LoadHighlights()
  if a:action == 1
    if exists('w:last_matches')
      call setmatches(w:last_matches)
  elseif a:action == 2
    if exists('g:last_matches')
      call setmatches(g:last_matches)
      call s:Hrestore('')
    let m = getmatches()
    if !empty(m)
      let w:last_matches = m
      let g:last_matches = m
      call s:Hsave('')
      call clearmatches()
" Return name of global variable to save value ('' if invalid).
function! s:NameForSave(name)
  if a:name =~# '^\w*$'
    return 'HI_SAVE_'.toupper(a:name)
  echo 'Error: Invalid name "'.a:name.'"'
  return ''
" Return custom completion string (match patterns).
function! s:MatchPatterns(A, L, P)
  return join(sort(map(getmatches(), 'v:val.pattern')), "\n")
" Return custom completion string (saved highlight names).
function! s:SavedNames(A, L, P)
  let l = filter(keys(g:), 'v:val =~# ''^HI_SAVE_\w''')
  return tolower(join(sort(map(l, 'strpart(v:val, 8)')), "\n"))
" Save current highlighting in a global variable.
function! s:Hsave(name)
  let sname = s:NameForSave(a:name)
  if !empty(sname)
    let l = getmatches()
    call map(l, 'join([, v:val.pattern, v:val.priority,], "\t")')
    let g:{sname} = join(l, "\n")
command! -nargs=? -complete=custom,s:SavedNames Hsave call s:Hsave('<args>')
" Restore current highlighting from a global variable.
function! s:Hrestore(name)
  call LoadHighlights()
  let sname = s:NameForSave(a:name)
  if !empty(sname)
    if exists('g:{sname}')
      let matches = []
      for l in split(g:{sname}, "\n")
        let f = split(l, "\t", 1)
        call add(matches, {'group':f[0], 'pattern':f[1], 'priority':f[2], 'id':f[3]})
      call setmatches(matches)
      echo 'No such global variable: '.sname
command! -nargs=? -complete=custom,s:SavedNames Hrestore call s:Hrestore('<args>')
" Clear a match, or clear all current matches. Example args:
"   '14' = hl14, '*' = all, '' = visual selection or cword,
"   'pattern' = all matches for pattern
function! s:Hclear(pattern) range
  if empty(a:pattern)
    call s:UndoHighlight(0)
  elseif a:pattern == '*'
    call s:WindowMatches(0)
  elseif a:pattern =~ '^[1-9][0-9]\?$'
    call s:DoHighlight(str2nr(a:pattern), '', 0)
    call s:UndoHighlight(a:pattern)
command! -nargs=* -complete=custom,s:MatchPatterns -range Hclear call s:Hclear('<args>')
" Create a scratch buffer with sample text, and apply all highlighting.
function! s:Hsample()
  call LoadHighlights()
  setlocal buftype=nofile bufhidden=hide noswapfile
  let lines = []
  let items = []
  for hl in filter(range(1, 99), 'v:val % 10 > 0')
    if hlexists('hl'.hl)
      let sample = printf('Sample%2d', hl)
      call s:DoHighlight(hl, sample, 0)
      let sample = '        '
    call add(items, sample)
    if len(items) >= 3
      call insert(lines, substitute(join(items), '\s\+$', '', ''))
      let items = []
  call append(0, filter(lines, 'len(v:val) > 0'))
command! Hsample call s:Hsample()
" Set a match, or display all current matches. Example args:
"   '14' = set hl14 for visual selection or cword,
"   '14 pattern' = set hl14 for pattern, '' = display all
function! s:Highlight(args) range
  if empty(a:args)
    echo 'Highlight groups and patterns:'
    for m in getmatches()
      echo m.pattern
  let l = matchlist(a:args, '^\s*\([1-9][0-9]\?\)\%($\|\s\+\(.*\)\)')
  if len(l) >= 3
    let hlnum = str2nr(l[1])
    let pattern = l[2]
    if empty(pattern)
      let pattern = s:Pattern(0)
    call s:DoHighlight(hlnum, pattern, 0)
  echo 'Error: First argument must be highlight number 1..99'
command! -nargs=* -range Highlight call s:Highlight('<args>')

Defining highlight groupsEdit

The script reads a CSV file with the same directory/name as the script, but with .csv extension. Each line should consist of five comma-separated fields, where the first field is a number from 1 to 99 inclusive (any other lines are ignored).

For example, the line “5,white,blue,black,green” would define a highlight group named hl5 which color terminals would display as white on blue, and gvim would display as black on green.

Create file ~/.vim/plugin/highlights.csv (Unix) or $HOME/vimfiles/plugin/highlights.csv (Windows) containing the sample below, then restart Vim.


See alsoEdit


How to highlight multiple words in gvim

How to highlight multiple patterns in vim

Can all the test signals be shared

In a Scan based design for testability we generally need the following test signals

  • scan_in
  • scan_out
  • scan_en
  • test_mode(optional)
If you are having only the first three test signals then you need to have scan_en dedicated and the rest two can be shared. However, it is recommended to use all the above listed signals wherein only test_mode will be dedicated and the rest can be shared. This dedicated test_mode signal can be used to control other non-scan test logic inserted into the design. 

What is the difference between Serail and Parallel Patterns

Parallel patterns are forced parallely (at the same instance of time) @ SI of each flop and measured @ SO. Basically these patterns are used for simulating the patterns faster. Here only two cycles are required to simulate a pattern : one to force all the flops and one for capture.
Serial patterns are the ones which are used @the tester. They are serially shifted and captured and shifted out.