2. Aims
• Convert people who still use nano, to using vim
• Eliminate "vimophobia" <-- its a thing.
• Improve performance, by showing you some
really powerful ideas and time-saving concepts.
• Improve knowledge within the team
• Give an entertaining and insightful training, even
old hands may learn a thing or two!
3. How to get the best out of
this presentation.
• Bring a laptop / device that you can run vim on, to play along with the exercises.
• If you're doing this deskside, it works best on a dual monitor set up.
• Have a PuTTY window open to a linux server or linux bastion on one screen (or a
local bash prompt if youre running linux as a Desktop)
• Have the Presentation on the other screen.
• The presentation does not automatically play through each slide, you must click to
continue, this will allow you to try out exercises and not feel like youre getting
behind.
• Pick Up and drop at your leisure (but you will get more out of it the longer you stay
with it).
• Try not to skip any exercises, ask for help, understand one exercise before moving
onto the second exercise (in some cases an exercise will rely on you having
completed the one before it).
4. –Richard A Forth
“Linux is like Brazilian Jiu Jitsu. Everyone wants to do
it, not everyone CAN do it, there will always be
someone better than you at it, and there are infinite
ways to get to the end goal.
!
There are also more efficient ways of working that
make your journey easier, and progression faster.
!
To progress you must be open to new ideas, and
concepts, in order to adapt and grow your
experience and knowledge, thus improving your
overall "game".
!
Using vim, and having basic vi skills, is, therefore, in
my professional opinion, one of the "game changers",
and cornerstone skills of a Linux Administrator”.
5. –Richard A. Forth
“If Linux really is 'the dark side', then vim is our equivalent of 'the force'.”
6. –Jared Wright
“NPS 10 - The experience was great, thank you
for doing it with me remotely”
Previous Feedback
10. seriously, though
• its a text mode editor
• its available on most linux distributions by default
(as 'vi')
• easy to install "vim";
• yum install vim (or vim-enhanced if available)
• apt-get install vim
11. • There is a GUI version of vim available, called
gVim
• gVim has been ported to Windows
13. vim was originally written on
the Lear-Siegler ADM-3A
!
!
!
It's keyboard was a little
quirky, lets look a bit closer...
image from google images
14. H, J, K, L
"Bill Joy orgnally developed vi to run on Lear-Siegler ADM-3a,
!
the H,J,K,L keys had little arrows on them, so he decided to
!
use those for the navigation keys in vi!"
!
!
! - abstracted from "Learning the Korn Shell" (o'reilly books)
image from google images
15. vim facts!
• Vim is a text editor
• Written by Bram Moolenaar
• First released publicly in 1991
• Based on the vi editor common to Unix-like
systems
16. vim facts!
• Has a graphical interface too (gVim)
• Also available on Windows (gVim for Windows)
• Vim was originally released for the Amiga
• Is now cross platform.
• In 2006 It was voted as "the most popular editor"
amongst Linux Journal readers.
17. vim facts!
• Is free and open source
• Released under a licence that is compatible with
the GNU General Public Licence
• The Licence has some charityware clauses asking
anyone who finds vim useful to consider donating
money to children in Uganda.
• Based on an earlier editor "Stevie" written for the
Atari ST.
18. vim facts!
• Vim is an acronym that stands for Vi - Improved
• Vim is an extended version of the original (vi)
with many additional features designed to be
helpful in editing program source code (syntax
highlighting and line numbering for example)
• Originally VIM stood for Vi - Imitation however
that was changed with the release of 2.0 in
December of 1993.
19. vim facts!
• There is also a new package available called "vim-
enhanced" which I also highly recommend.
• On some systems vi does exist but in most cases vi is an
alias to vim:
!
$ which vi
!
alias vi='vim'
!
/usr/bin/vim
!
22. • input mode is pretty much what it says on the tin,
its the mode in which you input your data.
• We do not spend much time discussing input
mode, as, if youve ever used a editor before,
you'll know what to do!
• input mode is NOT the default mode! (unlike
nano)
• The example that follows is a very common
rookie mistake....
23. So what happened here?
I opened up vim and typed "Hello world"....
24. To understand what happened, we must
first understand the different ways to get
into insert mode (clue in red).
• a = append (next char)
• A = append (at end of current line)
• i = insert (at current cursor)
• I = insert (at start of current line)
• o = open a new line (below current line)!
• O = open a new line (above current line)
• s = substitute (single character)
• S = substitute (replace a whole line)
25. • There are many other ways of getting into insert
mode which we will discuss and explore through
exercises as we go through the training but the
main ones are shown on the previous slide.
• So, lets cover exactly what happened in the
previous example.
27. # vim
• opening vim can be as simple
as typing 'vim' as a command
prompt.
• If you do it that way you will be
greeted by the following
screen: ----------------------->
• Most of the time vim is invoked
with a filename as an
argument.
28. This is the basic editor.
The first screen shows some useful help messages
Start typing some text and see what happens?!
Based on the knowledge so far gained,
can you explain why that happened?
29. So what ACTUALLY happened here?
Lets explore my "Hello world" example again....
30. • When you begin to type, say "Hello World" without entering insert mode
first, vim will try to execute all the commands you give it, this is
because you start off in command mode.
• The default mode is called 'command mode', thats quite a big mode to
cover (in fact 90% of material in this slideshow is command mode
based)
• Now we know that. We understand that vim was trying to execute the
following commands first:
• H = move to top of the file.
• e = move to end of word
• l = move to next letter
• l = move to next letter ...
31. • o = open a new line, underneath the current line
in insert mode.
• The rest, which is a space, and then "world!" is
all input normally. This is because it is only at the
pressing of 'o' in Hello, that you entered insert
mode.
32. Why not start in insert mode?
Truthfully, the power of vim comes in its "command"
mode, often incorrectly called "ex" mode (we will
cover ex mode later).
More often than not you'll want to manipulate
existing data (configuration files etc) more than
actually creating files from scratch (though you can
certainly do that!)
Also remember that Lear-Sigler ADM-3A I showed
you earlier?
34. It didnt have any cursor keys so you had to use H, J, K,
and L to get to where you wanted to insert data, press i (or
some other key) to get into insert mode, then start typing
data.
image from google images
image from google images
36. Exercise 1
• You can use either a linux bastion or a linux
desktop, or a cloud server for this and all future
exercises.
• Be sure to install "vim" if it is not already installed
• create a folder in your home area called
"vim_brownbag" to contain your working files
• in that folder create a file, using vim and the
following walkthrough...
37. # vim lazy_dog {enter}
Press i to get into insert mode
Notice the status bar
38. Notice when you pressed 'i', the status bar changed.
This lets you know youre in insert mode.
Notice the status bar
39. Type the following exactly as -is, then...
press {ESC} then :wq
If your screen looks similar to mine, you're in ex mode
press enter to EXecute the save and exit command.
Commonly referrred to as "write-quit"
Notice the status bar
Not the yellow numbers, they are line numbers, we'll explore how to add those in the later section called "customizing vim"
40. !
!
# cat lazy_dog
The quick brown fox
jumped over the lazy dog.
If you got that right, well done you created your first file in vim! if not,
repeat the exercise again, or ask your instructor for assistance.
Now cat the file you just created:
43. press {ESC} :%s/dog/cat/g {enter}
Notice the status bar
I'll explain what the command ':%s/cat/dog/g' does in more detail later
44. Does your screen look like mine?
If so, you just made a substitution command (find and replace)
(we explore these commands in more depth later)
Except the yellow numbers, they are line numbers, we'll explore how to add those in the later section called "customizing vim"
"dog"is now
"cat"
45. escape - colon - write - quit
{ESC}:wq
To save the file and exit....
(There are other ways to save and exit too, such as {ESC}ZZ)
46. We will cover these commands in more
detail later on but for now I just want to get
you using vim and getting comfortable
with the navigation, saving and exiting.
52. Command Mode Basics
• You can always tell what mode youre in by
looking at the bottom left corner
• In command mode, some of the normal letter
keys have a special meaning.
• These "commands" tell vim what to do, for
example 'yy' will copy the current line, and 'p'
will paste it below the current line.
53. Modes
-- insert -- = Insert Mode
= Command Mode
: = Ex Mode (EXecute commands)
-- replace -- = replace mode
recording = macro recording mode
-- VISUAL BLOCK -- Visual Block selection mode
bottom left corner statuses
The 3 most common modes you'll be in are
either Insert Mode Command Mode, or Ex Mode (Ex Mode is part of command mode but
For easier digestion I talk about it as the third mode)
!
Most people, including me, end up in Visual Block or recording modes by accident!
54. H, J, K, L are left down up right respectively.
(you can still use the cursor keys in most modern vims!)
Command Mode is where you can navigate using these keys:
image from google images
56. Open the file "lazy_dog" that we created earlier:
# vim lazy_dog
This will put you in command mode already, but you will find as
you use vim that you press {ESC} as a force of habit.
This ensures you are in command mode anyway before you run
any "commands".
Use H, J, K, and L to navigate left, right, up and down, spend a
few minutes playing with they keys.
I recommend placing your 4 fingers of your right hand on these
keys and looking at the screen, not the keyboard, and practice
navigating with each key.
57. • Put your cursor over the f of "fox"...
• press "c" and "w" (short for "change word")
• type "mouse"
• press {ESC} to return to command mode.
58.
59. escape - colon - write - quit
{ESC}:wq
To save the file and exit....
(There are other ways to save and exit too, such as {ESC}ZZ)
61. vim-adventures.com
• Uses the vim navigation keys
to navigate in the game
• Slowly introduces you to more
and more complex commands
as the game progresses.
• Highly recommended!
63. AFOTn
To conserve slide deck text space, when I refer forward or back to
particular techniques, I use the acronym AFOTn, which stands for
!
"Advanced File Opening Technique #n"
!
and where n is a number, for example "AFOT5" refers to
!
"Advanced File Opening Technique #5"
Acronym Alert!
64. AFOT Summaries
• AFOT1: Open at a specific line number.
• AFOT2: Open and queue up many files.
• AFOT3: Open an existing file inside of vim.
• AFOT4: Toggle current and last file.
• AFOT5: File navigation without quiting vim.
65. Advanced File Opening
Technique #1
!
Lets first create a file that has 100 Lines of text:
!
# for i in {1..100}; do echo "This is line $i" >> fileof100lines; done
!
# vim fileof100lines +87
!
Which line did your cursor land on?
!
Press {ESC} :q to exit, and try again with a different number:
For example:
!
# vim fileof100lines +7
!
# vim fileof100lines +63
66. Advanced File Opening
Technique #1
!
When is this useful?
!
Suppose the following (contrived) output of some bash, python,
perl, or php script:
!
Error on line 87.!
!
# vim fileof100lines +87
!
And boom youre there!
!
(as opposed to :set number and scrolling, or, cat -n fileof100lines)
67. Another use case for the AFOT1
!
# vim <file> +n
!
syntax is when you look at certain output, httpd -S springs to
mind:
!
$ httpd -S
!
Warning: DocumentRoot [/www/docs/dummy-host.example.com] does not exist
!
VirtualHost configuration:
!
wildcard NameVirtualHosts and _default_ servers:
!
*:80 dummy-host.example.com (/etc/httpd/conf/httpd.conf:1003)
!
Syntax OK
!
In this example we see that the vhost: dummy-host.example.com
starts on line 1003 of /etc/httpd/conf/httpd.conf.
!
To get there quickly:
!
# vim /etc/httpd/conf/httpd.conf +1003
68. Advanced File Opening
Technique #2
!
You can open many files with vim, but it opens them one AFTER
the other, not at the same time.
!
But note that this is not quite the same as a "for loop".
!
Create ten files with this quick one-liner:
!
# for i in {1..10}; do echo "This is file$i" > file$i; done
!
69. Advanced File Opening
Technique #2
!
Open 4 of them by specifying them as commandline arguments
to vim:
!
# vim file1 file2 file3 file4
!
Add the following line of text to the first file ( {ESC} then o ):
!
An extra line of text
!
What happens if you try to save and exit?
70. Vim is telling you that you have more files to edit.
Press ENTER
Or try :wn
72. Now repeat that, add the extra line, save, and move to the next file.
Repeat this for file3 and file4 and then cat all four files with the regex
command cat file[1234]
74. If you did that correctly, you should
have output similar to the above.
If not, repeat the exercise again,
or ask your instructor for help.
75. Repeating tasks!
You've probably noticed that the previous exercise was a
repeating task and you'll rightfully be wanting to know if we
can automate such tasks, the answer is yes, but now is not
the time to discuss such matters, as this section related to
different ways of opening vim, and automating tasks is quite
an advanced topic, my intention is to gradualy increase the
intensity so as not to put you off in the early stages.
!
I cover repeating tasks in more detail in the section
"Automating Repetitive Tasks"
!
For now lets crack on with different ways of opening files.
76. Advanced File Opening
Technique #3
!
You can even open files from within vim.
!
Though its not exactly File > Open, its really quite intuitive and
easy once you get used to it.
!
Lets go ahead and open vim with no arguments again.
!
# vim
!
77. As previously discussed, initially, youre already in
command mode, so press colon ([shift] + ;) to enter EX mode
Througout the rest of the slideshow, I refer to the :
command as 'colon', for example colon wq = :wq
78. This is EX mode, its part of command mode
but you could think of it as the third mode.
!
here, to edit file5, type:
!
:e file5 (note that the : acts a prompt now, so no need to type it twice)
The colon you type becomes the EX mode prompt.
82. If necessary, use the J, K, keys to move up and down
so that the cursor is on line 2.
!
Press 'yy'
!
Nothing will appear to have happened, but you've
copied that line where the cursor sits.
!
Now press colon to go back to ex mode, and type !
!
'e file5'
!
Press 'p' to paste the copied line from file4 below the
one in file5
!
colon w to write (save the file to disk)!
84. Advanced File Opening
Technique #4
!
Once you've got two files open in vim, there are shortcuts available to flip
between these two files in the file buffer:
!
# means alternate file
!
% means current file
!
Note: though you can open many more than two files in serial fashion,
vim only "remembers" or rather "buffers" 2 of these files, the current file
and the last file opened (the "alternate" file), all other files are either
queued for editing or lost once youve moved on (exept for #).
!
We will explore n, e, # , and % in depth in AFOT5.
86. Because we previously opened file4, and we currently have
file5 open still, the # and % variables look like this:
!
% = current file = file5
!
# = alternate file = file4
!
87. Note that % is only a pointer to the current file buffer and
therefore has no meaning for us in terms of editting, for
example you would not type:
!
:e %
!
Because we are already editting the current file!
(it does hold meaning in find and replace strings which
we explore later on)
88. So to quickly switch to file4 (the buffered alternate file),
type:
:e #
This is directly equivalent of typing
:e file4
Type:
:e #
again, which file are you in? (HINT: should be file5).
89. So typing
:e #
is a quick way of flipping between two files easily.
But what if we edit a third file?
:e file6
Now type
:e #
And repeat a few times, now file5 and file6 are the current and alternate files in
the buffer, and so file4 is no longer remembered.
To get back to file4, you'd need to type
:e file4
90. Advanced File Opening
Technique #5
!
We will explore n, e, # , and % in depth here in AFOT5.
!
First we need to repeat the first step of AFOT2 and open 4 files and
queue them up for editting:
!
# vim file1 file2 file3 file4
!
for those that enjoy regex:
!
# vim file[1234]
!
is directly equivalent!
91. • we will first explore :n
• :n is an EX command to move to the next file
• note that you cannot move to the next file if you have
made unsaved changes in the current file (in which
case use :wn instead)
• For now do not make any changes and just press
{ESC} colon n
in each file until you get to file4, then try to do it again
one last time...
92. Here vim is telling you there are no more files to edit,
therefore :n has no meaning, so press colon q to quit.
93. Again we need to repeat the first step of AFOT2/5 and open 4 files and
queue them up for editting:
!
# vim file1 file2 file3 file4
!
or
!
# vim file[1234]
!
This time press {SHIFT} + g to go to the last line of the first file.
!
Press o to open and input a new line:
!
The dubious third series.
!
Try to move on to the next file without saving, with colon n
94. !
Save and move on to the next file with colon wn!
!
Repeat for the remaining files.!
!
Do not quit after saving file4
95. e <file>
We've already met the 'e' EX command which edits
a specific file.
You also understand that % is a buffer reference to
the current file, and that # is a buffer reference to
the alternate file.
So if we editted file3 last, and we are currently in
file4, what happens if we press 'colon e #' ?
100. Confused?
We went through each of the queued files with
colon n, which means next file
• file1
• file2
• file3
• file4
101. Confused?
• file1 - alternate file when you open file2, forgotten
once you open file3.
• file2 - alternate file when you open file3, forgotten
once you open file4
• file3 - alternate file once you open file4
• file4 - current file
102. Confused?
• We then flipped between file3 and file4 with colon e # a few
times.
• We then opened up file1 and depending how many times
you flipped between file3 and file4 you'd then flip between
either file1 and file3 or file1 and file4, the other would be
forgotten, then we opened up file2 and either flipped
between file1 and file2 or either of file3 or file4, and file2,
the other is discarded.
• Its not important which files you ended up flipping
between. You can always tell which file youre in by looking
in the bottom left corner as soon as you open the file...
104. E165: Cannot go beyond last file
Its important to note that 'colon n' shifts to the next file
in the queue however, what is important to note about the error
above, is
!
'colon e file1' does not put you back at the start of the queue.
!
Lets explore that again
106. Again we need to repeat the first step of AFOT2/5 and open 4 files and queue them
up for editting:
!
# vim file1 file2 file3 file4
!
or
!
# vim file[1234]
!
Move on to the next file (file2) without saving with colon n
!
Now move on to file3, again with colon n.
!
Now move back to file2 with colon e file2
!
Now press colon n again
!
Which file are you in? Did you expect to be in file3 or file4?
108. Other notes about opening
files with vim
• If a file you open does not exist, it will open it for
you as a named blank temprary file, but it will not
actually be saved to disk until you press esc-
colon-wq.
• This also goes for typo's.
• For example vim file 5 actually opens two
fresh files, one called file and one called 5,
not file5, as you may have wished!
110. Save As
• Saving a new file for the first time
• Saving an existing file as a different filename
111. # vim
!
press 'i' to get into insert mode
!
Type Something Amazing
!
Press '{ESC} colon wq mynewfile':
!
Press ENTER to execute
112. # vim file10
!
press '{SHIFT} + g' to go to the bottom of the file
press o to open a newline and get into insert mode
!
Type Something Amazing
!
Press '{ESC} colon wq file11':
!
Press ENTER to execute
114. esc-colon-write-quit
• esc-colon gets you into EX mode from insert
mode
• the most used EX command is wq (write-quit)
• THIS IS THE MOST COMMON KEY
COMBINATION YOU WILL USE, IT BASICALLY
AMOUNTS TO "SAVE AND EXIT".
You can also use ZZ (SHIFT + z twice ) in command!
mode to do this without switching to EX mode
116. find and replace
• if you have used sed , or written any Perl before, you may
be familiar with this syntax (we also did this briefly in
Exercise 2)
• due to its acceptance of regular expression, and the need
to escapce certain special characters, it's can get very
complicated, very quickly
• this course only covers common find and replace
scenarios within vim that we might come across
• For a deeper dive have a look at "Sed and Awk" 2nd
Edition by Dougherty and Robbins
118. • find and replace is done in EX mode, not
command mode
• find and replace is not to be confused with find
only, which can be done in command mode with
the forwardslash / (covered later)
• we will look at some of the basic operators in a
find and replace operation and what they mean
• remember we did a find and replace in Exercise
2.
119. Review of Exercise 2
• we created a file called lazy dog
• we searched for the word 'dog' and replaced it
with the word 'cat'
• {ESC}:%s/dog/cat/g
• Lets explore exactly what that command is doing
120. Review of Exercise 2
• esc-colon takes us into EX mode
% in this case means all lines in the current file (remember AFOT4)
(absence of the % would mean "on the current line only")
• s tells vim we are searching
• /dog the first search term is what we are looking for
• /cat/ the second search term is what we want to replace it with,
followed by a closing /
• g means globally - all instances on the current line, not just the first
one.
• Putting that together we get esc-colon-%s/dog/cat/g
122. other ways to replace text
• r or cl = replace a single character
• cw = change word
• C (SHIFT + c) Change the current line
• ~ (tilde) Capitalise current character
124. with the skills you've
already learned:
• Create a new file
• Create the following content:
!
dog dog dog dog dog
cat cat cat cat
mouse mouse mouse
mouse cat
cat dog
dog mouse
mouse dog
!
• Save the file as a new file called "far"
(short for "find and replace"!)
125. • using the H, J, K, L keys, move the cursor to
line1 (see red footnote)
• try esc-colon s/dog/cat/
• what happened?
• press 'u' to undo
You can still use the cursor keys, but for the sake of
training, please try to get used to H, J, K, L
126. • try esc-colon %s/dog/cat/
• what happened?
• press 'u' to undo
127. • try esc-colon %s/dog/cat/g
• what happened?
• press 'u' to undo
128. • with the cursor still on line1 try the following:
• esc-colon 3s/mouse/rat/
• what happened?
• press 'u' to undo
129. • with the cursor still on line1 try the following:
• esc-colon 3s/mouse/rat/#3
• what happened?
• press 'u' to undo
• This is a bug in vim: It incorrectly makes substitutions on 3 lines
including line 3 (its supposed to change the 3rd word on line 3
if it is mouse, to rat)
• from :h todo
!
!
!
8 Add an argument after ":s/pat/str/" for a range of matches. For example,
!
":s/pat/str/#3-4" to replace only the third and fourth "pat" in a line.
!
130. • with the cursor still on line1 try the following:
• esc-colon 5,7s/dog/cat/
• what happened?
131. • OK last one for this exercise....
• with the cursor still on line1 try the following:
• esc-colon g/dog/s/mouse/cat/
• what happened?
134. searching for text
• searching for text can be done from command mode by
pressing the backslash / followed by your desired word
or phrase:
/mouse
willl highlight all instances of mouse, and put your cursor
on the first letter of the closest word to your cursor location.
• Press n to skip forward to the next iteration.
• Press {SHIFT} + n to skip backwards.
135. :nohl
• to get rid of the highlights caused by either
searching for terms or pressing the hash key
accidentally (which searches for all instances of
the current word) use colon nohl to turn off
highlights
137. with the skills you've
already learned:
• Create a new file
• Create the following content:
!
<VirtualHost *:80>
! ServerName mydomain.com
! ServerAlias www.mydomain.com
! DocumentRoot /var/www/vhosts/mydomain.com/httpdocs
!
!
! <Directory /var/www/vhosts/mydomain.com/httpdocs>
! AllowOverride All
! Order Allow, Deny
! Allow from All
! </Directory>
!
!
! ErrorLog logs/mydomain.com-error_log
! CustomLog logs/mydomain.com-access_log common
!
</VirtualHost>
!
!
!
• Save the file as a new file called "mydomain.com.conf"
138. • copy the file to "yourname.com.conf"
# cp mydomain.com.conf richardforth.com.conf
• Now open the file in vim and subsitute all instances on all lines of
mydomain with yourname eg:
colon-%s/mydomain/richardforth/g
colon-write-quit to save and exit the file.
143. • open the file called yourname.com.conf in vim
• this file is 14 lines long
• use the H,J,K,L keys to move the cursor to line1
(or press {SHIFT} + h)
• press {ESC} to enter command mode
• press '14yy' to 'yank' 14 lines
• Take a note of what is displayed in the bottom left
corner of the console window.
144. • Now move the cursor to the last line of the file,
either with the J key (down), or {SHIFT} + g.
• press 'p' to paste those 14 yanked lines
• you should have two virtualhosts now.
• make the second virtualhost run on port 443
• make up the paths to the certificate files, and it
doesnt matter here if you cant remember exactly
the syntax to use, this is vim training, not apache
training :) its just a proof of concept.
147. • Create a new file and call it httpd.conf
• add the following data
!
<IfModule prefork>
...
ServerLimit 256
MaxClients 256
</IfModule>
!
• Using H, J, K, Lkeys. put the cursor anywhere on the
line:
!
MaxClients 256
148. • Press 'yyp' to yank this line and paste the copy
immediately below the current line
• Comment out the current line
• On the next line, change maxclients to 120
• To do this in "the vim way", use H, J, K, L to move the
cursor over the 2 of 256, and press 'cw' which means
change word, then type 256
• repeat this for ServerLimit
• save and exit the file
149.
150. yanking words, and letters
• So far youve learned how to copy a line of text with the
command 'yy'
• You also learned that if you specify a number first, for
example 14yy, you can copy 14 lines of text, very
handy for quickly duplicating blocks or text, working
examples could include virtual host stanzas in apache
configurations, or slave stanzas in lsyncd
configurations
• But did you know you can also copy words and letters
too?
151. • to copy a word, use the command 'yw'
• to copy more than one word, use the command
y2w
• to copy a character (or letter) use the command
yl
• to copy 7 characters (or letters) use the
command y7l (thats an l for lima)
154. deleting lines, words, and
letters
• So far youve learned how to copy a line of text with the
command 'yy'
• You also learned that if you specify a number first, for
example 14yy, you can copy 14 lines of text, very handy
for quickly duplicating blocks or text, working examples
could include virtual host stanzas in apache
configurations, or slave stanzas in lsyncd configurations
• you also learned that you can use yw and yl to copy
words and letters and that you can use y4w and y4l to
copy multiple words and multple lines respectively
155. deleting lines, words, and
letters
• Each yank command has an equivalent cut command (or delete as
it is known)
• d is the command for deletion, it can be used to cut and paste text
because deleted text is moved into the paste buffer
• based on what you know, what do you think 'dd', 'dw', 'dl', '14dd',
'd7w', and 'd7l' does?
• 4dw, and 4dl are exactly equivalent to d4w, and d4l respectively.
• 'd5d' is the same as '5dd'
• Pressing d will paste the most recently yanked or deleted text from
the paste buffer.
156. pasting lines, words and
letters
• as with y (yank) and d (delete / cut) you can also
paste multiple times with the p command
• for example 10p will repeat paste whatever is in
the default paste buffer10 times
• open vim with no arguments
• go into insert mode, and type the words
This is a line of text
157. • now press ESC to enter command mode
• press yy to copy (yank) the line
• press 10p to paste 10 more lines.
• press u to undo
158. • now press ESC to enter command mode
• use H, J, K, L to move the cursor over the L of
word "line"
• press y3w to copy (yank) 3 words
• press $ (SHIFT + 3) to get to the end of the line
• press 10p to paste "line of text" 10 times.
• press u to undo
159. • now press ESC to enter command mode
• use H, J, K, L to move the cursor over the space
before the word "text"
• press y5l to copy (yank) 5 letters
• press $ (SHIFT + 3) to get to the end of the line
• press 10p to paste 10 more copies of the word "text"
• press u to undo
• press ESC q! to quit without saving any changes
160. Named Buffers
• so far with yank or delete, we have been saving to the
default paste buffer, but while working with complex
documents you can have several paste buffers and
name them for quick retreival later.
• again those familiar with sed programming may
recognise this feature
• Named buffers are quite an advanced topic but I
wanted to run you through a simple exercice to
demonstrate the difference between the default paste
buffer, and named buffers.
161. Named Buffers
• without even using named buffers, it is possible to recover
up to 9 yanks or deletes with the paste command
• for example:
p pastes the last yank
"2p pastes the second to last buffer
"3p pastes the third to last buffer
• and so on..
162. Named Buffers
• in addition to these 9 previous paste buffers, you
can have up to 26 "named" buffers, each one
representing a letter of the alphabet.
• to yank or delete into a paste buffer
• start the yank with a double speechmark, eg:
• "ayy
• "byy
163. Named Buffers
• to paste from a named buffer
• start the paste with a double speechmark and
the letter that represents that buffer, eg:
• "ap
• "bp
165. Create a file called test that contains the following text:
166. • use H, J, K, L to move the cursor to anywhere on
line 1
• press yy to copy this line into the default paste
buffer
• press p to test, then u to undo
167. • use H, J, K, L to move the cursor to anywhere on line 2
• press "ayy to copy this line into paste buffer a
• press "ap to test, then u to undo
• What is in the default paste buffer?
• What is in paste buffer a?
• Use the skills you've just learned to yank line3 into paste buffer b
• What is in the default paste buffer?
• What is in paste buffer a?
• What is in paste buffer b?
168. • use H, J, K, L to move the cursor to anywhere on
line 1
• press yy to copy this line into the default paste
buffer
• What is in the default paste buffer now?
• What is in paste buffer a?
• What is in paste buffer b?
169. Final notes on named
buffers
• Only complete lines or blocks of lines can be
saved into named paste buffers
• Partial lines (words or characters) cannot be
saved as named buffers, and will only exist in the
unnamed buffer, and must be pasted immediately
after the yank or delete, otherwise the next yank or
delete replaces that buffer.
• You can access up to nine previous unnamed
yanks.
171. Customizing Vim
The following EX mode commands might be useful
in setting up vim how you like it, here are the most
common ones that I use, there are many more!
!
172. :set bg=dark
By default vim assumes a light background and
dark text, if you use PuTTY on Windows, or you
have your Linux terminal coloursheme as dark with
light text, some syntax highlighting can strain your
eyes or become indestinguishable fore example
dark navy blue text on blackbackground is hard to
read:-
173. :set number
• As youve seen in most oof teh screenshots, :se
number sets the yellow line numbers in the laft
margin. Invaluable for all programmers out there!
174. :set cursorline
• Adds a line underneath the line on which the
cursor currently sits, great for troubleshooting
code which line wraps or as a visual aid for
finding where you are at in a file.
• Especially useful when editting column data, for
example a tab delimited file
175. :set directory +=$HOME
• Sets the directory to use for the default save
location of temprary files
!
• Better locations might be ~/tmp, or /tmp
177. :set tw=80
• tells vim that text width is 80 chars
• only seems to work at startup
178. :set ff=dos
• this option only really applies to gVim for
Windows.
• Sets the file format to DOS instead of UNIX
179. :colorscheme elflord
• this option also only really applies to
gVim for Windows.
• Sets the colorscheme to one of a handful
of built in colourschemes availiable
!
!
181. unsetting options
• Most of the previous options can be unset simpy by
prepending the word 'no' to the option, for example:
• set nonumber
• set nocursorline
• set nowrap
• Other options require new values, for example
• set bg=light
• set tw=0
186. _vimrc
• the equivalent of .vimrc on a windows computer is
_vimrc, which is NOT placed in the users home area
but in the vim program files folder, for example:
• C:Program Files (x86)Vim_vimrc
!
!
187. gVim for windows has a lot of intimidating stuff in its default
_vimrc, but, if you can see, my customizations start at line 30.
example _vimrc from my windows desktop pc
189. open up or create a new file
called .vimrc in your home folder
• Or edit the _vimrc file if you are usinf gVim for
windows.
• Add some options from the previous slides to
your taste
• save the file
• relaunch vim to see what effect this has on the
editor
191. Macros and Functions
• Automate common and repetitive tasks
• Saves on typing and RSI
• Speed up text manipulation
• Can be saved as startup macros (we saw one earlier):
• Can also be set up on the fly (short ones only
reccommended)
192. What is a macro?
• A macro is a recording of a series fo keystrokes
that mimic both command and input modes of
vim.
• an example macro might be 'cwhappy' which the
first two letters initiate a command called change
word and then input happy.
• Although you can repeat last command with the
period key (.), some complex operations are best
stored as macro functions.
194. to record a macro
interactively
• from command mode press 'qa' to start
recording a macro into buffer a
• to stop recording, press '{ESC}q'
• to play back the macro from buffer a, from
command mode press '@a'
Note that you can record a macro into any one of the 26
named buffers a through z.
195. Exercise 10
Create a signature macro using your vimrc file, assign it
to the letter "s".
196. • open your .vimrc file (in vim).
• open a new line at the bottom of the file (Go)
• type the following
• let @s="GoKind Regards,^M^MRichard Forth^MManaged Support - Linux^MRackspace - the #1 managed cloud companyet @s="GoKind Regards,^M^MRichard
Forth^MManaged Support - Linux^MRackspace - the #1 managed cloud company^[":wq
• Note : wherever you see ^M, the key combination is
• CTRL + v, CTRL+m (linux)
• CTRL+q, CTRL+m (Windows)
• NOT just CTRL +m
• ^[ therefore also means CTRL +v or q, CTRL+[
• If you did it right you shoudl see the control characters syntax highlighted, like so:
197. Open up a new file like so:
Press ESC to get back to command mode, then press '@s' to
run the macro saved to the named buffer 's':
!
198. Signature Use Case
• I use a firefox plugin called "Its All Text!" which allows me
to open up any text box in the browser with a windows key
combination (I use CTRL +ALT +e) to edit in an external
editor - for which I use gVim for Windows.
• This works exceptionally well with CORE and ENCORE
tickets.
• The macro '@s' allows me to painlessly add my signature
without my fingers leaving the keyboard (no mouse clicks
to insert a prefab signature.)
• Not everyone writes their ticket updates in VIM though!!
199. Exercise 11
Create a html template macro using your vimrc file,
assign it to the letter "h".
200. Save the ".vimrc" file. Open a new file
!
# vim index.html
!
@h
An example might look like this:
201. Use cases
• obviously html is a bit outdated nowadays but
you could apply this knowledge to create
whatever template or wireframe you like, other
examples might include vHosts (apache or
nginx), php code, perl, python, yaml syntax
(ansible) etc.
• Basically any time you find yourself repeating
keystrokes, set up a macro to save you time!
203. one time functions; what are they
and why would you use them
• In Exercise 12 we will set up a reconstruction of a real
life problem I had to solve, which I did in vim using a
one-time function
• It turns out that I could have done it more efficiently
with a sed script or a perl script but I didnt know either
language well enough to program that way at the time.
• Never the less it beautifully demonstrates the power
that vim automation offers
• So what are one time functions?
204. • One-time functions are basically macros that exist only in the current
vim session
• One time fuctions can be repeated as many times in the current
session, including opening other files, they exist as long as vim stays
open.
• They are destroyed when vim is closed down.
• They are likely to be very specific to the current task and not
repeatable thereafter therefore they have no benefit of beng saved in a
startup file
• Examples might include:
• Adding a specific header or footer to a document, making specific
edits at a cursor location, inserting blocks of code, deleting X lines of
code, deleting X words or characters. etc.
206. about the scenario
• A customer had about 50 nginx vhosts, each in a
separate file
• The requirement was to add a line exactly three
lines from the bottom of each file:
Include conf.d/*.conf
• This may not have been the actual line, but we will
go with this anyway, this isnt an NGINX course!
207. • The key strokes therefore went something like this:
• Go to the bottom of the file (G)
• press UP three times (kkk)
• press o to open a new line in insert mode
• type "Include conf.d/*.conf"
• save and move on to the next file
• repeat
209. • SHIFT + g => Go to bottom of file
• kkk => UP x3
• o => open new line in insert mode
• Include con.d/*.conf => input text
• CTRL +v, CTRL+[ => literal escape character
• :wn => ex mode "save (write)" and "next"
!
GkkkoInclude conf.d/*.conf^[:wn
210. • To create a one-time function, type the string out into vim, and
then save the line into a named buffer.
• In my case I saved it to buffer i (for insert)
• If you can try and use a named buffer that makes sense,
named buffers are A through Z.
• for example I use @s for "signature", it just feels right to use @s
rather than @j. There is n write or wrong here.
• Anyway, I saved this one time function as named buffer "i".
• For a recap on named buffers, go back to Exercise 8
• to do do this now, type "iyy (including the double speechmark)
211. • To execute a named buffer like a macro type
• @a (from command mode)@a
• just as we did with the saved macro @s
212. Exercise 12, lets go!
• Create 4 files with the following content:
!
server {
!
Include modules/*.conf
!
}
!
call them server1, server2, server3, and server4
213. • once created, vim all these files, use a regular
expression to shorten your typing:
vim server[1234]
!
Note that if the files do not exist, you will create a file
literally called "server[1234]" which is not what you want
214. • in the first file only (server1) press SHIFT+g to go to the bottom of
the file, press o to open a new lin, then type the following:
GkkkoInclude conf.d/*.conf^[:wn
• remember the ^[ is actually CTRL+v CTRL+[
• Cut this line in to named buffer i
"idd
• Play the macro four times in a row.
@i
You may get an error about not being able to go beyond the last file,
thats OK. ESC:q to exit
215. to see what happened
• that last macro was so efficient, it may have looked like you hadnt anctually made
any changes
• You can either cat each file or vim them again and use :n to move to the next file in
the sequence:
• vim server[12345]
• to slow down the macro and not save and move to the next file each time, drop the
":wn" from the end of the macro (which moves to the next file in the sequence):
• from
GkkkoInclude conf.d/*.conf^[:wn
• to
GkkkoInclude conf.d/*.conf^[
217. backup options
• are set at startup (ie in .vimrc)
• set backup - tells vim to perform a backup of the file
(think "gedit" if ever you seen all those tilde files
kicking around)
• set backupext - sets the default backup extention
(default is tilde (~) character) for example you could
change this to '.bak' if you wanted
• set backupdir - saves all the backups in one place
(default is current directory)
218. This is an example of how one might backup files
automatically, try this for yourselves.
220. Edit your ~/.vimrc file as above, use your own desired path
for the backupdir option.
!
Edit an existing file, save it, then list the backup directory to
see if your backup was created.
222. Navigation
• H, J, K, L are left, down, up, right respectively
• SHIFT + h = top of file
• SHIFT + g = bottom of file
• 123G = go to line 123
• vim file +87 = open file "file" at line 87
• :n = next file
• :e file10 = edit file10
• :q = quit
• :w = save
• :w newfilename = save as newfilename
223. Find and Replace
• :%s/this/that/g
• replaces all instances (g) of "this" with "that" on
all lines of the file (%)
224. Insert Mode
• i, I, o, O,a, A, are the most common ways of
getting into insert mode
• other ways exist such as r (replace single
character), R (overtype) s (substitute), S
(subsitiute line), cw (Change Word)
225. Save and Exit
• ZZ from command mode
• or ex command is :wq
226. Undo / Redo
u = undo
CTRL +r = redo
:rew! = rewind to last save
227. Copy
yy = copy line -- 4yy = copy 4 lines
yl = copy letter -- 4yl = copy 4 letters
yw = copy word -- y4w = copy 4 words
These yanks will yank text into the unnamed buffer, and will be overwritten if a new yank is made.!
!
There are also 26 named buffers that can be used, only for whole lines, to yank to a named buffer, start the yank
with a double quote followed by the letter, and yy, for example:!
!
"ayy
228. Cut / Delete
dd = cut line -- 4dd = cut 4 lines
'x' or 'dl' =cut letter -- 4dl = cut 4 letters
dw = cut word -- y4w = cut 4 words
REMEBER D = DELETE BUT IT ALSO SAVES TO THE PASTE BUFFER SO IT CAN
TECHNICALLY BE USED AS A "CUT"
These deletes will actually cut the text and save it into the unnamed buffer, and will be overwritten if a new yank
or delete is made.!
!
There are also 26 named buffers that can be used, only for whole lines, to delete to a named buffer, start the
delete with a double quote followed by the letter, and dd, for example:!
!
"add
229. Paste
p = paste after
P = paste before
4p = paste 4 times
You can also recall the last 9 unnamed buffers or 26 named buffers, for example!
!
p = paste most recent paste buffer!
"2p = paste second most recent paste buffer!
"9p = print oldest paste buffer!
"ap = paste buffer a!
"zp = paste buffer z
230. We also covered...
• Customising Vim using options, and / or a
startup file
• Setting up Macros for automation, both on the fly
and in a vimrc file
• Backups
231. Useful Links / Tools
• vimtutor - run this command (available on bastions)
• if youve got vim installed, you will most likely have vimtutor too
• http://vim-adventures.com - a game that teaches vim commands as you play
• Vi Cheat Sheet PDF (reference site is now a dead link, but I have copies available)
• http://www.yolinux.com/TUTORIALS/LinuxTutorialAdvanced_vi.html
232. Learning the Vi
and Vim
Editors
O'Reilly Books
!
!
Arnold Robins,
Elbert Hannah,
and
Linda Lamb
!
ISBN: 978-0-596-52983-3