Difference between revisions of "Inside ConTeXt"

From Wiki
Jump to navigation Jump to search
(→‎Commands and Arguments: typo+verbosity)
(Add hints on bracket usage; c&p from the list: https://www.mail-archive.com/ntg-context@ntg.nl/msg87937.html)
 
(12 intermediate revisions by 6 users not shown)
Line 1: Line 1:
< [[Main Page]] >
+
= Programming Topics =
  
== Programming Topics ==
+
== ConTeXt Features ==
 
 
=== ConTeXt Features ===
 
 
* [[Modes]]: Conditional processing of text
 
* [[Modes]]: Conditional processing of text
 +
* [[Setups]]: An alternative to macros for storing chunks of code
  
=== Commands and Arguments ===
+
== Commands and Arguments ==
 
* [[System Macros]] (''Recommended reading''. Topics: temporary variables, expansion control, argument grabbing and handling, definitions and assignments, branches and decisions, cases, comma separated lists, assignments and parameters, user interaction.)
 
* [[System Macros]] (''Recommended reading''. Topics: temporary variables, expansion control, argument grabbing and handling, definitions and assignments, branches and decisions, cases, comma separated lists, assignments and parameters, user interaction.)
 
* [[Programming in LuaTeX]] (Topic: alleviating the more cumbersome sides of TeX programming.)
 
* [[Programming in LuaTeX]] (Topic: alleviating the more cumbersome sides of TeX programming.)
Line 12: Line 11:
 
* [[Commands with optional arguments]]: (Topic: one or more optional arguments within brackets.)
 
* [[Commands with optional arguments]]: (Topic: one or more optional arguments within brackets.)
  
=== Module Parameters ===
+
== Module Parameters ==
 
* [[Module Parameters]]: Passing parameters to modules.
 
* [[Module Parameters]]: Passing parameters to modules.
  
=== Programming Techniques ===
+
== Programming Techniques ==
 
* [[Processing Lists]]: Processing lists of values
 
* [[Processing Lists]]: Processing lists of values
 
* [[Counters]]: Manipulating counters in context
 
* [[Counters]]: Manipulating counters in context
 
* [[Expressions]]: Evaluating expressions of type number, dimen, glue or muglue
 
* [[Expressions]]: Evaluating expressions of type number, dimen, glue or muglue
* [[executesystemcommand]]: process contents of an environment by another program
+
* [[Executesystemcommand]]: process contents of an environment by another program
 
* Loops and expansion [http://randomdeterminism.wordpress.com/2009/03/05/tex-programming-the-past-the-present-and-the-future/ (blog post)]
 
* Loops and expansion [http://randomdeterminism.wordpress.com/2009/03/05/tex-programming-the-past-the-present-and-the-future/ (blog post)]
  
=== Debugging ===
+
== Debugging ==
  
 
* [[Console Mode]]: Using ConTeXt on keyboard input directly, rather than loading a <tt>.tex</tt> file.
 
* [[Console Mode]]: Using ConTeXt on keyboard input directly, rather than loading a <tt>.tex</tt> file.
  
== Using variables ==
+
= Use of brackets =
 +
 
 +
One must '''not''' confuse with the LaTeX convention where "mandatory"
 +
arguments are contained in curly braces and brackets indicate
 +
"optional" arguments.
 +
 
 +
Curly braces not only give grouping but generally
 +
are used for objects to be typeset, as for \in{Figure}{a} [fig:ref].
 +
 
 +
For new users, it is worth repeating here that arguments within braces
 +
can be either a comma-separated list of words OR a comma-separated
 +
list of keyword=value pairs, BUT NOT A MIXTURE OF BOTH. Generally, a
 +
keyword=value exists for all words, for example \cite[authoryear][ref]
 +
and \cite[alternative=authoryear,reference=ref]
 +
 
 +
values can be grouped using curly braces, as in
 +
\cite[alternative=authoryear,lefttext={{see },}][ref1,ref2] where the
 +
lefttext is associated with the first cite reference (and none with the
 +
second). This can be tricky but is in fact rather straight-forward.
 +
 
 +
= Using variables =
  
 
There are several ways to handle variables in ConTeXt.
 
There are several ways to handle variables in ConTeXt.
Line 58: Line 77:
 
\getvariable{namespace}{key}
 
\getvariable{namespace}{key}
 
</texcode>
 
</texcode>
 
  
 
To avoid problems, also pay attention to the following:
 
To avoid problems, also pay attention to the following:
Line 67: Line 85:
 
On the other hand you can only process one variable at the same time, so
 
On the other hand you can only process one variable at the same time, so
 
<tt>\getvariable</tt> uses the '''singular''' form and works with '''braces'''.
 
<tt>\getvariable</tt> uses the '''singular''' form and works with '''braces'''.
 
 
  
 
OK, here comes a simple example. Let's say, that we want to have variable
 
OK, here comes a simple example. Let's say, that we want to have variable
Line 101: Line 117:
  
 
And don't forget:
 
And don't forget:
'''Just ensure, that all variables are set, before you use them!'''
+
'''Ensure that all variables are set before you use them!'''
 
 
 
 
==== Using setups for namespaces ====
 
Using <tt>\setups</tt> for a variable namespace allows an easier control over the
 
containing variables.
 
All you have to do is to define the setups
 
<tt>namespace:set</tt> and/or <tt>namespace:reset</tt>
 
for a given namespace.
 
Now every time a variable of that namespace is assigned (written), ConTeXt
 
automatically calls these setups. Reading of variables is totally unaffected by these
 
settings.
 
A possible use are default values, calculations and even verification.
 
 
 
So once you have 'setup' your variables proper, you don't have to worry about
 
unset variables and alike any more. Also changes can be made easy, as there is only
 
one common setup.
 
The drawback is the slower speed in use,
 
as every assignment to a variable calls these setups.
 
 
 
 
 
To give you the idea, try this example.
 
 
 
The <tt>set</tt>-part is called
 
* '''right after''' the definition of the namespace (initialisation) and
 
* '''after''' a value is assigned to a variable.
 
The <tt>reset</tt>-part is called
 
* '''right after''' any assignment, but still in front of the <tt>set</tt>-part.
 
 
 
<texcode>
 
\setupoutput[pdftex]
 
 
 
\startsetups namespace:set
 
%
 
\writestatus{VARIABLES}{namespace:set is beeing called..}%
 
\ {\green [namespace:set]}
 
  % whatever must be done with your variables after you assign a value
 
  %
 
  % (initialisation with defaults,..)
 
\stopsetups
 
 
 
 
 
\startsetups namespace:reset
 
%
 
\writestatus{VARIABLES}{namespace:set is beeing called..}%
 
\ {\green [namespace:reset]}
 
  % whatever must be done after an assignment (verification, calculation,..)
 
\stopsetups
 
 
 
 
 
% \setups[namespace:set] is automatically called right after 'set' is assigned
 
\setvariables[namespace]
 
  [set={\setups[namespace:set]},
 
  reset={\setups[namespace:reset]},
 
  ]
 
  
% watch for the colors
+
== CLD ==
\setupcolors[state=start]
+
How to pass variable from TeX to Lua and vice versa? See [[CLD_passing_variables#Variables|CLD passing variables]].
  
\starttext
+
= Defining new commands =
\hairline
 
{\bf reading has no effect\par}
 
{\tt Calling \type{\getvariable{namespace}{key}}...\getvariable{namespace}{key}}
 
  
\blank
+
== Special characters in command names ==
{\bf writing calls reset and set\par}
 
{\tt Calling \type{\setvariables[namespace][key=value]}...\setvariables[namespace][key=value]}
 
 
 
\stoptext
 
 
 
</texcode>
 
 
 
== Defining new commands ==
 
 
 
=== Special characters in command names ===
 
  
 
Some commands have special characters in their names, that TeX normally does not consider to be  
 
Some commands have special characters in their names, that TeX normally does not consider to be  
 
letters: <tt>@</tt>, <tt>!</tt> and <tt>?</tt>.  
 
letters: <tt>@</tt>, <tt>!</tt> and <tt>?</tt>.  
 
Before and after the use or definition of such protected commands in your input files, the catcode of these  
 
Before and after the use or definition of such protected commands in your input files, the catcode of these  
characters has to be changed. This is done by <cmd>unprotect</cmd> and <cmd>protect</cmd>:
+
characters has to be changed. This is done by {{cmd|unprotect}} and {{cmd|protect}}:
  
 
<texcode>
 
<texcode>
Line 188: Line 137:
 
</texcode>
 
</texcode>
  
The newly defined command <tt>\!test</tt> can of course only be called upon when we are in the <cmd>unprotect</cmd>ed state, otherwise TeX reads the command <tt>\!</tt>, followed by the word <tt>test</tt> (and probably complains loudly about not being in math mode). These protection/unprotection commands can be nested.  When the nesting becomes deeper than one level, the system reports the current protection level. It is a good habit to always start your macro files with <cmd>unprotect</cmd> and end them with <cmd>protect</cmd>.
+
The newly defined command <tt>\!test</tt> can of course only be called upon when we are in the {{cmd|unprotect}}ed state, otherwise TeX reads the command <tt>\!</tt>, followed by the word <tt>test</tt> (and probably complains loudly about not being in math mode). These protection/unprotection commands can be nested.  When the nesting becomes deeper than one level, the system reports the current protection level. It is a good habit to always start your macro files with {{cmd|unprotect}} and end them with {{cmd|protect}}.
  
  
 
+
= Passing verbatim text as macro parameter =
== Passing verbatim text as macro parameter ==
 
  
 
(For passing text to LuaTex verbatim, see the [[Programming_in_LuaTeX#Manipulating_verbatim_text_for_dummies|Programming in LuaTeX]] article on this wiki.)
 
(For passing text to LuaTex verbatim, see the [[Programming_in_LuaTeX#Manipulating_verbatim_text_for_dummies|Programming in LuaTeX]] article on this wiki.)
Line 253: Line 201:
 
</context>
 
</context>
  
== Setups ==
+
[[Category:Programming and Databases]]
In ConTeXt it is easy to create local variables and grouping. Local variables can be simulated as in:
+
[[Category:Tools]]
 
 
<texcode>
 
\startsetups whatever
 
% some useful definitions here
 
\stopsetups
 
 
 
\definestartstop[whatever][commands=\setups{whatever}]
 
 
 
\startwhatever
 
Using definitions here.
 
\stopwhatever
 
</texcode>
 
 
 
But you can place setups almost everywhere and environment will not be affected by their execution. It is useful to wrap overlay definitions and such in setups as in (copied from [[Colorful_CD_Inlay]] page):
 
 
 
<texcode>
 
\defineoverlay [origin] [\setups{origin}]
 
 
 
\startsetups origin
 
    \vbox to \overlayheight {
 
        \vfill\tfxx\setstrut
 
        \hsize\overlaywidth
 
        \hfill Fiona Apple\enspace EM\enspace2005\quad\strut\endgraf
 
        \kern1ex
 
    }
 
\stopsetups
 
</texcode>
 
 
 
You can even do things like:
 
 
 
<texcode>
 
\starttext
 
\startsetups settest
 
\def\command{do something with}
 
I want to \command{} command.
 
\stopsetups
 
 
 
\start
 
\setups{settest}
 
\stop
 
 
 
\command aaa  % will give "undefined control sequence" error
 
 
 
\stoptext
 
</texcode>
 
 
 
[[Category:Inside ConTeXt]]
 
[[Category:Programming]]
 

Latest revision as of 10:11, 16 December 2021

Programming Topics

ConTeXt Features

  • Modes: Conditional processing of text
  • Setups: An alternative to macros for storing chunks of code

Commands and Arguments

  • System Macros (Recommended reading. Topics: temporary variables, expansion control, argument grabbing and handling, definitions and assignments, branches and decisions, cases, comma separated lists, assignments and parameters, user interaction.)
  • Programming in LuaTeX (Topic: alleviating the more cumbersome sides of TeX programming.)
  • Commands with Key=Value arguments: (Topic: things like \command[thiskey=thatvalue].)
  • Commands with optional arguments: (Topic: one or more optional arguments within brackets.)

Module Parameters

Programming Techniques

Debugging

  • Console Mode: Using ConTeXt on keyboard input directly, rather than loading a .tex file.

Use of brackets

One must not confuse with the LaTeX convention where "mandatory" arguments are contained in curly braces and brackets indicate "optional" arguments.

Curly braces not only give grouping but generally are used for objects to be typeset, as for \in{Figure}{a} [fig:ref].

For new users, it is worth repeating here that arguments within braces can be either a comma-separated list of words OR a comma-separated list of keyword=value pairs, BUT NOT A MIXTURE OF BOTH. Generally, a keyword=value exists for all words, for example \cite[authoryear][ref] and \cite[alternative=authoryear,reference=ref]

values can be grouped using curly braces, as in \cite[alternative=authoryear,lefttext={{see },}][ref1,ref2] where the lefttext is associated with the first cite reference (and none with the second). This can be tricky but is in fact rather straight-forward.

Using variables

There are several ways to handle variables in ConTeXt. The recommended and easiest method is to use the \setvariables and \getvariable macros. Doing it this way you also avoid to get in conflict with already defined stuff (as variables use their own namespace).

To store variables, you can use the \setvariables macro.

% stores value in variable namespace:key
\setvariables[namespace][key=value]
% stores the expanded value
\setevariables[namespace][key=value]
% global
\setgvariables[namespace][key=value]
% global and expanded value
\setxvariables[namespace][key=value]

Use \getvariable to process a variable. Reading an undefined variable results in the \empty token. This is not a serious problem, as long as you expect text only. But be warned: the compilation process breaks, if you expect a dimension or number. So better take care, that you define your variables, before you use them.

% gets value of the variable namespace:key
\getvariable{namespace}{key}

To avoid problems, also pay attention to the following:

You can set several variables (same namespace) at the same time. So the command \setvariables logically uses the plural form and works with square brackets. On the other hand you can only process one variable at the same time, so \getvariable uses the singular form and works with braces.

OK, here comes a simple example. Let's say, that we want to have variable space before and after a letter macro called \Opening.

\long\def\Opening#1{%
  \getvariable{Letter:opening}{before}
  \noindent{\begstrut#1\endstrut}
  \getvariable{Letter:opening}{after}
}

By using variables in your macros, you can separate the layout definition, so that your macros get much more flexible. Just ensure, that all variables are set, before you use them!

In this example we want to have a blank line in front of the opening, and two blank lines right after it. The value for the second key contains square brackets, so it must be enclosed in braces.

\setvariables[Letter:opening]
  [before=\blank,
   after={\blank[2*big]},
  ]

You can now save this style setup (among others) in a separate file and include it at the start of your document (before \Opening is defined or at least used).

And don't forget: Ensure that all variables are set before you use them!

CLD

How to pass variable from TeX to Lua and vice versa? See CLD passing variables.

Defining new commands

Special characters in command names

Some commands have special characters in their names, that TeX normally does not consider to be letters: @, ! and ?. Before and after the use or definition of such protected commands in your input files, the catcode of these characters has to be changed. This is done by \unprotect and \protect:

\unprotect
\def\!test{alfa} 
\protect 

The newly defined command \!test can of course only be called upon when we are in the \unprotected state, otherwise TeX reads the command \!, followed by the word test (and probably complains loudly about not being in math mode). These protection/unprotection commands can be nested. When the nesting becomes deeper than one level, the system reports the current protection level. It is a good habit to always start your macro files with \unprotect and end them with \protect.


Passing verbatim text as macro parameter

(For passing text to LuaTex verbatim, see the Programming in LuaTeX article on this wiki.)

In case you want to write macros that should handle verbatim text, you can use the tex primitives \obeyspaces and \obeylines. \obeyspaces changes the category code of the space character, so that spaces become significant. \obeylines does the same for the newline character.

This works fine for the following example:

\framed{\obeyspaces{A gap from here     to there!}}

But if you pass this text as a parameter for your own macro \TextWithSpaces

\def\TextWithSpaces#1{\framed{\obeyspaces#1}}%
\TextWithSpaces{A gap from here     to there!}

the additional spaces are ignored. This happens because the category code change is not yet in effect when the argument is parsed, and the spaces are removed during parsing. To keep the spaces, the catcode change must be done before the argument is parsed.

Here is a two-part solution for the problem (suggested by Taco Hoekwater):

\def\TextWithSpaces{\bgroup\obeyspaces\doTextWithSpaces}
\def\doTextWithSpaces#1{\framed{#1}\egroup}

Another way is to postpone argument loading (suggested by Hans Hagen).

\def  \TextWithSpaces  {\framed\bgroup\obeyspaces\doTextWithSpaces}
\def\doTextWithSpaces     #1{#1\egroup} 

Both of these produce the desired result: