When editing a text file with vi If you want to save your changes and exit right away you can use __ command?

Last modified: Aug 16, 2022

An editor is a program that allows you to easily create and alter text files.

Because we are still working via text-mode connections, our editors will need to run within our SSH terminal windows. That means they will not provide menus, buttons, mouse interactions, and many of the conveniences that we get when connected in graphics mode. Instead we will need to give all of our instructions via the keyboard. Usually that means using special key sequences using the Ctrl or Alt keys to accomplish things like loading and saving files, copying and pasting text, etc.

Novice Linux users will find nano to be a good starting point. Later, many will appreciate the special features offered by vim or emacs. We’ll discuss each of these here. The eventual choice, however, is up to you.

1 nano

nano is a very basic text editor. It’s chief virtue is its ease of use because it pretty much tells you all the “special” commands available at any time.

You’ll find nano on almost all Linux machines. A few non-Linux Unix machines may have pico instead. pico was the original simple editor. nano was developed as an open-source look-alike.

Invoke nano as

nano path-to-existing-file

to edit an existing text file, or

nano path-to-new-file

to create and start editing a new, empty text file.

Example 1: Try This: Edit with nano

Start by copying a file into your directory to work with.

cd ~/playing cp ~cs252/Assignments/textFiles/snark.txt .

Then edit that file:

nano snark.txt
When editing a text file with vi If you want to save your changes and exit right away you can use __ command?

You should see something like the picture shown here.

  • You can see the current cursor position in the upper left.

    • Try using your arrow keys and Page Up/Page Down keys to move around.

  • In the bottom two lines, you should see a list of special commands that you can issue. The convention for these is that

    • The caret (^) indicates a control character. Type this by holding down your Ctrl key and typing the character. Even though control characters are traditionally shown as upper-case characters (e.g., ^G), do not hold the shift key down when typing them.

    • M- indicates a key sequence that can be typed by typing Esc followed by the next character (again, unshifted). You might also be able to type these key sequences by holding down your Alt key while typign the next character.

  1. For now, type ^G and read the help text. Return to your file via the “Exit” command (which will be listed at the bottom of the screen.

  2. Use the “Where is” command to hunt for the word “muffins”.

  3. Use the “Go to Line” command (note that this will require you to use the Shift key to get _ instead of -) to return to the first line of the file.

  4. Insert a line break after the comma so that the text “by Lewis Carroll” appears by itself on the second line.

  5. Move down to the line that starts “Title:”. Use ^K to cut that line. Use it again to cut the line after that as well

  6. Move down to the empty line just after the line starting with “Author:”. Use ^U to uncut (paste) the lines you had cut.

  7. Move back to line 1 of the file.

  8. Use the “Replace” command to replace all occurrences of “snark” by “snipe”.

  9. Use ^O to write the edited file out as a new file snark1.txt.

  10. Use ^X to exit nano.

    Back in the command line, let’s examine the changes you have made. 8. The diff command can be used to compare two text files and list the differences between them. Give the command

    diff snark.txt snark1.txt

    You should see that it lists the single lines that have been changed, showing both the old and new form of the line.

    We can also look for the specific substitutions that you were asked to make. The grep command can be used to search a file for lines containing a target string:

    grep snark snark.txt grep snark snark1.txt grep snipe snark1.txt

    Look closely at the output of each command to see if it makes sense in view of the changes you made in the editor.

    If we add a -i to a grep command, it ignores upper/lower case differences when it searches

    grep -i snark snark.txt grep -i snark snark1.txt grep -i snipe snark1.txt
  11. Let’s try something a variation on the previous work. Start by entering nano again:

    nano snark.txt
  12. Use the “Replace” command to replace all occurrences of “snark” by “snipe”, but this time, before giving your text to replace, use the “Case Sens” command to turn on case sensitivity. Notice the difference in behavior.

  13. Use the “Write Out” command to save your changes as a new file snark2.txt.

  14. Use the “Exit” command to leave nano.

  15. Examine your changes:

    diff snark.txt snark2.txt grep -i snark snark2.txt grep -i snipe snark2.txt

    Do you see the difference that the case sensitive mode made?

2 emacs

nano will suffice for basic editing, but I recommend that programmers also learn either emacs or vim because

  • They work nicely in both text and graphics mode. In graphics mode they offer menus, respond to mouse clicks, and do all the things would would expect in a window-based GUI.

  • They offer a number of aids for programmers, including syntax-based highlighting of different programming languages (using different colors/fonts for reserved words, comments, strings, etc.), commands for compiling programs and collecting the error messages, and for stepping through those error messages, and, with emacs, for debugging the compiled code.

That said, there is an almost religious fervor separating the emacs and vim camps. I think that you can do well with either. Personally, I prefer emacs because

  • I think it’s easier to get started with.
  • It has debugging support for programmers.
    • If you are going to do most of your programming work in IDEs, that may not be a big factor. In fact, I generally use emacs’ debugging support mainly for obscure programming languages where I don’t have a fancier IDE.

So, if you already know a little vi or vim and would prefer to stay in that world, or if you just think the name “emacs” is plain silly, you can skip down to the next section.

Like nano, you launch emacs by giving the command name (emacs) followed by the path to a file that you want to edit.

  • If you give a path to a file that does not exist yet, emacs will start you off with an empty file. The actual file will be created when you first save your work.

emacs has a built-in tutorial, and you should begin that very shortly. But first, just a couple of notes:

  • The tutorial describes a number of commands like this: C-_chr_, which means to hold down the Ctrl (a.k.a, Cntrl, Control, etc.) key while typing the character chr. For example, C-c means “hold down Ctrl while typing ‘c’.”

    You may have seen the notation ^_chr_ (e.g., ^c) used other places to mean the same thing.

  • The tutorial describes a number of commands like this: M-_chr_, and says the “M-” means to “hold the META or EDIT or ALT key down while typing” the other character, and says that if you don’t have a META, EDIT, or ALT key that you can type (and release) the Escape key instead.

    It’s worth noting that you may, indeed, have some of those keys on your keyboard, but your ssh client program might not pass them on. Some ssh programs may just ignore those keys. In other cases (especially the ALT keys), the Windows or other operating system may be jealously seizing upon those keys for its own purposes. In some cases, you may have 2 ALT keys, one on the left of the spacebar and one on the right. Sometimes one of these will work and the other will not, so try them both. But if nothing else works, the Escape key will always be there for you. (If you change ssh programs, though, or when you start using X to connect in graphics mode, you might want to check out those keys once again.)

Example 2: Try This: The emacs tutorial

Give the command

emacs -nw

to run emacs in a text-mode session.

Follow the directions given to bring up the tutorial (i.e., type ^h followed by “t”.).

Continue following the instructions to make your way through the tutorial.

Exit emacs when you have completed it.

Now let’s try actually using emacs to edit a file.

Example 3: Try This: Edit with emacs

You should still have a snark.txt file in your playing directory.

cd ~/playing emacs -nw snark.txt
  1. Try using your arrow keys and Page Up/Page Down keys to move around. These should work just as well as the control keys covered in the tutorial.

  2. Use the search (C-s) command to hunt for the word “muffins”.

  3. Use the M-< command to return to the first line of the file.

  4. Use the replace (M-%) command to replace all occurrences of “snark” by “snipe”. Notice as you go how emacs treats the various upper/lower case variations of “snark”.

  5. The “Undo” command in emacs is C-x u. Use it (repeatedly) to undo all of your replacements.

  6. Use the M-< command again to return to the first line of the file.

  7. Toggle the case sensitivity via the command M-x toggle-case-fold-search. You don’t need to type all of that out, however. Try doing M-x tog then hit the Tab key. emacs will attempt to compelte the command, adding gle-.

    It will stop there, because there are a lot of different commands that start with M-x toggle- and emacs doen’t know which one you want. (You can hit Tab again to see what they are.) Type a c and hit Tab again to complete your choice. Then use Enter to run the command.

  8. Use the replace (M-%) command to replace all occurrences of “snark” by “snipe”. Notice as you go how emacs treats the various upper/lower case variations of “snark” this time.

5.Use the C-x C-w command to save your changes as a new file snark3.txt.

6.Use the command C-x C-c to exit emacs.

  1. To see that you actually made a change, use diff and grep commands to examine the file: diff snark.txt snark3.txt grep -i snark snark3.txt grep -i snipe snark3.txt

    You should see your snark/snipe changes.

When you are done with the tutorial, here are few extra things you should know about emacs:

2.1 Emacs Modes

emacs offers customized modes for different kinds of files that you might be editing. Some of these are chosen automatically for you depending upon the file name you give. Others can be chosen automatically by giving the command M-x name-mode where name indicates the desired mode. Some of the most popular modes are: text, html, c, and c++. The programming language modes generally offer automatic indenting at the end of each line, though you may have to end lines with the “Line feed” or “C-j” key rather than “Return” or “Enter” to get this.

Example 4: Try this: C++ in emacs

cd ~/playing cp ~cs252/Assignments/textFiles/hello.cpp . emacs -nw hello.cpp

emacs will take note of the .cpp file extension and start this file in C++ mode.

If your terminal program supports color, you may see colored “syntax highlighting” as emacs renders reserved words, string constants, and comments in different colors and/or fonts.

And there are little, more subtle things that you will come to appreciate over time. Try typing a for loop

for (int i = 1; i <= 10; ++i) { cout << i << endl; }
  • Notice as you type the “)” and “}” in your code, the cursor briefly flashes back to the “(” or “{” that you just closed.
  • Notice also how the indentation is supplied automatically as you end each line.

Move your cursor back up to the endl and delete that word. Now type just the e and then do M-/.

  • The command M-/ is a special friend to all programmers who use long variable names but hate to type them. Type a few letters of any word, then hit M-/. emacs will search backwards through what you have previously typed looking for a word beginning with those letters. When it finds one, it fills in the remaining letters. If that wasn’t the word you wanted, just hit M-/ again and emacs will search for a different word beginning with the same characters.

2.2 The Mark and the Region

emacs has a number of commands that work on an entire block of text at a time. For example, the emacs tutorial told you how to delete a line using C-k. But what if you wanted to delete everything from the middle of one line to the 1st word five lines away? There is a command (C-w) for killing an entire region of text, but to use it you must first tell emacswhat region you want to kill.

The procedure for doing this is the same in all emacs commands that work on regions of text. The “current region” is the set of characters from the “mark” to the current cursor position. The “mark” is an imaginary position marker established by the set-mark-command. The keystrokes for that command are either C-[spc] (hold the control key and type a space) or C-@ (hold the control and shift keys and type ‘2’).

So to set up a region to operate on, you move the cursor to one end of the region, give the set-mark-command, then move the cursor to the other end of the region. Everything between the mark and the cursor constitutes the current region, and can be operated on by any region-based command. Some region commands of note are:

C-wKill the region, i.e., delete it but save the deleted text in the clipboard. You can “yank” (paste) the deleted text at the cursor position with C-y. M-wCopy the region, i.e., Save a copy of the region’s text in the clipboard. You can “yank” (paste) the deleted text at the cursor position with C-y.C-xC-xExchanges the mark and the cursor. Hitting this repeatedly will flip you back and forth between the start and end of the current region. Although often useful in its own right, this command also provides a quick way to check and see if the region is really where you think it is. C-cC-cComment out a region - in C++ and other programming modes, places comment markers in front of each line in the region.M-x ispell-region or M-x flyspell-regionRun a spell check on all text in the region.

2.3 Customizing emacs

emacs can be customized by placing various commands inside a file named .emacs in your home directory.

Here, for example, is my own .emacs file. I’ve been accumulating things in there for a long time, so there’s a lot in there. Some thing that might interest you are my key bindings:

  • M-\ will set/clear the mark.
  • The Home and End keys on most keyboards will move you to the beginning and end of the line, respectively.
  • The F2 key toggles case sensitivity on search and replacement.
  • The F5 key moves you to the next error message when emacs is used to compile C++ code (covered in an upcoming lesson).
  • The F6 key toggles spell checking on and off.
  • C-u N C-z jumps to line number N.

If you are interested in these, feel free to copy my .emacs file:

cp ~zeil/.emacs ~

2.4 Where’s the Documentation?

It’s in emacs. The end of the tutorial discussed some of the built-in help features in emacs. One that isn’t mentioned is the way to get to the entire “reference manual” for emacs. The “info viewer” gives you access to extensive documents about emacs (and about a number of other programs as well, as authors of many other programmers have found the info viewer a convenient way to package on-line documentation.) The commands C-h i or M-x info will launch the info viewer, and the first page of the viewer gives basic instructions on how to use it.

Finally, I have an emacs command reference sheet on the Resources page.

3 vim

If you are happy with emacs, you can skip this section.

But if you develop an incurable allergy to emacs, there are other editors that offer reasonable support to programmers. Some of the textbooks discuss vi, a popular editor that does not offer much support for programming, but a reasonable option is vim (“vi improved”).

Like emacs, vim is available on many, but not all, Unix systems and, once you have learned it, you can use it over telnet via keyboard commands. To learn the basics of running vim, give the command vimtutor.

Example 5: Try This: The vim tutorial

Give the command

vimtutor

Follow the instructions given there to learn the basic operation of vim.

Now, let’s try it out.

Example 6: Try This: Edit with vim

You should still have a snark.txt file in your playing directory.

cd ~/playing vim snark.txt
  1. Try using your arrow keys and Page Up/Page Down keys to move around. These should work just as well as the movement keys covered in the tutorial.

  2. Use the search (?) command to hunt for the word “muffins”.

  3. Position your cursor just after that word. Type ‘i’ to enter “Insert mode”. Insert the text “ and jam”. Use the Esc key to exit Insert mode.

  4. Use the gg command to return to the first line of the file.

  5. Use the replace (:%s/old/new/igc) command to replace all occurrences of “snark” by “snipe”. Notice as you go how vim treats the various upper/lower case variations of “snark”.

  6. The “Undo” command in vim is u. Use it (repeatedly) to undo all of your replacements.

  7. Use the gg command again to return to the first line of the file.

  8. Use the replace (:%s/old/new/gc) command to replace all occurrences of “snark” by “snipe”. Notice as you go how vim treats the various upper/lower case variations of “snark”.

5.Use the command :w snark4.txt command to save your changes as a new file snark4.txt.

  1. Use the command “:q!” to exist vim.

  2. To see that you actually made a change, use diff and grep commands to examine the file:

    diff snark.txt snark4.txt grep -i snark snark4.txt grep -i snipe snark4.txt

    You should see your snipe and jam changes.

3.1 vim and C++

Example 7: Try this: C++ in vim

cd ~/playing cp ~cs252/Assignments/textFiles/hello.cpp . vim hello.cpp

vim will take note of the .cpp file extension and start this file in C++ mode.

If your terminal program supports color, you may see colored “syntax highlighting” as emacs renders reserved words, string constants, and comments in different colors and/or fonts.

And there are little, more subtle things that you will come to appreciate over time. Try typing a for loop

for (int i = 1; i <= 10; ++i) { cout << i << endl; }

just after the existing cout <<… statement.

  • Notice as you type the “)” and “}” in your code, the cursor briefly flashes back to the “(” or “{” that you just closed.

Move your cursor back up to the endl and delete that word. Now type just the e and, while still in Insert mode, then do ^P.

  • The commands ^P and ^N are special friends to all programmers who use long variable names but hate to type them. Type a few letters of any word, then hit one of those control keys. vim will search backwards (^P) or forwards (^N) through what you have previously typed looking for a word beginning with those letters. When it finds one, it fills in the remaining letters. If that wasn’t the word you wanted, just hit the same key again and vim will search for a different word beginning with the same characters.

© 2015-2022, Old Dominion Univ.

When editing a text file with vi If you want to save your changes and exit right away?

To save a file in Vim / vi, press Esc key, type :w and hit Enter key. One can save a file and quit vim / Vi by pressing Esc key, type :x and hit Enter key.

What command is used with vi editor to save file and remain in editing mode?

To save a file and remain in vi editor, which one of the following command will be used? Explanation: For saving a file and to remain in editor we can use ':w' command in ex-mode. It is generally considered a good practice to save the contents of buffer regularly while working with files using ':w'.

How do I exit vi editor after saving?

Saving Changes and Quitting vi.
Save the contents of the buffer (write the buffer to the file on disk) by typing:.
Save and quit by typing:.
Press Return. Alternatively, type ZZ ..
When you've made no changes to a file and want to quit, type:.
If you do not want to save your changes, type:.
Press Return..

How do I edit text in vi?

Answer.
Connect to a Plesk server via SSH..
Install the improved vi text editor: ... .
Start editing a required file by typing: ... .
In the text editor, press computer's i key to edit the file. ... .
After editing the required string or pasting the text, press the Esc button. ... .
To discard the changes, type :q!.