%  cjkutf8-ko.sty
%
% Copyright (c) 2016-2024 Dohyun Kim <nomosnomos at gmail com>
%
% 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

\NeedsTeXFormat{LaTeX2e}[2023/06/01]
\ProvidesPackage{cjkutf8-ko}[2024/03/01 v2.5 Hangul typesetting on CJKutf8]

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

\DeclareKeys
{
  hangul.code         = \@hangultrue                        ,
  hangul.usage        = load                                ,
  hanja.code          = \@hanjatrue\@hangultrue             ,
  hanja.usage         = load                                ,
  usecjkt1font.code   = \let\usecjk@@font\empty\@hangultrue ,
  usecjkt1font.usage  = load                                ,
  usedotemph.code     = \let\usedot@mph\empty               ,
  usedotemph.usage    = load                                ,
  nojosa.code         = \let\use@josa\undefined             ,
  nojosa.usage        = preamble                            ,
  truetype.code       = \let\use@cjk@cmap@\relax            ,
  truetype.usage      = load                                ,
  mj.code             = \def\CJKKO@mjfont{#1}               ,
  mj.usage            = load                                ,
  gt.code             = \def\CJKKO@gtfont{#1}               ,
  gt.usage            = load
}
\DeclareUnknownKeyHandler{\PassOptionsToPackage{#1}{CJKutf8}}
\ProcessKeyOptions

\ifdefined\CJKKO@mjfont
  \IfFileExists{c70\CJKKO@mjfont.fd}{}{%
    \PackageError{cjkutf8-ko}{`c70\CJKKO@mjfont.fd' does not exist}{}
    \let\CJKKO@mjfont\undefined }
\fi
\ifdefined\CJKKO@gtfont
  \IfFileExists{c70\CJKKO@gtfont.fd}{}{%
    \PackageError{cjkutf8-ko}{`c70\CJKKO@gtfont.fd' does not exist}{}
    \let\CJKKO@gtfont\undefined }
\fi

\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}
  \IfFileExists{t1\CJKKO@mjfont.fd}{\let\rmdefault\CJKKO@mjfont}{}
  \IfFileExists{t1\CJKKO@gtfont.fd}{\let\sfdefault\CJKKO@gtfont}{}
\fi

\RequirePackage{CJKutf8}

\AddToHook{rmfamily}{\CJKfamily{\CJKKO@mjfont}}
\AddToHook{sffamily}{\CJKfamily{\CJKKO@gtfont}}
\AddToHook{ttfamily}{\CJKfamily{\CJKKO@gtfont}}

\AtBeginDocument{
  \edef\reserved@a{\familydefault}
  \edef\reserved@b{\rmdefault}
  \ifx\reserved@a\reserved@b
    \CJKfamily{\CJKKO@mjfont}
    \AddToHook{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}
    \AddToHook{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
}

\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
% protect utf8 octets
\count@"80 \loop
  \begingroup
  \lccode`\~\count@
  \lowercase{\endgroup \protected\edef~{\unexpanded\expandafter{~}}}
\ifnum\count@<"F4 \advance\count@\@ne \repeat

%%%%%%%%%%%%%%%%%%%%%%%%%
% italic correction after cjk
\AddToHook{cmd/maybe@ic@/before}{%
  \let\CJKKO@wasCJK\undefined
  \ifnum\lastkern=\@ne
    \unkern\unkern
    \let\CJKKO@wasCJK\empty
  \fi
}
\AddToHook{cmd/maybe@ic@/after}{%
  \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
    \AddToHook{cmd/CJK@empty/before}{\afterassignment\CJKKO@@empty@insert}
    \def\CJKKO@@empty@insert{\@tempdimb\CJK@scale\@tempdimb}
    % end of redefinition
    \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 {
\AddToHook{cmd/CJK@testLastCJK/after}{%
  \ifnum\lastkern=\@ne
  \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
  \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
    \AddToHook{cmd/CJKsymbol/before}{\leavevmode\lower\CJK@charlower\hbox\bgroup}
    \AddToHook{cmd/CJKsymbol/after}{\egroup}
  \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
  \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 % truetype
      \ifx\pdfnobuiltintounicode\undefined\else
        \AddToHook{cmd/CJK@addcmap/after}{\pdfnobuiltintounicode\font@name }
      \fi
    \else % type1
      \let\CJK@addcmap\@gobble
    \fi
  \fi
\fi

%%%%%%%%%%%%%%%%%%%%%%%%%
% allow non-cjk characters in labels
\def\CJK@XX#1#2{%
  \ifx #2\protect
    \expandafter\CJK@XXp\expandafter#1%
  \else
    \ifincsname \string#1\string#2\else % added
      \expandafter\ifx\csname u8:\string #1\string #2\endcsname \relax
        \csname CJK@\number `#1\endcsname{`#2}%
        \expandafter\expandafter % added wrt allowbreak before (
        \expandafter\CJK@ignorespaces
      \else
        \csname u8:\string #1\string #2\endcsname
      \fi
    \fi % added
  \fi}
\def\CJK@XXX#1#2#3{%
  \ifx #2\protect
    \expandafter\CJK@XXXp\expandafter#1#3%
  \else
    \ifincsname \string#1\string#2\string#3\else % added
      \expandafter\ifx\csname u8:\string #1\string #2\string #3\endcsname \relax
        \csname CJK@\number `#1\endcsname{`#2}{`#3}%
        \expandafter\expandafter % added wrt allowbreak before (
        \expandafter\CJK@ignorespaces
      \else
        \csname u8:\string #1\string #2\string #3\endcsname
      \fi
    \fi % added
  \fi}
\def\CJK@XXXX#1#2#3#4{%
  \ifx #2\protect
    \expandafter\CJK@XXXXp\expandafter#1#3%
  \else
    \ifincsname \string#1\string#2\string#3\string#4\else % added
      \csname CJK@\number `#1\endcsname{`#2}{`#3}{`#4}%
      \expandafter % added wrt allowbreak before (
      \CJK@ignorespaces
    \fi % added
  \fi}

%%% for fancyvrb/verbments package
%\AddToHook{env/VerbatimOut/begin}{\CJK@makeInactive}

%%% hyperref bookmarks.
\ifx\pdfstringdefPreHook\undefined
  \let\pdfstringdefPreHook\empty
\fi
\g@addto@macro\pdfstringdefPreHook{%
  \let\dotemph\@firstofone
}

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

\endinput
