Difference between revisions of "Verbatim text"

From Wiki
Jump to navigation Jump to search
(scite pretty printing)
(28 intermediate revisions by 13 users not shown)
Line 2: Line 2:
  
 
=Displayed text=
 
=Displayed text=
<cmd>starttyping</cmd>,
+
{{cmd|starttyping}},
<cmd>typebuffer</cmd>
+
{{cmd|typebuffer}}
  
 
Unlike LaTeX's <code>verbatim</code> environment, ConTeXt's <code>typing</code> environments have quite a range of built-in options for formatting the verbatim text, see below.
 
Unlike LaTeX's <code>verbatim</code> environment, ConTeXt's <code>typing</code> environments have quite a range of built-in options for formatting the verbatim text, see below.
  
=In-line text=
+
=Inline text=
  
<code>\startTEX ... \stopTEX</code> only works when typesetting the whole paragraph. If you need to type only a command or two as in-line text, you can use the following [[User:Taco|Taco's]] macro (hopefully this will land in the core once in the future):
+
To typeset code inside the paragraph, you have the command <code>\type</code>. It can be configured with <code>\setuptype[type][...]</code>.
  
<texcode>
+
To have colored code, you need to use <code>\definetype[NAME][option=TEX]</code> and use it with the name you chose. Other values are: <code>mp lua xml parsed-xml nested tex context</code>.
\def\typeTEX
+
 
  {\bgroup
+
An example that shows both features:
  \def\processinlineverbatim##1%
+
 
    {\processingverbatimtrue
+
<context source="yes">
      \localcatcodestrue
+
\definetype[inlineTEX][option=TEX]
      \def\endofverbatimcommand{\TEXendofcommand##1}%
+
 
      \bgroup
+
This is the way to type code: \type{the \ConTeXt\ command}.
      \aftergroup\endofverbatimcommand
 
      \futurelet\next\doprocessinlineverbatim}%
 
  \initializetyping{TEX}%
 
  \startverbatimcolor
 
  \processinlineverbatim\egroup }
 
</texcode>
 
  
Now you can say:
+
And this is the way to have colored code: \inlineTEX{the \ConTeXt\ command},
 +
</context>
  
<texcode>
+
= Making a tight vertical fit =
\typeTEX+\typeTEX{\typeTEX is a wonderful macro}+, isn't it?
+
By default, typing environments include some blank space before the first line and after the last line of the verbatim text. This is because the <tt>before</tt> and <tt>after</tt> commands are set to <tt>\blank</tt> by default. For example:
</texcode>
 
<context>
 
\setupcolors[state=start]
 
\def\typeTEX
 
  {\bgroup
 
  \def\processinlineverbatim##1%
 
    {\processingverbatimtrue
 
      \localcatcodestrue
 
      \def\endofverbatimcommand{\TEXendofcommand##1}%
 
      \bgroup
 
      \aftergroup\endofverbatimcommand
 
      \futurelet\next\doprocessinlineverbatim}%
 
  \initializetyping{TEX}%
 
  \startverbatimcolor
 
  \processinlineverbatim\egroup }
 
  
\typeTEX+\typeTEX{\typeTEX is a wonderful macro}+, isn't it?
+
<context source="yes">
 +
\framed[offset=0mm,strut=no,align=right]{
 +
\starttyping
 +
Foo
 +
\stoptyping
 +
}
 
</context>
 
</context>
  
Source: [http://archive.contextgarden.net/thread/20050907.093522.baf795f5.en.html]
+
Here, we've added a <tt>\framed</tt> so you can see the extra spacing, but with <tt>offset=0mm</tt> and <tt>strut=no</tt> to prevent framed from introducing spacing, and <tt>align=right</tt> to prevent framed from eating all newlines (not sure why that works like this).
 +
 
 +
To prevent this extra vertical space, we must unset the <tt>before</tt> and <tt>after</tt> options:
 +
<context source="yes">
 +
\setuptyping[before=,after=]
 +
\framed[offset=0mm,strut=no,align=right]{
 +
\starttyping
 +
Foo
 +
\stoptyping
 +
}
 +
</context>
  
 
= Embedded formatting commands =
 
= Embedded formatting commands =
Line 75: Line 70:
 
\stopC
 
\stopC
 
</context>
 
</context>
 +
 +
In mkiv option-commands is gone and escape no longer is an escape character but a condition (range or start), as in this example:
 +
 +
<texcode>
 +
\setuptyping[TEX][escape=yes]
 +
 +
\startTEX
 +
/BTEX\em sometex/ETEX
 +
/BTEX\em sometex/ETEX \after
 +
\before /BTEX\em sometex/ETEX
 +
\before /BTEX\em sometex/ETEX \after
 +
\before /BTEX\em sometex/ETEX \inbetween /BTEX\em sometex/ETEX \after
 +
\before \after
 +
\stopTEX
 +
 +
\setuptyping[TEX][escape={[[,]]}]
 +
 +
\startTEX
 +
[[\em sometex]]
 +
[[\em sometex]] \after
 +
\before [[\em sometex]]
 +
\before [[\em sometex]] \after
 +
\before [[\em sometex]] \inbetween [[\em sometex]] \after
 +
\before \after
 +
\stopTEX
 +
 +
\setuptyping[TEX][escape=//]
 +
 +
\startTEX
 +
//\em sometex
 +
\before //\em sometex
 +
\stopTEX
 +
</texcode>
 +
 +
[[Image:Verbatim-mkiv.png‎]]
 +
 +
= Pretty printing =
 +
The context distribution includes a number of formatters (or pretty
 +
printers), that can apply some nice formatting to your verbatim text.
 +
Each formatter knows how to handle a specific file format or programming
 +
language and applies syntax highlighting or other fancy displaying.
 +
 +
ConTeXt includes a number of predefined formatters, but it is also
 +
possible to define your own. Pretty printing has been completely
 +
redesigned in MkIV, so there are a few differences between MkII and
 +
MkIV. In particular, MkII commonly refers to "formatters", while MkIV
 +
often uses "pretty printers".
  
 
== Included Formatters ==
 
== Included Formatters ==
 
+
There are already some formatters for several programming languages in
There are already some formatters for several programming languages in the ConTeXt distribution:
+
the ConTeXt distributionr. The following list is for MkII and MkIV.
  
 
{|
 
{|
  ! Code !! Language
+
  ! Language !! Code for MkII !! Code for MkIV
 
  |-
 
  |-
  | [[source:verb-c.tex|C]] || C
+
  | C || [[source:verb-c.mkii|C]] || [[modules:pret-c|C]]
 
  |-
 
  |-
  | [[source:verb-eif.tex|EIF]] || Eiffel
+
  | Eiffel || [[source:verb-eif.mkii|EIF]] ||
 
  |-
 
  |-
  | [[source:verb-js.tex|JS]] || JavaScript
+
  | JavaScript || [[source:verb-js.mkii|JS]] ||
 
  |-
 
  |-
  | [[source:verb-jv.tex|JV]] || Java
+
  | Java || [[source:verb-jv.mkii|JV]] ||
 
  |-
 
  |-
  | [[source:verb-mp.tex|MP]] || MetaPost & MetaFont
+
  | Lua || || [[source:pret-lua.lua|LUA]]
 
  |-
 
  |-
  | [[source:verb-pas.tex|PAS]] || Pascal & Modula
+
  | MetaPost & MetaFont || [[source:verb-mp.mkii|MP]] || [[source:pret-mp.lua|MP]]
 
  |-
 
  |-
  | [[source:verb-pl.tex|PL]] || Perl 5
+
  | Pascal & Modula || [[source:verb-pas.mkii|PAS]] ||
 
  |-
 
  |-
  | [[source:verb-sql.tex|SQL]] || SQL
+
  | Perl 5 || [[source:verb-pl.mkii|PL]] ||
 
  |-
 
  |-
  | [[source:verb-tex.tex|TEX]] || TeX
+
  | SQL || [[source:verb-sql.mkii|SQL]] ||
 
  |-
 
  |-
  | [[source:verb-xml.tex|XML]] || XML
+
  | TeX || [[source:verb-tex.mkii|TEX]] || [[source:pret-tex.lua|TEX]]
 +
|-
 +
| XML || [[source:verb-xml.mkii|XML]] || [[source:pret-xml.lua|XML]]
 
  |-
 
  |-
 
|}
 
|}
  
 
== Your own formatter ==
 
== Your own formatter ==
 
(from a ML answer by Taco, 2006-12-25, "Making a verbatim file for another language")
 
  
 
You should start from the definition that is closest to the language you want to define (especially wrt comment and string syntax) and can probably have a go at making a version of this. Some   
 
You should start from the definition that is closest to the language you want to define (especially wrt comment and string syntax) and can probably have a go at making a version of this. Some   
 
questions occur:
 
questions occur:
 +
 +
=== How should I name my file? ===
 +
; MkII: <tt>verb-xxxx.tex</tt>, where <tt>xxxx</tt> is the lowercase name of the formatter.
 +
; MkIV: <tt>pret-xxxx.lua</tt>, where <tt>xxxx</tt> is the lowercase name of the pretty printer.
  
 
=== Where should i put my file? ===
 
=== Where should i put my file? ===
Line 121: Line 167:
 
=== Do I have to do anything else to get ConTeXt to recognise and use it? ===
 
=== Do I have to do anything else to get ConTeXt to recognise and use it? ===
  
Your file has to have a name like <tt>verb-xxxx.tex</tt>, with <tt>xxxx</tt> a lowercase short identifier (example: verb-php.tex), and then you have to use one or two commands to make ConTeXt use the file.
+
You refer to a pretty printer using its name (''e.g.'', the
 +
<tt>xxxx</tt> in <tt>verb-xxxx.tex</tt> or <tt>pret-xxxx.lua</tt>),
 +
which should be in lowercase. Before you can use a pretty printer, you
 +
should let ConTeXt know about it (this has already been done for the
 +
included formatters).
  
First:
 
 
<texcode>
 
<texcode>
 
\installprettytype [PHP]        [PHP]
 
\installprettytype [PHP]        [PHP]
 
</texcode>
 
</texcode>
This maps the command <code>\starttyping[option=PHP]</code> to <tt>verb-php.tex</tt>.
 
  
The first argument is the option as passed to \starttyping, the second argument is an uppercase version of <tt>xxxx</tt> (thus allowing ConTeXt to find the file),
+
This maps the command <code>\starttyping[option=PHP]</code> to the
 +
<tt>php</tt> pretty printer.
 +
 
 +
The first argument is the option as passed to \starttyping, the second
 +
argument is an uppercase version of the pretty printer name
 +
(''e.g.'' <tt>xxxx</tt>) (thus allowing ConTeXt to find the file).
  
 
And you probably also want:
 
And you probably also want:
Line 135: Line 188:
 
\definetyping[PHP]  [option=PHP]
 
\definetyping[PHP]  [option=PHP]
 
</texcode>
 
</texcode>
Because that allows  <code>\startPHP ... \stopPHP</code> as a shortcut to <tt>\setuptyping[option=PHP]</tt>
+
Because that allows  <code>\startPHP ... \stopPHP</code> as a shortcut
 +
to <tt>\starttyping[option=PHP] ... \stoptyping</tt>.
 +
 
 +
=== How to write the pretty printer? ===
 +
For MkII, there seems to be no real documentation here. You should take
 +
a good look at the existing formatters and base your work off those.
 +
However, if you really need custom pretty printing, you might be better
 +
of to look at MkIV instead, since that allows you to write a pretty
 +
printer in lua, which is a lot less painful than writing them in plain
 +
TeX.
 +
 
 +
For MkIV, you should simply write a lua script that processes each line
 +
of input and produces tex output. The details about this are discussed
 +
at [[Custom_pretty_printer]].
  
=== Wait for LuaTeX ===
+
== Improved pretty printing ==
  
Unless you need that highlighting urgently, I would wait for LuaTeX and write it in lua then (which is certainly less painful than writing it in plain TeX). But it's up to you. I found those TeX definitions too complicated to even try to understand, I would never dare to try writing one by myself. -- Mojca
+
Default ConTeXt comment handling can be shown in the following sample:
 +
 
 +
<context source="yes">
 +
\starttext
 +
\startbuffer[texcode]
 +
This is text. % and this is a comment
 +
\stopbuffer
 +
 
 +
\startbuffer[xmlcode]
 +
<p>This is text.<!--and this is a comment--></p>
 +
\stopbuffer
 +
 
 +
\startbuffer[luacode]
 +
if code=="code" then --this is a comment
 +
 
 +
--[[
 +
this is a
 +
 
 +
multiline comment
 +
--]]
 +
 
 +
---[[
 +
but this isn’t a
 +
 
 +
multiline comment
 +
--]]
 +
\stopbuffer
 +
 
 +
\typebuffer[texcode][option=TEX]
 +
\typebuffer[xmlcode][option=XML]
 +
\typebuffer[luacode][option=LUA]
 +
\stoptext
 +
</context>
 +
 
 +
If you want to improve Lua multiline comments and to color the whole comments (not only the comment marker), write <code>\usemodule[scite]</code> before <code>\starttext</code>. (I cannot show it here, since ConTeXt at the wiki seems to have a problem with that.)
  
 
= Tabbing =
 
= Tabbing =
Line 295: Line 395:
 
\stoptext
 
\stoptext
 
</context>
 
</context>
 +
 +
= Colored background =
 +
 +
<texcode>
 +
\setupcolors[state=start]
 +
 +
\definetextbackground[verbatim]
 +
[background=color,
 +
backgroundcolor=yellow,
 +
backgroundoffset=0cm,
 +
offset=0.5cm,
 +
frame=on,
 +
framecolor=black,
 +
location=paragraph,
 +
color=black]
 +
 +
% Setup verbatim
 +
\setuptyping[typing][margin=1cm,bodyfont=8.0pt,
 +
before={\starttextbackground[verbatim]},
 +
after={\stoptextbackground}]
 +
 +
\starttext
 +
\starttyping
 +
This is the first line.
 +
This is the second line.
 +
\stoptyping
 +
\stoptext
 +
</texcode>
  
 
= Line numbering =
 
= Line numbering =
  
In technical documents it can be required to display some code listings with the line numbers. You can do this with ConTeXt, and even more. All the features shown here are also available when displaying external files with <cmd>typefile</cmd>.
+
In technical documents it can be required to display some code listings with the line numbers. You can do this with ConTeXt, and even more. All the features shown here are also available when displaying external files with {{cmd|typefile}}.
  
 
== Preliminary setting ==
 
== Preliminary setting ==
Line 355: Line 483:
  
 
== Line numbers in the text ==
 
== Line numbers in the text ==
To have the line numbers in the text, change the linenumbering setup like this:
+
To have the line numbers in the text, change the linenumbering setup like this (<tt>location=text</tt> for mkiv resp.):
  
 
<texcode>
 
<texcode>
Line 510: Line 638:
 
\stopcode
 
\stopcode
 
</context>
 
</context>
 +
 +
== Referencing line numbers ==
 +
The following example from the mailing list [http://archive.contextgarden.net/thread/20101026.191201.55344b94.en.html#20101026.191201.55344b94] shows how to reference line numbers from a typing in the surrounding text (MkIV).
 +
 +
<texcode>
 +
\setuptyping[numbering=line,escape=yes]
 +
 +
\starttext
 +
 +
See \inline[line:single] and also \inline[line:range].
 +
 +
See \inline{typeline}[line:single] and also \inline{typelines}[line:range].
 +
 +
See line~\inlinerange[line:single] and also lines~\inlinerange[line:range].
 +
 +
\starttyping
 +
line 1
 +
line 2/BTEX\startline[line:range]/ETEX
 +
line 3/BTEX\someline[line:single]/ETEX
 +
line 4
 +
line 5/BTEX\stopline[line:range]/ETEX
 +
line 6
 +
\stoptyping
 +
 +
\stoptext
 +
</texcode>
  
  
Line 518: Line 672:
 
a) you are much more fluent in another programming language  than TeX  
 
a) you are much more fluent in another programming language  than TeX  
  
b) you have  a large project involving many code snippet to be inserted and colorized
+
b) you have  a large project involving many code snippets to be inserted and colorized
  
 
you can go for another, less elegant, way to format your verbatim text, which can include all the discussed ConTeXt benefits.  
 
you can go for another, less elegant, way to format your verbatim text, which can include all the discussed ConTeXt benefits.  
Line 524: Line 678:
 
== Writing  a parser/formatter ==
 
== Writing  a parser/formatter ==
  
It fairly simple to write a little parser which takes as its input your source file and gives in output a .tex file containing the code plus the opportune commands for colorization. You can then include the resulting .tex file in the global ConTeXt document file.
+
It is fairly simple to write a little parser which takes as its input your source file and gives in output a .tex file containing the code plus the opportune commands for colorization. You can then include the resulting .tex file in the global ConTeXt document file.
As an example, [http://www.cirma.unito.it/andrea/sw/sc/scToConTeXt.py this] is a Python script for the SuperCollider language, which has a striclty Smalltalk-like syntax.
+
As an example, [http://www.fonurgia.unito.it/andrea/sw/sc/scToConTeXt.py this] is a Python script for the SuperCollider language, which has a strict Smalltalk-like syntax.
  
Fed with this source code contained in example.sc file:
+
Fed with the following source code contained in e.g. example.sc file:
  
  
Line 547: Line 701:
 
<texcode>
 
<texcode>
 
\startSC
 
\startSC
/BTEX{\color[SCred] //// an example starting with a comment}/ETEX
+
/BTEX\color[SCred]{//// an example starting with a comment}/ETEX
/BTEX{\color[SCgrey] "this is a string"}/ETEX .postln ;
+
/BTEX\color[SCgrey]{"this is a string"}/ETEX .postln ;
  
/BTEX{\color[SCgreen] \letterbackslash aSymbol}/ETEX  ;
+
/BTEX\color[SCgreen]{\letterbackslash aSymbol}/ETEX  ;
  
/BTEX{\color[SCblue] ThisClassDoesNotExists}/ETEX  ;
+
/BTEX\color[SCblue]{ThisClassDoesNotExists}/ETEX  ;
 
\stopSC
 
\stopSC
 
</texcode>
 
</texcode>
  
 
Basically, the idea is to envelope each item to be colorized inside a /BTEX /ETEX block.  
 
Basically, the idea is to envelope each item to be colorized inside a /BTEX /ETEX block.  
Note that inside the block the text is no more verbatim, so you have to define some string replacement for special characters (e.g. _, %, $, \, etc).  
+
Note that inside the block the text is no more verbatim, so you have to define some string replacements for special characters (e.g. _, %, $, \, etc).  
As an example, the problem of the backslash (\) is solved here by replacing it with \letterbackslash. The example uses some definitions (explained before) which have to be put in the global ConTeXt file
+
As an example, the problem of the backslash (\) is solved here by replacing it with \letterbackslash.  
 +
 
 +
You can then insert example.tex in your ConTeXt file with
 +
 
 +
<texcode>
 +
\input example
 +
</texcode>
 +
 
 +
 
 +
The example.tex file uses some definitions (explained in the previous sections) which have to be put in the ConTeXt file (use <tt>escape=yes</tt> instead of <tt>option=commands</tt> for mkiv).
  
 
<texcode>
 
<texcode>
Line 575: Line 738:
 
</texcode>
 
</texcode>
  
also, example.tex requires color definitions, which are created following SuperCollider colorization interpreter scheme and have to be inserted in  the global ConTeXt file:
+
Also, example.tex requires color definitions, which are created following SuperCollider colorization interpreter scheme and have to be inserted in  the ConTeXt file too:
  
 
<texcode>
 
<texcode>
Line 589: Line 752:
 
</texcode>
 
</texcode>
 
   
 
   
You can then insert example.tex in the global ConTeXt file with
+
The previous definitions will be used for all the code files  inserted with \input.
 
+
After compiling, this is the result of the discussed example:
<texcode>
 
\input example
 
</texcode>
 
  
After compiling, this is the result.
 
  
 
<context>
 
<context>
Line 627: Line 786:
 
/BTEX{\color[SCgrey] "this is a string"}/ETEX .postln ;
 
/BTEX{\color[SCgrey] "this is a string"}/ETEX .postln ;
  
/BTEX{\color[SCgreen] \type{\}aSymbol}/ETEX  ;
+
/BTEX{\color[SCgreen] \letterbackslash aSymbol}/ETEX  ;
  
/BTEX{\color[SCblue] ThisClassDoesNotExist}/ETEX  
+
/BTEX{\color[SCblue] ThisClassDoesNotExists}/ETEX ;
 
\stopSC
 
\stopSC
  
Line 637: Line 796:
 
== Embedding the source code ==
 
== Embedding the source code ==
  
If your document is inteded to provide code examples to be tested by the readers, the presence of format signs (e.g. line numbers) can create some troubles while copying and pasting the code text from your document to the language environment. More generally, the copy and paste approach, being slow and possbily related to encodings, is not satisfying at all.
+
If your document is inteded to provide code examples to be tested by the readers, the presence of format signs (e.g. line numbers) can create some troubles while copying and pasting the code text from your document to the language environment. More generally, the copy and paste approach, being slow and possibly related to encodings, is not satisfying at all.
 
You can include source files in the pdf with a couple of ConTeXt commands:
 
You can include source files in the pdf with a couple of ConTeXt commands:
  
Line 645: Line 804:
 
</texcode>
 
</texcode>
  
The commands embed example.sc in the pdf, so that it is accessible by double-clicking on a generated icon.
+
 
If you use Acrobat Reader (Preview.app in MacOSX does not provide support for the behaviour) example.sc will be open in the related application (i.e. SuperCollider.app).
+
So that you can have this structure for each code snippet:
 +
 
 +
<texcode>
 +
\input example
 +
 
 +
\useattachment[ex][example.sc]
 +
\attachment[ex]
 +
</texcode>
 +
 
 +
 
 +
The commands embed example.sc in the pdf, so that it is accessible by double-clicking on a generated icon. In this case the icon is placed after the colorized code frame.
 +
If you use Acrobat Reader (Preview.app in MacOSX does not provide support for the behaviour) example.sc will be open in the related application (e.g. SuperCollider.app in the discussed case).
  
  

Revision as of 10:27, 3 September 2017

< Visuals | Verbatim with line breaks >

Displayed text

\starttyping, \typebuffer

Unlike LaTeX's verbatim environment, ConTeXt's typing environments have quite a range of built-in options for formatting the verbatim text, see below.

Inline text

To typeset code inside the paragraph, you have the command \type. It can be configured with \setuptype[type][...].

To have colored code, you need to use \definetype[NAME][option=TEX] and use it with the name you chose. Other values are: mp lua xml parsed-xml nested tex context.

An example that shows both features:

\definetype[inlineTEX][option=TEX]

This is the way to type code: \type{the \ConTeXt\ command}.

And this is the way to have colored code: \inlineTEX{the \ConTeXt\ command},

Making a tight vertical fit

By default, typing environments include some blank space before the first line and after the last line of the verbatim text. This is because the before and after commands are set to \blank by default. For example:

\framed[offset=0mm,strut=no,align=right]{
\starttyping
Foo
\stoptyping
}

Here, we've added a \framed so you can see the extra spacing, but with offset=0mm and strut=no to prevent framed from introducing spacing, and align=right to prevent framed from eating all newlines (not sure why that works like this).

To prevent this extra vertical space, we must unset the before and after options:

\setuptyping[before=,after=]
\framed[offset=0mm,strut=no,align=right]{
\starttyping
Foo
\stoptyping
}

Embedded formatting commands

The option=commands setting allows the usage of ConTeXt commands inside verbatim text, as in this example:

\definetyping[C][option=commands]
\startC
#include <stdio.h>
int main(){
	return 0;
	/BTEX{\em unreachedCode;}/ETEX
}
\stopC

In mkiv option-commands is gone and escape no longer is an escape character but a condition (range or start), as in this example:

\setuptyping[TEX][escape=yes]

\startTEX
/BTEX\em sometex/ETEX
/BTEX\em sometex/ETEX \after
\before /BTEX\em sometex/ETEX
\before /BTEX\em sometex/ETEX \after
\before /BTEX\em sometex/ETEX \inbetween /BTEX\em sometex/ETEX \after
\before \after
\stopTEX

\setuptyping[TEX][escape={[[,]]}]

\startTEX
[[\em sometex]]
[[\em sometex]] \after
\before [[\em sometex]]
\before [[\em sometex]] \after
\before [[\em sometex]] \inbetween [[\em sometex]] \after
\before \after
\stopTEX

\setuptyping[TEX][escape=//]

\startTEX
//\em sometex
\before //\em sometex
\stopTEX

Verbatim-mkiv.png

Pretty printing

The context distribution includes a number of formatters (or pretty printers), that can apply some nice formatting to your verbatim text. Each formatter knows how to handle a specific file format or programming language and applies syntax highlighting or other fancy displaying.

ConTeXt includes a number of predefined formatters, but it is also possible to define your own. Pretty printing has been completely redesigned in MkIV, so there are a few differences between MkII and MkIV. In particular, MkII commonly refers to "formatters", while MkIV often uses "pretty printers".

Included Formatters

There are already some formatters for several programming languages in the ConTeXt distributionr. The following list is for MkII and MkIV.

Language Code for MkII Code for MkIV
C C C
Eiffel EIF
JavaScript JS
Java JV
Lua LUA
MetaPost & MetaFont MP MP
Pascal & Modula PAS
Perl 5 PL
SQL SQL
TeX TEX TEX
XML XML XML

Your own formatter

You should start from the definition that is closest to the language you want to define (especially wrt comment and string syntax) and can probably have a go at making a version of this. Some questions occur:

How should I name my file?

MkII
verb-xxxx.tex, where xxxx is the lowercase name of the formatter.
MkIV
pret-xxxx.lua, where xxxx is the lowercase name of the pretty printer.

Where should i put my file?

  1. Possibly the best place is: In the context distribution, but that depends a bit on what language it is, precisely (you can email me the completed file, in that case).
  2. Second best place: http://modules.contextgarden.net, so it can be included in cont-ext.zip (third-party addons that are distributed by Pragma-Ade alongside the normal distribution).
  3. Third best: The directory <$HOME/texmf/tex/context/base> (the place where your TeX installation finds local files).
  4. Final option: Same directory as the file to be processed

Do I have to do anything else to get ConTeXt to recognise and use it?

You refer to a pretty printer using its name (e.g., the xxxx in verb-xxxx.tex or pret-xxxx.lua), which should be in lowercase. Before you can use a pretty printer, you should let ConTeXt know about it (this has already been done for the included formatters).

\installprettytype [PHP]        [PHP]

This maps the command \starttyping[option=PHP] to the php pretty printer.

The first argument is the option as passed to \starttyping, the second argument is an uppercase version of the pretty printer name (e.g. xxxx) (thus allowing ConTeXt to find the file).

And you probably also want:

\definetyping[PHP]   [option=PHP]

Because that allows \startPHP ... \stopPHP as a shortcut to \starttyping[option=PHP] ... \stoptyping.

How to write the pretty printer?

For MkII, there seems to be no real documentation here. You should take a good look at the existing formatters and base your work off those. However, if you really need custom pretty printing, you might be better of to look at MkIV instead, since that allows you to write a pretty printer in lua, which is a lot less painful than writing them in plain TeX.

For MkIV, you should simply write a lua script that processes each line of input and produces tex output. The details about this are discussed at Custom_pretty_printer.

Improved pretty printing

Default ConTeXt comment handling can be shown in the following sample:

\starttext
\startbuffer[texcode]
This is text. % and this is a comment
\stopbuffer

\startbuffer[xmlcode]

This is text.

\stopbuffer \startbuffer[luacode] if code=="code" then --this is a comment --[[ this is a multiline comment --]] ---[[ but this isn’t a multiline comment --]] \stopbuffer \typebuffer[texcode][option=TEX] \typebuffer[xmlcode][option=XML] \typebuffer[luacode][option=LUA] \stoptext

If you want to improve Lua multiline comments and to color the whole comments (not only the comment marker), write \usemodule[scite] before \starttext. (I cannot show it here, since ConTeXt at the wiki seems to have a problem with that.)

Tabbing

The tab character normally corresponds to one character, as can be seen above. That value can be adjusted, using the following code (available in the 2005.06.01 version and later):

\definetyping[C][tab=3]
% for older ConTeXt versions: \chardef\spacespertab=3
\startC
int func(int a){
	if(a > 4)
		return 0;
	else
		return 10;
}
\stopC

Syntax highlighting in color

\setupcolors[state=start]
\setuptyping[option=color]

\starttext
\startXML
... your XML code ...
\stopXML
\stoptext

Defining your own set of colors

Sometimes you may be not quite satisfied with the default colors used in the built-in syntax highlighting. Taco posted this solution in the discussion on the mailing list:

\setupcolors[state=start]
\setuptyping[option=color]

% define the colors to fit your document style
\definecolor[MYcolorone]  [r=.8,g=.5,b=.5]
\definecolor[MYcolortwo]  [r=.8,g=.5,b=.2]
\definecolor[MYcolorthree][r=.8,g=.5,b=.8]
\definecolor[MYcolorfour] [r=.8,g=.2,b=.5]

% define a palete using these four colors
\definepalet[MYcolors]
  [prettyone=MYcolorone,
   prettytwo=MYcolortwo,
   prettythree=MYcolorthree,
   prettyfour=MYcolorfour]

% XML code will be typeset with the palette you just defined
\definepalet[XMLcolorpretty] [MYcolors] % the name is magic !

\starttext
\startXML
... your XML code ...
\stopXML
\stoptext

This results in:

Colored background

\setupcolors[state=start]

\definetextbackground[verbatim]
[background=color,
backgroundcolor=yellow,
backgroundoffset=0cm,
offset=0.5cm,
frame=on,
framecolor=black,
location=paragraph,
color=black]

% Setup verbatim
\setuptyping[typing][margin=1cm,bodyfont=8.0pt,
before={\starttextbackground[verbatim]},
after={\stoptextbackground}]

\starttext
\starttyping
This is the first line.
This is the second line.
\stoptyping
\stoptext

Line numbering

In technical documents it can be required to display some code listings with the line numbers. You can do this with ConTeXt, and even more. All the features shown here are also available when displaying external files with \typefile.

Preliminary setting

Let's define our own typing style, named "code". The typing is put in a framedtext, to demonstrate the wrapping feature in a next section.

\defineframedtext
  [framedcode]
  [strut=yes,
   offset=2mm,
   width=7cm,
   align=right]

\definetyping[code][numbering=line,
                    bodyfont=small,
                    before={\startframedcode},
                    after={\stopframedcode}]

Default line numbering

With the defined typing, every line is numbered, and the number goes in the margin. The option to have the line numbers displayed is numbering=line.

\startcode
This is the first line
This is a rather long line that is wrapped, so look how the line numbering is done
Another line

Last line after an empty line
\stopcode

It is rendered as:

Line numbers in the text

To have the line numbers in the text, change the linenumbering setup like this (location=text for mkiv resp.):

\setuplinenumbering[location=intext]
\startcode
This is the first line
This is a rather long line that is wrapped, so look how the line numbering is done
Another line

Last line after an empty line
\stopcode

Continuing the numbering

Another handy feature is the ability to continue the numbering from one portion of code to another. Use the option continue for this.

\startcode
This is the first line
This is a rather long line that is wrapped, so look how the line numbering is done
Another line

Last line after an empty line
\stopcode

Some normal text to explain the first piece of code,
and introduce the following lines.

\startcode[continue]
This is the first continuing line
This is a rather long line that is wrapped, so look how the line numbering is done
Another line
Last line
\stopcode

Arbitrary starting line number

You can also decide what the starting line number is. Use the option start=number for this.

\startcode[start=200]
This is the first line
This is a rather long line that is wrapped, so look how the line numbering is done
Another line
Last line
\stopcode

Line number steps

You want to print a number every two lines? Ok, just use the option step=number for this.

\startcode[start=200,step=2]
This is the first line
This is a rather long line that is wrapped, so look how the line numbering is done
Another line
Last line
\stopcode

Referencing line numbers

The following example from the mailing list [1] shows how to reference line numbers from a typing in the surrounding text (MkIV).

\setuptyping[numbering=line,escape=yes]

\starttext

See \inline[line:single] and also \inline[line:range].

See \inline{typeline}[line:single] and also \inline{typelines}[line:range].

See line~\inlinerange[line:single] and also lines~\inlinerange[line:range].

\starttyping
line 1
line 2/BTEX\startline[line:range]/ETEX
line 3/BTEX\someline[line:single]/ETEX
line 4
line 5/BTEX\stopline[line:range]/ETEX
line 6
\stoptyping

\stoptext


A different approach to formatting and code colorization

Supposing that:

a) you are much more fluent in another programming language than TeX

b) you have a large project involving many code snippets to be inserted and colorized

you can go for another, less elegant, way to format your verbatim text, which can include all the discussed ConTeXt benefits.

Writing a parser/formatter

It is fairly simple to write a little parser which takes as its input your source file and gives in output a .tex file containing the code plus the opportune commands for colorization. You can then include the resulting .tex file in the global ConTeXt document file. As an example, this is a Python script for the SuperCollider language, which has a strict Smalltalk-like syntax.

Fed with the following source code contained in e.g. example.sc file:



the script outputs this tex code, which is written into a file contained in the same folder of the source file (named example.tex):

\startSC
/BTEX\color[SCred]{//// an example starting with a comment}/ETEX
/BTEX\color[SCgrey]{"this is a string"}/ETEX .postln ;

/BTEX\color[SCgreen]{\letterbackslash aSymbol}/ETEX  ;

/BTEX\color[SCblue]{ThisClassDoesNotExists}/ETEX  ;
\stopSC

Basically, the idea is to envelope each item to be colorized inside a /BTEX /ETEX block. Note that inside the block the text is no more verbatim, so you have to define some string replacements for special characters (e.g. _, %, $, \, etc). As an example, the problem of the backslash (\) is solved here by replacing it with \letterbackslash.

You can then insert example.tex in your ConTeXt file with

\input example


The example.tex file uses some definitions (explained in the previous sections) which have to be put in the ConTeXt file (use escape=yes instead of option=commands for mkiv).

\defineframedtext
  [framedSC]
  [framecolor=cirmaBlue,
   strut=yes,
   offset=2mm,
   width=local,
   align=right]

\definetyping[SC][option=commands, 
					tab=2,numbering=line,
                    before={\startframedSC},
                    after={\stopframedSC}]

Also, example.tex requires color definitions, which are created following SuperCollider colorization interpreter scheme and have to be inserted in the ConTeXt file too:

%% SC colors %%
\definecolor [SCwhite] [r=1.0, g=1.0, b=1.0] 
\definecolor [SCblack] [r=0.0, g=0.0, b=0.0] 
\definecolor [SCblue] [r=0.0, g=0.0, b=0.75] 
\definecolor [SCred] [r=0.75, g=0.0, b=0.0] 
\definecolor [SCgrey] [r=0.376, g=0.376, b=0.376] 
\definecolor [SCgreen] [r=0.0, g=0.45, b=0.0]

\definecolor[cirmaBlue] [r=.0,g=.2,b=.6]  % for frame

The previous definitions will be used for all the code files inserted with \input. After compiling, this is the result of the discussed example:


Embedding the source code

If your document is inteded to provide code examples to be tested by the readers, the presence of format signs (e.g. line numbers) can create some troubles while copying and pasting the code text from your document to the language environment. More generally, the copy and paste approach, being slow and possibly related to encodings, is not satisfying at all. You can include source files in the pdf with a couple of ConTeXt commands:

\useattachment[ex][example.sc]
\attachment[ex]


So that you can have this structure for each code snippet:

\input example

\useattachment[ex][example.sc]
\attachment[ex]


The commands embed example.sc in the pdf, so that it is accessible by double-clicking on a generated icon. In this case the icon is placed after the colorized code frame. If you use Acrobat Reader (Preview.app in MacOSX does not provide support for the behaviour) example.sc will be open in the related application (e.g. SuperCollider.app in the discussed case).


The discussed approach has been implemented here.

(-a- --> User:Andrea)