Snippet (programming)

From Wikipedia, the free encyclopedia
  (Redirected from Code snippets)
Jump to: navigation, search
Example of a code snippet.

Snippet is a programming term for a small region of re-usable source code, machine code, or text. Ordinarily, these are formally defined operative units to incorporate into larger programming modules. Snippets are often used to clarify the meaning of an otherwise "cluttered" function, or to minimize the use of repeated code that is common to other functions. The snippets themselves may be either literal text, or written in a simple template language to allow substitutions, such as variable names. Snippets are a small-scale form of copy and paste programming.[neutrality is disputed] Snippet management is a feature of some text editors, program source code editors, IDEs, and related software. It allows the user to persist and use snippets in the course of routine edit operations.[1]

Overview[edit]

Snippet management is a text editor feature popular among software developers or others who routinely require content from a catalogue of repeatedly entered text (such as with source code or boilerplate). Often this feature is justified because the content varies only slightly (or not at all) each time it is entered.

Snippets in text editors[edit]

Text editors that include this feature ordinarily provide a mechanism to manage the catalogue, and separate "snippets" in the same manner that the text editor and operating system allow management of separate files. These basic management abilities include operations such as viewing, adding, editing, deleting, sorting, filtering, grouping, renaming, and storing snippets in a repository, catalogue, or database.

Snippets in IDEs[edit]

Some programmer's applications such as Eclipse, NetBeans, and Microsoft's Visual Studio (a keyword and Tab ) and other IDEs include built-in parts of structure for ease of coding.

Other applications such as Macromedia Dreamweaver make use of these code snippets as well for Web development.

Snippets in JIT compilers[edit]

Just-in-time (JIT) compilers can "splice together" pre-compiled sections of code as longer object code/machine code segments. This reduces interpret time significantly and simultaneously speeds execution.

Definition[edit]

"Snippet" refers narrowly to a portion of source code that is literally included by an editor program into a file, and is a form of copy and paste programming.[neutrality is disputed] This concrete inclusion is in contrast to abstraction methods, such as a function, which is abstraction within the language, and processed by the compiler, or macros, which are abstractions using a separate language, and processed by the preprocessor. Snippets are thus primarily used when these alternative abstractions are not available or not desired, such as in languages that lack abstraction, or for clarity and absence of overhead (by contrast with the indirection of macros).

Snippets are similar to having static preprocessing included in the editor, and do not require support by a compiler: once a snippet is included into the text, no further processing occurs. On the flip side, this means that snippets cannot be modified after the fact (except via search and replace, assuming the code has not been changed), and thus is vulnerable to all of the problems of copy and paste programming. For this reason snippets are primarily used for simple sections of code (with little logic), or for boilerplate, such as copyright notices, function prototypes, or standard library imports.

Example[edit]

Consider the process of swapping the values of two variables, x and y. Assuming weak typing and not being concerned about name collision, this is represented by the code:

temp = x
x = y
y = temp

When the snippet is inserted, the programmer is prompted for the values of the two parameters. Assuming they are type foo and bar, which are the actual names of the variables they wish to swap, this will yield the code:

temp = foo
foo = bar
bar = temp

If the snippet is subsequently changed, say to use __temp instead of temp, it will not change the code that has already been inserted, but will be used in subsequent insertions of the snippet.

A snippet for this might be represented as:

temp = $1
$1 = $2
$2 = temp

Alternatives[edit]

In C, an alternative to snippets is the use of macros. A macro for swapping two integers may be specified as:

#define SWAP_INT(x, y) \
 {int temp; temp = x; x = y; y = temp;}

or more properly:

#define SWAP(type, x, y) \
  do { \
    type temp; temp = x; x = y; y = temp; \
  } while(0)

Note that the use of block scope in C means that the variable temp shadows any other variable with that name, and avoids name clashes; in the absence of such mechanisms, naming conventions such as __temp are necessary. Further, the do ... while(0) is used to allow this macro to be embedded anywhere a statement might be. (This is repetitive, so #define $1 do {$2} while(0) is a potential snippet if such macros are commonly used.) These concerns occur with macros because they can potentially be used anywhere, and since they are not expanded in place, the actual syntax is unclear at the inclusion site.

This would then be used as such:

#define SWAP(type, x, y) \
  do { \
    type temp; temp = x; x = y; y = temp; \
  } while(0)
 
void bubble_sort(int list[], int size)
{
    // ...
    SWAP(int, list[i], list[i+1]);
    // ...
}

Note that the macro definition and name are included in the file, and must be processed by the C preprocessor prior to compilation.

Alternatively, a function could be used; because it needs to modify the variables, the parameters must be passed by reference, here using pointers:

void swap_int(int *x, int *y)
{
    int temp = *x;
    *x = *y;
    *y = temp;
}
 
void bubble_sort(int list[], int size)
{
    // ...
    swap_int(&(list[i]), &(list[i+1]));
    // ...
}

In this case, using a macro or a function adds significant overhead to the simple task of swapping two variables, and would generally instead be written as following (showing a bit more context):

void bubble_sort(int list[], int size)
{
    // ...
    if (list[i] > list[i+1]) {
        int temp = list[i];
        list[i] = list[i+1];
        list[i+1] = temp;
    }
    // ...
}

The swapping code could then have been generated by the following snippet (specifying type, and the two variable names):

{
    $1 temp = $2
    $2 = $3
    $3 = temp
}


Conventions[edit]

In addition to the basic management abilities described previously, snippet management features can be classified according to the scope of interactivity between snippets and the text editor or application that hosts them.

These snippet feature groups include:

  • plain-text or "static" snippets
  • interactive or "dynamic" snippets
  • scriptable snippets

Static snippets consist primarily of fixed text that the user can choose to insert into the current document. The user is not able to specify anything else, except perhaps the cursor position relative to the newly inserted text. Static snippets are similar to simple macros.

Dynamic snippets consist of fixed text combined with dynamic elements. The user may specify both the content of the dynamic elements, as well as their position relative to the fixed text, as part of choosing what to insert into the current document. Examples of dynamic elements could be variables such as the current date or system time, or input from the user that is supplied via a GUI, or input from another application. (see also: programmable macro).

Scriptable snippets consist of runnable segments of code in either a macro language or a scripting language. Scriptable snippets provide the greatest degree of flexibility to the user, although that depends somewhat on the programming languages supported by the text editor, and whether or not the programming language is well-known, or particular and unique to that specific editor.

The type of scripting support varies, but may include features such as running shell commands, providing a GUI dialog or other methods of user interaction with the operating system; other applications; or other sub-components of the hosting application itself.

Snippet placeholders[edit]

Placeholders are elements within a snippet that are left to be supplied by the user or other external process. The values for placeholders are not determined until the text of the snippet is inserted during an editing session.

Placeholders may have special markup syntax that allows the editor to identify the boundaries of placeholders relative to the other text in the current edit buffer.

Other applications employ graphical user interfaces and modal dialog boxes that allow the user to enter one or more values to be supplied for the placeholders. Placeholder identifiers Placeholders are usually indicated by some special character or sequence of characters to distinguish them from the rest of the snippet text. Some systems allow snippet placeholders to be named identifiers. The identifiers may be useful for supporting such features as placeholder duplication or placeholder transformation.

The following example uses the identifiers first_name, last_name, and item:

Hello {%first_name%} {%last_name%},

Your shipment of {%item%} is now ready to pick up.

Thanks {%first_name%}!

Placeholder duplication[edit]

This allows the user to indicate that the value supplied for one placeholder should be replicated in multiple places, relative to the entire text of the programmable snippet. In the previous example, the named placeholder first_name is an example of this usage.

Placeholder transformation[edit]

This allows the user to indicate that one or more values supplied for a placeholder should be replicated and transformed in other places within the text of the programmable snippet. For example, the user may supply a document title in one part of the snippet, and specify that the document title should be repeated in other places, with the first instance being all-uppercase and every other instance being lower-case.

Snippet programming features[edit]

For applications that support scriptable snippets, the range of supported programming features varies. The following enumerates some of the features that are commonly implemented for programmable snippets.

Plain text[edit]

Although plain text is a fundamental feature included even with applications that support only non-programmable "static" snippets, programmable snippets are also used for working with plain text.

One common complication, however, is that environments that support programmable snippets often have to make distinctions between what counts as "plain text" and what counts as "programming instructions". Further complicating this distinction is the fact that applications that support programmable snippets almost always include support for recognition of multiple programming languages, either through basic syntax highlighting or execution of embedded commands.

For these and other reasons, emitting plain text from programmable snippets almost always entails being careful to avoid problems with syntax and delimiter collisions.

Constants and variables[edit]

Programmable snippets often include an ability to establish a binding to an existing variable scope or namespace, from which the user can select any of various constants or variables. These might include values such as the email address of the currently logged-in user on a given machine, the current system time and date, or the output value of a function.

Scriptable snippets are often associated with one or more currently active files. Consequently, variables may also include environment variables and arguments that specify the filename, cursor position, and parent directory among other stats relating to the files in a current editing session.

Interpreted code[edit]

Scriptable snippets may allow execution of code in one or more programming languages. This may include one or more standalone languages, or a language that is specific to the application in which the language is hosted.[2]

See also[edit]

Notes and references[edit]

  1. ^ "GEdit feature example". Retrieved 2010-01-09.  example of the feature in the gedit editor.
  2. ^ (See e.g., http://code.google.com/p/yasnippet/ YaSnippet, implemented for the Emacs text editor).

Examples of Code Snippets[edit]