3

In my document I want to change the colour of every instance of the * character to red.

How can I style every instance of a single word or character without interfering with the document's other styles?

7

If you stick to the * example, you can do the following:

\documentclass{article}
\usepackage{luacode}
\begin{document}

\begin{luacode}
dofile("star.lua")
\end{luacode}

Hello * cruel * world

\end{document}

and star.lua is the following:

local GLYF = node.id("glyph")
local HLIST = node.id("hlist")
local VLIST = node.id("vlist")

local colstackstart, colstackstop
colstackstart = node.new("whatsit","pdf_colorstack")
colstackstop  = node.new("whatsit","pdf_colorstack")

colstackstart.data = "1 0 0 rg "
colstackstart.stack = 0
colstackstop.data = ""
colstackstop.stack = 0

-- one could look for the availability of the field 'cmd' instead
if status.luatex_version < 79 then
    colstackstart.cmd = 1
    colstackstop.cmd = 2
else
    colstackstart.command = 1
    colstackstop.command = 2
end



function star( head )
    local curhead, orighead = head, head
    while head do
        -- recurse into the hbox or vbox, if there are any
        if head.id == HLIST or head.id == VLIST then star(head.list)
        -- the * is ascii 42, I hope
        elseif head.id == GLYF and head.char == 42 then
            curhead = node.insert_before(curhead,head,node.copy(colstackstart))
            curhead = node.insert_after(curhead,head,node.copy(colstackstop))
        end
        head = head.next
    end
    return orighead
end



luatexbase.add_to_callback('pre_linebreak_filter', star, 'colorstar')

This inserts a colorstack whatsit node before and after each occurence of the character with the number 42.

red stars

  • Will this leave e.g. \section*[]{} untouched? (I am not curious enough to run code I don't understand at all ;).) – cfr Mar 17 '15 at 0:25
  • 1
    @cfr it will only change the visible output, not the input. – topskip Mar 17 '15 at 8:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.