How I finished my AI grammar checker for LaTeX that feel illegal to know
The last bug I chased was not a linguistic one. It was an ampersand inside an align environment that my checker had interpreted as the end of a sentence. Before that, it had spent an afternoon insisting that \citep{vaswani2017attention} was a misspelling of something, and another hour rewriting the word "et" in "et al." into "and." Fixing English grammar inside a document format designed to ignore English turned out to be the entire job. The grammar was the easy part. The document was the hard part.
LaTeX is a typesetting system with a sixty-year-old assumption baked into it: prose is an opaque stream of characters, and the only thing that matters is where the letters land on the page. Mainstream word processors cannot open a .tex file with any dignity. Browser-based grammar extensions see a wall of backslashes and either surrender or hallucinate. Meanwhile, millions of physicists, mathematicians, economists, and graduate students write their most consequential sentences in exactly this format, with no real editorial safety net beyond a co-author's tired eyes.
That gap is what I spent the better part of a year closing. The result is a grammar and style checker that reads LaTeX as LaTeX — preamble, macros, math mode, citations, cross-references — and only then evaluates the English underneath. How I finished my AI grammar checker for LaTeX that feel illegal to know is mostly a story about unglamorous engineering, plus a handful of insights that genuinely changed how I think about automated editing.

The Complete Overview of [Topic]
The project began with a narrow frustration and grew into a general-purpose editorial engine. The frustration was that my own manuscripts, submitted to journals that still expect LaTeX source, contained the kind of errors a competent copy editor catches in seconds: article agreement failures, dangling modifiers, inconsistent terminology, passive constructions stacked three deep in a limitations section. The engine I built does not merely flag those. It flags them while preserving every byte of formatting, every macro definition, every line of a delicate tabular that a careless rewrite would shatter.
Architecturally, the system is two programs wearing one coat. The front end is a tokenizer and parser that turns a .tex source tree into a structured representation, marking regions as prose, mathematics, verbatim, comment, or metadata. The back end is a hybrid checker: a curated rule set for the errors that matter in technical writing, and a fine-tuned language model for fluency, clarity, and register. The parser decides what the model is allowed to see. That division of labour is the single most important decision in the whole build, and it is why finishing the AI grammar checker for LaTeX took four times longer than expected.
Historical Background and Evolution
Grammar checking as a discipline is older than computing. The twentieth century gave us the style manual and the human copy editor; the 1980s gave us punctuation dictionaries in word processors, which mostly counted spaces and shouted about double spaces. The 1990s and 2000s brought rule engines in earnest, most notably the rise of LanguageTool and its predecessors, which encoded linguistic knowledge as explicit patterns over part-of-speech tags. These systems were transparent, editable, and stubbornly literal. They remain the backbone of serious checking today, and any tool claiming to replace them is usually just wrapping one.
Table of Contents
- The Complete Overview of [Topic]
- Historical Background and Evolution
- Core Mechanisms: How It Works
- Key Benefits and Crucial Impact
- Major Advantages
- Comparative Analysis
- Future Trends and Innovations
- Conclusion
- Comprehensive FAQs
- Q: Why do standard grammar checkers perform so badly on LaTeX documents?
- Q: How does a structure-aware checker avoid altering equations and formatting?
- Q: Does the neural component replace traditional rule-based checking?
- Q: Can the checker run entirely offline on unpublished research?
- Q: How much time does a project like this realistically require?
- Q: Is it suitable for languages other than English, and for non-native speakers?
LaTeX, meanwhile, evolved on a separate track with no interest in prose at all. Donald Knuth built TeX in the late 1970s to typeset The Art of Computer Programming to his own standards; Leslie Lamport wrapped it in a document-preparation layer that made it usable by ordinary scientists. The ecosystem rewarded precision about layout and silence about language. Over the following decades, a handful of adapters appeared — detex, opendetex, later LanguageTool's own LaTeX mode, and various editor plugins — but they all shared one strategy: strip the markup, check the residue, then map the warnings back to source lines as best you can. That strategy loses information at every step. Math becomes noise, macros become unknown words, and the reported column number often points at a line the author did not write.
The transformer era changed what was possible without changing that structural problem. Neural models made fluency judgments cheap and reasonably good, which is why so many recent tools feel magical on plain text and useless on source code. My conclusion after several months of iteration was that the interesting work was not the model. It was the document model underneath it.
Core Mechanisms: How It Works
Ingestion is where the design lives. The tokenizer walks the file character by character with a stack-based state machine, tracking brace depth, environment nesting, and math mode. It recognises comments and discards them, treats \begin{verbatim} as sacrosanct, and classifies each remaining span. A user-defined macro in the preamble is parsed once and expanded wherever it appears, so a custom \newcommand{\R}{\mathbb{R}} never becomes a spelling error forty times in the results section. Crucially, the parser retains a bidirectional map between every prose token and its exact byte offset in the original file. Suggestions are computed against the cleaned prose stream and then projected back to source coordinates, which is what allows the tool to propose an edit to line 812 of a 900-line manuscript without disturbing the surrounding \section commands.
The checking stage runs in two passes. The rule pass handles categories where precision matters more than sophistication: article and preposition choice, subject–verb agreement across parentheticals, repeated words, inconsistent hyphenation of technical terms, notation drift such as switching between d/dt and d/dt within one section, and a house-style list the user can maintain. The neural pass receives only spans the parser has marked as prose, with math and citations replaced by neutral placeholders so the model does not attempt to edit an equation. Its output is constrained: it may propose a replacement for a span, never restructure across a span boundary, and never touch anything the parser marked as protected. Every suggestion carries a confidence value, and the interface suppresses anything below a user-set threshold, because a checker that cries wolf on technical prose gets muted within a week.
Key Benefits and Crucial Impact
The practical effect is difficult to overstate for anyone who writes with equations. Authors stop paying a tax for defensive writing — the habit of avoiding constructions the tool cannot handle, or of running every paragraph through a separate text file and pasting the result back with fingers crossed. Reviewers receive cleaner drafts. Non-native English speakers, who constitute a substantial share of the technical literature, gain a level of copy-editing that previously required institutional funding or a generous colleague.
There is a subtler benefit that I did not anticipate. Because the checker parses the document structure, it can reason about the document as a whole rather than sentence by sentence. It knows what section a sentence lives in, whether a term has been defined, whether a variable was introduced before it was used. That is where a LaTeX-aware grammar checker begins to feel like an editor rather than a spellchecker, and where the phrase how I finished my AI grammar checker for LaTeX that feel illegal to know starts to make sense: the capabilities that seem like cheating are just structural awareness applied to language.
Writing about the tool is harder than writing with it. The most common question I receive is whether it will make authors lazy. My answer is that a copy editor is a conversation, and a grammar checker is only dangerous when nobody is listening.
Major Advantages
- Format fidelity by construction. Because every suggestion is computed in a cleaned representation and mapped back to original byte offsets, equations, alignment environments, citation keys, and bibliography commands survive editing untouched. The failure mode of strip-and-check tools — silently mangling a matrix — is architecturally impossible rather than merely unlikely.
- Mathematical and notation awareness. The parser distinguishes a stray comma in prose from a comma inside a set-builder expression, which eliminates the flood of false positives that makes generic checkers intolerable on technical writing.
- Terminology and notation consistency across long documents. With document-level context, the system enforces that a symbol, an abbreviation, and a technical term are rendered the same way from the introduction through the appendix.
- Local and private operation. Unpublished research is sensitive. The whole pipeline runs on the author's machine, with an optional self-hosted server for shared lab use, so drafts never leave the institution.
- Extensible house style. Journals and labs maintain their own rule files in plain text, covering preferred phrasings, prohibited constructions, and citation conventions, and those rules are versioned alongside the manuscript.

Comparative Analysis
| Approach | Strengths and Failure Modes |
|---|---|
| Generic cloud grammar checkers on raw .tex source | Excellent English coverage and zero setup, but they treat markup as prose. Expect constant false positives on macros, broken math, and suggestion coordinates that do not correspond to the line the author actually typed. |
| Detex-style stripping plus a classical rule engine such as LanguageTool | Transparent, fast, and fully offline. Reliability depends on the quality of the stripping stage; nested environments, conditional compilation, and custom macros routinely degrade accuracy. |
| Neural rewrites without document structure | Produces fluent, confident prose and occasionally improves genuinely clumsy sentences, but it cannot tell an equation from a sentence and will happily normalise notation the author intended to keep distinct. |
| Structure-aware hybrid checker with local inference | Highest precision on technical writing and the only approach that preserves formatting guarantees, at the cost of a nontrivial build, per-project configuration, and a smaller pool of people able to maintain it. |
Future Trends and Innovations
The direction of travel is toward checkers that understand intent rather than correctness. If a system can parse the preamble, the theorem environments, and the cross-reference graph, it can tell an author that a claim in the introduction is stated more strongly than the corresponding theorem supports, or that a term introduced in Section 3 is used without definition in Section 5. Those are editorial judgments rather than grammatical ones, and they are the frontier. I expect consolidation here: within a few years, structure-aware checking will be a standard feature of LaTeX editors and continuous-integration pipelines for institutional repositories, running on every commit in the same way a linter already runs on source code.
The second trend is smaller and stranger models tuned for constrained output. My experience with finishing an AI grammar checker for LaTeX suggests that the value of a model in this setting lies less in raw capability than in obedience — accepting a protected-span contract and never violating it. Small models fine-tuned on narrow editorial tasks, executed locally, are already good enough for that, and they make privacy-preserving tooling the default rather than the premium option. The economics of technical publishing, where much of the labour is unpaid and the confidentiality obligations are real, point firmly in that direction.

Conclusion
Building this consumed more time than the original estimate by a wide margin, and nearly all of the overrun went into the parts nobody sees: environment nesting, macro expansion, byte-offset bookkeeping, the hundred small decisions about what counts as protected text. The lesson is not that LaTeX is difficult. It is that language tooling inherits the complexity of whatever format it is asked to edit, and that format complexity is where the real engineering sits. Anyone attempting something similar should budget for the parser first and the model second.
What remains is a tool I use daily and trust on my own manuscripts before submission. It is not a substitute for a human reader, and it does not pretend to be. It is a careful, private, structurally literate second pass that knows the difference between a sentence and a summation — and that, I have found, is worth considerably more than a generic assistant asked to guess at what a backslash means.
Comprehensive FAQs
Q: Why do standard grammar checkers perform so badly on LaTeX documents?
A: They are designed for plain prose and receive raw markup. A macro such as \emph{} or a command like \ref{fig:1} looks to them like a misspelled word, and mathematical expressions look like sentences with unusual vocabulary. The usual workaround is to strip the markup before checking, but stripping discards precisely the information needed to place a suggestion in the right location and to avoid touching anything the author protected. The result is a high volume of false positives and unreliable positions in the source file.
Q: How does a structure-aware checker avoid altering equations and formatting?
A: Through a two-representation design. The tool parses the source into a tree, classifies each region as prose, math, verbatim, comment, or metadata, and runs linguistic analysis only over the prose spans. Each token keeps a pointer to its original byte offset. Suggestions are generated in the cleaned representation and then projected back onto the source, so a change is applied to a specific character range rather than to a rewritten paragraph. Protected regions are never offered as edit targets.
Q: Does the neural component replace traditional rule-based checking?
A: No, and treating it as a replacement is a common and expensive mistake. Rule sets remain far more reliable for closed-class phenomena such as agreement, article choice, repeated words, and house-style prohibitions, and they are auditable by the user. The model is most useful for fluency, register, and awkward phrasing, where no finite rule list suffices. Combining both, with the model operating under strict structural constraints, outperforms either alone on technical prose.
Q: Can the checker run entirely offline on unpublished research?
A: Yes. That was a design requirement rather than an afterthought. Tokenizing, rule checking, and inference all execute locally, with an optional self-hosted instance for a research group sharing a house style. Drafts, including embargoed results and confidential peer review material, are never transmitted to a third-party service, which matters considerably for anyone subject to institutional data-handling policy.
Q: How much time does a project like this realistically require?
A: Expect the parsing and document-representation layer to dominate the schedule, often consuming three to four times the effort of the linguistic work itself. Edge cases accumulate slowly and individually: conditional compilation, nested environments, verb commands, custom macros declared in an included file, and unusual encodings. Anyone scoping such a project should prototype against a large corpus of real manuscripts early, because a handful of unusual journals will surface failure modes no synthetic test set contains.
Q: Is it suitable for languages other than English, and for non-native speakers?
A: The document layer is language-agnostic, since parsing LaTeX has nothing to do with English, while the checking layer must be localised separately with its own rule sets and models. For non-native speakers of English writing in LaTeX, the practical benefit is substantial: the tool delivers a consistent copy-editing pass at zero marginal cost, and the document-level view catches inconsistencies in terminology and notation that a sentence-by-sentence review usually misses.
Leave a Comment
Comments are moderated before appearing. The data you submit is processed according to the Privacy Policy of buydissertationyjxy.com.