Difference between revisions of "Inside ConTeXt"

From ConTeXt wiki
m (Added a ToDo and some minor formatting.)
m (typo correction)
 
(24 intermediate revisions by 12 users not shown)
Line 1: Line 1:
 
< [[Main Page]] >
 
< [[Main Page]] >
  
== Using variables ==
+
== Programming Topics ==
  
<texcode>
+
=== ConTeXt Features ===
\setvariables[namespace][key=value]
+
* [[Modes]]: Conditional processing of text
\getvariable{namespace}{key}
+
* [[Setups]]: An alternative to macros for storing chunks of code
</texcode>
 
  
{{todo|This could really use a specific example or two.}}
+
=== 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 KeyVal arguments|Commands with Key=Value arguments]]: (Topic: things like <code>\command[thiskey=thatvalue]</code>.)
 +
* [[Commands with optional arguments]]: (Topic: one or more optional arguments within brackets.)
  
== Defining new commands ==
+
=== Module Parameters ===
 +
* [[Module Parameters]]: Passing parameters to modules.
  
=== Special characters in command names ===
+
=== Programming Techniques ===
 +
* [[Processing Lists]]: Processing lists of values
 +
* [[Counters]]: Manipulating counters in context
 +
* [[Expressions]]: Evaluating expressions of type number, dimen, glue or muglue
 +
* [[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)]
  
Some commands have special characters in their names, that TeX normally does not consider to be
+
=== Debugging ===
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
 
characters has to be changed. This is done by <cmd>unprotect</cmd> and <cmd>protect</cmd>:
 
  
<texcode>
+
* [[Console Mode]]: Using ConTeXt on keyboard input directly, rather than loading a <tt>.tex</tt> file.
\unprotect
 
\def\!test{alfa}
 
\protect
 
</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>.
+
== Using variables ==
  
=== See also ===
+
There are several ways to handle variables in ConTeXt.
[[Commands with KeyVal arguments|Commands with Key=Value arguments]],
+
The recommended and easiest method is to use the
[[Commands with optional arguments]]
+
<tt>\setvariables</tt> and <tt>\getvariable</tt> macros.
>
+
Doing it this way you also avoid to get in conflict with
 +
already defined stuff (as variables use their own namespace).
  
== Processing lists of values ==
+
To store variables, you can use the <tt>\setvariables</tt>
=== Processing a comma-separated list of values ===
+
macro.
  
Suppose you defined a command like this one somewhere in your document:
 
 
<texcode>
 
<texcode>
\def\IHaveTo#1#2{I have to #1 on #2.\par}
+
% stores value in variable namespace:key
</texcode>
+
\setvariables[namespace][key=value]
So calling
+
% stores the expanded value
<texcode>
+
\setevariables[namespace][key=value]
\IHaveTo{tidy up}{Monday}
+
% global
 +
\setgvariables[namespace][key=value]
 +
% global and expanded value
 +
\setxvariables[namespace][key=value]
 
</texcode>
 
</texcode>
This will print out:
 
  
<context>
+
Use <tt>\getvariable</tt> to process a variable. Reading an undefined
\def\IHaveTo#1#2{I have to #1 on #2.\par}
+
variable results in the <tt>\empty</tt> token. This is not a serious problem,
\IHaveTo{tidy up}{Monday}
+
as long as you expect text only.
</context>
+
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.
  
But sometimes you have to repeat some task more than once. In this case you can define a new command:
 
 
<texcode>
 
<texcode>
\def\MyMumOrderedMeTo[#1]#2%
+
% gets value of the variable namespace:key
  {\processcommalist[#1]{\IHaveTo{#2}}}
+
\getvariable{namespace}{key}
 
</texcode>
 
</texcode>
Calling
 
<texcode>
 
\MyMumOrderedMeTo[Monday,Wednesday,Saturday]{tidy up}
 
</texcode>
 
will spare you some typing <i>(but not some tidying up!)</i>:
 
  
<context>
+
To avoid problems, also pay attention to the following:
\def\IHaveTo#1#2{I have to #1 on #2.\par}
+
 
\def\MyMumOrderedMeTo[#1]#2%
+
You can set several variables (same namespace) at the same time.
  {\processcommalist[#1]{\IHaveTo{#2}}}
+
So the command <tt>\setvariables</tt> logically uses the '''plural''' form
\MyMumOrderedMeTo[Monday,Wednesday,Saturday]{tidy up}
+
and works with '''square brackets'''.
</context>
+
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'''.
  
 +
OK, here comes a simple example. Let's say, that we want to have variable
 +
space before and after a letter macro called <tt>\Opening</tt>.
  
In case a command <tt>\IHaveTo</tt> is already defined in a slightly different way:
 
<texcode>
 
\def\IHaveTo[#1]#2{I have to #2 on #1.\par}
 
</texcode>
 
you can define <tt>\MyMumOrderedMeTo</tt> as:
 
 
<texcode>
 
<texcode>
\def\MyMumOrderedMeTo[#1]#2%
+
\long\def\Opening#1{%
   {\begingroup
+
   \getvariable{Letter:opening}{before}
  \def\processitem##1{\IHaveTo[##1]{#2}}%
+
  \noindent{\begstrut#1\endstrut}
  \processcommalist[#1]\processitem
+
  \getvariable{Letter:opening}{after}
  \endgroup}
+
}
 
</texcode>
 
</texcode>
  
This, again, produces:
+
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!
  
<context>
+
In this example we want to have a blank line in front of the opening, and
\def\IHaveTo[#1]#2{I have to #2 on #1.\par}
+
two blank lines right after it. The value for the second key contains
\def\MyMumOrderedMeTo[#1]#2%
+
square brackets, so it must be enclosed in braces.
  {\begingroup
 
  \def\processitem##1{\IHaveTo[##1]{#2}}%
 
  \processcommalist[#1]\processitem
 
  \endgroup}
 
\MyMumOrderedMeTo[Monday,Wednesday,Saturday]{tidy up}
 
</context>
 
 
 
=== Processing a dash-separated list of values ===
 
  
Sometimes you have more work to do than just that boring stuff at home. And as it is quite important as well, you don't want to loose your time enumerating all of the tasks. Being able to do something like
 
 
<texcode>
 
<texcode>
\IHaveToDoTheTasks[1-4,7,9-11]{until tomorrow}
+
\setvariables[Letter:opening]
 +
  [before=\blank,
 +
  after={\blank[2*big]},
 +
  ]
 
</texcode>
 
</texcode>
may sound like a good idea.
 
  
Suppose you already defined:
+
You can now save this style setup (among others) in a separate file and
<texcode>
+
include it at the start of your document (before <tt>\Opening</tt> is
\def\IHaveToDoTheTask[#1]#2{The task #1 has to be done #2.\par}
+
defined or at least used).
</texcode>
 
  
You have to define some macros first (thanks to Taco!):
+
And don't forget:
<texcode>
+
'''Ensure that all variables are set before you use them!'''
% a few auxiliary core macros are needed to uncompress the list.
 
%
 
% \uncompresslist is the twin of the already existing \compresslist
 
% which works in the other direction (syst-new)
 
%
 
\unprotect
 
  
% I guess this function is already available but couldnt find it...
 
%
 
\def\apptomac#1#2%
 
  {\ifx#1\empty\def#1{#2}\else \@EA\def\@EA#1\@EA{#1,#2}\fi}
 
  
% the next macro does this:
+
== Defining new commands ==
%
 
% \itemwithdash<<9-11>>- => \dorecurse {<<1+11-9>>}
 
%    {\apptomac\uncompressedlist<<9-1+\recurselevel>>}
 
%
 
% (the 1+ and -1 are needed to solve a counter offset.)
 
\def\itemwithdash#1-#2-%
 
  {\@EA\dorecurse\@EA
 
    {\the\numexpr 1+#2-#1\relax}%
 
    {\@EA\apptomac\@EA\uncompressedlist\@EA
 
      {\the\numexpr #1-1+\recurselevel\relax}}}%
 
  
% top level. The result will be in \uncompressedlist
+
=== Special characters in command names ===
\def\uncompresslist[#1]%
 
  {\def\uncompressedlist{}%
 
  \def\processitem##1%
 
    {\doifinstringelse{-}{##1}
 
      {\itemwithdash##1-}
 
      {\apptomac\uncompressedlist{##1}}}%
 
  \processcommalist[#1]\processitem }
 
  
\protect
+
Some commands have special characters in their names, that TeX normally does not consider to be
</texcode>
+
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
 +
characters has to be changed. This is done by <cmd>unprotect</cmd> and <cmd>protect</cmd>:
  
And then you're ready to define
 
 
<texcode>
 
<texcode>
\def\IHaveToDoTheTasks[#1]#2%
+
\unprotect
  {\begingroup
+
\def\!test{alfa}  
  \uncompresslist[#1]% <= Yeah!
+
\protect
  \def\processitem##1{\IHaveToDoTheTask[##1]{#2}}%
 
  \processcommacommand[\uncompressedlist]\processitem
 
  \endgroup}
 
 
</texcode>
 
</texcode>
  
Guess what! Your <tt>\IHaveToDoTheTasks[1-4,7,9-11]{until tomorrow}</tt> results in:
+
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>.
  
<context>
 
\def\IHaveToDoTheTask[#1]#2{The task #1 has to be done #2.\par}
 
  
% a few auxiliary core macros are needed to uncompress the list.
+
== Passing verbatim text as macro parameter ==
%
 
% \uncompresslist is the twin of the already existing \compresslist
 
% which works in the other direction (syst-new)
 
%
 
\unprotect
 
 
 
% I guess this function is already available but couldnt find it...
 
%
 
\def\apptomac#1#2%
 
  {\ifx#1\empty\def#1{#2}\else \@EA\def\@EA#1\@EA{#1,#2}\fi}
 
 
 
% the next macro does this:
 
%
 
% \itemwithdash<<9-11>>- => \dorecurse {<<1+11-9>>}
 
%    {\apptomac\uncompressedlist<<9-1+\recurselevel>>}
 
%
 
% (the 1+ and -1 are needed to solve a counter offset.)
 
\def\itemwithdash#1-#2-%
 
  {\@EA\dorecurse\@EA
 
    {\the\numexpr 1+#2-#1\relax}%
 
    {\@EA\apptomac\@EA\uncompressedlist\@EA
 
      {\the\numexpr #1-1+\recurselevel\relax}}}%
 
 
 
% top level. The result will be in \uncompressedlist
 
\def\uncompresslist[#1]%
 
  {\def\uncompressedlist{}%
 
  \def\processitem##1%
 
    {\doifinstringelse{-}{##1}
 
      {\itemwithdash##1-}
 
      {\apptomac\uncompressedlist{##1}}}%
 
  \processcommalist[#1]\processitem }
 
  
\protect
+
(For passing text to LuaTex verbatim, see the [[Programming_in_LuaTeX#Manipulating_verbatim_text_for_dummies|Programming in LuaTeX]] article on this wiki.)
 
 
\def\IHaveToDoTheTasks[#1]#2%
 
  {\begingroup
 
  \uncompresslist[#1]% <= Yeah!
 
  \def\processitem##1{\IHaveToDoTheTask[##1]{#2}}%
 
  \processcommacommand[\uncompressedlist]\processitem
 
  \endgroup}
 
 
 
\IHaveToDoTheTasks[1-4,7,9-11]{until tomorrow}
 
</context>
 
 
 
So - what are you still waiting for? Go back to work and do them right away!
 
 
 
=== Comments ===
 
Resulted from thread [http://archive.contextgarden.net/thread/20050704.151237.f815d89d.html] and will be used in some modules such as [[RawSteps]]. It would be nice if processing dash-separated lists of values would make it into the ConTeXt core.
 
 
 
 
 
== Passing verbatim text as macro parameter ==
 
  
 
In case you want to write macros that should handle verbatim text,
 
In case you want to write macros that should handle verbatim text,
Line 271: Line 182:
  
 
[[Category:Inside ConTeXt]]
 
[[Category:Inside ConTeXt]]
 +
[[Category:ConTeXt programming]]

Latest revision as of 07:39, 25 January 2017

< Main Page >

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.

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!


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: