![CodeCmmt002](https://upload.wikimedia.org/wikipedia/commons/7/75/CodeCmmt002.svg)
Snippet is a programming term for a small region of re-usable
source code
In computing, source code, or simply code, is any collection of code, with or without comments, written using a human-readable programming language, usually as plain text. The source code of a program is specially designed to facilitate the wo ...
,
machine code
In computer programming, machine code is any low-level programming language, consisting of machine language instructions, which are used to control a computer's central processing unit (CPU). Each instruction causes the CPU to perform a very ...
, or text. Ordinarily, these are formally defined operative units to incorporate into larger
programming modules. Snippet management is a feature of some
text editor
A text editor is a type of computer program that edits plain text. Such programs are sometimes known as "notepad" software (e.g. Windows Notepad). Text editors are provided with operating systems and software development packages, and can be us ...
s, program
source code editor
A source-code editor is a text editor program designed specifically for editing source code of computer programs. It may be a standalone application or it may be built into an integrated development environment (IDE) or web browser. Source-code ed ...
s,
IDEs Ides or IDES may refer to:
Calendar dates
* Ides (calendar), a day in the Roman calendar that fell roughly in the middle of the month. In March, May, July, and October it was the 15th day of the month; in other months it was the 13th.
**Ides of Mar ...
, and related
software
Software is a set of computer programs and associated documentation and data. This is in contrast to hardware, from which the system is built and which actually performs the work.
At the lowest programming level, executable code consists ...
. It allows the user to avoid repetitive typing in the course of routine edit operations.
[ Example of the feature in the Gedit editor.]
Definition
In programming practice, "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
Copy may refer to:
* Copying or the product of copying (including the plural "copies"); the duplication of information or an artifact
** Cut, copy and paste, a method of reproducing text or other data in computing
** File copying
**Photocopying, a ...
. This concrete inclusion is in contrast to abstraction methods, such as
functions or
macros, which are abstraction within the language. Snippets are thus primarily used when these abstractions are not available or not desired, such as in languages that lack abstraction, or for clarity and absence of overhead.
Snippets are similar to having static preprocessing included in the editor, and do not require support by a compiler. On the flip side, this means that snippets cannot be invariably modified after the fact, 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, common control structures, or standard library imports.
Overview
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
In computing, source code, or simply code, is any collection of code, with or without comments, written using a human-readable programming language, usually as plain text. The source code of a program is specially designed to facilitate the wo ...
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
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
Repository may refer to:
Archives and online databases
* Content repository, a database with an associated set of data management tools, allowing application-independent access to the content
* Disciplinary repository (or subject repository), an ...
, catalogue, or
database
In computing, a database is an organized collection of data stored and accessed electronically. Small databases can be stored on a file system, while large databases are hosted on computer clusters or cloud storage. The design of databases sp ...
. Some editors provide a macro ability to snippets allowing function prototypes and variable control structures to be generated based on a standard template.
Snippets in IDEs
Some programmer's applications such as
Eclipse
An eclipse is an astronomical event that occurs when an astronomical object or spacecraft is temporarily obscured, by passing into the shadow of another body or by having another body pass between it and the viewer. This alignment of three ce ...
,
NetBeans
NetBeans is an integrated development environment (IDE) for Java (programming language), Java. NetBeans allows applications to be developed from a set of modular software components called ''modules''. NetBeans runs on Microsoft Windows, Windows, ...
, and Microsoft's
Visual Studio
Visual Studio is an integrated development environment (IDE) from Microsoft. It is used to develop computer programs including web site, websites, web apps, web services and mobile apps. Visual Studio uses Microsoft software development platfor ...
(uses
TextMate
TextMate is a general-purpose Graphical user interface, GUI text editor for macOS created by Allan Odgaard. TextMate features declarative programming, declarative customizations, Tab (GUI), tabs for open documents, recordable Macro (computer scien ...
-inspired snippets underhood) and other
IDEs Ides or IDES may refer to:
Calendar dates
* Ides (calendar), a day in the Roman calendar that fell roughly in the middle of the month. In March, May, July, and October it was the 15th day of the month; in other months it was the 13th.
**Ides of Mar ...
include built-in parts of structure for ease of coding.
Other applications such as Macromedia
Dreamweaver
Adobe Dreamweaver is a proprietary web development tool from Adobe Inc. It was created by Macromedia in 1997 and developed by them until Macromedia was acquired by Adobe Systems in 2005.
Adobe Dreamweaver is available for the macOS and Windows ...
make use of these code snippets as well for
Web development
Web development is the work involved in developing a website for the Internet (World Wide Web) or an intranet (a private network). Web development can range from developing a simple single static page of plain text to complex web applications ...
.
Snippets in JIT compilers
Just-in-time (
JIT
Jit (also known as jiti, jit-jive and the Harare beat) is a style of popular Zimbabwean dance music. It features a swift rhythm played on drums and accompanied by a guitar. Jit evolved out many diverse influences, including domestic chimurenga, ...
) compilers can "splice together" pre-compiled sections of code as longer
object code
In computing, object code or object module is the product of a compiler.
In a general sense object code is a sequence of statements or instructions in a computer language, usually a machine code language (i.e., binary) or an intermediate langua ...
/
machine code
In computer programming, machine code is any low-level programming language, consisting of machine language instructions, which are used to control a computer's central processing unit (CPU). Each instruction causes the CPU to perform a very ...
segments. This reduces interpret time significantly and simultaneously speeds execution.
Snippets in shells
Snippets may be used inside commandline interfaces like bash, zsh (
GNU Linux/Unix-like) or powershell (
MS Windows). Features like completion and placeholders substitution may or may not be supported.
Example
Consider the process of swapping the values of two variables, ''x'' and ''y.'' Assuming
weak typing
In computer programming, one of the many ways that programming languages are colloquially classified is whether the language's type system makes it strongly typed or weakly typed (loosely typed). However, there is no precise technical definition o ...
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
Conventions
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 of this type 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, excepting that macro are often evaluated (or inserted) by a
command-line program instead of IDE.
;Dynamic
:Snippets consist of fixed text combined with dynamic elements (placeholders) which are allowed to be modified either by editor or by user. 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
A scripting language or script language is a programming language that is used to manipulate, customize, and automate the facilities of an existing system. Scripting languages are usually interpreted at runtime rather than compiled.
A scripting ...
. 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
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 interface
The GUI ( "UI" by itself is still usually pronounced . or ), graphical user interface, is a form of user interface that allows users to interact with electronic devices through graphical icons and audio indicator such as primary notation, inste ...
s 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
identifier
An identifier is a name that identifies (that is, labels the identity of) either a unique object or a unique ''class'' of objects, where the "object" or class may be an idea, physical countable object (or class thereof), or physical noncountable ...
s. 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 ,
Your shipment of is now ready to pick up.
Thanks !
Example of a snippet in
TexMate syntax:
Hello $ $,
Your shipment of $ is now ready to pick up.
Thanks $!
Placeholder duplication
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
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
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
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
Syntax highlighting is a feature of text editors that are used for programming, scripting, or markup languages, such as HTML. The feature displays text, especially source code, in different colours and fonts according to the category of terms ...
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
In linguistics, syntax () is the study of how words and morphemes combine to form larger units such as phrases and sentences. Central concerns of syntax include word order, grammatical relations, hierarchical sentence structure ( constituency) ...
and
delimiter collision
A delimiter is a sequence of one or more characters for specifying the boundary between separate, independent regions in plain text, mathematical expressions or other data streams. An example of a delimiter is the comma character, which acts a ...
s.
Constants and variables
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 variable
An environment variable is a dynamic-named value that can affect the way running processes will behave on a computer. They are part of the environment in which a process runs. For example, a running process can query the value of the TEMP env ...
s 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
Scriptable snippets may allow execution of code in one or more
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming ...
s. This may include one or more standalone languages, or a language that is specific to the application in which the language is hosted.
Alternatives
The most basic alternative to code snippets is
subroutine
In computer programming, a function or subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed.
Functions may ...
s in libraries. Subroutines can be incorporated into a reusable
software library
In computer science, a library is a collection of non-volatile resources used by computer programs, often for software development. These may include configuration data, documentation, help data, message templates, pre-written code and subr ...
and shared between multiple programming projects.
Design patterns
''Design Patterns: Elements of Reusable Object-Oriented Software'' (1994) is a software engineering book describing software design patterns. The book was written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, with a foreword ...
in object-oriented programming, and
functional programming
In computer science, functional programming is a programming paradigm where programs are constructed by Function application, applying and Function composition (computer science), composing Function (computer science), functions. It is a declar ...
, are both techniques that can allow programmers to avoid or reduce the practice of repeatedly inserting snippets into different pieces of code with slight variations each time. In languages in the
C family,
preprocessor
In computer science, a preprocessor (or precompiler) is a program that processes its input data to produce output that is used as input in another program. The output is said to be a preprocessed form of the input data, which is often used by so ...
s are sometimes used for this purpose.
The disadvantage of this approach however is that it's harder to remember pattern or documentation.
Software assistance
As of 2021 some sophisticated
deep-learning
Deep learning (also known as deep structured learning) is part of a broader family of machine learning methods based on artificial neural networks with representation learning. Learning can be supervised, semi-supervised or unsupervised.
D ...
tooling emerged that can help to infer specific functionality from a human readable text and generate corresponding source code snippets (e.g.
GitHub Copilot
GitHub Copilot is a cloud-based artificial intelligence tool developed by GitHub and OpenAI to assist users of Visual Studio Code, Visual Studio, Neovim, and JetBrains integrated development environments (IDEs) by autocompleting code. Currently ...
).
See also
*
*
*
*
*
*
*
*
References
Examples of code snippets
*
*
*
*
* {{cite web , title=Search Engine for Code Snippets , url=https://www.code-snippets.dev , website=www.code-snippets.dev , access-date=20 September 2022
Source code
Text editor features