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?

bgmCoder
  • 839
  • Here's one approach, demonstrated on individual capital letters: http://tex.stackexchange.com/questions/173209/change-the-color-of-capital-letters/173215#173215 – Steven B. Segletes Mar 16 '15 at 21:22
  • 1
    Here's another one that might possibly be adapted: http://tex.stackexchange.com/questions/165700/how-to-automatically-color-a-string-that-starts-by-a-specific-character/165722#165722. In either case, it might be easier to do in your text editor... – Steven B. Segletes Mar 16 '15 at 21:25

1 Answers1

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

topskip
  • 37,020