Pages

Search This Blog

Showing posts with label advanced vi/vim. Show all posts
Showing posts with label advanced vi/vim. Show all posts

Sunday, July 19, 2020

vi - A fast and powerful Text Editor


About this first blog, I was sure it would be about this beautiful little program called 'vi', the command-line text editor that amuse the users(sysads/progmrs) by its simple, yet powerful features. As a user spent time interacting with this little editor, more cool features gets unveiled before the user.



vi was originally created for Unix systems, by  Bill Joy in 1976, as the visual mode for a line editor called ex that Joy had written with Chuck Haley.  vi was derived from a sequence of UNIX command line editors, starting with ed, which was a line editor designed to work well on teleprinters, rather than display terminals. You could find this 'ed' editor in earlier distros of GNU/Linux ( I've seen it in Debian wheezy, but now in buster its not packaged). This ed editor has its own history too (ever wondered how the 'grep' command name originated?).

Joy was responsible for creating the first BSD Unix release in March, 1978, and included ex 1.1 in the distribution, thereby exposing his editor to an audience beyond UC Berkeley. From that release of BSD Unix onwards, the only editors that came with the Unix system were ed and ex. 

Eventually it was observed that most ex users were spending all their time in visual mode,and thus in ex 2.0, Joy created vi as a hard link to ex, such that when invoked as vi, ex would automatically start up in its visual mode. Thus, vi is not the evolution of ex, vi is ex. In your *nix distro you can verify this by executing ex -v filename which is the execution of the same vi .

Despite the existence of vi clones with enhanced featuresets, sometime before June 2000, Gunnar Ritter ported Joy's vi codebase (taken from 2.11BSD, February 1992) to modern Unix-based operating systems, such as Linux and FreeBSD. Initially, his work was technically illegal to distribute without an AT&T source license, but, in January 2002, those licensing rules were relaxed,[29] allowing legal distribution as an open-source project. Ritter continued to make small enhancements to the vi codebase similar to those done by commercial Unix vendors still using Joy's codebase, including changes required by the POSIX.2 standard for vi. His work is available as Traditional Vi, and runs today on a variety of systems.

You can read complete history here https://en.wikipedia.org/wiki/Vi from which the above excerpt is taken.


What are vi, ex, view; why are these binaries in my system.

Vi is a screen oriented text editor.

Ex is a line-oriented text editor. Ex and vi are different interfaces to the same program, and it is possible to switch back and forth during an edit session.

View behaves identically to vi except that it automatically opens all files as read-only.It is the equivalent of using the -R (read-only) option of vi.

The vi and ex components will be explained in the section Components of vi

All these binaries are actually links to one another, for e.g: in the Debian buster release vi, ex, and view are links to the binary vim.tiny.

root@localhost:~# readlink -f /usr/bin/vi

/usr/bin/vim.tiny


root@localhost:~# dpkg -S /usr/bin/vim.tiny

vim-tiny: /usr/bin/vim.tiny


root@localhost:~# ls -l /usr/bin/vi

lrwxrwxrwx 1 root root 20 Jan  6  2020 /usr/bin/vi -> /etc/alternatives/vi


root@localhost:~# ls -l /usr/bin/ex

lrwxrwxrwx 1 root root 20 Jan  6  2020 /usr/bin/ex -> /etc/alternatives/ex


root@localhost:~# ls -l /usr/bin/view

lrwxrwxrwx 1 root root 22 Jan  6  2020 /usr/bin/view -> /etc/alternatives/view


root@localhost:~# ls -l /etc/alternatives/vi

lrwxrwxrwx 1 root root 17 Jan  6  2020 /etc/alternatives/vi -> /usr/bin/vim.tiny


root@localhost:~# ls -l /etc/alternatives/ex

lrwxrwxrwx 1 root root 17 Jan  6  2020 /etc/alternatives/ex -> /usr/bin/vim.tiny


root@localhost:~# readlink -f /usr/bin/ex

/usr/bin/vim.tiny


root@localhost:~# ls -l /etc/alternatives/view

lrwxrwxrwx 1 root root 17 Jan  6  2020 /etc/alternatives/view -> /usr/bin/vim.tiny

In a Redhat distro, you will find these binaries are provided by package named vim-minimal ; ex and view are direct links to the vi binary

ex:
Start in Ex mode. Go to Normal mode with the ":vi" command. Can also be done with the "-e" argument.

view:
Start in read-only mode. You will be protected from writing the files. Can also be done with the "-R" argument.

vi will detect the name it was invoked as and act accordingly.

I think all these binaries and its relations boils down to the UNIX_philosopy "the power of a system comes more from the relationships among programs than from the programs themselves. Many UNIX programs do quite trivial things in isolation, but, combined with other programs, become general and useful tools."



vim- as the name sounds was earlier known as 'vi-imitation' which then later called as vi-Improved because of the added new features. vim is a clone, with additions, of vi editor. As vi editor was not free for a while, many clones began to get ported to Linux/FreeBSD's and vim is one such clone of vi.
In addition to syntax highlighting (when compiled with a support for it), Multi-level undo, it does automatic conversions of charactersets, line-endings and such. It has multiple ways of numbering lines, which is really convenient.
Vim certainly has a lot that speaks for it.  IMO and like-minded others, vim breaks the vi philosophy by mixing the editor modes and introducing a vast number of redundant functions.
Today, in most *nix distros, vi is actually a reference to vim.


Most of the GNU/Linux distros comes with vi/vim, if your OS release doesn't have vi/vim, you can install it via the package manager available in your OS.
Debian: apt install vim
Redhat: yum install vim
BSD: pkg install vim-console


There are two components to vi: a screen editor (Vi), and a line editor (Ex).
Each has a different set of commands; you can invoke the line editor from within the screen editor and conversely, you can invoke the screen editor from within the line editor.

In the screen editor, you are in either insert mode or command mode. In command mode, every character you type is immediately interpreted as a command. In insert mode, every character you type is added to the text that you are editing.

$ vi filename

Entering vi, by default you will be greeted by the normal mode that is the command mode where each characters you press will be interpreted as commands. Below are the commands that will help you move-by your first-steps.
       h      Move the cursor left one character.

       j      Move the cursor down one line.

       k      Move the cursor up one line.

       l      Move the cursor right one character.
            <cursor-arrows>
              The cursor arrow keys should work, too.

Press 'i' and you will be in the insert mode where every character you type is added to the text that you are editing.

Press 'Esc' and you will be back to normal mode (command mode).

Press ':' and you will be in the Ex mode, that is line editor mode. (you can also start the mode by invoking the command under the name ex; or you can invoke it under the name vi but specify the -e option. Similarly, there are two ways to start your session in Vi mode; you can invoke the command under the name vi without specifying -e; or you can invoke it under the name ex but specify -v ).

You can type ':q' which will tell the editor to quit the session or ':q!' to quit forcefully without saving.
 

Newbie vi troubleshooting

This is because you are in default vi version, that is vi compatible, if you need to use arrow keys in the insert mode, create a file named vimrc in your home directory and insert the line set nocompatible

$ vi ~.vimrc 
#(press i for insert mode)
set nocompatible

#(press Esc for command mode and enter :wq for saving the file in ex mode)

or
you can use the ex mode command by typing :set nocompatible  (the ex command need to be executed in normal mode/command mode) but the only problem is you need to issue this command each time you start vi. If this is in .vimrc then the set commands will automatically be executed while starting vi editor.

Why is the backspace not working? backspace working only with the current line and not working with the previous line.

This is also the default behaviour of original vi version. If you need to work this like a normal text editor, you can just execute the ex command  :set backspace=indent,eol,start  which sets backspacing for inserted indentation, line breaks and start of insert.
 
or
Like mentioned above you can create a .vimrc file in your home directory with the set commands in each lines.
$ vi ~.vimrc 
#(press i for insert mode)
set nocompatible
set backspace=indent,eol,start
At the time of vi development, the keyboard layout was a Lear Siegler ADM-3A terminal. On this terminal, the Escape key was at the location now occupied by the Tab key on the widely used IBM PC keyboard (on the left side of the alphabetic part of the keyboard, one row above the middle row). This made it a convenient choice for switching vi modes. Also, the keys h,j,k,l served double duty as cursor movement keys and were inscribed with arrows, which is why vi uses them in that way. There were no other arrow keys :P




It'll be easier if you go through an online interactive tutorial of vi/vim so that it'll make you hands-on to the editor in an interactive session. Below is such an interactive website which I found helpful.


Come back, once you have completed/learned the basics via those interactive lessons, which will help you understand the remaining commands:

All the below commands are entered in vi normal/command mode (if you are in insert mode the last line of the vi will show INSERT)
The commands to enter new text are: (which will enter you in insert mode go to command mode by 
<escape>)
a Append new text, after the cursor. i Insert new text, before the cursor. o Open a new line below the line the cursor is on, and start entering text. O Open a new line above the line the cursor is on, and start entering text. <escape> Once you've entered input mode using the one of the a, i, O or o commands, use <escape> to quit enter- ing text and return to command mode.
The commands to copy text are: yy Copy the line the cursor is on. p Append the copied line after the line the cursor is on. The commands to delete text are: dd Delete the line the cursor is on. x Delete the character the cursor is on. The commands to write the file are: :w<carriage-return> Write the file back to the file with the name that you originally used as an argument on the vi com- mand line. :w file_name<carriage-return> Write the file back to the file with the name ``file_name''.
The commands to quit editing and exit the editor are: :q<carriage-return> Quit editing and leave vi (if you've modified the file, but not saved your changes, vi will refuse to quit). :q!<carriage-return> Quit, discarding any modifications that you may have made.

[ At this point, if you are interested, you can read the man page of vi from 1996 -->


Above are the basic commands, you can find the vi/vim cheat sheet that explains the basic functions of each characters in vi command in the below link. You can download and save the sheet as lessons from this link.





Each command can be combined with other commands to perform related functions. For example:

                        w     for next word
                       dw    delete next word
                     2dw    delete next 2 words
                      5yy    yank 5 lines

                         
You can always repeat the previous command with vi command ' . '   If you have executed p command(which pasted the lines in the buffer to cursor) and you need to repeat the same command for 5 lines from cursor you can use '5 .' as a vi command

Buffers:

The result of a vi command will always be stored in a buffer. Objects that are deleted or otherwise manipulated have their original values placed in this buffer, You can use a named buffer. Buffers are named with single lowercase letters.

You can record the vi command actions and put it in a named buffer and execute those actions whenever necessary. The command is q for recording, followed by a character for named buffer. The below vi command will record the actions to buffer a (represented by @a)
                                    qa
You perform some actions say move the cursors and delete a character using the x command. Press Esc followed by q to stop recording. Then you can anytime use this buffer to be in action. If you need to perform the recorded action to 3 lines from the cursor position, the below command need to be executed.
                                    3@a
                            
You can mark the current cursor position to a named buffer. The vi command is m. If you need to mark the current cursor to buffer b, the command is
                                    mb
At any point of time in the editor if you need to go back to the marked cursor position you can execute the command
                                       `b
If you need to delete everything from the current cursor position to the marked position, the below command can be used
                                    d`b


ex Command Mode

vi enters Ex command mode if the program is invoked with the -e option or if the Q command is issued from Vi. You can issue a single Ex command from Vi mode by using the : command.

An Ex command takes the general form

[address-list] [[command] [!] [parameters]]

Each part is optional and may be invalid for some commands. You may specify multiple commands on a line by separating them with a vertical line character (|).

address-list 

Commands may take zero, one, or two addresses. The address % is a short form to indicate the entire file. You may omit any or all of the addresses

               
The basic and most useful ex command is the replace commands like below:

:%s/old/new/g Replace all occurences of old by new in file
:%s/old/new/gw Replace all occurences with confirmation
:2,35s/old/new/g Replace all occurences between lines 2 and 35

Do you need to delete lines from 13 to 56, just execute in ex mode :13,56d


Note:
You need to escape special characters using backslash in ex mode. Like, if you need to replace the word /home to /root (/ is a special character, likewise for %, <,>,*, $, etc.,)
                            :%s/\/home/\root/g

Search command:

You can use / (slash) to search for a character(s) in your file. if you need to search for foo just type below command in vi command mode.
                             /foo
by default it will show you with case, if you need to search without case you can set it in ex mode as :set ignorecase

For basic searching:

        /pattern       - search forward for pattern
        ?pattern       - search backward
        n              - repeat forward search
        N              - repeat backward

Some variables you might want to set:

        :set ignorecase - case insensitive
        :set smartcase  - use case if any caps used 
        :set incsearch  - show match as search proceeds
        :set hlsearch   - search highlighting


You can open multiple files in vi using filenames as arguments
                    localhost:~$ vi file1 file2
this will open two files in vi in the same window and you can switch between these files using ex command :n for next and :N for previous file
You can also use the split window ex command to split the screen vertically or horizontally by invoking
                            :vsplit filename  
                            :split filename


In some cases you need to see what files are in the current directory or to move the pwd  to some other directory, you can use the ex command
                             :sh  
which will put you in the current shell and you can execute commands and to return to vi you can execute the exit command in shell.


Indenting lines

If you are a programmer you might always want to indent those lines in the block, vi has this set of ex commands that you can use
             :set tabstop=8 - tabs are at proper location
             :set expandtab - don't use actual tab character (ctrl-v)
             :set shiftwidth=4 - indenting is 4 spaces
             :set autoindent - turns it on
             :set smartindent - does the right thing (mostly) in programs
             :set cindent - stricter rules for C programs

To indent current line(s):
In command(normal) mode, type >> to indent the current line, or << to unindent.
(combining commands example) 5>>.. shifts five lines to the right, and then repeats the operation twice so that the five lines are shifted three times.


------------------------------------------------------------------------------------------------------------------------------------


You can go through the below links which will help you master the vi editor commands, most of the commands will be common in these links but of-course there are commands that are unique to the specific author.

Basic level:

Basic - Intermediate

Advanced:


Please let me know if any of the above external links are not working. I would love to hear what your favourite secret little vi commands are.

GNU, Unix, Linux, *nix, FOSS, F(L)OSS,..

Woah, that's a long list keywords..and yes, these are some of the basic terms that comes in the minds of programmers or sysadmins(i gues...