Chapter 4. Creating Code Snippets

If you like using the command line, but also like some of the features associated with using graphical Integrated Development Environments (IDEs), then this chapter may reveal some new ideas to you. We can create shortcuts for commonly used script elements using the vi or vim text editors from the command line.

In this chapter, we will cover the following topics:

  • Creating abbreviations in .vimrc
  • Reading snippets with vim text editor
  • Using color in terminal

Abbreviations

We have already taken one short sojourn into the ~/.vimrc file and we will now revisit this file to look at abbreviations or abbr controls. This file acts as the run control mechanism for the vim text editor, which is likely to be installed on your Linux distribution. Older distributions or Unix variants may have the original vi text editor and will make use of the ~/.exrc file. If you are uncertain of the identity of your version of vi and the correct run control file to use, simply, enter the vi command. If a blank page opens, it is indeed vi. However, if a new blank document opens with the vim splash screens, then you are using the improved vim or Vi.

Abbreviations allow for a shortcut string to be used in place of a longer string. These abbreviations can be set during a vim session from the last line mode but are often set in the control file. The shebang can be easily represented by an abbreviation, as follows:

abbr _sh #!/bin/bash

The basic syntax of an abbreviation is shown in the following command:

abbr <shortcut><string>

Using this abbreviation, we just need to type _sh while in the edit mode. On pressing the ENTER key after the shortcut code, the full text for the shebang is printed. In reality, not just the ENTER key but pressing any key after the abbr code will expand the shortcut. Simple elements like this can add a lot to the experience of using vim as our text editor. The following screenshot shows the updated ~/.vimrc file:

Abbreviations

We are not limited to the single abbreviation code, as we can add more abbr entries. For example, to support the shebang for Perl scripts at the line:

abbr _pl #!/usr/bin/perl

The use of the underscore is not required, but the aim is to keep the shortcut code unique and not to have a typed error. We are also not limited to a single line; although, this is where abbreviations are most used. Consider the following abbreviation for an if statement:

abbr _if if [-z $1];then<CR>echo "> $0 <name><CR>exit 2<CR>fi

Although this does work, the formatting of the if statement will not be perfect and multiline abbreviations are far from ideal. This is where we may consider using code snippets that we prepared in advance.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.35.193