%  cjkutf8-ko.sty
%
% Copyright (c) 2016 Dohyun Kim <nomos at ktug org>
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program in doc/COPYING; if not, write to the Free
% Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
% MA 02110-1301 USA

\ProvidesPackage{cjkutf8-ko}[2016/04/04 v1.8 Hangul typesetting on CJKutf8]

\begingroup\expandafter\expandafter\expandafter\endgroup
\expandafter\ifx\csname eTeXversion\endcsname\relax
  \PackageError{cjkutf8-ko}
    {e-TeX engine is required}
    {Please update your TeX system to the latest distribution}
\endinput\fi

\newif\if@hangul
\newif\if@hanja
\let\use@josa\empty

\DeclareOption{hangul}{\@hangultrue}
\DeclareOption{hanja}{\@hanjatrue\@hangultrue}
\DeclareOption{usecjkt1font}{\let\usecjk@@font\empty\@hangultrue}
\DeclareOption{usedotemph}{\let\usedot@mph\empty}
\DeclareOption{nojosa}{\let\use@josa\undefined}
\DeclareOption{truetype}{\let\use@cjk@cmap@\relax}
\DeclareOption*{\expandafter\CJKKO@userfont@option\CurrentOption=\end}
\def\CJKKO@userfont@option#1=#2\end{%
  \ifx\empty#2\empty
    \PassOptionsToPackage{#1}{CJKutf8}
  \else
    \def\reserved@a{mj}\def\reserved@b{gt}\def\reserved@c{#1}
    \ifx\reserved@a\reserved@c
      \edef\CJKKO@mjfont{\CJKKO@removetrailingEQ#2}
      \IfFileExists{c70\CJKKO@mjfont.fd}{}{%
        \PackageError{cjkutf8-ko}{`c70\CJKKO@mjfont.fd' does not exist}{}
        \let\CJKKO@mjfont\undefined
      }
    \else
      \ifx\reserved@b\reserved@c
        \edef\CJKKO@gtfont{\CJKKO@removetrailingEQ#2}
        \IfFileExists{c70\CJKKO@gtfont.fd}{}{%
          \PackageError{cjkutf8-ko}{`c70\CJKKO@gtfont.fd' does not exist}{}
          \let\CJKKO@gtfont\undefined
        }
      \else
        \PackageError{cjkutf8-ko}
          {Unknown hangul font type: #1}
          {Allowed font types are `mj' and `gt'}
      \fi
    \fi
  \fi
}
\def\CJKKO@removetrailingEQ#1={#1}
\ProcessOptions\relax

\ifx\CJKKO@mjfont\undefined
  \IfFileExists{c70nanummj.fd}{\def\CJKKO@mjfont{nanummj}}{
    \def\CJKKO@mjfont{mj}
    \ifx\usedot@mph\undefined\else
      \def\dotemphraise{1ex}
      \def\dotemphchar{\Unicode{"02}{"D9}}
    \fi
  }
\fi
\ifx\CJKKO@gtfont\undefined
  \IfFileExists{c70nanumgt.fd}{\def\CJKKO@gtfont{nanumgt}}{\def\CJKKO@gtfont{mj}}
\fi

%%%%%%%%%%%%%%%%%%%%%%%%%
% font settings
\ifx\usecjk@@font\undefined\else
  \PassOptionsToPackage{T1}{CJKutf8}
  \RequirePackage{textcomp}
  \IfFileExists{t1\CJKKO@mjfont.fd}{\let\rmdefault\CJKKO@mjfont}{}
  \IfFileExists{t1\CJKKO@gtfont.fd}{\let\sfdefault\CJKKO@gtfont}{}
\fi

\RequirePackage{CJKutf8}

\g@addto@macro\rmfamily{\CJKfamily{\CJKKO@mjfont}}
\g@addto@macro\sffamily{\CJKfamily{\CJKKO@gtfont}}
\g@addto@macro\ttfamily{\CJKfamily{\CJKKO@gtfont}}

\AtBeginDocument{
  \edef\reserved@a{\familydefault}
  \edef\reserved@b{\rmdefault}
  \ifx\reserved@a\reserved@b
    \CJKfamily{\CJKKO@mjfont}
    \g@addto@macro\normalfont{\CJKfamily{\CJKKO@mjfont}}
    \if@hangul\ifx\usecjk@@font\undefined
      \IfFileExists{t1\CJKKO@mjfont .fd}{%
        \CJKKO@hangulspaceglue{t1\CJKKO@mjfont m}% space glue from hangul font
      }{}
    \fi\fi
  \else
    \CJKfamily{\CJKKO@gtfont}
    \g@addto@macro\normalfont{\CJKfamily{\CJKKO@gtfont}}
    \if@hangul\ifx\usecjk@@font\undefined
      \IfFileExists{t1\CJKKO@gtfont .fd}{%
        \CJKKO@hangulspaceglue{t1\CJKKO@gtfont m}% space glue from hangul font
      }{}
    \fi\fi
  \fi
  \let\reset@font\normalfont
}

\def\CJKKO@hangulspaceglue#1{\@ifclassloaded{minimal}{}{%
  \bgroup
  \@for\reserved@a:=,\small,\footnotesize,\large,\Large,\LARGE\do{%
    \reserved@a
    \font\x=#1 at \f@size\p@
    \fontdimen2\font=\fontdimen2\x
    \fontdimen3\font=.5\fontdimen2\x
    \fontdimen4\font=.3333\fontdimen2\x
    \fontdimen7\font=\fontdimen7\x }%
  \egroup }}

%%%%%%%%%%%%%%%%%%%%%%%%%
%%% dotemph
% Users can redefine \dotemphchar and \dotemphraise
\ifx\usedot@mph\undefined
  \def\dotemph{\PackageError{cjkutf8-ko}
    {To enable \string\dotemph, package option [usedotemph] is required}
    {CJKfntef.sty will be automatically loaded if [usedotemph] option is given}}
\else
  % CJKglue should be skip only. seems to do with \LA@CJKglue in CJKulem.sty
  \RequirePackage{ulem}[2000/05/26]
  \addto@hook\UL@hook{\let\CJKglue\HangulGlue}
  \RequirePackage{CJKfntef}
  \normalem % users should declare \ULforem to enable underlining for \emph
  \ifx\dotemphraise\undefined \def\dotemphraise{0.5ex}\fi
  \ifx\dotemphchar\undefined \def\dotemphchar{\bfseries\Unicode{"02}{"D9}}\fi
  % user command: dotemph
  \DeclareRobustCommand*\dotemph{%
    \CJKunderanysymbol{-\dotemphraise}{\dotemphchar}}
\fi

%%%%%%%%%%%%%%%%%%%%%%%%%
% start CJK env
\def\HangulGlue{\hskip0pt plus.1ex minus.01em }
\def\HangulPenalty{\ifnum\lastpenalty=\z@ \penalty50 \fi}
\def\CJKglue{\HangulPenalty\HangulGlue}
\def\CJKpostmathglue{\HangulPenalty\hskip.25ex plus.1ex minus.05ex }
\CJKspace
\CJK@envStart{}{UTF8}{\CJKKO@mjfont}
\makeatletter

%%%%%%%%%%%%%%%%%%%%%%%%%
% italic correction after cjk
\edef\maybe@ic@{%
  \unexpanded{%
    \let\CJKKO@wasCJK\undefined
    \ifnum\lastkern=\@ne
      \unkern\unkern
      \let\CJKKO@wasCJK\empty
    \fi
  }%
  \unexpanded\expandafter{\maybe@ic@
    \ifx\CJKKO@wasCJK\empty
      \CJK@CJK
      \CJKKO@check@next@tok@
      \let\CJKKO@wasCJK\undefined
    \fi
  }%
}

%%%%%%%%%%%%%%%%%%%%%%%%%
%%% CJKscale: scale CJK char size
\def\CJKscale#1{%
  \ifx\usecjk@@font\undefined
    \def\CJK@scale{#1}%
  \else
    \PackageError{cjkutf8-ko}
      {\string\CJKscale\space is not allowed}
      {\string\CJKscale\space cannot be used with option [usecjkt1font]}
  \fi}
\@onlypreamble\CJKscale
\def\cancelCJKscale{\let\CJK@scale\undefined}
\@onlypreamble\cancelCJKscale
\AtBeginDocument{
  \ifx\usecjk@@font\undefined
  \ifx\CJK@scale\undefined\else
    % redefine \CJK@empty
    \def\CJK@empty#1{%
      \@tempdimb \f@size\p@
      \@tempdimb\CJK@scale\@tempdimb %%% inserted
      \ifx\optional@arg \@empty
      \else
        \expandafter\ifx
         \csname CJK@\mandatory@arg/\f@size/\the\@tempdimb\endcsname \relax
          \@tempdimb \optional@arg\@tempdimb
          #1{Font\space shape\space `\curr@fontshape'\space
             will\space be\MessageBreak
             scaled\space to\space size\space \the\@tempdimb}%
          \expandafter
          \gdef\csname CJK@\mandatory@arg/\f@size/\the\@tempdimb\endcsname{}%
        \fi
      \fi
      \edef\external@font{%
        \mandatory@arg\CJK@plane\space at \the\@tempdimb}%
      \xdef\font@name{%
        \csname \curr@fontshape/\f@size/\CJK@plane\endcsname}%
      \expandafter\global\expandafter\let
       \csname \CJK@curr@fontshape\expandafter\endcsname
        \csname \curr@fontshape\endcsname}
    \if@hangul % hangul is main language
      % scale space glue
      \@ifclassloaded{minimal}{}{%
        \bgroup
        \@for\reserved@a:=,\small,\footnotesize,\large,\Large,\LARGE\do{%
          \fontdimen2\font=\CJK@scale\fontdimen2\font
          \fontdimen3\font=\CJK@scale\fontdimen3\font
          \fontdimen4\font=\CJK@scale\fontdimen4\font
          \fontdimen7\font=\CJK@scale\fontdimen7\font}
        \egroup
      }
      % scale parindent, footnotesep, footins
      \parindent\CJK@scale\parindent
      \footnotesep\CJK@scale\footnotesep
      \skip\footins=\CJK@scale\skip\footins plus6pt minus3pt
      % scale linespread
      \@tempdima\baselinestretch\p@
      \@tempdima\CJK@scale\@tempdima
      \edef\reserved@a{\strip@pt\@tempdima}
      \expandafter\expandafter\expandafter\linespread\expandafter{\reserved@a}
      \selectfont
    \fi
  \fi\fi
}

%%%%%%%%%%%%%%%%%%%%%%%%%
%%% insert CJKglue before opening ascii and letter
\def\CJK@ignorespaces{%
  \ifnum\lastkern=\@ne
    \spacefactor\@m % was normal cjk, so sf=1000
    \expandafter\expandafter\expandafter\CJKKO@check@next@tok
  \fi}
\def\CJKKO@check@next@tok{\futurelet\@let@token\CJKKO@check@next@tok@}
\def\CJKKO@check@next@tok@{%
  \ifx\@let@token(\CJKglue\else
  \ifx\@let@token`\CJKglue\else
  \ifx\@let@token[\CJKglue\else
  \ifx\@let@token<\CJKglue\else
  \ifx\@let@token\{\CJKglue\else
  \ifcat\noexpand\@let@token\CJKKO@catcodeXI
    \CJKglue
  \fi\fi\fi\fi\fi\fi}

\begingroup
  \catcode`\A=11 \global\let\CJKKO@catcodeXI=A
\endgroup

%%%%%%%%%%%%%%%%%%%%%%%%%
%%% allow break after ascii (except opening) and before cjk
%%% not a good solution. but...
\sfcode16=998 % t1 ``
\sfcode40=998 % (
\sfcode60=998 % <
\sfcode91=998 % [
\sfcode92=998 % ot1 ``
\sfcode96=998 % `
\sfcode102=998 % oms {
\sfcode123=998 % t1 {
\def\CJK@testLastCJK{%
  \global\CJK@false
  \ifnum\lastkern=\@ne
    \global \CJK@true
  %%% inserted
  \else
    \ifhmode
    \ifnum\lastkern=\tw@\else
    \ifnum\lastskip=\z@ % last node is not space (?)
    \ifnum\lastpenalty=\z@ % last node is not penalty (?)
    \ifnum\spacefactor=998 \else % last char is not opening ascii
      \ifx\CJK@plane\undefined\else
        \CJK@testPostPunct{\CJK@@@enc}{\CJK@plane}{\CJK@gtemp}%
      \fi
      \ifCJK@
        \global\CJK@false
      \else % this char is not closing cjk
        \ifnum\lastnodetype=10 \CJKpostmathglue % after math-off
        \else \CJKglue \fi
      \fi
    \fi\fi\fi\fi\fi
  %%% end of inserted
  \fi}

%%%%%%%%%%%%%%%%%%%%%%%%%
% half-width puncts
\def\CJKKO@XXX@plane{30}
\def\CJKKO@FF@plane{ff}
\DeclareRobustCommand\CJKpunctsymbol[1]{%
  \ifx\CJK@plane\CJKKO@XXX@plane
    \ifcase#1\CJKsymbol{#1}% 3000
    \or \CJKKO@normal@punct{#1}% 3001
    \or \CJKKO@normal@punct{#1}% 3002
    \or \CJKsymbol{#1}% 3003
    \or \CJKsymbol{#1}% 3004
    \or \CJKsymbol{#1}% 3005
    \or \CJKsymbol{#1}% 3006
    \or \CJKsymbol{#1}% 3007
    \or \CJKKO@opening@punct{#1}% 3008
    \or \CJKKO@normal@punct{#1}%  3009
    \or \CJKKO@opening@punct{#1}% 300A
    \or \CJKKO@normal@punct{#1}%  300B
    \or \CJKKO@opening@punct{#1}% 300C
    \or \CJKKO@normal@punct{#1}%  300D
    \or \CJKKO@opening@punct{#1}% 300E
    \or \CJKKO@normal@punct{#1}%  300F
    \or \CJKKO@opening@punct{#1}% 3010
    \or \CJKKO@normal@punct{#1}%  3011
    \or \CJKsymbol{#1}% 3012
    \or \CJKsymbol{#1}% 3013
    \or \CJKKO@opening@punct{#1}% 3014
    \or \CJKKO@normal@punct{#1}%  3015
    \or \CJKKO@opening@punct{#1}% 3016
    \or \CJKKO@normal@punct{#1}%  3017
    \or \CJKKO@opening@punct{#1}% 3018
    \or \CJKKO@normal@punct{#1}%  3019
    \or \CJKKO@opening@punct{#1}% 301A
    \or \CJKKO@normal@punct{#1}%  301B
    \else \CJKsymbol{#1}%
    \fi
  \else
    \ifx\CJK@plane\CJKKO@FF@plane
      \ifnum#1="08 \CJKKO@opening@punct{#1}% FF08
      \else\ifnum#1="09 \CJKKO@normal@punct{#1}% FF09
      \else \CJKsymbol{#1}%
      \fi\fi
    \else
      \CJKsymbol{#1}%
    \fi
  \fi}
\def\CJKKO@opening@punct#1{\leavevmode\hbox to.5em{\hss\CJKsymbol{#1}}}
\def\CJKKO@normal@punct#1{\leavevmode\hbox to.5em{\CJKsymbol{#1}\hss}}
\AtBeginDocument{
  \DeclareUnicodeCharacter{00B7}
  {\leavevmode\kern.25em \Unicode{0}{"B7}\hskip.25em\relax}
}

%%%%%%%%%%%%%%%%%%%%%%%%%
%%% lowercjkchar: eg, \lowercjkchar{-0.1em}
%%% do NOT use unit ex; hangul subfonts may not have x-height
\def\lowercjkchar#1{%
  \ifx\usecjk@@font\undefined
    \def\CJK@charlower{#1}%
  \else
    \PackageError{cjkutf8-ko}
      {\string\lowercjkchar\space is not allowed}
      {\string\lowercjkchar\space cannot be used with option [usecjkt1font]}
  \fi}
\let\lowerCJKchar\lowercjkchar
\@onlypreamble\lowercjkchar \@onlypreamble\lowerCJKchar
\def\cancellowercjkchar{\let\CJK@charlower\undefined}
\let\cancellowerCJKchar\cancellowercjkchar
\@onlypreamble\cancellowercjkchar \@onlypreamble\cancellowerCJKchar
\AtBeginDocument{
  \ifx\usecjk@@font\undefined
  \ifx\CJK@charlower\undefined\else
    \DeclareRobustCommand{\CJKsymbol}[1]{%
      \leavevmode\lower\CJK@charlower\hbox{% inserted
        \symbol{#1}%
        \ifCJK@bold@
          \hbox to \CJKboldshift{\hss\symbol{#1}}%
          \hbox to \CJKboldshift{\hss\symbol{#1}}%
        \fi
      }% inserted
    }
  \fi\fi
}

%%%%%%%%%%%%%%%%%%%%%%%%%
%%% nanummj has no hanja : texlive only
\def\CJKKO@mjdefault{nanummj}
\ifx\CJKKO@mjfont\CJKKO@mjdefault
  \RequirePackage{cjkutf8-nanummjhanja}
\fi

%%%%%%%%%%%%%%%%%%%%%%%%%
%%% auto-josa, light version
\RequirePackage{cjkutf8-josa}

%%%%%%%%%%%%%%%%%%%%%%%%%
% hangul captions, labels, and spacing
\RequirePackage{kolabels-utf}
\if@hangul
  \AtBeginDocument{\RequirePackage{konames-utf}}
  \linespread{1.3888}
  \footnotesep=1.3888\footnotesep
  \skip\footins=1.3888\skip\footins plus6pt minus3pt
  \frenchspacing
\fi

%\ifx\usecjk@@font\undefined
%  \CJKscale{0.95}
%  \lowercjkchar{-0.07em}
%\fi

%%%%%%%%%%%%%%%%%%%%%%%%%
%%% use pdftex's pdfgentounicode
\ifpdf
  \ifx\pdfgentounicode\undefined\else
    \ifx\use@cjk@cmap@\relax\else
      \InputIfFileExists{glyphtounicode}{%
        \let\CJK@addcmap\@gobble
        \pdfgentounicode\@ne
      }{}
    \fi
  \fi
\fi

%%%%%%%%%%%%%%%%%%%%%%%%%
%%% \makeindex in memoir class clashed with this package.
%%% cause:  memoir appempts to write index entries to a file
%%% at the end of document without protecting active characters.
%%% spotted by Juho Lee. thanks to him.
%\AtEndDocument{\CJK@makeInactive}
%%% still conflicts with package verbments.
%%% so now we make utf8 characters robust.
\count@"C2 \loop
  \uccode\count@\count@
  \lccode\count@\count@
  \begingroup
  \lccode`\~\count@
  \lowercase{\endgroup
  \protected\edef~{\unexpanded\expandafter{~}}}
\ifnum\count@<"F4 \advance\count@\@ne \repeat
% then we have to care about hyperref bookmarks.
\ifx\pdfstringdefPreHook\undefined
  \let\pdfstringdefPreHook\empty
\fi
\g@addto@macro\pdfstringdefPreHook{%
  \count@"C2 \loop
  \begingroup
  \lccode`\~\count@
  \lowercase{\endgroup
  \edef~{\unexpanded\expandafter{~}}}%
  \ifnum\count@<"F4 \advance\count@\@ne \repeat
  % and dotemph as well
  \let\dotemph\@firstofone
}
% protect against lowercase
\count@"80 \loop
  \uccode\count@\count@
  \lccode\count@\count@
\ifnum\count@<"BF \advance\count@\@ne \repeat

%%% ignore variation selectors for korean hanja
\DeclareUnicodeCharacter{FE00}{}
\DeclareUnicodeCharacter{FE01}{}
\DeclareUnicodeCharacter{FE02}{}

\endinput
