Jump to content

Prettyprint: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
→‎top: Code beautifier redirects here to Prettyprint. Marking term per MOS:BOLD.
m →‎See also: - (subordinate clause muddled overall meaning/intent; corrected)
 
(26 intermediate revisions by 19 users not shown)
Line 1: Line 1:
{{short description|Formatting to make code or markup easier to read}}
'''Prettyprint''' (or '''pretty-print''') is the application of any of various stylistic [[text formatting|formatting]] conventions to [[text file]]s, such as [[source code]], [[markup language|markup]], and similar kinds of content. These formatting conventions can adjust positioning and spacing ([[indent style]]), add color and contrast ([[syntax highlighting]]), adjust size, and make similar modifications intended to make the content easier for people to view, read, and understand. Prettyprinters for programming language source code are sometimes called '''code beautifier'''.
{{Use dmy dates|date=April 2016|cs1-dates=y}}
'''Pretty-printing''' (or '''prettyprinting''') is the application of any of various stylistic [[text formatting|formatting]] conventions to [[text file]]s, such as [[source code]], [[markup language|markup]], and similar kinds of content. These formatting conventions may entail adhering to an [[indentation style]], using different color and typeface to [[Syntax highlighting|highlight syntactic elements]] of source code, or adjusting size, to make the content easier for people to read, and understand. Pretty-printers for source code are sometimes called '''code formatters''' or '''beautifiers'''.


==Pretty-printing mathematics==
==Pretty-printing mathematics==


[[Image:MathematicaTypesetExpression.png|thumb|210px|A typeset mathematical expression]]
[[Image:MathematicaTypesetExpression.png|thumb|210px|A typeset mathematical expression]]
Pretty-printing usually refers to displaying [[mathematical expression]]s similar to the way they would be [[formula editor|typeset]] professionally. For example, in [[computer algebra system]]s such as [[Maxima (software)|Maxima]] or [[Mathematica]] the system may write output like "<tt>x ^ 2 + 3 * x</tt>" as {{No wrap|"<math>x^2+3x</math>".}} Some [[graphing calculator]]s, such as the [[Casio 9860 series]], [[HP-49 series]], [[TI-84 Plus]], [[TI-89]], and [[TI-Nspire]], the [[TI-83 Plus]] with the [http://www.ticalc.org/archives/files/fileinfo/208/20807.html PrettyPt] add-on, or the [[TI-84 Plus]] with the same add-on or the "MathPrint"-enabled OSes, can perform pretty-printing. Additionally, a number of newer scientific calculators are equipped with dot matrix screens capable of pretty-printing such as the Casio FX-ES series (Natural Display), [[Sharp EL-W series]] (WriteView), HP SmartCalc 300s, and [[TI-30#TI-30 models|TI-30XB]].
Pretty-printing usually refers to displaying [[mathematical expression]]s similar to the way they would be [[formula editor|typeset]] professionally. For example, in [[computer algebra system]]s such as [[Maxima (software)|Maxima]] or [[Mathematica]] the system may write output like "<samp>x ^ 2 + 3 * x</samp>" as {{No wrap|"<math>x^2+3x</math>".}} Some [[graphing calculator]]s, such as the [[Casio 9860 series]], [[HP-49 series|HP-49/50 series]] and [[HP Prime]], [[TI-84 Plus]], [[TI-89]], and [[TI-Nspire]], the [[TI-83 Plus]] with the PrettyPt<ref>{{Cite web |title=PrettyPrint - ticalc.org |url=https://www.ticalc.org/archives/files/fileinfo/208/20807.html |access-date=2022-04-13 |website=www.ticalc.org}}</ref> add-on, or the [[TI-84 Plus]] with the same add-on or the "MathPrint"-enabled OSes, can perform pretty-printing. Additionally, a number of newer scientific calculators are equipped with dot matrix screens capable of pretty-printing such as the Casio FX-ES series (Natural Display), [[Sharp EL-W series]] (WriteView), [[HP SmartCalc series|HP SmartCalc 300s]], [[TI-30XB]], and [[NumWorks|Numworks]].


Many text formatting programs can also typeset mathematics: [[TeX]] was developed specifically for high-quality mathematical [[typesetting]].
Many text formatting programs can also typeset mathematics: [[TeX]] was developed specifically for high-quality mathematical [[typesetting]].


==Pretty-printing markup and tag-based code==
==Pretty-printing markup and tag-based code==
[[File:HTML source code example.svg|thumb|HTML source code, pretty-printed to better show the hierarchical relationships of its elements (called tags)]]
Pretty-printing in markup language instances is most typically associated with [[indentation (typesetting)|indentation]] of tags and string content to visually determine hierarchy and nesting. Although the syntactical structures of tag-based languages do not significantly vary, the indentation may vary significantly due to how a markup language is interpreted or due to the data it describes.
Pretty-printing in markup language instances is most typically associated with [[indentation (typesetting)|indentation]] of tags and string content to visually determine hierarchy and nesting. Although the syntactical structures of tag-based languages do not significantly vary, the indentation may vary significantly due to how a markup language is interpreted or due to the data it describes.


In [[MathML]], [[whitespace character]]s do not reflect data, meaning, or syntax above what is required by [[XML]] syntax. In [[HTML]], whitespace characters between tags are considered text and are parsed as text nodes into the parsed result.<ref>{{cite web |url=https://developer.mozilla.org/en-US/docs/Whitespace_in_the_DOM |title=Whitespace in the DOM |first=L. David |last=Baron |publisher=Mozilla Developer Network |accessdate=27 August 2012}}</ref> While indentation may be generously applied to a MathML document, sufficient additional care must be taken in prettyprinting an HTML document to ensure additional text nodes are not created or destroyed in general proximity to the content or content-reflective tag elements. This difference in complexity is non-trivial from the perspective of an automated pretty-print operation where no special rules or edge cases are necessary, as in the more simple MathML example. The HTML example may require a series of progressive interrelated algorithms to account for various patterns of tag elements and content that conforms to a uniform style and is consistent in application across various instances, as evidenced by the [https://github.com/prettydiff/prettydiff/blob/master/beautify/markup.ts markup.ts] application component used to beautify HTML, XML, and related technologies for the [[Pretty Diff]] tool.
In [[MathML]], [[whitespace character]]s do not reflect data, meaning, or syntax above what is required by [[XML]] syntax. In [[HTML]], whitespace characters between tags are considered text and are parsed as text nodes into the parsed result.<ref>{{cite web |url=https://developer.mozilla.org/en-US/docs/Whitespace_in_the_DOM |title=Whitespace in the DOM |first=L. David |last=Baron |publisher=Mozilla Developer Network |accessdate=27 August 2012}}</ref> While indentation may be generously applied to a MathML document, sufficient additional care must be taken in pretty-printing an HTML document to ensure additional text nodes are not created or destroyed in general proximity to the content or content-reflective tag elements. This difference in complexity is non-trivial from the perspective of an automated pretty-print operation where no special rules or edge cases are necessary, as in the more simple MathML example. The HTML example may require a series of progressive interrelated algorithms to account for various patterns of tag elements and content that conforms to a uniform style and is consistent in application across various instances, as evidenced by the markup.ts<ref>[https://github.com/prettydiff/prettydiff/blob/master/beautify/markup.ts markup.ts]</ref> application component used to beautify HTML, XML, and related technologies for the [[Pretty Diff]] tool.


==Programming code formatting and beautification==
==Programming code formatting==
Programmers often use tools to format [[programming language]] [[source code]] in a particular manner. Proper code formatting makes it easier to read and understand. Different programmers often prefer different styles of formatting, such as the use of code [[indentation (typesetting)|indentation]] and whitespace or positioning of [[bracket|braces]]. A code formatter converts source code from one format style to another. This is relatively straightforward because of the unambiguous syntax of programming languages. Code beautification involves parsing the source code into component structures, such as assignment statements, ''if'' blocks, [[program loop|loop]]s, etc. (see also [[control flow]]), and formatting them in a manner specified by the user in a configuration file.
Programmers often use tools to format [[programming language]] [[source code]] in a particular manner. Proper code formatting makes it easier to read and understand. Different programmers often prefer different styles of formatting, such as the use of code [[indentation (typesetting)|indentation]] and whitespace or positioning of [[bracket|braces]]. A code formatter or [[code indenter]] converts source code from one format style to another. This is relatively straightforward because of the unambiguous syntax of programming languages. Code beautification involves parsing the source code into component structures, such as assignment statements, ''if'' blocks, [[program loop|loop]]s, etc. (see also [[control flow]]), and formatting them in a manner specified by the user in a configuration file.


Code beautifiers exist as standalone applications and built into [[text editor]]s and [[integrated development environment]]s. For example, [[Emacs]]' various language modes can correctly [[indentation (typesetting)|indent]] blocks of code attractively.<ref>{{cite web |url=https://www.gnu.org/software/emacs/manual/html_node/emacs/Program-Indent.html#Program-Indent |title=Indentation for Programs |first=Richard M. |last=Stallman |publisher=Free Software Foundation |work=GNU Emacs Manual |accessdate=20 October 2011 }}</ref>
Code beautifiers exist as standalone applications and built into [[text editor]]s and [[integrated development environment]]s. For example, [[Emacs]]' various language modes can correctly [[indentation (typesetting)|indent]] blocks of code attractively.<ref>{{cite web |url=https://www.gnu.org/software/emacs/manual/html_node/emacs/Program-Indent.html#Program-Indent |title=Indentation for Programs |first=Richard M. |last=Stallman |publisher=Free Software Foundation |work=GNU Emacs Manual |accessdate=20 October 2011}}</ref>


===HTML===
===HTML===
Line 22: Line 25:


===Lisp pretty-printer===
===Lisp pretty-printer===
An early example of pretty-printing was [[Bill Gosper]]'s "GRINDEF" (''i.e.'' 'grind function') program (''c.'' 1967), which used [[combinatorial optimization|combinatorial search]] with pruning to format [[Lisp programming language|LISP]] programs. Early versions operated on the executable (list structure) form of the Lisp program and were oblivious to the special meanings of various functions. Later versions had special read conventions for incorporating non-executable comments and also for preserving [[read macro]]s in unexpanded form. They also allowed special indentation conventions for special functions such as <code>if</code>.<ref>Ira Goldstein, "Pretty Printing : Converting List to Linear Structure", Artificial Intelligence Memo 279, Massachusetts Institute of Technology, February 1973. [http://www.softwarepreservation.org/projects/LISP/MIT/AIM-279-Goldstein-Pretty_Printing.pdf/view full text]</ref><ref>Richard C. Waters, "Using the new common Lisp pretty printer", ''ACM SIGPLAN Lisp Pointers'' '''5''':2:27-34, April–June 1992. [ftp://publications.ai.mit.edu/ai-publications/pdf/AIM-1102.pdf full text]</ref>
An early example of pretty-printing was [[Bill Gosper]]'s "GRINDEF" (''i.e.'' 'grind function') program (''c.'' 1967), which used [[combinatorial optimization|combinatorial search]] with pruning to format [[Lisp programming language|LISP]] programs. Early versions operated on the executable (list structure) form of the Lisp program and were oblivious to the special meanings of various functions. Later versions had special read conventions for incorporating non-executable comments and also for preserving [[read macro]]s in unexpanded form. They also allowed special indentation conventions for special functions such as <code>if</code>.<ref>Ira Goldstein, "Pretty Printing : Converting List to Linear Structure", Artificial Intelligence Memo 279, Massachusetts Institute of Technology, February 1973. [http://www.softwarepreservation.org/projects/LISP/MIT/AIM-279-Goldstein-Pretty_Printing.pdf/view full text]</ref><ref>Richard C. Waters, "Using the new common Lisp pretty printer", ''ACM SIGPLAN Lisp Pointers'' '''5''':2:27-34, April–June 1992. [https://web.archive.org/web/20170706120420/ftp://publications.ai.mit.edu/ai-publications/pdf/AIM-1102.pdf full text]</ref> The term "grind" was used in some Lisp circles as a synonym for pretty-printing.<ref>[[Jargon File]], ''s.v.'' grind</ref>
The term "grind" was used in some Lisp circles as a synonym for pretty-printing.<ref>[[Jargon File]], ''s.v.'' grind</ref>


===Project style rules===
===Project style rules===
Many open source projects have established rules for code layout. The most typical are the [https://www.gnu.org/prep/standards/standards.html#Formatting GNU style] and the [http://www.freebsd.org/cgi/man.cgi?query=style&sektion=9 BSD style]. The biggest difference between the two is the location of the braces: in the GNU style, opening and closing braces are on lines by themselves, with the same indent. BSD style places an opening brace at the end of the preceding line, and the closing braces can be followed by '''else'''. The size of indent and location of whitespace also differs.
Many open source projects have established rules for code layout. The most typical are the [[GNU]] formatting<ref>[https://www.gnu.org/prep/standards/standards.html#Formatting GNU style]</ref> and the BSD style.<ref>[http://www.freebsd.org/cgi/man.cgi?query=style&sektion=9 BSD style]</ref> The biggest difference between the two is the location of the braces: in the GNU style, opening and closing braces are on lines by themselves, with the same indent. BSD style places an opening brace at the end of the preceding line, and the closing braces can be followed by '''else'''. The size of indent and location of whitespace also differs.


===Example of formatting and beautifying code===
===Example of formatting and beautifying code===
The following example shows some typical C structures and how various [[indent style|indentation style]] rules format them. Without any formatting at all, it looks like this:
The following example shows some typical C structures and how various [[indentation style]] rules format them. Without any formatting at all, it looks like this:
<source lang="c">
<syntaxhighlight lang="c">
int foo(int k){if(k<1||k>2){printf("out of range\n");
int foo(int k){if(k<1||k>2){printf("out of range\n");
printf("this function requires a value of 1 or 2\n");}else{
printf("this function requires a value of 1 or 2\n");}else{
printf("Switching\n");switch(k){case 1:printf("1\n");break;case
printf("Switching\n");switch(k){case 1:printf("1\n");break;case
2:printf("2\n");break;}}}
2:printf("2\n");break;}}}
</syntaxhighlight>
</source>
The [[indent (Unix)|GNU indent program]] produces the following output when asked to indent according to the [[indent style#GNU style|GNU rules]]:
The [[indent (Unix)|GNU indent program]] produces the following output when asked to indent according to the [[indent style#GNU style|GNU rules]]:
<source lang="c">
<syntaxhighlight lang="c">
int
int
foo (int k)
foo (int k)
Line 60: Line 62:
}
}
}
}
</syntaxhighlight>
</source>
It produces this output when formatting according to BSD rules:
It produces this output when formatting according to BSD rules:
<source lang="c">
<syntaxhighlight lang="c">
int
int
foo(int k) {
foo(int k) {
Line 80: Line 82:
}
}
}
}
</syntaxhighlight>
</source>

==Formatted text==
[[Formatted text]] can be considered a generalized form of pretty-printing.


==See also==
==See also==
Related concepts
*[[Elastic tabstop]], a feature of some source code editors that detects and maintains aligned indents
*[[Elastic tabstop]], a feature of many source code editors that detects and maintains aligned indents
*[[enscript]], a general text printing tool with prettyprinting functions
* [[Minification (programming)|Minification]], making source code compact, even if it becomes harder for humans to understand
*[[indent (Unix)|indent]]
* [[Obfuscation (software)|Obfuscation]], deliberately making source code very difficult for humans to understand - especially as it becomes more convoluted
*[[Pretty Diff]] a pretty printer attached to a [[file comparison]] tool, such as a [[diff utility]]
Utilities


*[[enscript]], a text-to-PostScript converter, with pretty-printing features
==Notes==

<references/>
==References==
{{reflist}}


==External links==
==External links==
*[http://portal.acm.org/citation.cfm?id=365673&dl=ACM&coll=ACM Algorithm 268: ALGOL 60 reference language editor] ''[[William M. McKeeman]]'': Commun. ACM 8(11): 667-668 (1965)
* [http://portal.acm.org/citation.cfm?id=365673&dl=ACM&coll=ACM Algorithm 268: ALGOL 60 reference language editor] ''[[William M. McKeeman]]'': Commun. ACM 8(11): 667-668 (1965)
*[https://www.ctan.org/pkg/lgrind?lang=en lgrind], Comprehensive TEX Archive Network
* [https://www.ctan.org/pkg/lgrind?lang=en lgrind], Comprehensive TEX Archive Network
*[http://doi.acm.org/10.1145/362790.362796 NEATER2: a PL/I source statement reformatter] ''Kenneth Conrow, Ronald G. Smith'': Commun. ACM 13(11): 669-675 (1970)
* [http://doi.acm.org/10.1145/362790.362796 NEATER2: a PL/I source statement reformatter] ''Kenneth Conrow, Ronald G. Smith'': Commun. ACM 13(11): 669-675 (1970)
*[http://comjnl.oxfordjournals.org/cgi/content/abstract/14/2/133 SOAP - A Program which Documents and Edits ALGOL 60 Programs.] ''R. S. Scowen, D. Allin, A. L. Hillman, M. Shimell'': Comput. J. 14(2): 133-135 (1971)
* [http://gtoal.com/languages/algol60/KDF9/SOAP%20description%20and%20Algol60%20source%20-%20CCU6.pdf SOAP - Simplify Obscure Algol Programs] ''R. S. Scowen, D. Allin, A. L. Hillman, M. Shimell'': National Physical Laboratory Central Computer Unit report [https://discovery.nationalarchives.gov.uk/details/r/C4192654 CCU6] (April, 1969) Includes formatted listing of SOAP source code.
** [https://web.archive.org/web/20061012173444/http://comjnl.oxfordjournals.org/cgi/content/abstract/14/2/133 SOAP - A Program which Documents and Edits ALGOL 60 Programs.] ''R. S. Scowen, D. Allin, A. L. Hillman, M. Shimell'': Comput. J. 14(2): 133-135 (1971)
**[https://www.gtoal.com/languages/algol60/KDF9/soap.a60 Original SOAP Source Code from the KDF9]
*[http://history.dcs.ed.ac.uk/archive/os/emas/users/ecslib/emas-a/impis-unpacked/soapdoc.txt SOAP User's Guide.] (for [[Edinburgh IMP]]) ''Peter Salkeld Robertson'' (1976)
** [https://gtoal.com/languages/algol60/KDF9/soap.a60.html Original SOAP Source Code from the KDF9]
* [http://history.dcs.ed.ac.uk/archive/os/emas/users/ecslib/emas-a/impis-unpacked/soapdoc.txt SOAP User's Guide.] (for [[Edinburgh IMP]]) ''Peter Salkeld Robertson'' (1976)
**[http://history.dcs.ed.ac.uk/archive/os/emas/users/ecslib/emas-a/impis-unpacked/soaps.txt SOAP Source Code] in/for [[Edinburgh IMP|IMP9]]
** [http://history.dcs.ed.ac.uk/archive/os/emas/users/ecslib/emas-a/impis-unpacked/soaps.txt SOAP Source Code] in/for [[Edinburgh IMP|IMP9]]
*[http://history.dcs.ed.ac.uk/archive/os/emas/emas2/compilers/imputils/soap80/soap80li.html Soap80: A Program for Formatting IMP80 Source Programs.] ''J.M. Murison, Edinburgh Regional Computer Center'' (1980)
* [http://history.dcs.ed.ac.uk/archive/os/emas/emas2/compilers/imputils/soap80/soap80li.html Soap80: A Program for Formatting IMP80 Source Programs.] ''J.M. Murison, Edinburgh Regional Computer Center'' (1980)
**[http://history.dcs.ed.ac.uk/archive/os/emas/emas2/compilers/imputils/soap80/soap80s.imp.html SOAP Source Code] in/for [[Edinburgh IMP|IMP80]] ''E. N. Gregory, University of Kent at Canterbury; Peter D. Stephens, Edinburgh Regional Computer Center''
** [http://history.dcs.ed.ac.uk/archive/os/emas/emas2/compilers/imputils/soap80/soap80s.imp.html SOAP Source Code] in/for [[Edinburgh IMP|IMP80]] ''E. N. Gregory, University of Kent at Canterbury; Peter D. Stephens, Edinburgh Regional Computer Center''
*[http://www.moorecad.com/standardpascal/prettyp.pas PRETTYP.PAS] Early pascal prettyprinter. ''Ledgard et al.''
* [http://www.moorecad.com/standardpascal/prettyp.pas PRETTYP.PAS] Early pascal prettyprinter. ''Ledgard et al.''
*[http://www.alibris.com/search/books/qwork/5001951/used/Pascal%20with%20Style:%20Programming%20Proverbs Pascal With Style] (1979)
* [http://www.alibris.com/search/books/qwork/5001951/used/Pascal%20with%20Style:%20Programming%20Proverbs Pascal With Style] (1979)
*[http://www.freebsd.org/cgi/man.cgi?query=style&sektion=9 style(9)] FreeBSD style guidelines
* [http://www.freebsd.org/cgi/man.cgi?query=style&sektion=9 style(9)] FreeBSD style guidelines
*[http://heirloom.sourceforge.net/doctools/vgrind.1b.html vgrind], The [Unix] Heirloom Project
* [http://heirloom.sourceforge.net/doctools/vgrind.1b.html vgrind], The [Unix] Heirloom Project
*[https://www.gnu.org/prep/standards/standards.html#Formatting Formatting your source code] GNU style guidelines
* [https://www.gnu.org/prep/standards/standards.html#Formatting Formatting your source code] GNU style guidelines

{{Use dmy dates|date=April 2016}}


[[Category:Articles with example C code]]
[[Category:Articles with example C code]]

Latest revision as of 11:20, 25 June 2024

Pretty-printing (or prettyprinting) is the application of any of various stylistic formatting conventions to text files, such as source code, markup, and similar kinds of content. These formatting conventions may entail adhering to an indentation style, using different color and typeface to highlight syntactic elements of source code, or adjusting size, to make the content easier for people to read, and understand. Pretty-printers for source code are sometimes called code formatters or beautifiers.

Pretty-printing mathematics

[edit]
A typeset mathematical expression

Pretty-printing usually refers to displaying mathematical expressions similar to the way they would be typeset professionally. For example, in computer algebra systems such as Maxima or Mathematica the system may write output like "x ^ 2 + 3 * x" as "". Some graphing calculators, such as the Casio 9860 series, HP-49/50 series and HP Prime, TI-84 Plus, TI-89, and TI-Nspire, the TI-83 Plus with the PrettyPt[1] add-on, or the TI-84 Plus with the same add-on or the "MathPrint"-enabled OSes, can perform pretty-printing. Additionally, a number of newer scientific calculators are equipped with dot matrix screens capable of pretty-printing such as the Casio FX-ES series (Natural Display), Sharp EL-W series (WriteView), HP SmartCalc 300s, TI-30XB, and Numworks.

Many text formatting programs can also typeset mathematics: TeX was developed specifically for high-quality mathematical typesetting.

Pretty-printing markup and tag-based code

[edit]
HTML source code, pretty-printed to better show the hierarchical relationships of its elements (called tags)

Pretty-printing in markup language instances is most typically associated with indentation of tags and string content to visually determine hierarchy and nesting. Although the syntactical structures of tag-based languages do not significantly vary, the indentation may vary significantly due to how a markup language is interpreted or due to the data it describes.

In MathML, whitespace characters do not reflect data, meaning, or syntax above what is required by XML syntax. In HTML, whitespace characters between tags are considered text and are parsed as text nodes into the parsed result.[2] While indentation may be generously applied to a MathML document, sufficient additional care must be taken in pretty-printing an HTML document to ensure additional text nodes are not created or destroyed in general proximity to the content or content-reflective tag elements. This difference in complexity is non-trivial from the perspective of an automated pretty-print operation where no special rules or edge cases are necessary, as in the more simple MathML example. The HTML example may require a series of progressive interrelated algorithms to account for various patterns of tag elements and content that conforms to a uniform style and is consistent in application across various instances, as evidenced by the markup.ts[3] application component used to beautify HTML, XML, and related technologies for the Pretty Diff tool.

Programming code formatting

[edit]

Programmers often use tools to format programming language source code in a particular manner. Proper code formatting makes it easier to read and understand. Different programmers often prefer different styles of formatting, such as the use of code indentation and whitespace or positioning of braces. A code formatter or code indenter converts source code from one format style to another. This is relatively straightforward because of the unambiguous syntax of programming languages. Code beautification involves parsing the source code into component structures, such as assignment statements, if blocks, loops, etc. (see also control flow), and formatting them in a manner specified by the user in a configuration file.

Code beautifiers exist as standalone applications and built into text editors and integrated development environments. For example, Emacs' various language modes can correctly indent blocks of code attractively.[4]

HTML

[edit]

Lisp pretty-printer

[edit]

An early example of pretty-printing was Bill Gosper's "GRINDEF" (i.e. 'grind function') program (c. 1967), which used combinatorial search with pruning to format LISP programs. Early versions operated on the executable (list structure) form of the Lisp program and were oblivious to the special meanings of various functions. Later versions had special read conventions for incorporating non-executable comments and also for preserving read macros in unexpanded form. They also allowed special indentation conventions for special functions such as if.[5][6] The term "grind" was used in some Lisp circles as a synonym for pretty-printing.[7]

Project style rules

[edit]

Many open source projects have established rules for code layout. The most typical are the GNU formatting[8] and the BSD style.[9] The biggest difference between the two is the location of the braces: in the GNU style, opening and closing braces are on lines by themselves, with the same indent. BSD style places an opening brace at the end of the preceding line, and the closing braces can be followed by else. The size of indent and location of whitespace also differs.

Example of formatting and beautifying code

[edit]

The following example shows some typical C structures and how various indentation style rules format them. Without any formatting at all, it looks like this:

int foo(int k){if(k<1||k>2){printf("out of range\n");
printf("this function requires a value of 1 or 2\n");}else{
printf("Switching\n");switch(k){case 1:printf("1\n");break;case
2:printf("2\n");break;}}}

The GNU indent program produces the following output when asked to indent according to the GNU rules:

int
foo (int k)
{
  if (k < 1 || k > 2)
    {
      printf ("out of range\n");
      printf ("this function requires a value of 1 or 2\n");
    }
  else
    {
      printf ("Switching\n");
      switch (k)
        {
        case 1:
          printf ("1\n");
          break;
        case 2:
          printf ("2\n");
          break;
        }
    }
}

It produces this output when formatting according to BSD rules:

int
foo(int k) {
	if (k < 1 || k > 2) {
		printf("out of range\n");
		printf("this function requires a value of 1 or 2\n");
	} else {
		printf("Switching\n");
		switch (k) {
		case 1:
			printf("1\n");
			break;
		case 2:
			printf("2\n");
			break;
		}
	}
}

See also

[edit]

Related concepts

  • Elastic tabstop, a feature of many source code editors that detects and maintains aligned indents
  • Minification, making source code compact, even if it becomes harder for humans to understand
  • Obfuscation, deliberately making source code very difficult for humans to understand - especially as it becomes more convoluted

Utilities

  • enscript, a text-to-PostScript converter, with pretty-printing features

References

[edit]
  1. ^ "PrettyPrint - ticalc.org". www.ticalc.org. Retrieved 2022-04-13.
  2. ^ Baron, L. David. "Whitespace in the DOM". Mozilla Developer Network. Retrieved 2012-08-27.
  3. ^ markup.ts
  4. ^ Stallman, Richard M. "Indentation for Programs". GNU Emacs Manual. Free Software Foundation. Retrieved 2011-10-20.
  5. ^ Ira Goldstein, "Pretty Printing : Converting List to Linear Structure", Artificial Intelligence Memo 279, Massachusetts Institute of Technology, February 1973. full text
  6. ^ Richard C. Waters, "Using the new common Lisp pretty printer", ACM SIGPLAN Lisp Pointers 5:2:27-34, April–June 1992. full text
  7. ^ Jargon File, s.v. grind
  8. ^ GNU style
  9. ^ BSD style
[edit]