% engine=luatex

% Macros to handle a particular combining sequence of Unicode characters
% in ConTeXt Mark IV by modifying the token list.
% © A. Reutenauer, January 2008.
% This file is distributed under the terms of the WTF Public License
% (http://sam.zoy.org/wftpl/)

\usetypescript[iwona]
\setupbodyfont[iwona, 14pt]

% Convert the sequence <U+006C LATIN SMALL LETTER L, U+0303 COMBINING TILDE>
% to an appropriate ConTeXt representation (\buildtextaccent\texttilde l).
% Strongly influenced by macros by Taco.
% See http://www.ntg.nl/pipermail/ntg-context/2007/027095.html
\def\handletokens[#1][#2]{\ctxlua{collectors.handle("#1", #2)}}

\def\startcombining{\ctxlua{collectors.install("combining", "stopcombining")}}

\startluacode
  -- The actual conversion function: we loop over the characters in 'str'.
  function convert_combining(str)
    -- l is true if we have just read an 'l'.
    -- t is the list of tokens read thus far.
    local l, t = false, { }
    -- The following should check if we read ‘l’ and ‘combining tilde’
    -- consecutively.  A lot of overhead; it would be much prettier to
    -- implement a finite automaton :-)
    for _, v in ipairs(str) do
      if not l then
        if v[2] == 0x6c -- v is LATIN SMALL LETTER L: set l to true, and hold
        then l = true
        else t[#t+1] = v -- Otherwise, append v to the token list
        end
      else -- l is true
        if v[2] == 0x0303 then -- v is COMBINING TILDE
          -- Found!  Append the ConTeXt sequence for “l with tilde” to t!
          t[#t+1] = token.create('buildtextaccent')
          t[#t+1] = token.create('texttilde')
          t[#t+1] =  token.create(0x6c, 11)
          l = false -- Don't forget to set l back to false
        else -- This is annoying: we need to check if v is ‘l’ again.
          t[#t+1] = token.create(0x6c, 11) -- First append the previous ‘l’
          if v[2] == 0x6c -- v is LATIN SMALL LETTER L: start all over again
          then l = true
          else
            t[#t+1] = v
            l = false
          end
        end -- of "if l"
      end -- of "if not l"
    end -- of for loop
    return t
  end -- of function
\stopluacode

\def\stopcombining
  {\handletokens[combining][convert_combining]
   \flushtokens[combining]}

% Now we can use \start ... \stopcombining below.

\starttext

% There are two “l with tilde”: one on the second ‘l’ of “Hell̃o”, and the
% other one on “kal̃bame”.  (No, Idris, the Lithuanian radical kalb-
% doesn't mean “dog” ;-)
\startcombining
Hell̃o, world! Mẽs visì kal̃bame lietùviškai.
\stopcombining

\stoptext
