\enableregime[utf]
\usemodule[chi-00]
\mainlanguage[cn]
\directlua0{
    % 利用舊有的系統處理換行
    function wrap(str)
        rt = ''
        for u in string.utfvalues(str) do
            up = math.ceil(u / 0x100)
            low = u - math.ceil(u / 0x100) * 0x100
            if u < 127 then % need to be replace by cjk range
                rt = rt .. unicode.utf8.char(u)
            else
                rt = rt .. '\\lookaheaduchar{' .. up ..'}{' .. low ..'}'
            end
        end
        return rt
    end
    callback.register('process_input_buffer', wrap)
}
\beginLUATEX\insertunicodeglyph
   \unexpanded\def\insertunicodeglyph
   {\doinsertunicodeglyph\unicodeone\unicodetwo}
   \unexpanded\def\doinsertunicodeglyph#1#2%
   {\char\numexpr(#2+(#1*256))\relax}
\endLUATEX
\def\enwrap#1{%
   \hskip\chinesesurroundskip
   \hskip\chineseinterglyphskip\relax
   #1%
   \hskip\chineseinterglyphskip\relax
   \hskip\chinesesurroundskip
   \hskip\chinesesurroundskip
   \hskip\chinesesurroundskip
   \hskip\chinesesurroundskip
   \hskip\chinesesurroundskip
   \hskip\chinesesurroundskip
   \hskip\chinesesurroundskip
   \ignorespaces
}
% 設定中文字型
\starttypescript [sans] [cwheib] [name]
    \definefontsynonym [Sans]              [ChineseRegular]
    \definefontsynonym [SansItalic]        [ChineseItalic]
    \definefontsynonym [SansSlanted]       [ChineseSlanted]
    \definefontsynonym [SansBold]          [ChineseBold]
    \definefontsynonym [SansBoldSlanted]   [ChineseBoldSlanted]
    \definefontsynonym [SansBoldItalic]    [ChineseBoldItalic]
    \definefontsynonym [ChineseRegular]    [cwheib]
    \definefontsynonym [ChineseItalic]     [cwheib]
    \definefontsynonym [ChineseSlanted]    [cwheib]
    \definefontsynonym [ChineseBold]       [cwheib]
    \definefontsynonym [ChineseBoldSlanted][cwheib]
    \definefontsynonym [ChineseBoldItalic] [cwheib][encoding=cjk-uni]
    \defineunicodefont [Chi][Chinese][chinese]
\stoptypescript
\starttypescript [my] [cwheib]
    \definetypeface [cwheib][ss][sans][cwheib][default]
\stoptypescript
\starttypescript [sans] [vera] [name]
    \definefontsynonym [Sans]              [Vera]
\stoptypescript
\starttypescript [my] [vera]
    \definetypeface [vera][ss][sans][vera][default][rscale=0.85]
\stoptypescript
\usetypescript[my][cwheib]
\usetypescript[my][vera]
\setupbodyfont[cwheib,ss,10pt]
\def\doenskip#1{{\switchtobodyfont[vera,ss]\enwrap{#1}}}
\let\en\doenskip
\Chi

\setupcolors[state=start]       % otherwise you get greyscale
\definecolor[headingcolor][r=1,b=0.4]
% for the document info/catalog (reported by 'pdfinfo', for example)
\setupinteraction[state=start,  % make hyperlinks active, etc.
  title={ConTeXt + LuaTeX + Chinese Howto},
  subtitle={A ConTeXt example},
  author={Kanru Chen},
  keyword={template}]
\useURL[author-email][mailto:kanru@csie.us][][\en{kanru@csie.us}]
\useURL[wiki][http://wiki.contextgarden.net][][\en{\ConTeXt\ Wiki}]
\useURL[debian][http://www.debian.org][][\en{Debian}]
\useURL[contextdownload][http://www.pragma-ade.com/download-1.htm][][\en{\ConTeXt\ Download}]
\useURL[luatexdownload][http://www.luatex.org/download.html][][\en{Lua\TeX\ Download}]
\useURL[luatex][http://www.luatex.org][][\en{Lua\TeX}]
\useURL[lua][http://www.lua.org][][\en{Lua}]

\defineframedtext
  [framedCode]
  [corner=round, width=\textwidth, backgroundcolor=gray, background=color]
\definetyping
    [Code]
    [before=\startframedCode, after=\stopframedCode]

\setuppapersize[A4][A4]
\setuplayout[topspace=0.5in, backspace=1in, header=24pt, footer=36pt,
  height=middle, width=middle]
\setupfooter[style=\it]
\setupfootertexts[\en{\ConTeXt\ + Lua\TeX\ + Chinese Howto}\hfill]
\setuppagenumbering[location={footer,right}, style=bold]
\setuphead[section,chapter,subject][color=headingcolor]
\setuphead[section,subject][style={\ss\bfa},
  before={\bigskip\bigskip}, after={\blank[line]}]
\setuphead[chapter][style={\ss\bfd}]
\setuphead[title][style={\ss\bfd},
  before={\begingroup\setupbodyfont[12pt]},
  after={\leftline{\ss\tfa\en{Kanru Chen <}\from[author-email]\en{>}}
         \bigskip\bigskip\endgroup}]
\setupwhitespace[medium]
\setupinterlinespace[medium]
%\setupindenting[medium, yes]


\starttext
\title{\en{\ConTeXt\ + Lua\TeX\ + Chinese Howto}}
%\placecontent
%\page
\en{\ConTeXt}是比\en{\LaTeX}年輕的\en{\TeX\ macro}套件，雖然說年輕，但是也已經
有十幾年的開發歷史了。\en{Lua\TeX}是從\en{pdf\TeX}和其他眾多計劃延伸出來的\en{\TeX}
引擎，加入了Lua(一個script language)的支援，可以在\en{\TeX}裡面用\en{Lua}
來寫程式，而且可以直接處理編譯過程中的各個環節。直接支援\en{Unicode}也是一個重點，
另外一個很重要的功能是可以直接取用系統上的\en{OTF, TTF}字型。\en{Lua\TeX}的主要開發者%
\en{Hans Hagen}也是\en{\ConTeXt}的主要開發者，所以這兩個東西就這樣很自然的結合起來了。
我以前從來沒有用過\en{\ConTeXt}，弄了半天終於讓\en{\ConTeXt}、\en{Lua\TeX}、中文
這三樣東西可以一起跑起來了，這個\en{HowTo}就是結果，希望可以有更多人來測試改進。\en{:-)}

\subject{安裝\en{\ConTeXt}跟\en{Lua\TeX}}

如果你跟我一樣是用\from[debian]的話，在\en{\type{/etc/apt/source.list}}中加入以下
路徑即可：
\startCode
# for lmodern
deb http://people.debian.org/~preining/TeX/ lmodern/
deb-src http://people.debian.org/~preining/TeX/ lmodern/

# for context
deb http://people.debian.org/~preining/TeX/ context/
deb-src http://people.debian.org/~preining/TeX/ context/

# for luatex
deb http://people.debian.org/~preining/TeX/ luatex/
deb-src http://people.debian.org/~preining/TeX/ luatex/
\stopCode

安裝：
\startCode
$ apt-get install context
$ apt-get install luatex
\stopCode

手動安裝的話，可以到\from[contextdownload]跟\from[luatexdownload]去下載最新的
版本之後，依照裡面的\en{INSTALL}檔案編譯安裝，其實\en{\ConTeXt}只需要把檔案解壓縮在%
\en{\type{\~/texmf-local}}就可以了，跟安裝其他\en{\TeX\ macro}一樣。

\subject{設定\en{Lua\TeX}}

都安裝好後，設定以下環境變數，如：
\startCode
$ export TEXMFCNF=/usr/share/texmf/web2c
$ export TEXMF='{/usr/share/texmf,/usr/share/texmf-texlive,/home/kanru/texmf}'
$ export TEXMFCACHE=/tmp
$ export OSFONTDIR='{/usr/share/fonts/truetype,/home/kanru/.fonts}'
\stopCode

其中\en{\type{OSFONTDIR}}是\en{Lua\TeX}會去額外搜尋系統字型的路徑，目前不會遞迴搜尋，所以
如果有多個目錄的話，請個別設定。

設定好後，執行：
\startCode
$ texexec --make --lua en
\stopCode %$

這樣\en{\ConTeXt}就會開始設定並預先產生需要的\en{cache}。
\subject{測試}
接下來可以先測試一下\en{Lua\TeX}是不是真的已經可以用了，打開一個文件比如說\en{\type{test.tex}}，裡面寫下：
\startCode
\starttext
Hello World!
\stoptext
\stopCode
執行
\startCode
$ texexec --lua test.tex
\stopCode %$
如果有產生\en{\type{test.pdf}}的話，那表示\en{Lua\TeX}已經可以用了。
\subject{設定中文}
接下來可以開始設定中文，首先要確定有字型可以用，以本文為例，是使用\en{cw\TeX}的\en{\type{cwheib.ttf}}字型，如果這個字型有放在剛剛所設定的目錄中的話，用
\startCode
$ luatools cwheib.ttf
\stopCode %$
應該可以找到這個字型的位置。

確定字型可以用之後，將以下設定貼入剛剛的\en{\type{test.tex}}中：
\startCode
\enableregime[utf]
\usemodule[chi-00]
\directlua0{
    function wrap(str)
        rt = ''
        for u in string.utfvalues(str) do
            up = math.ceil(u / 0x100)
            low = u - math.ceil(u / 0x100) * 0x100
            if u < 127 then % need to be replace by cjk range
                rt = rt .. unicode.utf8.char(u)
            else
                rt = rt .. '\\lookaheaduchar{' .. up ..'}{' .. low ..'}'
            end
        end
        return rt
    end
    callback.register('process_input_buffer', wrap)
}
\beginLUATEX\insertunicodeglyph
   \unexpanded\def\insertunicodeglyph
   {\doinsertunicodeglyph\unicodeone\unicodetwo}
   \unexpanded\def\doinsertunicodeglyph#1#2%
   {\char\numexpr(#2+(#1*256))\relax}
\endLUATEX
\def\en#1{%
   \hskip\chinesesurroundskip
   \hskip\chineseinterglyphskip\relax
   #1%
   \hskip\chineseinterglyphskip\relax
   \hskip\chinesesurroundskip
   \hskip\chinesesurroundskip
   \hskip\chinesesurroundskip
   \hskip\chinesesurroundskip
   \hskip\chinesesurroundskip
   \hskip\chinesesurroundskip
   \hskip\chinesesurroundskip
   \ignorespaces
}
\starttypescript [sans] [cwheib] [name]
    \definefontsynonym [Sans]              [cwheib]
    \definefontsynonym [SansItalic]        [cwheib]
    \definefontsynonym [SansSlanted]       [cwheib]
    \definefontsynonym [SansBold]          [cwheib]
    \definefontsynonym [SansBoldSlanted]   [cwheib]
    \definefontsynonym [SansBoldItalic]    [cwheib]
\stoptypescript
\starttypescript [my] [cwheib]
    \definetypeface [cwheib][ss][sans][cwheib][default]
\stoptypescript
\usetypescript[my][cwheib]
\setupbodyfont[cwheib,ss,10pt]
\stopCode
接下來就可以輸入中文測試了。
%\startCode
%\starttext
%測試\en{Hello World}
%\stoptext
%\stopCode

\subject{未來工作}

目前這個修改只是利用舊有處理中文的方法來處理中文的換行，中英字型間距等等，完全沒有動到%
\en{\ConTeXt}的核心部份，事實上像是中英間距還有問題，是用不太巧妙的方法處理掉的，未來應
該要用\en{Lua}重新架構中文處理的部份。

目前還有的問題有：
\startitemize
\item 沒有辦法方便的切換中英字型(寫\en{macro}解決)。
\item 中英間距自動調整錯誤。
\item \en{luatools}沒辦法遞迴搜尋字型(其實應該跟系統字型機制連結)。
\item \en{starttyping}也就是表列模式中沒辦法用中文(因為\en{macro}不會被展開)。
\item \en{Lua\TeX}產生的\en{PDF}沒辦法複製貼上，不過這已在官方的修正計劃中。
\item 沒有粗斜體的字型，就是沒有粗斜體。我忘了\en{\LaTeX-CJK}是怎麼解決的了……好像是用模擬的？
\item 把中文相關的修正整理為一個可以引用的\en{module}。
\stopitemize

\subject{其他資源}

想要開始寫\en{\ConTeXt}或是開始\en{hack}，可以參考以下資源：
\startitemize[n]
\item 本文原始碼，裡面有些用法跟上面的範例不一樣。
\item \from[wiki]，裡面有許多文件跟範例。
\item \from[luatex]網站，裡面有使用說明可以下載。
\item \from[lua]網站，要寫\en{Lua}可能需要參考一下手冊。
\stopitemize

\subject{後記}

研究\en{\ConTeXt}是很有趣的事，看了這麼久，竟然也會看\en{\TeX\ macro}了，\en{macro}語言
有趣的地方就是他會層層遞迴展開，而且可以重複更改某\en{macro}的定義，所以要修改某一功能，
有時可以不用修改原程式碼，可以用重新定義\en{macro}的方式做到。

\en{\ConTeXt}某部份來說，其實是比較接近\en{Plain \TeX}的，不需用到許多外部套件的特性，讓
閱讀\en{\ConTeXt}的程式簡單許多。

\en{Lua\TeX}的擴展性真的很不錯，看文件就可以知道有許多地方是可以\en{hook}的，未來利用這種
特性，應該會有奇妙的發展。

\rightaligned{\currentdate\en{version 0.1}陳侃如}
\stoptext
