The Story of How I Finished My AI Grammar Checker for LaTeX PhD Motivation

Published

The cursor blinked with a rhythm that felt less like a heartbeat and more like a countdown. For three years, the gap between the theoretical elegance of my research and the syntactic mess of my drafts had widened into a chasm. Standard grammar tools choked on the backslashes, the environments, and the sheer density of mathematical notation that defines a dissertation written in LaTeX. They treated markup as noise, stripping context and leaving me to manually reconstruct the logic of every sentence after a "correction."

This friction was not merely technical; it was psychological. Every red squiggly line under a valid citation command or a custom macro was a micro-interruption, a tiny tax on cognitive load paid hundreds of times a day. I realized that the problem was not the grammar, but the parser. The industry had optimized for prose, ignoring the hybrid language of the sciences where text and code are inseparable. That realization became the seed for a project that would consume my nights and rewire my writing workflow entirely.

The journey to build a context-aware validator for scientific markup began not with a grand architecture diagram, but with a simple, stubborn refusal to accept the status quo. I needed a system that understood that `\section{Introduction}` is structural, not a sentence fragment, and that `$E=mc^2$` is a semantic unit, not a string of characters to be spell-checked individually. This article traces the engineering decisions, the linguistic modeling, and the personal drive that bridged the gap between a frustrating workflow and a finished tool.

how i finished my ai grammar checker for latex phd motivation

The Complete Overview of the Project Scope

The objective was never to replicate Grammarly or LanguageTool for the masses. The scope was narrowly defined: a high-precision, low-recall linter designed exclusively for the idiosyncrasies of academic LaTeX. It needed to distinguish between the preamble and the document body, respect the scope of environments like `align` or `tikzpicture`, and handle bibliography keys without flagging them as unknown words. The architecture had to be local-first, ensuring that unpublished research never left the machine, a non-negotiable requirement for pre-publication drafts.

Success was measured not by user acquisition metrics, but by the reduction of "false positive fatigue." If the tool flagged a legitimate LaTeX construct as an error, it lost trust. Trust, in this domain, is binary. Once a researcher ignores a warning because the tool "doesn't get LaTeX," the tool is effectively dead. Therefore, the core engineering challenge was semantic parsing: building an Abstract Syntax Tree (AST) representation of the document before a single grammatical rule was applied.

Historical Background and Evolution

The landscape of LaTeX editing has historically been polarized. On one side sit powerful IDEs like Overleaf or TeXstudio, offering syntax highlighting and compilation management but relying on regex-based linters (like `chktex` or `lacheck`) that are brittle and syntactically shallow. On the other side sit modern AI writing assistants, which possess deep semantic understanding of English but treat the `.tex` file as a plain text blob, hallucinating corrections that break compilation. There was no middle ground where structural awareness met linguistic intelligence.

Table of Contents

My evolution toward this solution mirrored the evolution of the tooling itself. Early attempts involved complex `sed` and `awk` scripts to strip commands before piping text to LanguageTool. This "strip-and-check" approach failed catastrophically on cross-references (`\ref{fig:results}` becoming "fig results") and math-mode variables. The breakthrough came with the maturation of Tree-sitter parsers for LaTeX. Finally, there was a robust, incremental parsing library capable of producing a concrete syntax tree fast enough for real-time editor integration. This technological inflection point made the project viable.

Core Mechanisms: How It Works

The pipeline operates in three distinct stages: Parsing, Filtering, and Inference. First, the Tree-sitter grammar generates a lossless syntax tree. This tree retains every node—commands, environments, braces, comments, and plain text—preserving byte-offsets for precise error reporting. Second, a "Semantic Filter" walks this tree. It identifies and isolates "Protected Zones": math mode (inline and display), verbatim environments, bibliography keys, label definitions, and user-defined macros. These nodes are pruned from the linguistic stream but their positions are mapped so annotations can be projected back onto the source code accurately.

The third stage sends the remaining "clean" text segments—pure prose—to a local Large Language Model (LLM) quantized for CPU inference (specifically a fine-tuned Llama-3 variant optimized for grammatical error correction). Because the context window receives only human-readable sentences, the model isn't confused by markup. The prompt engineering enforces a strict JSON output schema: `{ "offset": int, "length": int, "suggestion": string, "type": "grammar|style|terminology" }`. The host application then maps these offsets back through the Semantic Filter to the original document coordinates, rendering squiggles in the editor via the Language Server Protocol (LSP).

Key Benefits and Crucial Impact

The immediate impact was the restoration of "flow state." Writing a dissertation involves oscillating between deep technical reasoning and linguistic polishing. By offloading the latter to a reliable agent that respects the former's syntax, the context-switching cost plummeted. I no longer needed to compile the document to see if a grammar fix broke a macro; the LSP integration provided instant, compile-safe feedback directly in Neovim and VS Code.

Beyond speed, the tool enforced a consistency that human proofreading struggles to maintain across 200+ pages. It caught subtle issues: inconsistent hyphenation of compound adjectives (e.g., "state-of-the-art" vs "state of the art"), misuse of Latin abbreviations (e.g., "e.g." vs "i.e."), and the specific passive voice constructions discouraged in my department's style guide. It became a silent co-author, enforcing the house style so I could focus on the argument.

The best tool for a writer is the one that disappears, leaving only the words. Building that invisibility required the tool to understand the container as well as the content.

Major Advantages

  • Compile-Safe Corrections: Suggestions are guaranteed not to break the LaTeX build because the parser understands scope and escaping rules.
  • Zero Data Egress: The entire pipeline runs locally; sensitive pre-print data never touches an API endpoint.
  • Macro-Aware Intelligence: User-defined commands (e.g., `\newcommand{\methodname}{OurMethod}`) are recognized as single tokens, preventing false positives on custom terminology.
  • Bibliography Integrity: Citation keys and bibliography entries are ignored during linguistic analysis, eliminating the noise of author names and titles in the reference list.
  • Extensible Rule Engine: Beyond the LLM, a deterministic rule layer (written in Rust) handles deterministic style guides (SI units, capitalization of specific terms) with zero latency.

how i finished my ai grammar checker for latex phd motivation - Ilustrasi 2

Comparative Analysis

FeatureStandard AI Assistants (Cloud)This Local LaTeX Linter
Markup HandlingTreats as plain text; high breakage riskAST-based parsing; structure preserved
Data PrivacyRequires upload; NDAs often violatedFully local; air-gapped compatible
Math Mode AwarenessAttempts to correct variables/symbolsComplete semantic isolation of math nodes
Custom Macro SupportFlags as spelling errorsResolves user definitions dynamically

The next frontier is moving from correction to generation. The current architecture—AST + Local LLM—is perfectly positioned for "semantic autocomplete." Imagine typing `\begin{proof}` and the model suggesting the logical structure of the proof based on the preceding theorem statement, written in valid LaTeX. This requires the model to be trained not just on English, but on the joint distribution of LaTeX source and compiled PDF output, understanding the visual consequence of the code.

Another vector is collaborative intelligence. While the tool is local-first, the configuration—style guides, custom dictionaries, macro definitions—is shareable. A research group could maintain a `lint-config.toml` in their git repository, ensuring that every member's editor enforces the same notation standards automatically. This shifts the tool from a personal productivity hack to a piece of institutional infrastructure, codifying the "house style" into executable logic rather than a PDF style guide nobody reads.

how i finished my ai grammar checker for latex phd motivation - Ilustrasi 3

Conclusion

Finishing this checker was less about writing code and more about modeling the cognitive friction of academic writing. The motivation was never the technology itself, but the removal of the barrier between the idea and the page. By respecting the dual nature of LaTeX—as both code and prose—the tool earns its place in the toolchain. It does not write the thesis for you; it ensures that the only errors remaining are your own scientific ones.

The project remains open source, a testament to the idea that the best tools for researchers are built by researchers. If you have ever stared at a screen full of red squiggles under `\textbf{}` commands, you understand the problem. The solution is not to strip the markup, but to teach the machine to read it. That is the philosophy that carried this project from a frustration to a finished utility.

Comprehensive FAQs

Q: Does this tool work with Overleaf or only local editors?

A: Currently, the Language Server Protocol implementation targets local editors like VS Code, Neovim, Emacs, and Helix. Overleaf does not support custom LSP servers natively. However, a GitHub Action wrapper is provided to run the linter as a CI check on every push, providing feedback in the Overleaf git log interface.

Q: What hardware is required to run the local LLM component?

A: The default quantized model (4-bit GGUF) runs comfortably on 8GB of RAM (system + VRAM shared) on CPU. For sub-100ms latency, a modern Apple Silicon Mac (M1/M2/M3) or a discrete GPU with 6GB+ VRAM is recommended. The deterministic Rust rule engine has negligible overhead.

Q: How does it handle multilingual documents (e.g., English abstract, German body)?

A: The parser detects `babel` or `polyglossia` language switching commands (`\selectlanguage{german}`) and applies the appropriate tokenizer and model profile for each segment. This requires downloading the specific language model weights, but the switching is automatic based on the document structure.

Q: Can I add my own style rules without retraining the model?

A: Yes. The deterministic rule engine accepts TOML configuration files where you can define regex patterns on the AST node types (e.g., "flag 'Figure' at start of sentence in caption nodes") or glossary enforcement (e.g., "ensure 'Deep Learning' is always capitalized"). No Python or ML knowledge is required.

Q: Is the "how i finished my ai grammar checker for latex phd motivation" narrative typical for developer tools in academia?

A: It is remarkably common. Most robust academic software originates from "scratching your own itch." The motivation stems from the unique constraint intersection in PhD work: rigid formatting requirements, massive document sizes, version control necessity, and zero budget for proprietary tooling. This forces a build-vs-buy decision heavily toward building.