Difference between revisions of "Changing the font for a script"

From LuaTeXWiki
(Created page with "Typically, fonts contain only a selection of scripts, and changing them automatically (as well as the writing direction) to make sure the document is properly typeset would be a ...")
 
Line 11: Line 11:
 
local DIR = node.id("dir")
 
local DIR = node.id("dir")
 
function show_nodes (head)
 
function show_nodes (head)
   isArab = false
+
   local isArab = false
 
   for item in node.traverse_id(node.id"glyph", head) do
 
   for item in node.traverse_id(node.id"glyph", head) do
 
     if item.char > 1536 and item.char < 1792 then
 
     if item.char > 1536 and item.char < 1792 then

Revision as of 09:16, 19 June 2016

Typically, fonts contain only a selection of scripts, and changing them automatically (as well as the writing direction) to make sure the document is properly typeset would be a nice feature. Here is a mock up.

It is based on the pre_linebreak_filter callback, which contains the horizontal list of glyphs, kerns, whatsits, etc., before building the paragraph. This callback is used by the font loader, too. It works with LaTeX 2016 and LuaTeX 0.95, but it should work with previous versions with minimal changes.

It is intended just for small chunks of text (a proper noun, a few words, etc.). For proper bidi writing, see typo-dha.lua, typo-dua.lua, typo-dub.lua and typo-duc.lua in context.

\documentclass{article}

\directlua{
local DIR = node.id("dir")
function show_nodes (head)
  local isArab = false
  for item in node.traverse_id(node.id"glyph", head) do
    if item.char > 1536 and item.char < 1792 then
      item.font = arabicfont % Defined below
      if isArab == false then 
        isArab = true
        d = node.new(DIR)
        d.dir = '+TRT'
        node.insert_before(head, item, d)       
      end
    else
      if isArab == true then
        isArab = false
        d = node.new(DIR)
        d.dir = '-TRT'
        node.insert_after(head, prevglyf, d)
      end
    end
    prevglyf = item % A bit dangerous, but usually OK.
  end
  return head
end
luatexbase.add_to_callback("pre_linebreak_filter", show_nodes, 'desc')
luatexbase.add_to_callback("hpack_filter", show_nodes, 'desc')
}

% The contextual analysis for arabic must be after the font
% changes. It fontspec is loaded before, then the callbacks must be
% reorderer, which is feasible.

\usepackage{fontspec}
\setmainfont{Iwona}
\newfontfamily\amiri[Script=Arabic]{Amiri}

\begin{document}

{\amiri (نص قصير)\directlua{ arabicfont = font.current() }} Some text

Some text نص قصير Some text

\begin{tabular}{rr}
One & Two \\
Three & أربعة % :-/ Estra space
\end{tabular}

Some text.

\end{document}