Added whole documents to the Translation, Grammar & Spelling, and Rewrite & Improve assistants (#1179)

Co-authored-by: Thorsten Sommer <SommerEngineering@users.noreply.github.com>
This commit is contained in:
Sabrina-devopsandThorsten Sommer authored and GitHub committed 2026-11-28 20:27:23 +01:00
1 parent f7666861f1
commit 918572c158
150 files changed
+12850 -302

No files matched your search

@@ -0,0 +1,10 @@
namespace AIStudio.Tools.DocumentSegments.Latex;
/// <summary>
/// An argument of a command or of the start of an environment.
/// </summary>
/// <param name="IsOptional">Whether the argument stands in brackets or parentheses rather than in braces.</param>
/// <param name="ContentStart">Where its content starts in the source, behind the opening bracket or brace.</param>
/// <param name="ContentEnd">Where its content ends in the source, before the closing bracket or brace.</param>
/// <param name="Children">Its content; empty for an argument which LaTeX reads as it stands, e.g., an address.</param>
internal sealed record LatexArgument(bool IsOptional, int ContentStart, int ContentEnd, IReadOnlyList<LatexNode> Children);
@@ -0,0 +1,33 @@
namespace AIStudio.Tools.DocumentSegments.Latex;
/// <summary>
/// What the parser and the reader know about a command.
/// </summary>
/// <param name="Role">What the command means for the segments.</param>
/// <param name="MandatoryArguments">How many arguments in braces the command takes.</param>
/// <param name="TakesOptionalArguments">Whether the command takes arguments in brackets before its last argument in braces, or anywhere when it takes none in braces.</param>
/// <param name="TextArgument">Which of the arguments in braces holds the words of a WORDS or HEADING command, counted from 0.</param>
internal sealed record LatexCommand(LatexCommandRole Role, int MandatoryArguments, bool TakesOptionalArguments, int TextArgument = 0)
{
/// <summary>
/// A command the reader does not know, e.g., a macro of the document: a tag of its own with every argument
/// which follows right after it, since such a macro may hold anything.
/// </summary>
public static readonly LatexCommand UNKNOWN = new(LatexCommandRole.INLINE, int.MaxValue, true) { IsKnown = false };
/// <summary>
/// Whether the reader knows the command. Only the arguments of a known command may follow after white space;
/// for any other, a group after a space is words of its own.
/// </summary>
public bool IsKnown { get; init; } = true;
/// <summary>
/// Whether LaTeX reads the first argument in braces as it stands, e.g., the address of \url, in which a percent sign is no comment.
/// </summary>
public bool HasRawFirstArgument { get; init; }
/// <summary>
/// Whether the command takes an argument in parentheses, e.g., the trimming of \cmidrule(lr).
/// </summary>
public bool TakesParenthesizedArgument { get; init; }
}
@@ -0,0 +1,42 @@
namespace AIStudio.Tools.DocumentSegments.Latex;
/// <summary>
/// What a command means for the segments of a document.
/// </summary>
internal enum LatexCommandRole
{
/// <summary>
/// Marks up words, e.g., \textbf or \footnote: its text argument becomes a pair of tags.
/// </summary>
WORDS,
/// <summary>
/// A heading or a caption, e.g., \section: its text argument and its optional arguments are segments of their own.
/// </summary>
HEADING,
/// <summary>
/// An item of a list, which starts a segment; its optional argument is its label, a segment of its own.
/// </summary>
ITEM,
/// <summary>
/// Ends a paragraph, as \par does.
/// </summary>
PARAGRAPH,
/// <summary>
/// Breaks a line, as \\ does: within a table, it ends a row and so a segment; elsewhere, it is layout.
/// </summary>
LINE_BREAK,
/// <summary>
/// Layout without words, e.g., \label or \centering: a tag of its own, which stays outside of a segment at its edges.
/// </summary>
LAYOUT,
/// <summary>
/// Anything else, e.g., \ref or \cite: a tag of its own within the words, since it stands for something a reader sees.
/// </summary>
INLINE,
}
@@ -0,0 +1,159 @@
using System.Collections.Frozen;
namespace AIStudio.Tools.DocumentSegments.Latex;
/// <summary>
/// The commands and environments of LaTeX and its common packages, as far as the segments need to know them.
/// </summary>
/// <remarks>
/// Commands with letters which stand for words, e.g., \ss or \glqq, are known by LatexWords instead. Whatever is
/// missing here stays as it is: an unknown command becomes a tag of its own with its arguments, an unknown
/// environment holds paragraphs.
/// </remarks>
internal static class LatexCommands
{
private static readonly FrozenDictionary<string, LatexCommand> COMMANDS = CreateCommands();
private static readonly FrozenDictionary<string, LatexEnvironmentRole> ENVIRONMENTS = CreateEnvironments();
/// <summary>
/// Parts of the names of environments which hold code or drawings, e.g., of lstlisting, pycode, or tikzcd.
/// </summary>
private static readonly string[] VERBATIM_NAME_PARTS = ["verbatim", "listing", "code", "minted", "tikz"];
/// <summary>
/// Finds what the reader knows about a command.
/// </summary>
/// <param name="name">The name of the command without its backslash and star, e.g., "section" or "\" for \\.</param>
public static LatexCommand Of(string name) => COMMANDS.GetValueOrDefault(name, LatexCommand.UNKNOWN);
/// <summary>
/// Finds what an environment means for the segments.
/// </summary>
/// <param name="name">The name of the environment, e.g., "itemize" or "align*".</param>
public static LatexEnvironmentRole EnvironmentOf(string name)
{
var baseName = name.TrimEnd('*');
if (ENVIRONMENTS.TryGetValue(baseName, out var role))
return role;
return VERBATIM_NAME_PARTS.Any(part => baseName.Contains(part, StringComparison.OrdinalIgnoreCase))
? LatexEnvironmentRole.VERBATIM
: LatexEnvironmentRole.CONTAINER;
}
private static FrozenDictionary<string, LatexCommand> CreateCommands()
{
var commands = new Dictionary<string, LatexCommand>(StringComparer.Ordinal);
void Add(LatexCommand command, params string[] names)
{
foreach (var name in names)
commands[name] = command;
}
//
// Words in another look, with a link, or in a note, which become a pair:
//
Add(new(LatexCommandRole.WORDS, 1, false),
"textbf", "textit", "textsl", "textsc", "textup", "textmd", "textrm", "textsf", "textnormal", "emph",
"underline", "uline", "uuline", "uwave", "sout", "xout", "hl", "ul", "textsuperscript", "textsubscript",
"enquote", "mbox", "fbox", "thanks", "alert", "structure");
Add(new(LatexCommandRole.WORDS, 1, true), "footnote", "footnotetext", "marginpar", "makebox", "framebox", "hyperref");
Add(new(LatexCommandRole.WORDS, 2, true, 1), "textcolor", "colorbox", "parbox", "raisebox");
Add(new(LatexCommandRole.WORDS, 3, true, 2), "fcolorbox", "multirow");
Add(new(LatexCommandRole.WORDS, 3, false, 2), "multicolumn");
Add(new(LatexCommandRole.WORDS, 2, false, 1), "hyperlink", "hypertarget");
Add(new(LatexCommandRole.WORDS, 2, false, 1) { HasRawFirstArgument = true }, "href");
//
// Headings and captions, which are segments of their own:
//
Add(new(LatexCommandRole.HEADING, 1, true),
"part", "chapter", "section", "subsection", "subsubsection", "paragraph", "subparagraph", "addpart",
"addchap", "addsec", "minisec", "caption", "subcaption", "title", "subtitle", "frametitle", "framesubtitle");
Add(new(LatexCommandRole.HEADING, 2, true, 1), "captionof");
Add(new(LatexCommandRole.ITEM, 0, true), "item");
Add(new(LatexCommandRole.PARAGRAPH, 0, false), "par");
Add(new(LatexCommandRole.LINE_BREAK, 0, true), "\\", "tabularnewline");
// The ends of the rows which a long table repeats on each page, which end a row as \\ does:
Add(new(LatexCommandRole.LINE_BREAK, 0, false), "endhead", "endfirsthead", "endfoot", "endlastfoot");
//
// Layout without words:
//
Add(new(LatexCommandRole.LAYOUT, 0, false),
"noindent", "indent", "centering", "raggedright", "raggedleft", "justifying", "vfill", "hfill", "medskip",
"smallskip", "bigskip", "newpage", "clearpage", "cleardoublepage", "maketitle", "tableofcontents",
"listoffigures", "listoftables", "appendix", "frontmatter", "mainmatter", "backmatter", "hline",
"phantomsection", "FloatBarrier", "small", "footnotesize", "scriptsize", "tiny", "large", "Large", "LARGE",
"huge", "Huge", "normalsize", "bfseries", "itshape", "mdseries", "upshape", "slshape", "scshape",
"rmfamily", "sffamily", "ttfamily", "normalfont", "em", "bf", "it", "rm", "sf", "tt", "sc", "sl",
"selectfont", "relax", "null", "pause", "makeatletter", "makeatother", "boldmath", "unboldmath", "sloppy",
"fussy", "onecolumn", "newline", "def", "gdef", "edef", "xdef");
Add(new(LatexCommandRole.LAYOUT, 0, true),
"pagebreak", "nopagebreak", "linebreak", "printbibliography", "toprule", "midrule", "bottomrule",
"addlinespace", "twocolumn");
Add(new(LatexCommandRole.LAYOUT, 1, false),
"label", "vspace", "hspace", "stepcounter", "refstepcounter", "thispagestyle", "pagestyle", "input",
"include", "bibliography", "bibliographystyle", "cline", "pagenumbering", "markright", "hypersetup",
"graphicspath", "newlength", "selectlanguage", "usetheme", "usecolortheme", "usefonttheme", "useinnertheme",
"useoutertheme", "arrayrulecolor", "addbibresource");
Add(new(LatexCommandRole.LAYOUT, 1, true),
"includegraphics", "rowcolor", "cellcolor", "columncolor", "usepackage", "RequirePackage", "documentclass",
"captionsetup", "newcounter", "lstinputlisting", "inputminted");
Add(new(LatexCommandRole.LAYOUT, 1, true) { TakesParenthesizedArgument = true }, "cmidrule");
Add(new(LatexCommandRole.LAYOUT, 2, false),
"setlength", "addtolength", "setcounter", "addtocounter", "markboth", "setkomafont", "addtokomafont");
Add(new(LatexCommandRole.LAYOUT, 2, true), "newcommand", "renewcommand", "providecommand", "DeclareMathOperator", "newtheorem");
Add(new(LatexCommandRole.LAYOUT, 3, false), "addcontentsline", "definecolor");
Add(new(LatexCommandRole.LAYOUT, 3, true), "newenvironment", "renewenvironment");
//
// Things a reader sees, which a model keeps as they are:
//
Add(new(LatexCommandRole.INLINE, 1, true),
"ref", "eqref", "pageref", "autoref", "cref", "Cref", "nameref", "vref", "cite", "citep", "citet",
"citealp", "citealt", "citeauthor", "citeyear", "parencite", "textcite", "autocite", "footcite",
"fullcite", "smartcite", "nocite", "gls", "Gls", "glspl", "Glspl", "acrshort", "acrlong", "acrfull", "ac",
"Ac", "acp", "Acp", "acs", "acl", "acf", "index", "todo", "si", "num", "unit", "ang", "footnotemark");
Add(new(LatexCommandRole.INLINE, 1, false), "texttt");
Add(new(LatexCommandRole.INLINE, 2, true), "SI", "qty", "foreignlanguage", "crefrange");
Add(new(LatexCommandRole.INLINE, 1, false) { HasRawFirstArgument = true }, "url", "path", "nolinkurl");
Add(new(LatexCommandRole.INLINE, 0, false),
"today", "LaTeX", "TeX", "LaTeXe", "xspace", "slash", "enspace", "quad", "qquad", "thinspace",
"nobreakspace", "dag", "ddag", "P", "copyright", "textregistered", "texttrademark", "pounds", "euro",
"texteuro", "textbackslash", "textasciitilde", "textasciicircum", "textbar", "textless", "textgreater",
"textdegree", "textperthousand", "protect", "thepage");
return commands.ToFrozenDictionary(StringComparer.Ordinal);
}
private static FrozenDictionary<string, LatexEnvironmentRole> CreateEnvironments()
{
var environments = new Dictionary<string, LatexEnvironmentRole>(StringComparer.Ordinal);
void Add(LatexEnvironmentRole role, params string[] names)
{
foreach (var name in names)
environments[name] = role;
}
Add(LatexEnvironmentRole.VERBATIM,
"comment", "filecontents", "pgfpicture", "circuitikz", "forest", "picture", "asy", "thebibliography",
"tabbing", "alltt", "python", "sagesilent", "sageblock", "dot2tex", "gnuplot");
Add(LatexEnvironmentRole.MATH,
"equation", "align", "alignat", "flalign", "gather", "multline", "eqnarray", "displaymath", "math", "dmath",
"dgroup", "dseries", "xalignat", "xxalignat");
Add(LatexEnvironmentRole.TABLE,
"tabular", "tabularx", "tabulary", "longtable", "supertabular", "xtabular", "mpsupertabular", "tabu",
"longtabu", "tblr", "longtblr", "talltblr", "NiceTabular", "NiceTabularX");
Add(LatexEnvironmentRole.CONTAINER_WITH_TITLE, "frame", "block", "alertblock", "exampleblock");
Add(LatexEnvironmentRole.CONTAINER_WITH_NAME,
"theorem", "lemma", "corollary", "proposition", "definition", "example", "remark", "proof", "note",
"exercise", "problem", "solution", "claim", "conjecture", "assumption", "hypothesis", "observation", "fact",
"notation", "axiom", "satz", "beweis", "beispiel", "bemerkung", "folgerung");
return environments.ToFrozenDictionary(StringComparer.Ordinal);
}
}
@@ -0,0 +1,37 @@
namespace AIStudio.Tools.DocumentSegments.Latex;
/// <summary>
/// What an environment means for the segments of a document.
/// </summary>
internal enum LatexEnvironmentRole
{
/// <summary>
/// Holds paragraphs, e.g., itemize or figure; the arguments of its start are layout.
/// </summary>
CONTAINER,
/// <summary>
/// Holds paragraphs and has a title as its arguments in braces, e.g., a frame of Beamer.
/// </summary>
CONTAINER_WITH_TITLE,
/// <summary>
/// Holds paragraphs and may have a name as its argument in brackets, e.g., a theorem.
/// </summary>
CONTAINER_WITH_NAME,
/// <summary>
/// A table, whose cells are segments of their own: an ampersand or a line break ends one.
/// </summary>
TABLE,
/// <summary>
/// A formula, e.g., equation: a tag of its own within the words around it.
/// </summary>
MATH,
/// <summary>
/// Code, a drawing, or anything else which stays out entirely, e.g., verbatim or tikzpicture.
/// </summary>
VERBATIM,
}
@@ -0,0 +1,30 @@
namespace AIStudio.Tools.DocumentSegments.Latex;
/// <summary>
/// A part of a LaTeX document, with where it lies in the source.
/// </summary>
/// <param name="Kind">What the part is.</param>
/// <param name="Start">Where the part starts in the source.</param>
/// <param name="End">Where the part ends in the source, exclusive.</param>
internal sealed record LatexNode(LatexNodeKind Kind, int Start, int End)
{
/// <summary>
/// The name of a command or an environment, without a star, e.g., "section"; the character of a special one.
/// </summary>
public string Name { get; init; } = string.Empty;
/// <summary>
/// The words which escaped markup stands for.
/// </summary>
public string Words { get; init; } = string.Empty;
/// <summary>
/// The arguments of a command or of the start of an environment, in their order.
/// </summary>
public IReadOnlyList<LatexArgument> Arguments { get; init; } = [];
/// <summary>
/// The content of a group or of an environment.
/// </summary>
public IReadOnlyList<LatexNode> Children { get; init; } = [];
}
@@ -0,0 +1,62 @@
namespace AIStudio.Tools.DocumentSegments.Latex;
/// <summary>
/// What a part of a LaTeX document is, as LatexParser reads it.
/// </summary>
internal enum LatexNodeKind
{
/// <summary>
/// Words and the white space between them, without any character which LaTeX treats specially.
/// </summary>
TEXT,
/// <summary>
/// One blank line or more, which end a paragraph.
/// </summary>
PARAGRAPH_BREAK,
/// <summary>
/// A comment, from its percent sign to the end of its line.
/// </summary>
COMMENT,
/// <summary>
/// Markup which stands for words, e.g., \% for a percent sign or \"a for an umlaut; LatexNode.Words holds them.
/// </summary>
ESCAPED_WORDS,
/// <summary>
/// A command with its arguments.
/// </summary>
COMMAND,
/// <summary>
/// A group in braces.
/// </summary>
GROUP,
/// <summary>
/// A formula within the words, e.g., $x$ or \[x\].
/// </summary>
MATH,
/// <summary>
/// Code which LaTeX prints as it stands, e.g., \verb|x|.
/// </summary>
VERBATIM,
/// <summary>
/// An environment, from its \begin to its \end.
/// </summary>
ENVIRONMENT,
/// <summary>
/// A character which LaTeX treats specially, e.g., ~ or &amp;; LatexNode.Name holds it.
/// </summary>
SPECIAL,
/// <summary>
/// Markup the parser cannot follow, e.g., a closing brace without an opening one, or a formula without its end.
/// </summary>
INVALID,
}
@@ -0,0 +1,839 @@
namespace AIStudio.Tools.DocumentSegments.Latex;
/// <summary>
/// Reads the markup of a LaTeX document into nodes, with where each one lies in the source.
/// </summary>
/// <remarks>
/// <para>
/// The parser reads only as much as the segments need: it expands no macro and follows no change of category
/// codes. Which arguments a command takes comes from LatexCommands; an unknown command takes every argument which
/// follows right after it.
/// </para>
/// <para>
/// It never fails. Markup it cannot follow, e.g., a closing brace without an opening one or a formula without its
/// end, becomes an INVALID node, so that the reader leaves the paragraph around it as it is. A group without its
/// closing brace, or one nested deeper than MAX_NESTING_DEPTH, takes only the rest of its paragraph, so that the
/// paragraphs after it are read as usual.
/// </para>
/// <para>
/// It reads every part of a document about once, whatever the document holds. An argument without its closing
/// brace is read once more as a group, see ParseArguments, so the parser notes each opening which turned out to
/// have no end and does not read it again; otherwise, each further such opening within it would double the work.
/// </para>
/// </remarks>
internal sealed class LatexParser
{
/// <summary>
/// The longest overlay specification of Beamer which may follow a command, e.g., &lt;2-&gt;.
/// </summary>
private const int MAX_OVERLAY_LENGTH = 40;
/// <summary>
/// The longest name of an environment.
/// </summary>
private const int MAX_ENVIRONMENT_NAME_LENGTH = 64;
/// <summary>
/// How deep groups, arguments, and environments nest at most; far deeper than any document needs, but shallow
/// enough that the recursion of the parser and of the reader stays within the stack of a thread.
/// </summary>
private const int MAX_NESTING_DEPTH = 128;
private readonly string text;
/// <summary>
/// The openings, i.e., braces and brackets, which turned out to have no end before the given limit.
/// </summary>
private readonly HashSet<Opening> unclosedOpenings = [];
private int position;
private int depth;
private LatexParser(string text, int start)
{
this.text = text;
this.position = start;
}
/// <summary>
/// Reads a part of a document.
/// </summary>
/// <param name="text">The document.</param>
/// <param name="start">Where the part starts.</param>
/// <param name="end">Where the part ends, exclusive.</param>
/// <returns>The nodes, which cover the part without gaps.</returns>
public static IReadOnlyList<LatexNode> Parse(string text, int start, int end) => new LatexParser(text, start).ParseSequence(end, null, null);
/// <summary>
/// Reads nodes until the end of what is read, a closing character, or the end of an environment.
/// </summary>
private List<LatexNode> ParseSequence(int limit, char? closing, string? environment)
{
var nodes = new List<LatexNode>();
this.depth++;
try
{
while (this.position < limit && this.text[this.position] != closing)
{
if (this.TryReadEnd(this.position, limit, out var name, out var end))
{
if (name == environment)
break;
// The end of an environment which is not open here:
nodes.Add(new(LatexNodeKind.INVALID, this.position, end));
this.position = end;
continue;
}
nodes.Add(this.ParseNode(limit, closing));
}
}
finally
{
this.depth--;
}
return nodes;
}
/// <summary>
/// Whether the content of an opening at the position may be read: it lies not too deep, and it did not turn out to have no end before.
/// </summary>
private bool MayRead(int opening, int limit) => this.depth < MAX_NESTING_DEPTH && !this.unclosedOpenings.Contains(new(opening, limit));
/// <summary>
/// Notes an opening without its end, and makes the rest of its paragraph an INVALID node.
/// </summary>
private LatexNode Unclosed(int opening, int limit)
{
this.unclosedOpenings.Add(new(opening, limit));
this.position = opening + 1;
this.position = this.ParagraphEnd(limit);
return new(LatexNodeKind.INVALID, opening, this.position);
}
private LatexNode ParseNode(int limit, char? closing)
{
var start = this.position;
var character = this.text[start];
switch (character)
{
case '\\':
return this.ParseControlSequence(limit);
case '{':
return this.ParseGroup(limit);
case '%':
return this.ParseComment(limit);
case '$':
return this.ParseDollarMath(limit);
case '}':
this.position++;
return new(LatexNodeKind.INVALID, start, this.position);
case '~' or '&' or '^' or '_' or '#':
this.position++;
return new(LatexNodeKind.SPECIAL, start, this.position) { Name = character.ToString() };
case '\r' or '\n' when this.IsParagraphBreak(start, limit):
this.SkipWhiteSpace(limit);
return new(LatexNodeKind.PARAGRAPH_BREAK, start, this.position);
default:
this.SkipText(limit, closing);
return new(LatexNodeKind.TEXT, start, this.position);
}
}
private void SkipText(int limit, char? closing)
{
// The first character is words in any case, e.g., a closing bracket outside of an optional argument:
this.position++;
while (this.position < limit)
{
var character = this.text[this.position];
if (IsSpecial(character) || character == closing || (character is '\r' or '\n' && this.IsParagraphBreak(this.position, limit)))
return;
this.position++;
}
}
private static bool IsSpecial(char character) => character is '\\' or '{' or '}' or '%' or '$' or '~' or '&' or '^' or '_' or '#';
private LatexNode ParseGroup(int limit)
{
var start = this.position;
if (!this.MayRead(start, limit))
return this.Unclosed(start, limit);
this.position++;
var children = this.ParseSequence(limit, '}', null);
if (this.position >= limit)
return this.Unclosed(start, limit);
this.position++;
return new(LatexNodeKind.GROUP, start, this.position) { Children = children };
}
private LatexNode ParseComment(int limit)
{
var start = this.position;
this.SkipToLineEnd(limit);
// As for TeX, the line end belongs to the comment, unless a blank line follows, which ends the paragraph:
if (this.position < limit && !this.IsParagraphBreak(this.position, limit))
{
this.SkipLineEnd(limit);
this.SkipSpaces(limit);
}
return new(LatexNodeKind.COMMENT, start, this.position);
}
private LatexNode ParseDollarMath(int limit)
{
var start = this.position;
var terminator = start + 1 < limit && this.text[start + 1] == '$' ? "$$" : "$";
this.position = start + terminator.Length;
if (this.TrySkipMath(limit, terminator))
return new(LatexNodeKind.MATH, start, this.position);
this.position = start + 1;
return new(LatexNodeKind.INVALID, start, this.position);
}
private LatexNode ParseMath(int start, string terminator, int limit)
{
if (this.TrySkipMath(limit, terminator))
return new(LatexNodeKind.MATH, start, this.position);
this.position = start + 2;
return new(LatexNodeKind.INVALID, start, this.position);
}
/// <summary>
/// Skips a formula up to and including its terminator, e.g., "$" or "\)".
/// </summary>
/// <returns>Whether the formula ends within its paragraph.</returns>
private bool TrySkipMath(int limit, string terminator)
{
while (this.position < limit)
{
if (this.text.AsSpan(this.position, limit - this.position).StartsWith(terminator, StringComparison.Ordinal))
{
this.position += terminator.Length;
return true;
}
switch (this.text[this.position])
{
case '\\':
this.position = Math.Min(this.position + 2, limit);
break;
case '%':
this.SkipToLineEnd(limit);
break;
case '\r' or '\n' when this.IsParagraphBreak(this.position, limit):
return false;
default:
this.position++;
break;
}
}
return false;
}
private LatexNode ParseControlSequence(int limit)
{
var start = this.position;
if (start + 1 >= limit)
{
this.position = limit;
return new(LatexNodeKind.INVALID, start, limit);
}
var next = this.text[start + 1];
if (char.IsAsciiLetter(next))
{
var nameEnd = start + 1;
while (nameEnd < limit && char.IsAsciiLetter(this.text[nameEnd]))
nameEnd++;
var name = this.text[(start + 1)..nameEnd];
this.position = nameEnd;
return name switch
{
"begin" => this.ParseEnvironment(start, limit),
"end" => new(LatexNodeKind.INVALID, start, nameEnd),
"verb" or "Verb" => this.ParseVerb(start, limit),
"lstinline" or "mintinline" => this.ParseInlineCode(start, name, limit),
"def" or "gdef" or "edef" or "xdef" => this.ParseDefinition(start, name, limit),
_ => this.TryParseLetterWords(start, name, limit) ?? this.TryParseAccent(start, name, limit) ?? this.ParseCommand(start, name, limit),
};
}
this.position = start + 2;
switch (next)
{
case '(':
return this.ParseMath(start, @"\)", limit);
case '[':
return this.ParseMath(start, @"\]", limit);
case '%' or '&' or '$' or '#' or '_' or '{' or '}':
return Escaped(start, this.position, next.ToString());
case ' ' or '\t':
return Escaped(start, this.position, " ");
case '\r' or '\n':
this.position = start + 1;
this.SkipLineEnd(limit);
return Escaped(start, this.position, " ");
// A possible hyphenation, a correction of italics, or a hint for the space after a full stop:
case '-' or '/' or '@':
return Escaped(start, this.position, string.Empty);
case ',':
return Escaped(start, this.position, LatexWords.THIN_SPACE);
}
if (LatexWords.IsSymbolAccent(next))
return this.TryParseAccent(start, next.ToString(), limit) ?? new LatexNode(LatexNodeKind.INVALID, start, this.position);
return this.ParseCommand(start, next.ToString(), limit);
}
private static LatexNode Escaped(int start, int end, string words) => new(LatexNodeKind.ESCAPED_WORDS, start, end) { Words = words };
/// <summary>
/// Reads a command with letters which stands for a character, e.g., \ss.
/// </summary>
private LatexNode? TryParseLetterWords(int start, string name, int limit)
{
if (!LatexWords.TryLetterCommand(name, out var words))
return null;
this.SkipSpaceAfterControlWord(limit);
return Escaped(start, this.position, words);
}
/// <summary>
/// Reads an accent with its letter, e.g., \"a, \"{a}, or \c{c}.
/// </summary>
/// <returns>The letter with its accent, or null with the position unchanged when no letter follows.</returns>
private LatexNode? TryParseAccent(int start, string accent, int limit)
{
if (!LatexWords.TryAccent(accent, out var combining))
return null;
var afterAccent = this.position;
var isLetterAccent = char.IsAsciiLetter(accent[0]);
if (isLetterAccent)
this.SkipSpaces(limit);
// An accent of letters takes a letter only after a space, since \cc would be a command of its own:
if (this.TryReadAccentBase(limit, allowsBareLetter: !isLetterAccent || this.position > afterAccent, out var letter))
return Escaped(start, this.position, LatexWords.WithAccent(letter, combining));
// \~{} and \^{} stand for the character itself, e.g., a tilde in an address:
this.position = afterAccent;
if (accent is "~" or "^" && this.text.AsSpan(this.position, limit - this.position).StartsWith("{}", StringComparison.Ordinal))
{
this.position += 2;
return Escaped(start, this.position, accent);
}
return null;
}
private bool TryReadAccentBase(int limit, bool allowsBareLetter, out char letter)
{
letter = '\0';
var rest = this.text.AsSpan(this.position, limit - this.position);
if (allowsBareLetter && rest.Length > 0 && char.IsAsciiLetter(rest[0]))
{
letter = rest[0];
this.position++;
return true;
}
// A dotless i or j, as in \"\i:
if (rest is ['\\', 'i' or 'j', ..] && (rest.Length == 2 || !char.IsAsciiLetter(rest[2])))
{
letter = rest[1];
this.position += 2;
this.SkipSpaceAfterControlWord(limit);
return true;
}
if (rest is ['{', var single, '}', ..] && char.IsAsciiLetter(single))
{
letter = single;
this.position += 3;
return true;
}
if (rest is ['{', '\\', 'i' or 'j', '}', ..])
{
letter = rest[2];
this.position += 4;
return true;
}
return false;
}
private LatexNode ParseCommand(int start, string name, int limit)
{
var command = LatexCommands.Of(name);
if (this.position < limit && this.text[this.position] == '*')
this.position++;
this.SkipOverlay(limit);
var arguments = this.ParseArguments(command, limit);
return new(LatexNodeKind.COMMAND, start, this.position) { Name = name, Arguments = arguments };
}
/// <remarks>
/// An argument which turns out to have no end, e.g., a brace without its closing brace, ends the arguments: the
/// position goes back to its opening, which the sequence then reads as a group, i.e., as INVALID up to the end of
/// its paragraph. The opening is noted by then, see MayRead, so it is not read a second time.
/// </remarks>
private List<LatexArgument> ParseArguments(LatexCommand command, int limit)
{
var arguments = new List<LatexArgument>();
var mandatoryCount = 0;
while (true)
{
var before = this.position;
if (command.IsKnown)
this.SkipSpaceWithinParagraph(limit);
var next = this.position < limit ? this.text[this.position] : '\0';
var argument = next switch
{
'[' when command.TakesOptionalArguments && (mandatoryCount < command.MandatoryArguments || command.MandatoryArguments == 0) => this.ParseOptionalArgument(limit),
'(' when command.TakesParenthesizedArgument && mandatoryCount == 0 => this.ParseParenthesizedArgument(limit),
'{' when mandatoryCount < command.MandatoryArguments && command.HasRawFirstArgument && mandatoryCount == 0 => this.ParseRawArgument(limit),
'{' when mandatoryCount < command.MandatoryArguments => this.ParseMandatoryArgument(limit),
_ => null,
};
if (argument is null)
{
this.position = before;
return arguments;
}
if (!argument.IsOptional)
mandatoryCount++;
arguments.Add(argument);
}
}
private LatexArgument? ParseMandatoryArgument(int limit)
{
var start = this.position;
if (!this.MayRead(start, limit))
return null;
this.position++;
var children = this.ParseSequence(limit, '}', null);
if (this.position >= limit)
{
this.unclosedOpenings.Add(new(start, limit));
return null;
}
this.position++;
return new(false, start + 1, this.position - 1, children);
}
/// <summary>
/// Reads an argument in brackets, which ends within its paragraph.
/// </summary>
private LatexArgument? ParseOptionalArgument(int limit)
{
var argumentLimit = this.ParagraphEnd(limit);
var start = this.position;
if (!this.MayRead(start, argumentLimit))
return null;
this.position++;
var children = this.ParseSequence(argumentLimit, ']', null);
if (this.position >= argumentLimit)
{
this.unclosedOpenings.Add(new(start, argumentLimit));
return null;
}
this.position++;
return new(true, start + 1, this.position - 1, children);
}
private LatexArgument? ParseParenthesizedArgument(int limit)
{
var start = this.position;
var end = this.text.AsSpan(start, limit - start).IndexOfAny(')', '\r', '\n');
if (end < 0 || this.text[start + end] != ')')
return null;
this.position = start + end + 1;
return new(true, start + 1, start + end, []);
}
/// <summary>
/// Reads an argument in braces which LaTeX takes as it stands, e.g., an address with a percent sign.
/// </summary>
private LatexArgument? ParseRawArgument(int limit)
{
var start = this.position;
var braceDepth = 0;
for (var index = start; index < limit; index++)
{
switch (this.text[index])
{
case '\\':
index++;
break;
case '{':
braceDepth++;
break;
case '}':
braceDepth--;
if (braceDepth > 0)
break;
this.position = index + 1;
return new(false, start + 1, index, []);
}
}
return null;
}
private LatexNode ParseEnvironment(int start, int limit)
{
this.SkipSpaces(limit);
if (!this.TryReadName(limit, out var name))
return new(LatexNodeKind.INVALID, start, this.position);
var role = LatexCommands.EnvironmentOf(name);
if (role is LatexEnvironmentRole.VERBATIM or LatexEnvironmentRole.MATH)
{
// The content is no markup to read, and only this exact end ends it:
var endMarkup = @"\end{" + name + "}";
var endIndex = this.text.IndexOf(endMarkup, this.position, limit - this.position, StringComparison.Ordinal);
if (endIndex < 0)
{
this.position = limit;
return new(LatexNodeKind.INVALID, start, limit);
}
this.position = endIndex + endMarkup.Length;
return new(LatexNodeKind.ENVIRONMENT, start, this.position) { Name = name };
}
// An environment nested too deep is markup the reader cannot follow anyway:
if (this.depth >= MAX_NESTING_DEPTH)
{
this.position = this.ParagraphEnd(limit);
return new(LatexNodeKind.INVALID, start, this.position);
}
this.SkipOverlay(limit);
var arguments = this.ParseEnvironmentArguments(limit);
var children = this.ParseSequence(limit, null, name);
if (this.TryReadEnd(this.position, limit, out _, out var end))
this.position = end;
return new(LatexNodeKind.ENVIRONMENT, start, this.position) { Name = name, Arguments = arguments, Children = children };
}
/// <summary>
/// Reads the arguments which follow the start of an environment on its line, e.g., the columns of a table.
/// </summary>
private List<LatexArgument> ParseEnvironmentArguments(int limit)
{
var arguments = new List<LatexArgument>();
while (true)
{
var before = this.position;
this.SkipSpaces(limit);
var argument = this.position < limit ? this.text[this.position] switch
{
'[' => this.ParseOptionalArgument(limit),
'{' => this.ParseMandatoryArgument(limit),
_ => null,
} : null;
if (argument is null)
{
this.position = before;
return arguments;
}
arguments.Add(argument);
}
}
/// <summary>
/// Reads the name of an environment in braces.
/// </summary>
private bool TryReadName(int limit, out string name)
{
name = string.Empty;
if (this.position >= limit || this.text[this.position] != '{')
return false;
var length = Math.Min(limit - this.position - 1, MAX_ENVIRONMENT_NAME_LENGTH + 1);
var close = this.text.AsSpan(this.position + 1, Math.Max(length, 0)).IndexOfAny('}', '\r', '\n');
if (close <= 0 || this.text[this.position + 1 + close] != '}')
return false;
name = this.text.Substring(this.position + 1, close);
this.position += close + 2;
return true;
}
/// <summary>
/// Matches \end{name} at a position.
/// </summary>
private bool TryReadEnd(int at, int limit, out string name, out int end)
{
name = string.Empty;
end = at;
const string END = @"\end";
if (!this.text.AsSpan(at, limit - at).StartsWith(END, StringComparison.Ordinal))
return false;
var index = at + END.Length;
if (index < limit && char.IsAsciiLetter(this.text[index]))
return false;
while (index < limit && this.text[index] is ' ' or '\t')
index++;
var before = this.position;
this.position = index;
var isEnd = this.TryReadName(limit, out name);
end = this.position;
this.position = before;
return isEnd;
}
/// <summary>
/// Reads \verb with its delimiters, e.g., \verb|x|.
/// </summary>
private LatexNode ParseVerb(int start, int limit)
{
if (this.position < limit && this.text[this.position] == '*')
this.position++;
return this.ParseDelimitedCode(start, limit);
}
/// <summary>
/// Reads \lstinline or \mintinline with its options and its code, in braces or between delimiters.
/// </summary>
private LatexNode ParseInlineCode(int start, string name, int limit)
{
if (this.position < limit && this.text[this.position] == '[')
{
var close = this.text.AsSpan(this.position, limit - this.position).IndexOfAny(']', '\r', '\n');
if (close < 0 || this.text[this.position + close] != ']')
return new(LatexNodeKind.INVALID, start, this.position);
this.position += close + 1;
}
// The language of \mintinline:
if (name == "mintinline" && (this.position >= limit || this.text[this.position] != '{' || this.ParseRawArgument(limit) is null))
return new(LatexNodeKind.INVALID, start, this.position);
if (this.position < limit && this.text[this.position] == '{')
{
return this.ParseRawArgument(limit) is null
? new(LatexNodeKind.INVALID, start, this.position)
: new(LatexNodeKind.VERBATIM, start, this.position);
}
return this.ParseDelimitedCode(start, limit);
}
private LatexNode ParseDelimitedCode(int start, int limit)
{
if (this.position >= limit || char.IsWhiteSpace(this.text[this.position]) || char.IsAsciiLetter(this.text[this.position]))
return new(LatexNodeKind.INVALID, start, this.position);
var delimiter = this.text[this.position];
var close = this.text.AsSpan(this.position + 1, limit - this.position - 1).IndexOfAny(delimiter, '\r', '\n');
if (close < 0 || this.text[this.position + 1 + close] != delimiter)
{
this.position++;
return new(LatexNodeKind.INVALID, start, this.position);
}
this.position += close + 2;
return new(LatexNodeKind.VERBATIM, start, this.position);
}
/// <summary>
/// Reads the definition of a macro, e.g., \def\name#1{...}, which is markup as a whole.
/// </summary>
private LatexNode ParseDefinition(int start, string name, int limit)
{
var afterName = this.position;
this.SkipSpaces(limit);
if (this.position + 1 < limit && this.text[this.position] == '\\')
{
this.position++;
if (char.IsAsciiLetter(this.text[this.position]))
{
while (this.position < limit && char.IsAsciiLetter(this.text[this.position]))
this.position++;
}
else
this.position++;
// The parameters, e.g., #1#2, up to the body:
while (this.position < limit && this.text[this.position] is not ('{' or '}' or '%' or '\r' or '\n'))
this.position++;
if (this.position < limit && this.text[this.position] == '{' && this.ParseMandatoryArgument(limit) is not null)
return new(LatexNodeKind.COMMAND, start, this.position) { Name = name };
}
this.position = afterName;
return new(LatexNodeKind.COMMAND, start, afterName) { Name = name };
}
/// <summary>
/// Skips an overlay specification of Beamer right after a command, e.g., &lt;2-&gt; of \item&lt;2-&gt;.
/// </summary>
private void SkipOverlay(int limit)
{
if (this.position >= limit || this.text[this.position] != '<')
return;
var index = this.position + 1;
while (index < limit && index - this.position <= MAX_OVERLAY_LENGTH && this.text[index] is not ('>' or '<' or '{' or '}' or '\\') && !char.IsWhiteSpace(this.text[index]))
index++;
if (index < limit && index > this.position + 1 && this.text[index] == '>')
this.position = index + 1;
}
/// <summary>
/// Whether a line end starts a blank line, i.e., ends a paragraph.
/// </summary>
private bool IsParagraphBreak(int at, int limit)
{
if (at >= limit || this.text[at] is not ('\r' or '\n'))
return false;
var index = at + (this.text[at] == '\r' && at + 1 < limit && this.text[at + 1] == '\n' ? 2 : 1);
while (index < limit && this.text[index] is ' ' or '\t')
index++;
return index < limit && this.text[index] is '\r' or '\n';
}
/// <summary>
/// Finds where the paragraph at the position ends.
/// </summary>
private int ParagraphEnd(int limit)
{
for (var index = this.position; index < limit; index++)
{
if (this.text[index] is '\r' or '\n' && this.IsParagraphBreak(index, limit))
return index;
}
return limit;
}
/// <summary>
/// Skips the spaces after a command with letters, which TeX drops, or the empty group which keeps them.
/// </summary>
private void SkipSpaceAfterControlWord(int limit)
{
if (this.text.AsSpan(this.position, limit - this.position).StartsWith("{}", StringComparison.Ordinal))
{
this.position += 2;
return;
}
this.SkipSpaceWithinParagraph(limit);
}
/// <summary>
/// Skips spaces and at most one line end, as long as no blank line follows.
/// </summary>
private void SkipSpaceWithinParagraph(int limit)
{
this.SkipSpaces(limit);
if (this.position < limit && this.text[this.position] is '\r' or '\n' && !this.IsParagraphBreak(this.position, limit))
{
this.SkipLineEnd(limit);
this.SkipSpaces(limit);
}
}
private void SkipSpaces(int limit)
{
while (this.position < limit && this.text[this.position] is ' ' or '\t')
this.position++;
}
private void SkipWhiteSpace(int limit)
{
while (this.position < limit && this.text[this.position] is ' ' or '\t' or '\r' or '\n')
this.position++;
}
private void SkipLineEnd(int limit)
{
if (this.position < limit && this.text[this.position] == '\r')
this.position++;
if (this.position < limit && this.text[this.position] == '\n')
this.position++;
}
private void SkipToLineEnd(int limit)
{
var lineEnd = this.text.AsSpan(this.position, limit - this.position).IndexOfAny('\r', '\n');
this.position = lineEnd < 0 ? limit : this.position + lineEnd;
}
/// <summary>
/// A brace or a bracket which opens at a position, read up to a limit.
/// </summary>
/// <remarks>
/// Only its equality counts, since the parser notes the openings without an end in a set.
/// </remarks>
/// <param name="Position">Where it opens.</param>
/// <param name="Limit">Up to where its end was looked for.</param>
// ReSharper disable NotAccessedPositionalProperty.Local
private readonly record struct Opening(int Position, int Limit);
// ReSharper restore NotAccessedPositionalProperty.Local
}
@@ -0,0 +1,45 @@
using AIStudio.Tools.PluginSystem;
using AIStudio.Tools.Rust;
namespace AIStudio.Tools.DocumentSegments.Latex;
/// <summary>
/// LaTeX documents (.tex), whose paragraphs, headings, captions, list items, table cells, and title a model works on,
/// while the preamble, formulas, code, drawings, and comments stay as they are.
/// </summary>
/// <remarks>
/// <para>
/// The new document is the source with the words of each segment replaced, see LatexSegmentReader. New words are
/// escaped where LaTeX treats a character specially, see LatexWords, and go into the document as UTF-8.
/// </para>
/// <para>
/// The format leaves the language settings alone, e.g., of babel or polyglossia: a document may switch between
/// languages on purpose, and another script may need other packages or fonts, which only its author can choose.
/// The document counts as UTF-8 unless a byte order mark says otherwise; a document in another encoding is refused, see TextDocumentFile.
/// </para>
/// </remarks>
public sealed class LatexSegmentFormat : TextSegmentFormat
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(LatexSegmentFormat).Namespace, nameof(LatexSegmentFormat));
/// <inheritdoc />
public override FileTypeFilter FileType => FileTypes.TEX;
/// <inheritdoc />
public override string LimitsNotice => TB("Formulas, code, drawings, comments, and the preamble apart from the title stay as they are, as does text in commands which the document defines itself. The language settings, e.g., of babel or polyglossia, stay unchanged, and a language with another script may need further packages.");
/// <inheritdoc />
/// <remarks>
/// The markup the parser reads, the segments, and the new words take up to about 35 times the size of the file.
/// </remarks>
protected override int MemoryFactor => 35;
/// <inheritdoc />
protected override IReadOnlyList<TextSegment> ReadSegments(string text) => LatexSegmentReader.SegmentsOf(text);
/// <inheritdoc />
protected override string EncodedWords(string words) => LatexWords.Encoded(words);
/// <inheritdoc />
protected override string? DeclaredEncodingOf(string text) => LatexSegmentReader.DeclaredEncodingOf(text);
}
@@ -0,0 +1,595 @@
using System.Collections.Frozen;
using System.Text;
using System.Text.RegularExpressions;
namespace AIStudio.Tools.DocumentSegments.Latex;
/// <summary>
/// Reads the segments of a LaTeX document: its paragraphs, the texts of its headings and captions, the labels of its
/// list items, the cells of its tables, and its title.
/// </summary>
/// <remarks>
/// <para>
/// The segments come from the positions LatexParser reads for each part of the document, so the new document is the
/// source with the words of each segment replaced, and everything else stays byte for byte. Only the body is read,
/// apart from the title and subtitle in the preamble; a document without \begin{document}, e.g., a chapter which
/// another document includes, is a body as a whole.
/// </para>
/// <para>
/// Commands which mark up words, e.g., \textbf, \footnote, or \href, and groups in braces become pairs of tags, which
/// stand for their markup. Formulas, references, citations, code, and every command the reader does not know become
/// tags of their own. Layout, e.g., \label, \centering, \hline, or a comment, stays outside of a segment at its
/// edges, so that a model cannot move it into the words.
/// </para>
/// </remarks>
internal sealed partial class LatexSegmentReader
{
/// <summary>
/// The commands of the preamble whose texts a reader sees.
/// </summary>
private static readonly FrozenSet<string> PREAMBLE_HEADINGS = FrozenSet.Create(StringComparer.Ordinal, "title", "subtitle");
private const string BEGIN_DOCUMENT = @"\begin{document}";
private const string END_DOCUMENT = @"\end{document}";
/// <summary>
/// Markup which ends in a command with letters, e.g., \today: TeX would take letters right after it for part of
/// its name and drop a space after it.
/// </summary>
[GeneratedRegex(@"\\(?<name>[A-Za-z]+)\*?\z")]
private static partial Regex EndsWithControlWordRegex();
private readonly string text;
private readonly List<TextSegment> segments = [];
private LatexSegmentReader(string text) => this.text = text;
/// <summary>
/// Reads the segments of a document, in the order of the document.
/// </summary>
/// <param name="text">The document.</param>
public static List<TextSegment> SegmentsOf(string text)
{
var reader = new LatexSegmentReader(text);
var (preambleEnd, bodyStart) = RegionsOf(text);
foreach (var node in LatexParser.Parse(text, 0, preambleEnd))
{
if (node.Kind is LatexNodeKind.COMMAND && PREAMBLE_HEADINGS.Contains(node.Name))
reader.AddHeading(node);
}
reader.CollectBlocks(BodyNodesOf(text, bodyStart), isTable: false);
return reader.segments;
}
/// <summary>
/// Finds the encoding which a document names for itself, by the option of inputenc or by \inputencoding.
/// </summary>
/// <remarks>
/// Without either, LaTeX reads a document as UTF-8 since 2018, and XeLaTeX and LuaLaTeX always do. A document
/// may name several encodings, e.g., to switch between them; any of them other than UTF-8 is reason enough to
/// refuse the document, so that one is returned. Names in comments do not count.
/// </remarks>
/// <param name="text">The document.</param>
/// <returns>The first name of an encoding other than UTF-8, e.g., "latin1", or else the last name of UTF-8; null when the document names none.</returns>
public static string? DeclaredEncodingOf(string text)
{
string? declared = null;
foreach (Match match in InputEncodingRegex().Matches(text))
{
if (IsInComment(text, match.Index))
continue;
var options = (match.Groups["options"].Success ? match.Groups["options"].Value : match.Groups["encoding"].Value)
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
foreach (var option in options)
{
if (declared is null || TextDocumentFile.IsUtf8(declared))
declared = option;
}
}
return declared;
}
[GeneratedRegex(@"\\usepackage\s*\[(?<options>[^\]]*)\]\s*\{inputenc\}|\\inputencoding\s*\{(?<encoding>[^}]*)\}")]
private static partial Regex InputEncodingRegex();
/// <summary>
/// Finds where the preamble ends and the body starts; a document without \begin{document}, e.g., a chapter, is all body.
/// </summary>
private static Regions RegionsOf(string text)
{
var begin = IndexOutsideOfComments(text, BEGIN_DOCUMENT, 0);
return begin < 0 ? new Regions(0, 0) : new Regions(begin, begin + BEGIN_DOCUMENT.Length);
}
/// <summary>
/// Reads the body up to its \end{document}.
/// </summary>
/// <remarks>
/// The parser finds that end, since it skips comments, verbatim environments, and \verb, where a tutorial may well
/// show \end{document} as code. It reads the end as an INVALID node: the end of an environment which is not open.
/// </remarks>
private static List<LatexNode> BodyNodesOf(string text, int bodyStart)
{
var nodes = LatexParser.Parse(text, bodyStart, text.Length).ToList();
var end = nodes.FindIndex(node => node.Kind is LatexNodeKind.INVALID && IsEndOfDocument(text, node));
return end < 0 ? nodes : nodes[..end];
}
private static bool IsEndOfDocument(string text, LatexNode node) => string.Equals(
string.Concat(text.AsSpan(node.Start, node.End - node.Start).ToString().Where(character => !char.IsWhiteSpace(character))),
END_DOCUMENT,
StringComparison.Ordinal);
private static int IndexOutsideOfComments(string text, string value, int from)
{
var index = text.IndexOf(value, from, StringComparison.Ordinal);
while (index >= 0 && IsInComment(text, index))
index = text.IndexOf(value, index + value.Length, StringComparison.Ordinal);
return index;
}
private static bool IsInComment(string text, int index)
{
var lineStart = index == 0 ? 0 : text.LastIndexOfAny(['\r', '\n'], index - 1) + 1;
for (var position = lineStart; position < index; position++)
{
if (text[position] != '%')
continue;
// A percent sign after an odd number of backslashes is escaped:
var backslashes = 0;
while (position - backslashes - 1 >= lineStart && text[position - backslashes - 1] == '\\')
backslashes++;
if (backslashes % 2 == 0)
return true;
}
return false;
}
/// <summary>
/// Collects the segments of nodes which may hold paragraphs: the body, an environment, or a group with paragraphs.
/// </summary>
private void CollectBlocks(IReadOnlyList<LatexNode> nodes, bool isTable)
{
var items = new List<Item>();
foreach (var node in nodes)
{
if (!this.TryAddBlock(node, items, isTable))
this.AddInline(node, items, isTable);
}
this.Flush(items, isInBrackets: false);
}
/// <summary>
/// Handles a node which ends the paragraph before it, e.g., a blank line, a heading, or an environment.
/// </summary>
/// <returns>Whether the node ends the paragraph; otherwise, it belongs to the words.</returns>
private bool TryAddBlock(LatexNode node, List<Item> items, bool isTable)
{
switch (node.Kind)
{
case LatexNodeKind.PARAGRAPH_BREAK:
case LatexNodeKind.SPECIAL when isTable && node.Name == "&":
this.Flush(items, isInBrackets: false);
return true;
case LatexNodeKind.GROUP when ContainsBlocks(node.Children, isTable):
this.Flush(items, isInBrackets: false);
this.CollectBlocks(node.Children, isTable);
return true;
case LatexNodeKind.ENVIRONMENT when LatexCommands.EnvironmentOf(node.Name) is not LatexEnvironmentRole.MATH:
this.Flush(items, isInBrackets: false);
this.AddEnvironment(node);
return true;
case LatexNodeKind.COMMAND:
return this.TryAddBlockCommand(node, items, isTable);
default:
return false;
}
}
private void AddEnvironment(LatexNode environment)
{
var role = LatexCommands.EnvironmentOf(environment.Name);
if (role is LatexEnvironmentRole.VERBATIM)
return;
foreach (var argument in environment.Arguments)
{
if ((role is LatexEnvironmentRole.CONTAINER_WITH_TITLE && !argument.IsOptional) || (role is LatexEnvironmentRole.CONTAINER_WITH_NAME && argument.IsOptional))
this.AddArgument(argument, argument.IsOptional);
}
this.CollectBlocks(environment.Children, role is LatexEnvironmentRole.TABLE);
}
private bool TryAddBlockCommand(LatexNode node, List<Item> items, bool isTable)
{
var command = LatexCommands.Of(node.Name);
switch (command.Role)
{
case LatexCommandRole.HEADING:
this.Flush(items, isInBrackets: false);
this.AddHeading(node);
return true;
case LatexCommandRole.ITEM:
this.Flush(items, isInBrackets: false);
foreach (var label in node.Arguments.Where(argument => argument.IsOptional))
this.AddArgument(label, isInBrackets: true);
return true;
case LatexCommandRole.PARAGRAPH:
case LatexCommandRole.LINE_BREAK when isTable:
this.Flush(items, isInBrackets: false);
return true;
case LatexCommandRole.WORDS when TextArgumentOf(node, command) is { } argument && ContainsBlocks(argument.Children, isTable):
this.Flush(items, isInBrackets: false);
this.CollectBlocks(argument.Children, isTable);
return true;
default:
return false;
}
}
/// <summary>
/// Adds the segments of a heading or a caption: its text and its optional arguments, e.g., a short title.
/// </summary>
private void AddHeading(LatexNode heading)
{
var command = LatexCommands.Of(heading.Name);
var mandatoryIndex = 0;
foreach (var argument in heading.Arguments)
{
if (argument.IsOptional)
this.AddArgument(argument, isInBrackets: true);
else if (mandatoryIndex++ == command.TextArgument)
this.AddArgument(argument, isInBrackets: false);
}
}
/// <summary>
/// Adds the segment of an argument which holds words, or the segments of its paragraphs.
/// </summary>
private void AddArgument(LatexArgument argument, bool isInBrackets)
{
if (ContainsBlocks(argument.Children, isTable: false))
{
this.CollectBlocks(argument.Children, isTable: false);
return;
}
var items = new List<Item>();
foreach (var child in argument.Children)
this.AddInline(child, items, isTable: false);
this.Flush(items, isInBrackets);
}
/// <summary>
/// Adds a node within the words of a paragraph.
/// </summary>
private void AddInline(LatexNode node, List<Item> items, bool isTable)
{
switch (node.Kind)
{
case LatexNodeKind.TEXT:
this.AddText(node, items);
break;
case LatexNodeKind.ESCAPED_WORDS:
items.Add(new WordsItem(node.Start, node.End, node.Words));
break;
case LatexNodeKind.SPECIAL when node.Name == "~":
items.Add(new WordsItem(node.Start, node.End, LatexWords.NO_BREAK_SPACE));
break;
case LatexNodeKind.COMMENT:
items.Add(this.Comment(node));
break;
case LatexNodeKind.MATH or LatexNodeKind.VERBATIM:
case LatexNodeKind.SPECIAL when node.Name != "&":
case LatexNodeKind.ENVIRONMENT when LatexCommands.EnvironmentOf(node.Name) is LatexEnvironmentRole.MATH:
items.Add(this.Placeholder(node, isLayout: false));
break;
case LatexNodeKind.GROUP:
items.Add(this.Pair(node.Start, node.End, node.Children, isTable));
break;
case LatexNodeKind.COMMAND:
items.Add(this.InlineCommand(node, isTable));
break;
// An ampersand outside of a table, a block within words, or markup the parser could not follow:
default:
items.Add(new InvalidItem(node.Start, node.End));
break;
}
}
private Item InlineCommand(LatexNode node, bool isTable)
{
var command = LatexCommands.Of(node.Name);
return command.Role switch
{
LatexCommandRole.WORDS when TextArgumentOf(node, command) is { } argument => this.Pair(node.Start, node.End, argument.Children, isTable),
LatexCommandRole.LAYOUT or LatexCommandRole.LINE_BREAK => this.Placeholder(node, isLayout: true),
LatexCommandRole.WORDS or LatexCommandRole.INLINE => this.Placeholder(node, isLayout: false),
_ => new InvalidItem(node.Start, node.End),
};
}
private PairItem Pair(int start, int end, IReadOnlyList<LatexNode> nodes, bool isTable)
{
var children = new List<Item>();
foreach (var child in nodes)
this.AddInline(child, children, isTable);
return new PairItem(start, end, children);
}
/// <summary>
/// Splits words at their white space, so that the white space at the edges of a segment stays outside of it.
/// </summary>
private void AddText(LatexNode node, List<Item> items)
{
var index = node.Start;
while (index < node.End)
{
var isSpace = IsWhiteSpace(this.text[index]);
var end = index + 1;
while (end < node.End && IsWhiteSpace(this.text[end]) == isSpace)
end++;
items.Add(isSpace ? new SpaceItem(index, end) : new WordsItem(index, end, this.text[index..end]));
index = end;
}
}
private static bool IsWhiteSpace(char character) => character is ' ' or '\t' or '\r' or '\n';
/// <summary>
/// A comment ends with its line, and TeX skips the spaces at the start of the next one. Its markup starts with a
/// space when the source has one before it, so that words placed right before it stay apart from the words after it.
/// </summary>
private PlaceholderItem Comment(LatexNode node)
{
var markup = this.text[node.Start..node.End];
if (node.Start > 0 && IsWhiteSpace(this.text[node.Start - 1]))
markup = " " + markup;
return new PlaceholderItem(node.Start, node.End, markup, IsLayout: true);
}
private PlaceholderItem Placeholder(LatexNode node, bool isLayout) => new(node.Start, node.End, this.text[node.Start..node.End], isLayout);
/// <summary>
/// Finishes the segment of a paragraph, if it has any words.
/// </summary>
private void Flush(List<Item> items, bool isInBrackets)
{
if (this.Build(items, isInBrackets) is { } segment)
this.segments.Add(segment);
items.Clear();
}
private TextSegment? Build(List<Item> items, bool isInBrackets)
{
var first = items.FindIndex(IsContent);
if (first < 0 || items.Any(IsInvalid))
return null;
var last = items.FindLastIndex(IsContent);
var builder = new TextSegmentBuilder();
this.Emit(items, first, last, builder);
return builder.TryBuild(items[first].Start, items[last].End, isInBrackets ? LatexWords.EncodedInBrackets : null);
}
/// <summary>
/// Puts items together into a segment; markup right next to markup becomes one tag, e.g., ~\ref{a}\cite{b}.
/// </summary>
private void Emit(List<Item> items, int first, int last, TextSegmentBuilder builder)
{
var markup = new StringBuilder();
for (var index = first; index <= last; index++)
{
var item = items[index];
if (this.PlaceholderMarkupOf(item) is { } placeholder)
{
markup.Append(placeholder);
continue;
}
AddPlaceholder(markup, builder);
switch (item)
{
case WordsItem words:
builder.Words(words.Words);
break;
case SpaceItem:
builder.Words(" ");
break;
case PairItem pair:
this.EmitPair(pair, builder);
break;
}
}
AddPlaceholder(markup, builder);
}
/// <summary>
/// Writes a pair, whose layout and white space at its edges belong to its markup, e.g., \bfseries of {\bfseries words}.
/// </summary>
/// <remarks>
/// A label is no layout of the pair but a target of references, e.g., \label within a footnote: it becomes a tag of
/// its own, which follows the words when the model drops the pair, rather than going with the markup of the pair.
/// </remarks>
private void EmitPair(PairItem pair, TextSegmentBuilder builder)
{
var first = pair.Children.FindIndex(item => IsContent(item) || IsLabel(item));
var last = pair.Children.FindLastIndex(item => IsContent(item) || IsLabel(item));
var id = builder.Open(KeptApart(this.text[pair.Start..pair.Children[first].Start]));
this.Emit(pair.Children, first, last, builder);
builder.Close(id, this.text[pair.Children[last].End..pair.End]);
}
private static void AddPlaceholder(StringBuilder markup, TextSegmentBuilder builder)
{
if (markup.Length == 0)
return;
builder.Placeholder(KeptApart(markup.ToString()));
markup.Clear();
}
/// <summary>
/// Ends markup which ends in a command with letters, so that new words after it, with or without a space, stay
/// words of their own. Unchanged segments keep the source as it is.
/// </summary>
/// <remarks>
/// After a command which shows something, e.g., \today, an empty group keeps the space which the new words may
/// start with. After layout, e.g., \hline, a space ends the command: TeX drops it, which changes nothing there,
/// while an empty group would count as the content of a cell of a table, after which \hline or \multicolumn are
/// misplaced.
/// </remarks>
private static string KeptApart(string markup) => EndsWithControlWordRegex().Match(markup) switch
{
{ Success: false } => markup,
var command when LatexCommands.Of(command.Groups["name"].Value).Role is LatexCommandRole.LAYOUT or LatexCommandRole.LINE_BREAK => markup + " ",
_ => markup + "{}",
};
/// <summary>
/// The markup of an item which becomes a tag of its own: a placeholder, or a pair without letters, e.g., \textbf{42}.
/// </summary>
private string? PlaceholderMarkupOf(Item item) => item switch
{
PlaceholderItem placeholder => placeholder.Markup,
PairItem pair when !HasLetters(pair) => this.text[pair.Start..pair.End],
_ => null,
};
private static bool IsContent(Item item) => item is not (SpaceItem or PlaceholderItem { IsLayout: true });
private static bool IsLabel(Item item) => item is PlaceholderItem { Markup: var markup } && LabelRegex().IsMatch(markup);
[GeneratedRegex(@"\A\s*\\label\b")]
private static partial Regex LabelRegex();
private static bool IsInvalid(Item item) => item is InvalidItem || (item is PairItem pair && pair.Children.Any(IsInvalid));
private static bool HasLetters(Item item) => item switch
{
WordsItem words => words.Words.HasLetters,
PairItem pair => pair.Children.Any(HasLetters),
_ => false,
};
/// <summary>
/// Whether nodes hold something which ends a paragraph, so that they cannot be the words of a pair.
/// </summary>
private static bool ContainsBlocks(IReadOnlyList<LatexNode> nodes, bool isTable) => nodes.Any(node => node.Kind switch
{
LatexNodeKind.PARAGRAPH_BREAK => true,
LatexNodeKind.SPECIAL => isTable && node.Name == "&",
LatexNodeKind.GROUP => ContainsBlocks(node.Children, isTable),
LatexNodeKind.ENVIRONMENT => LatexCommands.EnvironmentOf(node.Name) is not LatexEnvironmentRole.MATH,
LatexNodeKind.COMMAND => IsBlockCommand(node, isTable),
_ => false,
});
private static bool IsBlockCommand(LatexNode node, bool isTable)
{
var command = LatexCommands.Of(node.Name);
return command.Role switch
{
LatexCommandRole.HEADING or LatexCommandRole.ITEM or LatexCommandRole.PARAGRAPH => true,
LatexCommandRole.LINE_BREAK => isTable,
LatexCommandRole.WORDS => TextArgumentOf(node, command) is { } argument && ContainsBlocks(argument.Children, isTable),
_ => false,
};
}
/// <summary>
/// Finds the argument in braces which holds the words of a command.
/// </summary>
private static LatexArgument? TextArgumentOf(LatexNode node, LatexCommand command)
{
var mandatoryIndex = 0;
foreach (var argument in node.Arguments)
{
if (argument.IsOptional)
continue;
if (mandatoryIndex++ == command.TextArgument)
return argument;
}
return null;
}
/// <summary>
/// A part of a paragraph, with where it lies in the source.
/// </summary>
private abstract record Item(int Start, int End);
/// <summary>
/// Words, as a model gets them.
/// </summary>
private sealed record WordsItem(int Start, int End, string Words) : Item(Start, End);
/// <summary>
/// White space, which a model gets as one space.
/// </summary>
private sealed record SpaceItem(int Start, int End) : Item(Start, End);
/// <summary>
/// Markup which becomes a tag of its own; layout stays outside of a segment at its edges.
/// </summary>
private sealed record PlaceholderItem(int Start, int End, string Markup, bool IsLayout) : Item(Start, End);
/// <summary>
/// Markup around words, e.g., \textbf{...} or a group.
/// </summary>
private sealed record PairItem(int Start, int End, List<Item> Children) : Item(Start, End);
/// <summary>
/// Markup the reader cannot make words of, which leaves its paragraph as it is.
/// </summary>
private sealed record InvalidItem(int Start, int End) : Item(Start, End);
/// <summary>
/// Where the preamble of a document ends and its body starts.
/// </summary>
/// <param name="PreambleEnd">Where the preamble ends: at \begin{document}; 0 for a document without one.</param>
/// <param name="BodyStart">Where the body starts: right after \begin{document}; 0 for a document without one.</param>
private readonly record struct Regions(int PreambleEnd, int BodyStart);
}
@@ -0,0 +1,141 @@
using System.Collections.Frozen;
using System.Diagnostics.CodeAnalysis;
using System.Text;
namespace AIStudio.Tools.DocumentSegments.Latex;
/// <summary>
/// Turns the markup of LaTeX which stands for words into those words, and new words into markup.
/// </summary>
/// <remarks>
/// A model gets the words as a reader of the document sees them, e.g., "ü" for \"u, so that it never has to keep
/// markup within a word. New words go into the document as UTF-8, which LaTeX reads by default since 2018; only
/// the characters which LaTeX treats specially get escaped.
/// </remarks>
internal static class LatexWords
{
/// <summary>
/// What a tilde stands for.
/// </summary>
public const string NO_BREAK_SPACE = " ";
/// <summary>
/// What \, stands for, e.g., in "z.\,B.".
/// </summary>
public const string THIN_SPACE = " ";
/// <summary>
/// Commands with letters which stand for a character, e.g., \ss or \glqq.
/// </summary>
private static readonly FrozenDictionary<string, string> LETTER_COMMANDS = new Dictionary<string, string>(StringComparer.Ordinal)
{
["ss"] = "ß", ["ae"] = "æ", ["AE"] = "Æ", ["oe"] = "œ", ["OE"] = "Œ", ["aa"] = "å", ["AA"] = "Å", ["o"] = "ø",
["O"] = "Ø", ["l"] = "ł", ["L"] = "Ł", ["i"] = "ı", ["j"] = "ȷ",
["glqq"] = "„", ["grqq"] = "“", ["glq"] = "‚", ["grq"] = "‘", ["flqq"] = "«", ["frqq"] = "»", ["flq"] = "‹",
["frq"] = "›", ["quotedblbase"] = "„", ["quotesinglbase"] = "‚", ["textquotedblleft"] = "“",
["textquotedblright"] = "”", ["textquoteleft"] = "‘", ["textquoteright"] = "’", ["guillemotleft"] = "«",
["guillemotright"] = "»", ["guillemetleft"] = "«", ["guillemetright"] = "»", ["guilsinglleft"] = "‹",
["guilsinglright"] = "›", ["ldots"] = "…", ["dots"] = "…", ["textellipsis"] = "…", ["textendash"] = "–",
["textemdash"] = "—", ["S"] = "§",
}.ToFrozenDictionary(StringComparer.Ordinal);
/// <summary>
/// The accents of LaTeX with the combining characters of Unicode they stand for.
/// </summary>
private static readonly FrozenDictionary<string, char> ACCENTS = new Dictionary<string, char>(StringComparer.Ordinal)
{
["\""] = '̈', ["'"] = '́', ["`"] = '̀', ["^"] = '̂', ["~"] = '̃', ["="] = '̄',
["."] = '̇', ["c"] = '̧', ["v"] = '̌', ["u"] = '̆', ["H"] = '̋', ["r"] = '̊',
["k"] = '̨', ["d"] = '̣', ["b"] = '̱',
}.ToFrozenDictionary(StringComparer.Ordinal);
/// <summary>
/// Finds the character a command with letters stands for, e.g., "ß" for \ss.
/// </summary>
/// <param name="name">The name of the command, without its backslash.</param>
/// <param name="words">The character.</param>
public static bool TryLetterCommand(string name, [NotNullWhen(true)] out string? words) => LETTER_COMMANDS.TryGetValue(name, out words);
/// <summary>
/// Finds the combining character an accent stands for, e.g., U+0308 for \".
/// </summary>
/// <param name="accent">The name of the accent, without its backslash, e.g., "\"" or "c".</param>
/// <param name="combining">The combining character.</param>
public static bool TryAccent(string accent, out char combining) => ACCENTS.TryGetValue(accent, out combining);
/// <summary>
/// Whether a character after a backslash is an accent, e.g., the quote of \"a.
/// </summary>
public static bool IsSymbolAccent(char character) => character is '"' or '\'' or '`' or '^' or '~' or '=' or '.';
/// <summary>
/// Puts a letter and an accent together, e.g., "ü" for u and \".
/// </summary>
public static string WithAccent(char letter, char combining) => string.Concat(letter.ToString(), combining.ToString()).Normalize(NormalizationForm.FormC);
/// <summary>
/// Makes new words fit into the text of a document.
/// </summary>
public static string Encoded(string words) => Encode(words, isInBrackets: false);
/// <summary>
/// Makes new words fit into an optional argument, e.g., the short title of a section, which a closing bracket would end.
/// </summary>
public static string EncodedInBrackets(string words) => Encode(words, isInBrackets: true);
private static string Encode(string words, bool isInBrackets)
{
// A blank line would end the paragraph, a line break within it changes nothing:
words = TextSegmentWriter.InOneLine(words);
var builder = new StringBuilder(words.Length + 16);
var isAtStart = true;
for (var index = 0; index < words.Length; index++)
{
var character = words[index];
switch (character)
{
case '\\':
builder.Append(@"\textbackslash{}");
break;
case '{' or '}' or '$' or '&' or '%' or '#' or '_':
builder.Append('\\').Append(character);
break;
case '^':
builder.Append(@"\^{}");
break;
case '~':
builder.Append(@"\textasciitilde{}");
break;
case ' ':
builder.Append('~');
break;
// pdfLaTeX knows no thin spaces as characters:
case ' ' or ' ':
builder.Append(@"\,");
break;
// After a line break or an item, a bracket would open an optional argument, also after spaces, which LaTeX skips there:
case '[' when isAtStart:
builder.Append("{[}");
break;
case ']' when isInBrackets:
builder.Append("{]}");
break;
default:
builder.Append(character);
break;
}
isAtStart &= character is ' ' or '\t';
}
return builder.ToString();
}
}