Code Indenter
   HOME

TheInfoList



OR:

In
computer programming Computer programming or coding is the composition of sequences of instructions, called computer program, programs, that computers can follow to perform tasks. It involves designing and implementing algorithms, step-by-step specifications of proc ...
, indentation style is a convention or
style Style, or styles may refer to: Film and television * ''Style'' (2001 film), a Hindi film starring Sharman Joshi, Riya Sen, Sahil Khan and Shilpi Mudgal * ''Style'' (2002 film), a Tamil drama film * ''Style'' (2004 film), a Burmese film * '' ...
, governing the
indentation __FORCETOC__ In the written form of many languages, indentation describes empty space ( white space) used before or around text to signify an important aspect of the text such as: * Beginning of a paragraph * Hierarchy subordinate concept * Qu ...
of lines of
source code In computing, source code, or simply code or source, is a plain text computer program written in a programming language. A programmer writes the human readable source code to control the behavior of a computer. Since a computer, at base, only ...
. An indentation style generally specifies a consistent number of
whitespace character A whitespace character is a character data element that represents white space when text is rendered for display by a computer. For example, a ''space'' character (, ASCII 32) represents blank space such as a word divider in a Western scrip ...
s before each line of a block, so that the lines of code appear to be related, and dictates whether to use spaces or tabs as the indentation character.


Overview

This article primarily addresses styles for free-form
programming language A programming language is a system of notation for writing computer programs. Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
s. As the name implies, such language code need not follow an indentation style. Indentation is a secondary notation that is often intended to lower
cognitive load In cognitive psychology, cognitive load is the effort being used in the working memory. According to work conducted in the field of instructional design and pedagogy, broadly, there are three types of cognitive load: * ''Intrinsic'' cognitive load ...
for a programmer to understand the structure of the code. Indentation can clarify the separation between the code executed based on
control flow In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an '' ...
. Structured languages, such as Python and occam, use indentation to determine the structure instead of using braces or keywords; this is termed the
off-side rule The off-side rule describes syntax of a computer programming language that defines the bounds of a code block via indentation. The term was coined by Peter Landin, possibly as a pun on the offside law in association football. An off-side ...
. In such languages, indentation is meaningful to the language processor (such as
compiler In computing, a compiler is a computer program that Translator (computing), translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primaril ...
or
interpreter Interpreting is translation from a spoken or signed language into another language, usually in real time to facilitate live communication. It is distinguished from the translation of a written text, which can be more deliberative and make use o ...
). A programmer must conform to the language's indentation rules although may be free to choose indentation size. This article focuses on curly-bracket languages (that delimit blocks with curly brackets, a.k.a. curly braces, a.k.a. braces) and in particular C-family languages, but a convention used for one language can be adapted to another language. For example, a language that uses BEGIN and END keywords instead of braces can be adapted by treating BEGIN the same as the open brace and so on. Indentation style only applies to text-based languages.
Visual programming language In computing, a visual programming language (visual programming system, VPL, or, VPS), also known as diagrammatic programming, graphical programming or block coding, is a programming language that lets users create computer program, programs by ...
s have no indentation.


Research

Despite the ubiquitous use of indentation styles, little research has been conducted on its value. First experiments, conducted by Weissman in 1974, did not show any effect. In 2023, an experiment by Morzeck et al. showed a significant positive effect for nested if statements where non-indented code required on average 179% more time to read than indented code. A follow up-experiment by Hanenberg et al. confirmed a large effect (although in that experiment non-indented code just took 113% more time to read) and revealed that the differences in reading times can be explained by the code that can be skipped (for indented code). In another experiment on JSON objects non-indented code took even 544% more time to read.


Notable styles

The table below includes code examples of various indentation styles. For consistency, indentation size for example code is 4 spaces even though this varies by coding convention.


C/C++ styles

Attributes of C, C++ and other curly-brace programming language coding style include but are not limited to: * Placement of braces relative to other code elements * Use of tabs or spaces * Wrapping single-statement blocks in braces. Advocates cite the advantage that resulting code is safer since inserting a statement cannot result in control flow that disagrees with indentation. A cited disadvantage is that the code is longer since one line is needed for the closing brace of a block (except for the else if construct and a dowhile block).


K&R

The Kernighan & Ritchie (K&R) style is commonly used for C and C++ code and is the basis for many derivative styles. It is used in the original Unix kernel, Kernighan and Ritchie's book ''
The C Programming Language ''The C Programming Language'' (sometimes termed ''K&R'', after its authors' initials) is a computer programming book written by Brian Kernighan and Dennis Ritchie, the latter of whom originally designed and implemented the C programming langu ...
'', as well as Kernighan and Plauger's book '' The Elements of Programming Style''. Although ''
The C Programming Language ''The C Programming Language'' (sometimes termed ''K&R'', after its authors' initials) is a computer programming book written by Brian Kernighan and Dennis Ritchie, the latter of whom originally designed and implemented the C programming langu ...
'' does not explicitly define this style, it follows it consistently. From the book:
The position of braces is less important, although people hold passionate beliefs. We have chosen one of several popular styles. Pick a style that suits you, then use it consistently.
In this style, a function has its opening and closing braces on their own lines and with the same indentation as the declaration, while the statements in the body of the function are indented an additional level. A multi-statement block inside a function, however, has its opening brace on the same line as its control clause while the closing brace remains on its own line unless followed by a keyword such as else or while. Example code: int main(int argc, char *argv[])


Egyptian braces

The non-typographic alignment, aligned braces of the multi-line blocks are nicknamed "Egyptian braces" (or "Egyptian brackets") for their resemblance to arms in some fanciful poses of ancient Egyptians.


Single statements

A single-statement block does not have braces, which is a cause of easy-to-miss bugs such as the goto fail bug.


One True Brace

The ''One True Brace Style'' (abbreviated 1TBS or OTBS) is like the K&R style, but functions are formatted like multi-statement blocks with the opening brace on the same line as the declaration, and braces are ''not'' omitted for a single-statement block. bool is_negative(int x) Although not required by languages such as C/C++, using braces for single-statement blocks ensures that inserting a statement does not result in control flow that disagrees with indenting, as seen for example in Apple's infamous goto fail bug. Cited advantages include shorter code (than K&R) since the starting brace needs no extra line, that the ending brace lines up with the statement it conceptually belongs to, and the perceived stylistic consistency of using the same brace style in both function bodies and multi-line statement blocks. Sources disagree as to the meaning of One True Brace Style. Some say that it is the variation specified here, while others say it is "hacker jargon" for K&R.


Linux kernel

The
Linux kernel The Linux kernel is a Free and open-source software, free and open source Unix-like kernel (operating system), kernel that is used in many computer systems worldwide. The kernel was created by Linus Torvalds in 1991 and was soon adopted as the k ...
source tree is styled in a variant of K&R.
Linus Torvalds Linus Benedict Torvalds ( , ; born 28 December 1969) is a Finnish software engineer who is the creator and lead developer of the Linux kernel. He also created the distributed version control system Git. He was honored, along with Shinya Yam ...
advises contributors to follow it. Attributes include: * Uses
tab character Tab, TAB, tabs, or TABS may refer to: Places * Tab, Hungary, a town * Tab District, Hungary, whose seat is Tab * Tab, Indiana, United States, an unincorporated community * Arthur Napoleon Raymond Robinson International Airport, Tobago, IATA c ...
s for indentation (not spaces) and assumes
tab stop A tab stop on a typewriter is a location where the carriage movement is halted by an adjustable end stop. Tab stops are set manually, and pressing the tab key causes the carriage to go to the next tab stop. In text editors on a computer, the sam ...
s every 8 spaces * Brace layout matches K&R, with the braces of function definitions on their own lines and the opening brace of compound statements on the same line as the control clause, separated by a space * Labels in a switch statement are aligned with the enclosing block (there is only one level of indents) * Maximum line length is 100 characters although the pre-2020 limit of 80 characters is preferred. * A single-statement body of a compound statement (such as if, while, and do-while) does not need to be surrounded by curly braces. If, however, one or more of the substatements in an if-else statement require braces, then both substatements should be wrapped in braces: int power(int x, int y)


Java

A significant body of
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
code uses a variant of the K&R style in which the opening brace is on the same line not only for the blocks inside a function, but also for class or method declarations. This style is widespread largely because
Sun Microsystems Sun Microsystems, Inc., often known as Sun for short, was an American technology company that existed from 1982 to 2010 which developed and sold computers, computer components, software, and information technology services. Sun contributed sig ...
's original style guides used this K&R variant, and as a result, most of the standard source code for the
Java API There are two types of Java programming language application programming interfaces (APIs): * The official core Java API, contained in the Android (Google), SE (OpenJDK and Oracle), MicroEJ. These packages (java.* packages) are the core Java ...
is written in this style. It is also a popular indentation style for
ActionScript ActionScript is an object-oriented programming language originally developed by Macromedia Inc. (later acquired by Adobe). It is influenced by HyperTalk, the scripting language for HyperCard. It is now an implementation of ECMAScript (mean ...
and
JavaScript JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior. Web browsers have ...
, along with the
Allman style In computer programming, indentation style is a convention or style, governing the indentation of lines of source code. An indentation style generally specifies a consistent number of whitespace characters before each line of a block, so that t ...
.


Stroustrup

Bjarne Stroustrup Bjarne Stroustrup (; ; born 30 December 1950) is a Danish computer scientist, known for the development of the C++ programming language. He led the Large-scale Programming Research department at Bell Labs, served as a professor of computer sci ...
adapted the K&R style for C++ in his books, such as ''Programming: Principles and Practice using C++'' and ''
The C++ Programming Language ''The C Programming Language'' (sometimes termed ''K&R'', after its authors' initials) is a computer programming book written by Brian Kernighan and Dennis Ritchie, the latter of whom originally designed and implemented the C programming lang ...
''. Unlike the variants above, Stroustrup does not use a "cuddled else". Thus, Stroustrup would write if (x < 0) else Stroustrup extends K&R style for classes, writing them as follows: class Vector ; Stroustrup does not indent the labels and . Also, in this style, while the opening brace of a function starts on a new line, the opening brace of a class is on the same line as the class name. Stroustrup allows writing short functions all on one line. Stroustrup style is a named indentation style available in the editor
Emacs Emacs (), originally named EMACS (an acronym for "Editor Macros"), is a family of text editors that are characterized by their extensibility. The manual for the most widely used variant, GNU Emacs, describes it as "the extensible, customizable, s ...
. Stroustrup encourages a K&R-derived style layout with C++ as stated in his modern ''C++ Core Guidelines''.


BSD KNF

The
Berkeley Software Distribution The Berkeley Software Distribution (BSD), also known as Berkeley Unix or BSD Unix, is a discontinued Unix operating system developed and distributed by the Computer Systems Research Group (CSRG) at the University of California, Berkeley, beginn ...
(BSD) operating systems uses a style that is sometimes termed kernel normal form (KNF). Although mostly intended for kernel code, it is also widely used in userland code. It is essentially a thoroughly documented variant of K&R style as used in the Bell Labs version 6 & 7
Unix Unix (, ; trademarked as UNIX) is a family of multitasking, multi-user computer operating systems that derive from the original AT&T Unix, whose development started in 1969 at the Bell Labs research center by Ken Thompson, Dennis Ritchie, a ...
source code. The SunOS kernel and userland uses a similar indentation style. Like KNF, this also was based on AT&T style documents and is sometimes termed Bill Joy Normal Form. The SunOS guideline was published in 1996; ANSI C is discussed briefly. The correctness of the indentation of a list of source files can be verified by the ''cstyle'' program written by Bill Shannon. In this style, the hard tabulator (ts in vi) is kept at eight columns, while a soft tabulator is often defined as a helper also (sw in vi), and set at four. The hard tabulators are used to indent code blocks, while a soft tabulator (four spaces) of additional indentation is used for all continuing lines that must be split over multiple lines. Moreover, function calls do not use a space before the parenthesis, although C-language native statements such as if, while, do, switch and return do (in the case where return is used with parens). Functions that declare no local variables in their top-level block should also leave an empty line after their opening block brace. Examples: while (x

y) final_thing();
if (data != NULL && res > 0) else static JSBool pgresult_constructor(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)


Allman

The Allman style is named after
Eric Allman Eric Paul Allman (born September 2, 1955) is an American computer programmer who developed sendmail and its precursor delivermail in the late 1970s and early 1980s at UC Berkeley. In 1998, Allman and Greg Olson co-founded the company Sendmail ...
. It is also sometimes termed ''BSD style'' since Allman wrote many of the utilities for
BSD The Berkeley Software Distribution (BSD), also known as Berkeley Unix or BSD Unix, is a discontinued Unix operating system developed and distributed by the Computer Systems Research Group (CSRG) at the University of California, Berkeley, beginni ...
Unix (although this should not be confused with the different "BSD KNF style"; see above). This style puts the brace associated with a control statement on the next line, indented to the same level as the control statement. Statements within the braces are indented to the next level. while (x

y) final_thing();
This style is similar to the standard indentation used by the Pascal languages and
Transact-SQL Transact-SQL (T-SQL) is Microsoft's and Sybase's proprietary extension to the SQL (Structured Query Language) used to interact with relational databases. T-SQL expands on the SQL standard to include procedural programming, local variables, vari ...
, where the braces are equivalent to the keywords begin and end. (* Example Allman code indentation style in Pascal *) procedure dosomething(x, y: Integer); begin while x = y do begin something(); something_else(); end; end; Consequences of this style are that the indented code is clearly set apart from the containing statement by lines that are almost all
whitespace White space or whitespace may refer to: Technology * Whitespace characters, characters in computing that represent horizontal or vertical space * White spaces (radio), allocated but locally unused radio frequencies * TV White Space Database, a m ...
and the closing brace lines up in the same column as the opening brace. Some people feel this makes it easy to find matching braces. The blocking style also delineates the block of code from the associated control statement. Commenting out or removing a control statement or block of code, or
code refactoring In computer programming and software design, code refactoring is the process of restructuring existing source code—changing the '' factoring''—without changing its external behavior. Refactoring is intended to improve the design, structure, ...
, are all less likely to introduce syntax errors via dangling or missing braces. Also, it is consistent with brace placement for the outer-function block. For example, the following is still correct syntactically: // while (x

y)
As is this: // for (int i=0; i < x; i++) // while (x

y) if (x

y)
Even like this, with conditional compilation: int c; #ifdef HAS_GETCH while ((c = getch()) != EOF) #else while ((c = getchar()) != EOF) #endif


Variant: Allman-8

Allman-8 uses the 8-space indentation tabs and 80-column limit of the Linux Kernel variant of K&R. The style purportedly helps improve readability on projectors. Also, the indentation size and column restriction help create a visual cue for identifying excessive nesting of code blocks. These advantages combine to help provide newer developers and learners implicit guidance to manage code complexity.


Whitesmiths

The Whitesmiths style, also sometimes termed Wishart style, was originally used in the documentation for the first commercial C compiler, the
Whitesmiths Whitesmiths Ltd. was a software company founded in New York City by P. J. Plauger, Mark Krieger and Gabriel Pham, and last located in Westford, Massachusetts. It sold a Unix-like operating system called Idris, as well as the first commercial C ...
Compiler. It was also popular in the early days of Windows, since it was used in three influential Windows programming books, '' Programmer's Guide to Windows'' by Durant, Carlson & Yao, '' Programming Windows'' by Petzold, and '' Windows 3.0 Power Programming Techniques'' by Norton & Yao. Whitesmiths, along with Allman, were claimed to have been the most common bracing styles in 1991 by the
Jargon File The Jargon File is a glossary and usage dictionary of slang used by computer programmers. The original Jargon File was a collection of terms from technical cultures such as the MIT Computer Science and Artificial Intelligence Laboratory, MIT AI Lab ...
, with roughly equal popularity at the time. This style puts the brace associated with a control statement on the next line, indented. Statements within the braces are indented to the same level as the braces. Like Ratliff style, the closing brace is indented the same as statements within the braces. while (x

y) final_thing();
The advantages of this style are similar to those of the
Allman style In computer programming, indentation style is a convention or style, governing the indentation of lines of source code. An indentation style generally specifies a consistent number of whitespace characters before each line of a block, so that t ...
. Blocks are clearly set apart from control statements. The alignment of the braces with the block emphasizes that the full block is conceptually, and programmatically, one compound statement. Indenting the braces emphasizes that they are subordinate to the control statement. The ending brace no longer lines up with the statement, but instead with the opening brace. An example: if (data != NULL && res > 0) else if (!JS_DefineProperty(cx, o, "data", OBJECT_TO_JSVAL(NULL), NULL, NULL, JSPROP_ENUMERATE)) else if are treated as statement, much like the #elif preprocessor statement.


GNU

Like the Allman and
Whitesmiths Whitesmiths Ltd. was a software company founded in New York City by P. J. Plauger, Mark Krieger and Gabriel Pham, and last located in Westford, Massachusetts. It sold a Unix-like operating system called Idris, as well as the first commercial C ...
styles,
GNU GNU ( ) is an extensive collection of free software (394 packages ), which can be used as an operating system or can be used in parts with other operating systems. The use of the completed GNU tools led to the family of operating systems popu ...
style puts braces on a line by themselves, indented by two spaces, except when opening a function definition, where they are not indented. In either case, the contained code is indented by two spaces from the braces. Popularised by
Richard Stallman Richard Matthew Stallman ( ; born March 16, 1953), also known by his initials, rms, is an American free software movement activist and programmer. He campaigns for software to be distributed in such a manner that its users have the freedom to ...
, the layout may be influenced by his background of writing
Lisp Lisp (historically LISP, an abbreviation of "list processing") is a family of programming languages with a long history and a distinctive, fully parenthesized Polish notation#Explanation, prefix notation. Originally specified in the late 1950s, ...
code. In Lisp, the equivalent to a block (a progn) is a first-class data entity, and giving it its own indentation level helps to emphasize that, whereas in C, a block is only syntax. This style can also be found in some
ALGOL ALGOL (; short for "Algorithmic Language") is a family of imperative computer programming languages originally developed in 1958. ALGOL heavily influenced many other languages and was the standard method for algorithm description used by the ...
and XPL programming language textbooks from the 1960s and 1970s. Although not indentation per se, GNU coding style also includes a space after a function name before the left parenthesis of an argument list. static char * concat (char *s1, char *s2) This style combines the advantages of Allman and
Whitesmiths Whitesmiths Ltd. was a software company founded in New York City by P. J. Plauger, Mark Krieger and Gabriel Pham, and last located in Westford, Massachusetts. It sold a Unix-like operating system called Idris, as well as the first commercial C ...
, thereby removing the possible Whitesmiths disadvantage of braces not standing out from the block. One disadvantage is that the ending brace no longer lines up with the statement it conceptually belongs to. Another possible disadvantage is that it might waste space by using two visual levels of indents for one conceptual level, but in reality this is unlikely because, in systems with single-level indentation, each level is usually at least 4 spaces, same as 2 * 2 spaces in GNU style. The GNU Coding Standards recommend this style, and nearly all maintainers of
GNU project The GNU Project ( ) is a free software, mass collaboration project announced by Richard Stallman on September 27, 1983. Its goal is to give computer users freedom and control in their use of their computers and Computer hardware, computing dev ...
software use it. The
GNU Emacs GNU Emacs is a text editor and suite of free software tools. Its development began in 1984 by GNU Project founder Richard Stallman, based on the Emacs editor developed for Unix operating systems. GNU Emacs has been a central component of the GNU ...
text editor and the GNU systems' indent command will reformat code according to this style by default. Those who do not use GNU Emacs, or similarly extensible/customisable editors, may find that the automatic indentation settings of their editor are unhelpful for this style. However, many editors defaulting to KNF style cope well with the GNU style when the tab width is set to two spaces; likewise, GNU Emacs adapts well to KNF style by simply setting the tab width to eight spaces. In both cases, automatic reformatting destroys the original spacing, but automatic line indenting will work properly.
Steve McConnell Steven C. McConnell is an author of software engineering textbooks such as '' Code Complete'', ''Rapid Development'', and ''Software Estimation''. He is cited as an expert in software engineering and project management. Career McConnell gradua ...
, in his book
Code Complete ''Code Complete'' is a software development book, written by Steve McConnell and published in 1993 by Microsoft Press, encouraging developers to continue past code-and-fix programming and the big design up front and waterfall models. It is a ...
, advises against using this style: he marks a code sample which uses it with a "Coding Horror" icon, symbolizing especially dangerous code, and states that it impedes readability. The
Linux kernel The Linux kernel is a Free and open-source software, free and open source Unix-like kernel (operating system), kernel that is used in many computer systems worldwide. The kernel was created by Linus Torvalds in 1991 and was soon adopted as the k ...
coding style documentation also recommends against this style, urging readers to burn a copy of the GNU coding standards as a "great symbolic gesture".


Horstmann

The 1997 edition of ''Computing Concepts with C++ Essentials'' by Cay S. Horstmann adapts Allman by placing the first statement of a block on the same line as the opening brace. This style is also used in examples in Jensen and Wirth's ''Pascal User Manual and Report''. while (x

y) final_thing();
This style combines the advantages of Allman by keeping the vertical alignment of the braces for readability, and identifying blocks easily, with the saving of a line of the K&R style. However, the 2003 edition now uses Allman style throughout.


Pico

This is the style used most commonly in the language
Pico Pico may refer to: Places The Moon * Mons Pico, a lunar mountain in the northern part of the Mare Imbrium basin Portugal * Pico, a civil parish in the municipality of Vila Verde * Pico da Pedra, a civil parish in the municipality of Ribe ...
by its designers. Pico lacks return statements, and uses semicolons as statement separators instead of terminators. It yields this syntax:
stuff(n):

The advantages and disadvantages are similar to those of saving screen real estate with K&R style. An added advantage is that the starting and closing braces are consistent in application (both share space with a line of code), relative to K&R style, where one brace shares space with a line of code and one brace has a line alone.


Ratliff

In the book ''Programmers at Work'', C. Wayne Ratliff, the original programmer behind the popular
dBase dBase (also stylized dBASE) was one of the first database management systems for microcomputers and the most successful in its day. The dBase system included the core database engine, a query system, a Form (programming), forms engine, and a pr ...
-II and -III
fourth-generation programming language A fourth-generation programming language (4GL) is a high-level programming language, high-level computer programming language that belongs to a class of languages envisioned as an advancement upon third-generation programming languages (3GL). Each ...
s, discussed a style that is like 1TBS but the closing brace lines up with the indentation of the nested block. He indicated that the style was originally documented in material from
Digital Research Digital Research, Inc. (DR or DRI) was a privately held American software company created by Gary Kildall to market and develop his CP/M operating system and related 8-bit, 16-bit and 32-bit systems like MP/M, Concurrent DOS, FlexOS, Multiuser ...
Inc. This style has sometimes been termed ''banner'' style, possibly for the resemblance to a banner hanging from a pole. In this style, which is to
Whitesmiths Whitesmiths Ltd. was a software company founded in New York City by P. J. Plauger, Mark Krieger and Gabriel Pham, and last located in Westford, Massachusetts. It sold a Unix-like operating system called Idris, as well as the first commercial C ...
as K&R is to Allman, the closing control is indented the same as the last item in the list (and thus properly loses salience) The style can make visual scanning easier for some, since the ''headers'' of any block are the only thing exdented at that level (the theory being that the closing control of the prior block interferes with the visual flow of the next block header in the K&R and Allman styles). Kernighan and Plauger use this style in the Ratfor code in ''Software Tools''. // In C for (i = 0; i < 10; i++)


C derived language styles

The following styles are common for various languages derived from C that are both significantly similar and dissimilar. And, they can be adapted to C as well. They might be applied to C code written as part of a project ''mostly'' written in one of these other languages, where maintaining a consistent ''look and feel'' to the project's core code overrides considerations of using more conventional C style.


Lisp style

While GNU style is sometimes characterized as C code indented by a Lisp programmer, one might even go so far as to insert closing braces together in the last line of a block. This style makes indentation the only way to distinguish blocks of code, but has the advantage of containing no uninformative lines. This could easily be called the Lisp style because this style is very common in Lisp code. In Lisp, the grouping of identical braces at the end of expression trees is meant to signify that it is not the user's job to visually track nesting levels, only to understand the structure of the tree. The traditional Lisp variant of this style prefers extremely narrow levels of indentation (typically two spaces) because Lisp code usually nests very deeply since Lisp features only expressions, with no distinct class of
statement Statement or statements may refer to: Common uses *Statement (computer science), the smallest standalone element of an imperative programming language *Statement (logic and semantics), declarative sentence that is either true or false *Statement, ...
s; function arguments are mostly indented to the same level to illustrate their shared status within the enclosing expression. This is also because, braces aside, Lisp is conventionally a very terse language, omitting even common forms of simple boilerplate code as uninformative, such as the else keyword in an if : then , else block, instead rendering it uniformly as (if expr1 expr2 expr3). // C for (i = 0; i < 10; i++)   ;; Lisp (dotimes (i 10) (if (= (rem i 2) 0) (do-something i) (progn (do-something-else i) (do-third-thing i)))) Note: progn is a procedure for evaluating multiple sub-expressions sequentially for
effects Effect may refer to: * A result or change of something ** List of effects ** Cause and effect, an idiom describing causality Pharmacy and pharmacology * Drug effect, a change resulting from the administration of a drug ** Therapeutic effect, ...
, while discarding all but the final (nth) return value. If all return values are desired, the values procedure would be used.


Haskell style

Haskell Haskell () is a general-purpose, statically typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research, and industrial applications, Haskell pioneered several programming language ...
layout can make the placement of braces optional, although braces and semicolons are allowed in the language. The two segments below are equally acceptable to the compiler: braceless = do text <- getContents let firstWord = head $ words text bigWord = map toUpper firstWord putStrLn bigWord braceful = do In Haskell, layout can replace braces. Usually the braces and semicolons are omitted for procedural do sections and the program text in general, but the style is commonly used for lists, records and other syntactic elements made up of some pair of parentheses or braces, which are separated with commas or semicolons. If code following the keywords where, let, or of omits braces and semicolons, then indentation is significant.


APL style

For an example of how terse APL typically is, here is the implementation of the step function for the Game of Life: life← APL style C resembles the terse style of APL code, and is commonly used in their implementations. This style was pioneered by Arthur Whitney, and is heavily used in the implementation of K, Arthur's own project. The J programming language is implemented in this style as well. Notably, not all implementations of APL use this style of C, namely: GNU APL and Dyalog APL. In addition to APL style C indentation, typically the names are shortened to either single or double characters: To reduce the amount of indentation, and expressions spanning multiple lines.


Indentation size

Typically, programmers use the same width of whitespace to indent each block of code with commonly used widths varying from 1 to 4 spaces. An experiment performed on PASCAL code in 1983, found that indentation size significantly affected comprehensibility. Indentation sizes between 2 and 4 characters proved optimal. Although they both affect the general layout of code, indentation ''size'' is independent of the indentation ''style'' discussed here.


Tab vs. space

Typically, a programmer uses a text editor that provides tab stops at fixed intervals (a number of spaces), to assist in maintaining whitespace according to a style. The interval is called the ''tab width''. Sometimes the programmer stores the code with tab characters one for each tab key press or they store a sequence of spaces equal in number to the tab width. Storing
tab character Tab, TAB, tabs, or TABS may refer to: Places * Tab, Hungary, a town * Tab District, Hungary, whose seat is Tab * Tab, Indiana, United States, an unincorporated community * Arthur Napoleon Raymond Robinson International Airport, Tobago, IATA c ...
s in code can cause visual misalignment when viewed in different contexts, which counters the value of the indentation style. Programmers lack consensus on storing tab characters. Proponents of storing tab characters cite ease of typing and smaller text files since a single tab character serves the purpose of multiple spaces. Opponents, such as
Jamie Zawinski Jamie Werner Zawinski (born November 3, 1968), commonly known as jwz, is an American computer programmer, blogger, and impresario. He is best known for his role in the creation of Netscape Navigator, Netscape Mail, Lucid Emacs, Mozilla.org, an ...
, state that using spaces instead increases
cross-platform Within computing, cross-platform software (also called multi-platform software, platform-agnostic software, or platform-independent software) is computer software that is designed to work in several Computing platform, computing platforms. Some ...
portability. Others, such as the writers of the
WordPress WordPress (WP, or WordPress.org) is a web content management system. It was originally created as a tool to publish blogs but has evolved to support publishing other web content, including more traditional websites, electronic mailing list, ma ...
coding standards, state the opposite: that hard tabs increase portability. A survey of the top 400,000 repositories on
GitHub GitHub () is a Proprietary software, proprietary developer platform that allows developers to create, store, manage, and share their code. It uses Git to provide distributed version control and GitHub itself provides access control, bug trackin ...
found that spaces are more common. Many text editors, including
Notepad++ Notepad++ (sometimes npp or NPP) is a text and source code editor for use with Microsoft Windows. It supports tabbed editing, which allows working with multiple open files in one window. The program's name comes from the C postfix increment op ...
,
TextEdit TextEdit is an open-source software, open-source word processor and text editor, first featured in NeXT's NeXTSTEP and OPENSTEP. It is now distributed with macOS since Apple Inc.'s acquisition of NeXT, and available as a GNUstep application fo ...
,
Emacs Emacs (), originally named EMACS (an acronym for "Editor Macros"), is a family of text editors that are characterized by their extensibility. The manual for the most widely used variant, GNU Emacs, describes it as "the extensible, customizable, s ...
, vi, and nano, can be configured to either store tab characters when entered via the tab key or to convert them to spaces (based on the configured tab width) so that tab characters are not added to the file when the tab key is pressed. Some editors can convert tab to space characters and vice versa. Some text file pagers, such as
less Less or LESS may refer to: Computing * less (Unix), a Unix utility program * Less (style sheet language), a dynamic style sheet language * Large-Scale Scrum (LeSS), a product development framework that extends Scrum Other uses * -less, a priv ...
, can be configured for a tab width. Some tools such as expand/ unexpand can convert on the fly via filters.


Style automation

A tool can automate formatting code per an indentation style, for example the
Unix Unix (, ; trademarked as UNIX) is a family of multitasking, multi-user computer operating systems that derive from the original AT&T Unix, whose development started in 1969 at the Bell Labs research center by Ken Thompson, Dennis Ritchie, a ...
indent command.
Emacs Emacs (), originally named EMACS (an acronym for "Editor Macros"), is a family of text editors that are characterized by their extensibility. The manual for the most widely used variant, GNU Emacs, describes it as "the extensible, customizable, s ...
provides commands to modify indentation, including hitting Tab on a given line. M-x indent-region indents code. Elastic tabstops is a tabulation style which requires support from the text editor, where entire blocks of text are kept automatically aligned when the length of one line in the block changes.


Losing track of blocks

In more complicated code, the programmer may lose track of block boundaries while reading the code. This is often experienced in large sections of code containing many compound statements nested to many levels of indentation. As the programmer scrolls to the bottom of a huge set of nested statements, they may lose track of context such as the control structure at the top of the block. Long compound statements can be a
code smell In computer programming, a code smell is any characteristic in the source code of a program that possibly indicates a deeper problem. Determining what is and is not a code smell is subjective, and varies by language, developer, and development met ...
of over complexity which can be solved by
refactoring In computer programming and software design, code refactoring is the process of restructuring existing source code—changing the '' factoring''—without changing its external behavior. Refactoring is intended to improve the design, structure, ...
. Programmers who rely on counting the opening braces may have difficulty with indentation styles such as K&R, where the starting brace is not visually separated from its control statement. Programmers who rely more on indentations will gain more from styles that are vertically compact, such as K&R, because the blocks are shorter. To avoid losing track of control statements such as
for For or FOR may refer to: English language *For, a preposition *For, a complementizer *For, a grammatical conjunction Science and technology * Fornax, a constellation * for loop, a programming language statement * Frame of reference, in physics * ...
, a large indentation can be used, such as an 8-unit-wide hard tab, along with breaking up large functions into smaller and more readable functions. Linux is done this way, while using the K&R style. Some text editors allow the programmer to jump between the two corresponding braces of a block. For example, vi jumps to the brace enclosing the same block as the one under the cursor when pressing the % key. Since the text cursor's next key (viz., the n key) retained directional positioning information (whether the up or down key was formerly pressed), the dot macro (the . key) could then be used to place the text cursor on the next brace, given a suitable coding style. Instead, inspecting the block boundaries using the % key can be used to enforce a coding standard. Another way to maintain block awareness, is to use comments after the closing brace. For example: for (int i = 0; i < total; i++) //for (i) if (x < 0) //if (x < 0) A disadvantage is maintaining the same code in multiple locations above and below the block. Some editors provide support for maintaining block awareness. A
folding editor Code or text folding, or less commonly holophrasting, is a feature of some graphical user interfaces that allows the user to selectively hide ("fold") or display ("unfold") parts of a document. This allows the user to manage large amounts of text ...
can hide (fold) and reveal (unfold) blocks by indentation level. Some editors highlight matching braces when the cursor is positioned next to one.


See also

* Secondary notation *
Syntax highlighting Syntax highlighting is a feature of text editors that is used for programming language, programming, scripting language, scripting, or markup language, markup languages, such as HTML. The feature displays text, especially source code, in differe ...
* * '' Bachmanity Insanity'', a ''
Silicon Valley Silicon Valley is a region in Northern California that is a global center for high technology and innovation. Located in the southern part of the San Francisco Bay Area, it corresponds roughly to the geographical area of the Santa Clara Valley ...
'' episode featuring the topic *
Source-code formatter Pretty-printing (or prettyprinting) is the application of any of various stylistic text formatting, formatting conventions to text files, such as source code, markup language, markup, and similar kinds of content. These formatting conventions may ...


References


External links


''C Style: Standards and Guidelines: Defining Programming Standards for Professional C Programmers''
Prentice Hall, / (full text is also online). Straker, David (1992).




Tabs and spaces



by Jamie Zawinski

by Adam Spiers

(archived)
''Elastic tabstops – the solution to the tabs-versus-spaces issue''
{{DEFAULTSORT:Indent Style Software wars Text editor features Source code