% unipersian-listings.sty
%
% UniPersian: Persian language support for LaTeX.
%
% Copyright (C) 2026 Amer Amikhteh
%
% This file is part of the UniPersian package.
%
% This work is free software: you may redistribute it and/or modify
% it under the terms of the LaTeX Project Public License as published
% by the LaTeX Project, either version 1.3c of the License, or
% (at your option) any later version.
%
% This work 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.
%
% The full license text is available at:
% https://www.latex-project.org/lppl/
%
% This work is "maintained" by Amer Amikhteh.
%
% The current maintainer of this work is Amer Amikhteh.

\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{unipersian-listings}[2026/09/08 v0.1.0 Persian support for listings package]

\RequirePackage{listings}

\@ifpackageloaded{xepersian}{%
    \input{unipersian-listings-fallback.def}%
}{}

\makeatletter

\let\falst@style\relax
\lst@AddToHook{Output}{\global\let\falst@style\lst@thestyle}
\lst@AddToHook{OutputOther}{\global\let\falst@style\lst@thestyle}

\newsavebox{\falst@box}
\newdimen\falst@avail
\newdimen\falst@effectivewidth

\newcommand{\falstNoPar}{%
    \ifhmode
        \ifinner
        \else
            \unskip
        \fi
    \fi
}

\DeclareRobustCommand{\fa}[1]{%
    \leavevmode
    \begingroup
    \ifx\falst@style\relax\else\falst@style\fi
    \upshape
    \persianttfamily
    \ifnum\lst@length>\z@ \lst@PrintToken \fi
    \falst@effectivewidth=\linewidth
    \falst@avail=\falst@effectivewidth
    \advance\falst@avail by -\lst@currlwidth
    \sbox\falst@box{\hbox{\beginR#1\endR}}%
    \ifdim\wd\falst@box<\falst@avail
        \hbox{\beginR#1\endR}%
    \else
        % \hfill
        % \par
        \beginR
        \let\\\@normalcr
        \parindent=0pt
        \rightskip=0pt
        \leftskip=0pt plus 1fil
        \parfillskip=0pt
        \hyphenpenalty=10000
        \pretolerance=10000
        \tolerance=10000
        \hspace*{\fill}
        #1%
        \endR
        \lst@NewLine
    \fi
    \endgroup
}

\makeatother
\endinput
