Showing posts with label Vim. Show all posts
Showing posts with label Vim. Show all posts

11 February 2026

In vim, how to make the first letter of every word into uppercase?

https://dev.to/gokayburuc/vim-regex-tricks-capitalize-every-first-letter-526j

To capitalize the first letter of each word in a sentence, use the following Vim command:

:s/\<\w/\u&/g

Explanation of the Command

  • :s/ starts the substitution command in Vim, which is used to find a pattern and replace it with a specified value.
  • \< matches the beginning of a word. In Vim, a word is defined as a sequence of letters, digits, or underscores.
  • \w matches any word character (letters, digits, or underscores).
  • \u is a replacement flag in Vim that converts the next character in the replacement string to uppercase.
  • & represents the entire matched text from the search pattern (in this case, the first character of each word).
  • /g applies the substitution globally, ensuring every matching occurrence in the line is processed rather than just the first one.

By running this command, Vim will capitalize the first letter of each word in the specified text.

 

 

 

25 January 2026

The list of all the format options of the gq command in vim?

In Vim, the
'formatoptions' setting controls how automatic text formatting is performed. It accepts a string of single-character flags, each enabling a specific behavior. You can view the current value in your Vim session with the command :set fo? or get a detailed explanation of all flags using the Vim help documentation via :help fo-table. 
The common and widely recognized formatoptions flags are:
  • t: Auto-wrap text at the width specified by the 'textwidth' option.
  • c: Auto-wrap comments at 'textwidth', automatically inserting the current comment leader character(s) (defined by 'comments' or 'commentstring').
  • q: Allow formatting with the gq operator.
  • r: Automatically insert the current comment leader after pressing <Enter> in Insert mode.
  • o: Automatically insert the current comment leader after pressing o or O in Normal mode.
  • n: Recognize numbered lists when formatting, using the pattern defined in 'formatlistpat'. This helps avoid joining list items into a single paragraph.
  • b: Auto-wrap text (backwards) when a line grows longer than 'textwidth'. The line is broken at the last white space before 'textwidth'.
  • v: Vi-compatible auto-wrapping (wraps at 'textwidth' in Insert mode).
  • j: Delete comment characters when joining lines using the J command.
  • l: Leave long lines as they are when entering Insert mode; only format if a line explicitly exceeds 'textwidth' due to typing.
  • m: Join with a space between the joined lines if there isn't one already.
  • p: Do not auto-wrap paste. When pasting text in Insert mode, do not apply auto-wrapping based on 'textwidth'.
  • u: Undo separate; make an undo command revert one line at a time instead of the entire paragraph formatting operation.
  • 2: Keep the indent of the second line when a paragraph is formatted (useful for some programming styles).
  • 1: Do not break a line after a single character (e.g., prevent single-letter words from being alone on the next line). 
  • a: Automatic formatting of paragraphs (changes are immediately reformatted). 
The default value is typically tcq. To add an option, you can use :set formatoptions+=<char>, and to remove one, use :set formatoptions-=<char>. 

Vim global command - how to apply 2 or more patterns?

:g/====\|----/-1p

Prints the line above all the lines with '====', and the line above all the lines with '----'

25 December 2025

How to compare differences of files in Vim?

In Vim, you can compare (diff) the file you already have open with another file in a few common ways. Here are the most practical ones.


1️⃣ From inside Vim (recommended)

If you already have file A open and want to compare it with file B:

:vert diffsplit path/to/other_file
  • Opens the other file in a vertical split

  • Vim automatically enters diff mode

  • Differences are highlighted

Horizontal split (if you prefer):

:diffsplit path/to/other_file

2️⃣ If both files are already open in Vim

If you opened two files normally (no diff yet):

:diffthis

Run this command in each window you want to compare.

To turn diff mode off later:

:diffoff

3️⃣ Start Vim in diff mode (for future reference)

From the terminal:

vim -d file1 file2

or

vimdiff file1 file2

4️⃣ Useful diff navigation commands

While in diff mode:

CommandWhat it does
]cJump to next difference
[cJump to previous difference
:diffgetGet change from the other file
:diffputPut change to the other file
dodiff obtain (same as diffget)
dpdiff put

5️⃣ Exit diff mode cleanly

:diffoff!

or close one of the windows:

:q

💡 Tip (since you use Linux a lot)

Vertical diff is often easier on wide terminals:

:vert diffsplit other_file

If you want, I can also show:

  • how to compare 3 files

  • how to diff against the current buffer on disk

  • how to use Vim diff with Git

Just tell me 👍

How to compare 3 files, please.

 

 

In Vim, comparing 3 files is very doable. Here are the clean, correct ways, from simplest to more advanced.


✅ Method 1: Start Vim with 3 files in diff mode (best & simplest)

From the terminal:

vimdiff file1 file2 file3

or

vim -d file1 file2 file3

Result:

  • All 3 files open side-by-side

  • Vim automatically enters diff mode

  • Differences highlighted across all three


✅ Method 2: Add a 3rd file while already diffing 2 files

If you already have file1 open and diffed with file2:

:vert diffsplit file3

Vim will:

  • Open file3 in a new split

  • Automatically include it in the diff

💡 For horizontal split instead:

:diffsplit file3

✅ Method 3: Files already open → manually enable diff

If all three files are open in different windows but not diffed yet:

  1. Go to each window and run:

    :diffthis
    
  2. Repeat for all three windows

To exit later:

:diffoff

🧭 Navigating differences (very important with 3 files)

CommandDescription
]c / [cNext / previous diff
doTake change from another file
dpPut change into another file
:diffget LOCALGet change from current window
:diffget REMOTEGet change from another window

👉 With 3 files, Vim labels them as:

  • LOCAL

  • BASE

  • REMOTE

You can be explicit:

:diffget BASE
:diffget LOCAL
:diffget REMOTE

🧠 Common real-world example (Git-style 3-way diff)

vimdiff mine theirs base

Typical meaning:

  • BASE = original

  • LOCAL = your version

  • REMOTE = incoming version


🧹 Exit diff mode

:diffoff!

or close windows normally:

:q

⭐ Pro tips

  • Use vertical splits on wide screens:

    set diffopt+=vertical
    
  • Synchronize scrolling:

    :set scrollbind
    

If you want, I can also explain:

  • 3-way merge conflict resolution

  • diff against Git commits

  • color customization for diffs

Just say the word 👍

14 December 2025

In Vim, how to run one of the commands I ran before again?

    To re-run a command from your Vim history, you can use the following methods:
    1. Using the Command-line Window (q:)
    The most common and interactive way is to open the command-line window: 
    1. Press q:. This opens a special window in your Vim buffer which lists all previously executed commands, similar to a regular file buffer.
    2. Use the standard Vim movement keys (j, k, G, etc.) to navigate to the command you wish to re-run.
    3. Press Enter while your cursor is on the line of the desired command. Vim will execute that command and close the history window.
    4. To exit the window without running a command, use :q or Ctrl-C. 
    2. Using Command-line History Navigation
    You can cycle through your command history directly from the command prompt: 
    1. Type : to start a new command line.
    2. Use the Up Arrow (<Up>) or Ctrl-P to go back through the history of previous commands.
    3. Use the Down Arrow (<Down>) or Ctrl-N to go forward through the history.
    4. When the desired command appears on the command line, press Enter to execute it. 
    3. Using History Search (q/ or q?) 
    If you have a long history and want to find a specific command quickly, you can search for it:
    1. Press q/ (for forward search) or q? (for backward search) to open the search history window.
    2. Type your search pattern (e.g., s/) and press Enter. The window will list commands matching that pattern.
    3. Navigate to the command you want to run and press Enter to execute it. 
    4. Running a Specific History Index 
    You can also run a specific command by its index number if you know it from viewing :history. This is less common but useful if you need an exact, old command: 
    1. Type :@: followed by the number of the history entry you want to execute (e.g., :@:25 to run command number 25).

03 December 2025

Creating links for table of contents of markdown files

Step 1 - add [ to start of each line

:'a,s/^/[

[1.0 Mobile Devices
[1.1 installing and configuring a battery replacement in a laptop
[1.2 Installing and configuring a keyboard replacement in a laptop

Step 2 - append ] to last non-space in each line

:'a,g/^/normal g_a]

[1.0 Mobile Devices]
[1.1 installing and configuring a battery replacement in a laptop]
[1.2 Installing and configuring a keyboard replacement in a laptop]

Step 3 - copy each whole line and append it to each line

:'a,g/^/normal 0yg_g_p

Step 4 - Change the 2nd '[' into '('

:'a,g/^/normal 0f[r(

Step 5 - Change the 2nd ']' into ')'

:'a,g/^/normal 2f]r)


[1.0 Mobile Devices](Mobile Devices) 

[1.1 installing and configuring a battery replacement in a laptop](installing and configuring a battery replacement in a laptop) 

[1.2 Installing and configuring a keyboard replacement in a laptop](Installing and configuring a keyboard replacement in a laptop) 

Step 6 - Insert a Carriage Return between ']' and '(', i.e. replacing '](' with ']\r(' in every line

:'a,s/\](/\]\r(/
or
:'a,s/\(/\r\(/


Step 7 - In every () line, replace every space with a hyphen

:'a,g/(/s/ /-/g

Step 8 - in every () line, change every uppercase letter into lowercase letter

:'a,g/(/normal 0gu$

Step 9 - in every () line, add '#' after '('

:'a,g/(/normal 0a#


Step 10 - go to every [] line, run the command 'gJ'

:'a,g/\[/normal gJ

Notes:
'J' - there will be a space between the 2 lines which are now joined together
'gJ' - there will be no space between the 2 lines which are now joined together




01 December 2025

How to automatically create 'Table of Contents' of a markdown text file in vim?

To use the Vim global command for lines containing only "===" or "---", the pattern needs to match the entire line content exactly.
Here is how to construct the pattern:
Code
:g/^\(===\|---\)/-1p
Explanation of the pattern:
  • ^: This anchor matches the beginning of the line. It ensures that the pattern must start at the very beginning of the line.
  • \(...\): This creates a capturing group for alternation.
  • ===: This matches the literal string "===".
  • \|: This is the OR operator within a regular expression. It allows matching either the pattern before it or the pattern after it.
  • ---: This matches the literal string "---".
  • \): This closes the capturing group.
  • -1 : Print the line above the '===' line (or '---' line)
  • p : Print

28 November 2025

How to delete time lines in vim?

e.g.

0:00  

Think of the A+ Core 2 exam like a complex machine. We're going to take it apart, understand each component, and  

0:07  

put it back together in record time. We're starting with the first objective of the first domain, operating systems.  

0:16  

By the time we're done, you'll be the master mechanic, ready to ace the exam. Let's tackle the first hurdle, 


You can delete all the time lines using the following command:

:g/^\d\{1,2\}:\d\{2\}/d

Command Breakdown

  • :: Starts command-line mode.

  • g: Stands for "global." It applies the subsequent command (d) to every line that matches the preceding pattern.

  • /^\d\{1,2\}:\d\{2\}/: This is the pattern (regex) to match the time lines.

    • ^: Matches the start of the line.

    • \d\{1,2\}: Matches one or two digits (for the minute/hour part, e.g., '0' or '10'). \d is the escape for a digit, and \{1,2\} is the quantifier.

    • :: Matches the literal colon.

    • \d\{2\}: Matches exactly two digits (for the seconds part, e.g., '00' or '07').

  • d: The command to execute on the matched lines, which is delete.




05 March 2025

How To Search And Replace String Across Multiple Files in Vim

https://irian.to/blogs/how-to-search-and-replace-string-across-multiple-files-in-vim

 

Perform substitution with macros and repeat it

While recording a macro, perform substitution on one file, and repeat the macros across all args.

Assuming the same folder structure and args, here is how it is done:

qq                                          // start macro in q register
%s/stringToBeReplaced/replacementString/ge  // the e flag tells vim to not throw an error if there is no match
:wnext                                      //important. This is similar to `:next`, but it also writes the current file
q                                           // stop macro
999@q                                       //repeat this macros either 999 times or to remaining files.

That's it!

08 April 2024

How to move in insert mode in vim?

https://vi.stackexchange.com/questions/10296/navigation-in-insert-mode


If you just need to modify a small amount of text or a word, you can use <Ctrl-O>h/j/k/l.

<Ctrl-O> takes you back to Normal mode just for that command, and then drops you back into insert mode, so it saves you some amount of key presses, if you need to go into normal mode for a small movement.

22 December 2023

How to use regex in vim to replace with an incrementing number variable

https://stackoverflow.com/questions/57756503/how-to-use-regex-in-vim-to-replace-with-an-incrementing-number-variable

I have a file which content like this:

id      phone   name
x'1234' 12345   jack
x'4567' 45678   Jojo
x'7890'  89456  Dio
x'4591'  34872  joseph

and i want to parse it into like this:

id  phone   name
1   12345   jack
2   45678   Jojo
3    89456  Dio
4    34872  joseph

I know basic regular expression could replace all id to any string like this:

:%s/x'\(\w\+\)'/\1/g

and it will become:

id  phone   name
1   12345   jack
1   45678   Jojo
1    89456  Dio
1    34872  joseph

How to replace id to an increment variable ?

 ===================================

 

Mind that you can use an expression as the replacement string in the substitute command (:s). When the replacement string starts with \= it is evaluated as an expression.

Here, one possible solution is

:let i=1 | g/^x'\d\+'/s//\=i/ | let i=i+1

It finds all occurrences (one per line) of the ^x'\d\+' pattern and replaces it with the value if i that is incremented each time the match is found. As has been noted in comments, the | is a part of the g replacing "code", as "| is used to execute more than one command at a time".

Another solution is using the line() command (taking into account that your file has a header top line, so you should actually subtract 1 from the value returned with line()):

%s/^x'\d\+'/\=line('.')-1/

The ^x'\d\+' regex matches

  • ^ - start of a line
  • x' - x' string
  • \d\+ - 1+ digits
  • ' - a ' char.

There are other interesting "increment number in regex" examples at the Using an expression in substitute command page:

  • Number all the lines in a file (insert line number followed by a tab):
    :%s/^/\=line('.')."\t"/
  • Number a range of lines (from line 10 to line 20):
    :10,20s/^/\=line('.')."\t"/
  • Number a range of lines sequentially starting from 1:
    :let counter=0|10,20g//let counter=counter+1|s/^/\=counter."\t"
  • Number all the paragraphs in range starting from 1 (assuming the paragraphs are separated by one or more blank lines):
    :let counter=0|1,20g/^$\n^\s*[^\s]/let counter=counter+1|+1s/^/\=counter."\t"
    Note: The above command does not work for the first paragraph in the file if there is no blank line above it.

 

17 September 2023

How to copy from vim to system clipboard on ubuntu?

https://superuser.com/questions/1559544/how-to-copy-from-vim-to-clipboard-on-ubuntu-20-04


You need to make sure clipboard is activated (which is probably not the case).

Run : vim --version | grep 'clipboard'

if you get "-clipboard" then you would have to install vim again with the "clipboard" functionality.

You can do it it by installing "vim-gtk3" or "gvim".

Solution

sudo apt-get install vim-gtk3 -y

With that, you will be able to copy into clipboard by typing (including the plus) "+y

How to set up a command for toggling line wrapping in vim?

In .vimrc, add a line -

map <C-a> :set wrap!<CR>

Thus you press Ctrl-A and toggle between line wrapping and unwrapping

12 August 2023

How to install NERDTree for vim? | How to always display a file explorer at the left side in vim?

https://github.com/preservim/nerdtree#readme

How to install NERDTree?

Pathogen Pathogen is more of a runtime path manager than a plugin manager. You must clone the plugins' repositories yourself to a specific location, and Pathogen makes sure they are available in Vim.
  1. In the terminal,
    git clone https://github.com/preservim/nerdtree.git ~/.vim/bundle/nerdtree
  2. In your vimrc,
    call pathogen#infect()
    syntax on
    filetype plugin indent on
  3. Restart Vim, and run :helptags ~/.vim/bundle/nerdtree/doc/ or :Helptags.

 How to display file explorer in vim?

 :NERDTree

06 August 2023

My .vimrc

set showcmd
"
" set linewidth      

" set textwidth=78     

set encoding=utf-8   
set fileencoding=utf-8

" enable syntax highlighting
syntax enable        

" show line numbers  
set number           

" set tabs to have 4 spaces
set ts=4             

" indent when moving to the next line while writing code
set autoindent       

" expand tabs into spaces
set expandtab        

" when using the >> or << commands, shift lines by 4 spaces
set shiftwidth=4 

" show a visual line under the cursor's current line

" set cursorline        

" show the matching part of the pair for [] {} and ()
set showmatch           

set guifont=Consolas:h11

" avoid word breaking at end of each screen line
set linebreak           

" enable all Python syntax highlighting features
let python_highlight_all = 1

set splitbelow          
set splitright          

nmap <C-h> <C-w>h       
nmap <C-j> <C-w>j       
nmap <C-k> <C-w>k       
nmap <C-l> <C-w>l       

" vim-pathogen          
execute pathogen#infect()

syntax on               

filetype plugin indent on

" Ctrl-P                
set runtimepath^=~/.vim/bundle/ctrlp.vim
"                                                                 *'g:ctrlp_map'*
" Use this option to change the mapping to invoke CtrlP in |Normal| mode:
let g:ctrlp_map = '<c-p>'
"                                                                 *'g:ctrlp_cmd'*
" Set the default opening command to use when pressing the above mapping:
let g:ctrlp_cmd = 'CtrlP'
"                                                  *'g:ctrlp_working_path_mode'*
" When starting up, CtrlP sets its local working directory according to this
" variable: >        
let g:ctrlp_working_path_mode = 'ra'

set colorcolumn=5,9,13,17,21,25,29,33,37,41,45,49,53,57,61,65

" NERDTree settings  
" Start NERDTree. If a file is specified, move the cursor to its window.
autocmd StdinReadPre * let s:std_in=1
autocmd VimEnter * NERDTree | if argc() > 0 || exists("s:std_in") | wincmd p | endif
" Open the existing NERDTree on each new tab.
autocmd BufWinEnter * if getcmdwintype() == '' | silent NERDTreeMirror | endif
let NERDTreeWinSize = 20
" toggle between line wrapping and unwrapping
map <C-a> :set wrap!<CR>

" set colorcolumn color
:hi ColorColumn ctermbg=lightgrey guibg=lightgrey

" set foreground and background colours for vim window
" :highlight Normal ctermfg=black ctermbg=lightyellow guifg=black guibg=lightyellow