Moving to a new blog

It has been almost three years since I last posted here. I got busy. Both in my personal and professional life. I am now attempting to restart the blog, but not on wordpress. I am moving to a static website generator and hosting my blog on github. I even wrote a new post on correcting math escape in t-vim. Go check it out and update your bookmarks!

Metapost and TeX labels

Default Metapost has the concept of two types of labels, postscript labels and TeX labels. Postscript labels are created using

label("text", location);

while TeX labels are created using

label(btex text etex, location);

In the latter case, Metapost collects everything between btex and etex in a separate file, processes that file through TeX, and includes the resulting postscript code at an appropriate location. Such a Golberg-esque mechanism is needed to propertly typeset mathematics, get proper kerning, etc.; tasks that TeX can do but Postscript cannot.

ConTeXt has always been tightly integrated with Metapost, but in the pdftex days typesetting labels was slow. ConTeXt (i.e. pdftex) calls Metapost (to draw a figure, say), and then Metapost calls pdftex (to typeset a label), and imports the result to the postscript; this postscript file is passed to ConTeXt and translated into PDF code using TeX macros and the result in inserted in the PDF file that pdftex is generating. Phew!

Six or seven years ago, Hans Hagen and Mojca Miklavec had an idea to speed up this process by collecting all the labels at the ConTeXt end, typesetting them in boxes, and pass on the dimension of the boxes to Metapost. See Mojca’s My Way describing this mechanism. To use this feature, one had to type:

label(\sometxt{text}, location);

With luatex, Metapost can be called as a library, and the basic idea of preprocessing the labels at the TeX end and passing the resulting dimensions to Metapost has been implemented more robustly in Lua. (The conversion of the PS generated by Metapost to PDF is also done in Lua). So one could just type

label(btex text etex, location);

and ConTeXt would parse the Metapost environment and do all the book-keeping at the back.

However, I had always been unstastified with the user interface. There are very few situations where I as a user want postscript labels. So, why not redefine the label macro so that

label("text", location);

is equivalent to the btexetex version. I had made such a suggestion back in 2007, and for some years had been using a private macro for such purposes.

Today, while answering a question at TEX.SX, I noticed that now there is no difference between the postscript and the TeX labels!. For example

\setupbodyfont[times]
\starttext

\startMPpage[offset=2mm]
  draw "$w$" infont defaultfont scaled defaultscale;
  draw btex $p$ etex shifted (1cm,0);
\stopMPpage
\stoptext

gives

result

Notice that both w and p are in the Times Math font. So, there is no need for those pesky btex ... etex tags anymore.

I really don’t know when this change was implemented. As far as I can tell, nothing has changed at the ConTeXt end, so it appears that MetaPost is now directly parsing the postscript labels using TeX. Nonetheless, this means that there is one less thing to worry about while learning and using Metapost. Yay!

Announcing the overview module

A few years ago, I came across impressive, which is a python script that adds extra oomph to presentations. It uses openGL for effects like highlight boxes, spotlight effect, and overview pages. If you haven’t used it, I’d definitely recommend to give it a try. I don’t use it personally as I find it to be a bit slow and unreliable, but I like the options that the script provides. So, I thought that it would be useful to implement these effects in TeX.

Since I first came across this script, I thought that it will be useful to add some of these presentation features to my workflow. It has taken a while to get around to actually do that.

The feature that I liked the most is the overview page: at the end of the presentation, show the thumbnails of the slides, and if someone has any question, you can click on the thumbnail and go to any slide in the presentation. In fact, I’d prefer not to show all the slides, but only the important ones (like the start of a new section).

Thanks to Wolfgang Schuster and Hans Hagen, I am happy to announce the overview module that provides this feature. I have yet to write the complete documentation, but since it is the new year, I thought that I’d at least annouce the module. The basic usage is as follows:

\usemodule[overviewpage][level=section]

\setupinteraction[state=start]
\setuppapersize[S4]
\setuphead[section][page=yes]

\starttext

\startsection[title={....}]
  ...
\stopsection

\startsection[title={....}]
  ...
\stopsection

\startsection[title={....}]
  ...
\stopsection

\placeoverviewpage

The \placeoverviewpage macro creates the overview slide. The easiest way to explain the output is through an example.


\setupinteraction[state=start]
% Minimalistic subsection layout
\setuppapersize[S4]
\setupwhitespace
\setuphead[section, subsection][color=blue, page=yes]
\setupbodyfont[dejavu, sans, 12pt]
\usemodule[overviewpage][level=section]
% Filler text
\startbuffer[subsection]
\startsubsection[title={Some random bullet points}]
\startitemize
\item First point
\item Second point
\item Third point
\item And so on \unknown
\stopitemize
\stopsubsection
\stopbuffer
\starttext
\startsection[title={First topic in the presentation}]
\startplacefigure[location={here,nonumber}, title={A cute cat}]
\externalfigure[http://placekitten.com/g/800/300][method=jpg, width=0.7\textwidth]
\stopplacefigure
According to the above layout, a topic consists of multiple subsections. Think of
it as a \type{section} in \type{beamer}.
\dorecurse{4}{\getbuffer[subsection]}
\stopsection
\startsection[title={Second topic in the presentation}]
\startplacefigure[location={here,nonumber}, title={A cute cat}]
\externalfigure[http://placekitten.com/g/800/350][method=jpg, width=0.7\textwidth]
\stopplacefigure
Another topic and some random stuff to explain about this topic.
\dorecurse{4}{\getbuffer[subsection]}
\stopsection
\startsection[title={Third topic in the presentation}]
\startplacefigure[location={here,nonumber}, title={A cute cat}]
\externalfigure[http://placekitten.com/g/800/380][method=jpg, width=0.7\textwidth]
\stopplacefigure
Another topic and some random stuff to explain about this topic.
\dorecurse{4}{\getbuffer[subsection]}
\stopsection
\startsection[title={Fourth topic in the presentation}]
\startplacefigure[location={here,nonumber}, title={A cute cat}]
\externalfigure[http://placekitten.com/g/800/325][method=jpg, width=0.7\textwidth]
\stopplacefigure
Another topic and some random stuff to explain about this topic.
\dorecurse{4}{\getbuffer[subsection]}
\stopsection
\placeoverviewpage
\stoptext

The final page of this file is:

Overview page created by the above codeClicking on one of the rectangles takes you to the corresponding page. Check out the complete PDF file.

The only caveat in using the module is that you can only create a thumbnail of a numbered head. Thus, unnumbered heads like subject, subsubject, etc. do not work. If you want to create a thumbnail of a unnumbered head, the best way is to declare it as a numbered head but do not display the number. For example:

\setuphead[section][numbercommand=\gobbleoneargument]

Please go and give the module a spin and let me know what you think.

Creating a clean presentation style in 40 commits

Did you always want to learn ConTeXt, but did not know where to start? I have written a git-based tutorial that should help you get started.

The idea of the tutorial is to start with an empty document, and add features one-by-one. Each git commit corresponds to one small change in the document, and includes pointers to the documentation corresponding to that change. Continue reading

Separation of content and presentation for tables (part 1)

Separation of content and presentation is one of the selling points of TeX over word-processors. Strictly speaking, TeX is not superior compared to word-processors in this regard. It is possible to obtain a clean separation between content and presentation in word-processors (using styles) and it is possible to mix content and presentation in TeX code, as is illustrated by the following example from sample tex file for the IEEE Conference on Decision and Control:

\title{\LARGE \bf
Preparation of Papers for IEEE CSS Sponsored Conferences \& Symposia
}

(Seriously, how can anyone recommend writing TeX code like that!) In spite of the falseness of the argument, the general sentiment is true. It is much easier to write structured code (that separates content and presentation) in TeX than in word-processors. A testament to this is the ease with which one can convert a LaTeX document written in the style of one publisher house to that in the style of another publisher by simply changing the class file.

However, when it comes to tabular data, TeX, or rather LaTeX, is a mess. Simply browse through the questions tagged tables on TeX.SE if you don’t believe me. In this blog post, I want to argue that a clean separation between content and presentation is possible in TeX. The mess that is LaTeX tables is a limitation of LaTeX, and not of TeX. To illustrate this point, I’ll use ConTeXt and LuaTeX.

Lets start with a simple example.

which was typeset using the following code:

\bTABLE
    \bTR
        \bTD Course      \eTD
        \bTD Description \eTD
        \bTD Term Taught \eTD
        \bTD Enrollment  \eTD
    \eTR

    \bTR
        \bTD NAME 101 \eTD
        \bTD A description of the course that is typically one paragraph long.
             A description of the course that is typically one paragraph long.
             A description of the course that is typically one paragraph long. \eTD
        \bTD Fall 2010 \eTD
        \bTD 45 \eTD
    \eTR
    \bTR
        \bTD NAME 215 \eTD
        \bTD A description of the course that is typically one paragraph long.
             A description of the course that is typically one paragraph long.
             A description of the course that is typically one paragraph long. \eTD
        \bTD Winter 2011 \eTD
        \bTD 120 \eTD
    \eTR
    \bTR
        \bTD NAME 555 \eTD
        \bTD A description of the course that is typically one paragraph long.
             A description of the course that is typically one paragraph long.
             A description of the course that is typically one paragraph long. \eTD
        \bTD Fall 2012 \eTD
        \bTD 15 \eTD
    \eTR
\eTABLE

The ConTeXt interface is relatively clean. Rows are indicated by \bTR...\eTR and columns by \bTD...\eTD. The names of the command and the user interface is inspired from HTML tables.

So far, there is a clear separation between content and presentation, simply because we haven’t tweaked the presentation at all. Now suppose, I want to typeset the header as white on blue.

The clean way to add this achieve this is to define a new setup

 \startsetups table:header
 \setupTABLE[row][first][background=color, backgroundcolor=darkblue, color=white, style=bold]
 \stopsetups

and simply change the first line of the table to

\bTABLE[setups={table:header}]

Note that the presentation element (how to style the first row) is defined in the document preamble, and the setup can be shared in all the tables that need that particular style. Now, suppose that in addition to the header, we want to remove the vertical lines in the middle of the table.

Again, to achieve this, define a new setups as follows:

\startsetups table:frame
  \setupTABLE[frame=off]
  \setupTABLE[topframe=on,bottomframe=on]
  \setupTABLE[column][first][leftframe=on]
  \setupTABLE[column][last][rightframe=on]
\stopsetups

and add the setups table:frame to the first line of the table

\bTABLE[setups={table:header, table:frame}]

Continuing this way, suppose we want to change the alignment of cells, say vertically middle align the first column, horizontally middle align the third column, add hyphenation to the second column; and add some offset between the cells.

(I am not arguing that this is a good visual style; just using this as an example without making the use case too complicated). As before, we define a new setups

\startsetups table:style
  \setupTABLE[column][1][align={middle,lohi}]
  \setupTABLE[column][2][align={normal,hyphenated,verytolerant}]
  \setupTABLE[column][3][align=middle]
  \setupTABLE[loffset=1mm,roffset=1mm]
\stopsetups

and add the setups table:style to the first line of the table.

\bTABLE[setups={table:header, table:frame, table:style}]

See, separation of presentation and content need not be difficult in TeX. Let’s see if this approach is flexible to change. Suppose, I don’t like the vertical middle alignment of the first column. I can simply change the \setupTABLE[column][2][align=...] to my liking, and the change will be applied to all tables using the table:style setups. (Contrast this with what you need to do in LaTeX to achieve the same, and you’ll understand why LaTeX tables are considered hard.)

The above examples illustrate a simple example. In a future blog post, I’ll show how one can use Lua to simplify typesetting of complicated tables, while still maintaining a separation of content and presentation.

Announcing the visualcounter module

It has been almost two years since I posted about the main idea of the visualcounter module. I am happy to announce the official release of the module. I have been using this module in my presentations for almost two years without any problems, so I believe that it is stable enough to be released.

At present, the module is available on github and it should be available through ConTeXt garden soon. Look at the documentation to see some of the features of the module (in particular, the "star rating" example based on Jim Hefferon’s article in the Practex Journal).

The module provides six counters. Two of these were created for proof of concept and are not well tested; the remaining four—scratchcounter, mayanumbers, markers, and countdown—are well tested and, hopefully, their interface will not change.

This was my first module that uses the ConTeXt namespace macros. If you peek into the module, you’ll notice that I only define one macro; everything else is handled by the ConTeXt namespace macro \definenamespace.

The other interesting feature of this module is that I use a separate metapost instance for displaying the counters. This avoids conflict with user definitions. For example, if a user decides to change the metapost definition of fill for whatever reason,

\startMPdefinitions
let fill = draw;
\stopMPdefnition

such a change will not affect the visual counter module!

Any feedback is appreciated.

Removing multiple blank lines when typesetting code listings

The listings package in LaTeX has an option to collapse multiple empty lines into a single empty line when typesetting code lists. Today, there was a question on TeX.se how to do something similar when using the minted package. Since the vim module uses the same principle as the minted package, I wondered how one could collapse multiple empty lines into a single line?

One of the fetures of the vim module is that you can source an arbitrary vimrc file before processing the code through the vim editor to generate syntax highlighted code. This feature makes it possible to delegate the task to collapsing multiple blanks lines into a single blank line to vim, the editor. Since the vim module first writes the source code in a file with extension .tmp, the following vimrc snippet will collapse all multiple blank lines into a single blank line whenever a .tmp file is loaded:

au BufEnter *.tmp %s/\(^\s*\n\)\{2,\}/\r/ge | w

Use this inside the vim module as follows (example also available on github):

\usemodule[vim]

\startvimrc[name=collapse]
au BufEnter *.tmp %s/\(^\s*\n\)\{2,\}/\r/ge | w
\stopvimrc


\definevimtyping[CPPtyping][syntax=cpp, vimrc=collapse]

\starttext
\startCPPtyping
  i++;


  i++;






  i--;
\stopCPPtyping
\stoptext

Agreed, this is not as simple as the extralines=1 option in the listings package. But, it is not too complicated when you consider the fact that I had not thought about this feature at all when I wrote the vim module.

A ConTeXt style file for formatting RSS feeds for Kindle

As I said in the last post, I bought an Amazon Kindle Touch sometime back, and I find it very useful for reading on the bus/train while commuting to work.I use it read novels and books, a few newspapers and magazines that I subscribe to, and RSS feeds of different blogs that I follow. Until now, I had been using ifttt to send RSS feeds to Instapaper; Instapaper then emails a daily digest as an ebook to kindle account at midnight; in the morning, I switch on my Kindle for a minute; the Kindle syncs new content over Wifi; and off I go.

However, Kindle typesets ebooks very poorly,  so I decided to write a ConTeXt style file to typeset RSS feed (check it out on github).  To use this style:

\usemodule[rssfeed]

\starttext
\setvariables
    [rssfeed]
    [title={Title of the feed},
     description={Description of the feed},
     link={A link to the feed},
    ]

\starttitle[title={First feed entry}]
....
\stopttitle

\starttitle[title={Second feed entry}]
...
\stoptitle

\stoptext

It uses the eink module to set the page layout and fonts, and use a light and clean style for formatting feed entries. Since the proof is in the pudding, look at following PDFs to see the style for different types of blogs.

I use a simple ruby script to parse RSS feeds and uses Pandoc to convert the contents of each entry to ConTeXt. The script is without bells and whistles, and there is no site specific formatting of feeds. All feeds are handles the same way, and as a result, there are a few glitches: For example, IEEE uses some non-standard tags to denote math) which Pandoc doesn’t handle and the images generated by WordPress blogs that use $latex=...$ to typeset math are not handled correctly by ConTeXt, etc.

The script also uses Mutt to email the generated PDF to my Kindle account. This way, I can simply add a cron job that runs the script at appropriate frequency (daily for usual blogs, weekly for low traffic blogs, and once a month for table of contents of different journals).

A style file for eink readers

Recently I bought an Amazon Kindle touch. It is more convenient than the IREX DR1000 for reading morning news and blogs (thanks to instapaper’s automated delivery of “Read Later” articles, and ifttt for sending RSS feeds to Instapaper).

I have also started reading novels on the Kindle as opposed to the DR1000. Being small, the Kindle is easier to carry; and its hardware just works better than the DR1000: instant startup, huge battery life, and wifi; all areas where DR1000 was lacking. Still DR1000 is the best device when it comes to reading and annotating academic papers, which is surprising given that DR1000 came out 3.5 years ago; perhaps the “eink devices for reading and annotating academic papers” is too niche a niche market to have a successful product. DR1000 was $800 and IREX is now bankrupt.

Anyways, since I am reading novels on Kindle, I have updated my old ConTeXt style file for DR1000 to also handle Kindle and am releasing that as a ConTeXt module. Actually, as two ConTeXt modules: t-eink-devices that stores the dimensions and desired font sizes for eink devices (currently, it has data only for DR1000 and Kindle as those are the only devices that I have) and t-eink that sets an easy to read style that includes:

  • Paper size that matches the screen dimensions
  • Tiny margins, no headers and footers
  • Bookmarks for titles and chapters (both DR1000 and Kindle can use PDF bookmarks as table of contents)
  • A reasonable default style for chapter and title headings
  • A \startinterlude\stopinterlude environment for title pages, dedication, etc.

I have only tested this with simple novels (mostly texts and pictures). That is why the module does not set any style for sections, subsections, etc, as I did not need them so far.

This is mostly for personal use, but I am announcing this module in case someone wants to give it a shot. To use the module, simply add

\usemodule[irex] 
 [ 
 % alternative=kinde, % or DR1000 
 % mainfont={Tex Gyre Schola}, 
 % sansfont={Tex Gyre Heros}, 
 % monofont={Latin Modern Mono}, 
 % mathfont={Xits}, 
 % size=, % By default, kindle uses 10pt and DR1000 uses 12pt font.
 % Use this setting if you want to set a font size.
 ]

This module passes the font loading to the simplefonts module. So, use any name for mainfont etc. that simplefonts will understand. If you don’t set any option, then the default values, indicated above, are used. So, to test out the module, you can just use (for kindle):

\usemodule[eink]

or (for DR1000)

\usemodule[eink][alternative=DR1000]

Below are the samples from Le Petit Prince. The text and images were taken from this website and converted to ConTeXt using Pandoc. The text is also available from Project Gutenburg, Australia.

If you have a Kindle or a DR1000, you can compare the quality of these PDFs (hyphenation, line-breaking, widows and orphans) from what you get from the eBook version. If I am to spend 5-10 hours reading a novel, I don’t mind spending 15 minutes extra (to create a PDF version of the book) to make that reading experience pleasant.

The output is not perfect, especially in terms for float placement in the Kindle version (Page 5 has an underfull page because the figure was too big to fit in the page, the right float image on page 10 would have been better as a here figure, the right float figures on page 13-14 are much lower compared to where they are referred, etc.). But, I find these more tolerable than a chapter title appearing at the bottom of the page and occasionally loosing pagination when I highlight text (both of which happen with epub documents).

Reading remote files

Won’t it be nice if TeX could pretty-print files hosted on github, e.g.,

\typeRUBYfile{https://raw.github.com/adityam/filter/master/Rakefile}

or include a remotely hosted markdown file in your document

\processmarkdownfile{https://raw.github.com/adityam/filter/master/README.md}

I wanted to add this feature to the filter and vim modules.
Although I knew that ConTeXt could read remote files directly, I thought that it would be hard to plug into this mechanism.

Boy, was I wrong. Look at the commit history of the change needed to add this feature.

All I needed to do, was add \locfilename to get the local file name for a file. If the requested file is a remote file (i.e., starts with http:// or ftp://), ConTeXt downloads the file and stores it in the cache directory, and return the name of the cached file. Pretty neat, eh?

With this change, \process<filter>file macro of the filter module can read remote files. Since, the vim module is built on top of the filter module, the \type<vim>file can also read remote files.

The above feature is currently only available in the dev branch. I’ll make a new release once I add hooks to force re-download of remote files. Meanwhile, if you have a ConTeXt macro that reads files, just add a \locfilename at appropriate place, and your macro will be able to read remote files