[NTG-context] String substitution using regular expressions and backreferences

Thangalin thangalin at gmail.com
Thu Aug 25 21:44:12 CEST 2022

I've attempted to apply Wolfgang's subtle suggestion of using Lua to parse
the input document using a regular expression via lpeg.replacer. The
replacement itself works fine; however, in doing so the XML document
structure is converted to text, which means that it is no longer possible
to "flush" the XML for further processing as XML. The result is that any
unresolved XML tags are written verbatim to the PDF:


There are two other issues with this approach. First is efficiency. Second
is that the processing function would have to be called for every XML
element to capture the replacement.

My original post asked about applying regex word substitution in a ConTeXt
way, such as:

\definereplacement[SubstMac][ match={Mc([A-Z].*)}, replace={\Mac \\1} ]
\definereplacement[SubstPostmeridian][ match={[Pp]\\.[Mm]\\.},
replace={\cap{pm}} ]

That seems like the cleanest approach because it would work on top of XML
or any other source document. Nevertheless, here is what I tried, which
partially works:

  <p>“Mr. McAnulty, I presume?”</p>
  <p>Regular text. <em>Irregular text.</em></p>
\startxmlsetups xml:xhtml
\startxmlsetups xml:html
% Paragraphs are followed by a paragraph break, but only if not
nested.\startxmlsetups xml:p
\startxmlsetups xml:em
function xml.functions.p( t )
  rep = { [1] = { "McAnulty", "\\Mac Anulty" } }
  x = lpeg.replacer( rep ):match( tostring( xml.text( t ) ) )

  buffers.assign( "p", context( x ) )
  context.getbuffer{ "p" }
  % Determine the sizes of 'M' and 'c'.
  % Cheat to dynamically derive the kerning size by putting Mc in a box.
  \setbox\MacKernBox\hbox{\inframed[offset=\zeropoint, width=fit]{Mc}}%
  \def\MacRule{\vrule width \MacUWidth height .04em depth \zeropoint \relax}%
  % Write Mc, where c has a macron, to the document.

As shown in the screen shot, this doesn't correctly handle nested XML

Any ideas on what approach to take to perform a string replacement in

Thanks again!

[Your] input is XML which means a lot more can be done than your simple TeX
> based example demonstrates.
> Wolfgang
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mailman.ntg.nl/pipermail/ntg-context/attachments/20220825/5054c8a6/attachment.htm>

More information about the ntg-context mailing list