Skip to content

Render BST preview italics and bold as text, not math letters - #17902

Merged
koppor merged 7 commits into
mainfrom
bst-preview-emph
Nov 26, 2026
Merged

koppor merged 7 commits into
mainfrom
bst-preview-emph

Conversation

@koppor

@koppor koppor commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Summary

Entry previews with a BST style (e.g. abbrv.bst) showed italic and bold text, such as journal names, as Unicode mathematical letters (𝐵𝑟𝑖𝑡𝑖𝑠ℎ), which cannot be found by search or copied as text, and screen readers read them letter by letter. They are now real italics and bold, also when the emphasized text contains braces. The customized preview additionally shows small caps and no longer shows LaTeX commands inside emphasized text.

Analogies: the journal name used to be chocolate letters, pretty but useless for search and screen readers; now it is plain text tilted like a crescent moon, and finding it in the preview is as easy as finding honey in a hive.

Steps to test

  1. In Preferences → Entry preview, add a .bst file such as abbrv.bst and select it.
  2. Select an article with a journal.
  3. The journal name in the preview is italic, and searching the preview for a word of it finds it.

BST preview with italic journal

Related issues and pull requests

Closes TODO

Triggered by github.com/palukku/pull/67 (hover citation in JabLS showed the math letters).

AI usage

Claude Code (model claude-opus-5-5), AIL3.

AI CHECKLIST.md walkthrough

1. Code self-review

  • No == null / != null checks — JSpecify annotations (@NullMarked, @Nullable, @NonNull) used instead.
  • No Objects.requireNonNull(...) — nullability expressed via JSpecify annotations.
  • [/] New classes annotated with @NullMarked (org.jspecify.annotations.NullMarked).
  • [/] New packages annotated with @NullMarked (org.jspecify.annotations.NullMarked).
  • [/] Optional consumed with ifPresent / ifPresentOrElse / map / orElseThrow — never orElse(unusedValue) nor an isPresent() + get() block.
  • [/] StringUtil.isBlank(...) used instead of s == null || s.isBlank().
  • [/] No catch (Exception e) — only specific exceptions are caught.
  • [/] No throw new RuntimeException(...) / IllegalStateException(...) — these tear down the whole application.
  • [/] Logged exceptions are passed as the last logger argument (LOGGER.info("...", e)), not concatenated into the message string.
  • [/] New BibEntry objects built with withers (withField, not setField).
  • [/] Modern Java used: List.of() / Map.of() / Set.of(), Path.of(), SequencedCollection / SequencedSet, text blocks.
  • [/] Regexes use a precompiled Pattern.compile(...) constant, not String.matches(...).
  • [/] Keep alphabetical ordering when adding variables or enum items.
  • [/] Background work uses org.jabref.logic.util.BackgroundTask, not new Thread().
  • No commented-out code, no trivial comments restating the code, no AI-disclosure comments in source.
  • Markdown Javadoc (///) uses Markdown syntax, not JavaDoc inline tags: `code` instead of {@code}, [ClassName] instead of {@link}.
  • [/] All user-facing text localized (Localization.lang in Java, % prefix in FXML).
  • [/] Sentence case (not Title Case); no trailing !; labels do not end with :.
  • [/] Variance expressed with placeholders ("...: %0"), not string concatenation.
  • [/] User-controlled data (request params, entry fields, file contents) is HTML-escaped before being written into any text/html response — including exception/error messages, not just the success body (XSS).
  • In case issue lists an example, this concrete example is covered by a test case.
  • Behavior changes in org.jabref.model / org.jabref.logic have added or updated tests.
  • Tests assert object contents (assertEquals), use plain JUnit asserts (not AssertJ), have no @DisplayName, do not catch exceptions (let them propagate so JUnit reports setup/teardown failures directly), and use @TempDir instead of manual temp directories.
  • [/] Fetcher tests hit the live endpoints — the remote API is not mocked or stubbed (automated-review suggestions to mock it are rejected on purpose).

2. Verification commands

  • ./gradlew :jablib:check (or ./gradlew check for all modules).
  • ./gradlew checkstyleMain checkstyleTest checkstyleJmh.
  • ./gradlew modernizer.
  • ./gradlew --no-configuration-cache :rewriteDryRun reports no changes (run ./gradlew rewriteRun to fix).
  • ./gradlew javadoc.
  • npx markdownlint-cli2 "docs/**/*.md" "*.md" (only if Markdown changed).
  • [/] npm ci && npm run textlint reports no misspellings (only if Markdown changed).
  • [/] Only if formatting is still off after rewriteRun: docker run -v $(pwd):/github/workspace ghcr.io/leventebajczi/intellij-format:master "*.java" "" ".idea/codeStyles/Project.xml".

3. Documentation

  • CHANGELOG.md entry added if the change is visible to the user (end-user wording, no extra blank lines, sorted in next to existing entries about the same component/feature). Link the issue if one exists; link the PR only when no issue exists. Use TODO as the placeholder when neither is known yet — never a fake number. No entry for fixes to changes that were themselves introduced after the last release (feature only in ## [Unreleased]) — update the existing unreleased entry instead if needed.
  • Searched jabref/issues and jabref-koppor/issues for a related issue; linked only on a confident match, otherwise kept TODO (no closes/fixes for merely-similar issues).
  • [/] Requirement added to docs/requirements/<area>.md if the change is a new feature or significant bug fix (skip for refactors, minor fixes, and internal changes).
  • [/] Developer documentation under docs/ updated if behavior or architecture changed.

4. Pull request

  • PR body built from .github/PULL_REQUEST_TEMPLATE.md, every section filled.
  • All checklist items kept and marked [x], [ ], or [/].
  • "Steps to test" is a numbered list with a cropped screenshot of the result for every visible change; no video (only allowed when another program is involved, e.g. drag and drop or push to an external application).
  • All HTML comments removed from the PR body.
  • PR created with gh pr create --body-file <file> (not --body).
  • If CHANGELOG.md used a TODO placeholder (no issue confidently identified yet — an existing issue link always stays), the PR was opened as draft, the placeholder was replaced with the real PR-number link after PR creation, committed and pushed, and only then was the PR marked ready for review. If an issue is identified or created later, the link is switched to the issue.

Checklist

  • I own the copyright of the code submitted and I license it under the MIT license
  • If AI tools were used, I disclosed them in the "AI usage" section and reviewed, understood, and take full ownership of all AI-generated code
  • I manually tested my changes in running JabRef (always required)
  • I added JUnit tests for changes (if applicable)
  • I added screenshots in the PR description (if change is visible to the user)
  • I added one sentence (max 20 words) to CHANGELOG.md describing the change from the user's point of view (if the change is visible to the user)
  • [/] I checked the user documentation for up to dateness and submitted a pull request to our user documentation repository

🤖 Generated with Claude Code

Italic and bold were converted only after the LaTeX-to-Unicode step, which
had already turned them into Unicode mathematical letters. They are now
converted first, with the balanced-brace parsing small caps already use, so
nested braces such as {\em The {\TeX} Book} stay italic as a whole.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Render BST preview emphasis as searchable HTML text

🐞 Bug fix ✨ Enhancement 🧪 Tests 📝 Documentation 🕐 20-40 Minutes

Grey Divider

AI Description

• Render BST preview italics, bold, and small caps as HTML instead of mathematical letters or
 visible LaTeX commands.
• Reuse the HTML formatter to handle nested formatting, whitespace, and escaped braces.
• Expand regression tests and document the user-visible fixes.
Merge Risk 🟡 Medium

Blast radius 🔴 High 💥 4 capabilities

  • 4 affected capabilities span independent functional scopes: entry_preview_rendering, openoffice_integration.
  • The changed pipeline directly transforms the end-to-end bibliography preview returned by BstPreviewLayout; it affects rendered preview content rather than a separate storage or export subsystem.
  • LayoutEntry exposes HTMLChars as a formatter, so the affected behavior is the bounded HTML rendering path for formatted entry fields.
  • Nested parsing and small-caps handling are implementation hops within that path, not independent capabilities.
  • HTMLChars directly consumes the shared getPart result while parsing formatted entry fields, making this a parsing condition within the HTML preview/layout scope.
  • JStyle wires OOPreFormatter into OpenOffice field formatting, and OOPreFormatter independently calls the shared parser.
  • This produces a separate document-integration outcome from HTML preview rendering.
Behavioral complexity 🟡 Medium 🧩 Interacting branches, Data transformation

  • Before, BST output used separate limited regex conversions and then removed commands; after, it enters the recursive HTMLChars parser before Unicode conversion and cleanup.
  • The new correctness conditions are ordering, nested formatting, whitespace-separated commands, and preservation of later symbol conversion.
  • The recursive transformation is changed logic, not merely reuse of an unchanged formatter.
Potential damage 🟢 Low 🩹 Cosmetic

  • If the changed parser regresses, BST previews could show missing, malformed, or incorrectly styled text.
  • The effect is presentation-only and reverting the formatter pipeline restores output behavior; no stored data is changed.
  • A code revert or follow-up formatter fix restores subsequent previews; previously copied incorrect preview text may need to be recopied.
Assessed commit b38e540
Diagram

graph TD
  Entry["Bibliography entry"] --> Bst["BST renderer"] --> Lines["Newline cleanup"] --> Html["HTMLChars formatter"] --> Unicode["Unicode conversion"] --> Cleanup["Final cleanup"] --> Preview["HTML preview"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Keep a BST-specific converter
  • ➕ Limits formatting changes to BST previews.
  • ➖ Duplicates LaTeX parsing and formatting behavior.
  • ➖ Requires separate handling for nested commands and escaped braces.

Recommendation: Reusing HTMLChars is preferable because it already handles LaTeX-to-HTML conversion and avoids a second BST-specific parser. Review its shared-formatter effects alongside the intended preview changes, particularly HTML entities and superscript output.

Files changed (7) +100 / -165

Enhancement (1) +32 / -4
HTMLChars.javaExtend HTML conversion for nested formatting and small caps +32/-4

Extend HTML conversion for nested formatting and small caps

• Adds small-caps tags, accepts whitespace before formatting arguments, and recursively converts LaTeX inside formatted text. Distinguishes formatting switches from argument-taking commands.

jablib/src/main/java/org/jabref/logic/layout/format/HTMLChars.java

Bug fix (2) +12 / -139
BstPreviewLayout.javaConvert BST formatting to HTML before Unicode conversion +6/-139

Convert BST formatting to HTML before Unicode conversion

• Runs HTMLChars after newline cleanup and before LatexToUnicodeFormatter so emphasis remains tagged text. Removes the preview-specific emphasis patterns, small-caps parser, and tilde conversion.

jablib/src/main/java/org/jabref/logic/preview/BstPreviewLayout.java

StringUtil.javaKeep escaped braces intact when reading groups +6/-0

Keep escaped braces intact when reading groups

• Updates getPart to consume escaped characters together, preventing escaped braces from changing group depth.

jablib/src/main/java/org/jabref/logic/util/strings/StringUtil.java

Tests (3) +53 / -22
BstPreviewLayoutTest.javaCover BST emphasis and revised HTML output +40/-21

Cover BST emphasis and revised HTML output

• Adds a journal-emphasis regression test and cases for italic, bold, small caps, and nested formatting. Updates expectations for HTML entities, superscripts, subscripts, and remaining unknown-command text.

jablib/src/test/java/org/jabref/logic/bst/BstPreviewLayoutTest.java

HTMLCharsTest.javaTest recursive formatting and small-caps conversion +11/-1

Test recursive formatting and small-caps conversion

• Adds cases for small-caps forms, spaced arguments, nested tags, accented text, and LaTeX commands within emphasis.

jablib/src/test/java/org/jabref/logic/layout/format/HTMLCharsTest.java

StringUtilTest.javaTest group parsing with escaped braces +2/-0

Test group parsing with escaped braces

• Adds a getPart case confirming escaped braces do not terminate or alter the enclosing group.

jablib/src/test/java/org/jabref/logic/util/strings/StringUtilTest.java

Documentation (1) +3 / -0
CHANGELOG.mdDocument BST preview formatting fixes +3/-0

Document BST preview formatting fixes

• Adds user-facing entries for corrected italic and bold rendering and for small caps and emphasized-text cleanup.

CHANGELOG.md

@github-actions github-actions Bot added the status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers label Nov 23, 2026
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (2)

Grey Divider


Remediation recommended

1. Deeply nested entries break previews 🐞 Bug
Description
HTMLChars.convert recursively converts every formatting argument without a depth limit, and
getPart returns the remaining text even when braces are unmatched. An entry containing
sufficiently many nested \textit{ commands can therefore overflow the stack during preview
generation; rescanning each remaining argument also makes deep nesting disproportionately expensive.
Code

jablib/src/main/java/org/jabref/logic/layout/format/HTMLChars.java[135]

+                        sb.append('<').append(tag).append('>').append(convert(part)).append("</").append(tag.split(" ")[0]).append('>');
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Unbounded recursive formatting can overflow the stack on deeply nested or unterminated LaTeX arguments, while repeatedly scanning nested arguments increases processing cost.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/logic/layout/format/HTMLChars.java[129-135]
- jablib/src/main/java/org/jabref/logic/util/strings/StringUtil.java[90-119]
## Recommended Fix
Parse nested formatting iteratively, or enforce a safe nesting limit with a readable fallback. Avoid rescanning the entire remaining argument at each level, and test deeply nested valid and unterminated input.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View medium (1)
2. Unknown LaTeX commands show up as words in BST previews 🐞 Bug
Description
generatePreview now passes the whole BST output through HTMLChars before
LatexToUnicodeFormatter and RemoveLatexCommandsFormatter, and HTMLChars strips unknown
commands down to their names or braced arguments. When a field or style output contains an unmapped
command, the later formatters can no longer remove it or convert a supported expression such as
\mathbb{F} to 𝔽.
Code

jablib/src/main/java/org/jabref/logic/preview/BstPreviewLayout.java[R148-150]

+        // Before LatexToUnicodeFormatter, which would turn italic and bold into Unicode mathematical letters
+        // (not searchable, read out letter by letter by screen readers)
+        result = new HTMLChars().format(result);
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
BST previews pass the whole output through `HTMLChars` before LaTeX conversion and cleanup. Unknown commands lose their backslashes or are reduced to their arguments, leaving stray command names in the preview and preventing supported expressions such as `\mathbb{F}` from becoming `𝔽`.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/logic/preview/BstPreviewLayout.java[146-158]
- jablib/src/main/java/org/jabref/logic/layout/format/HTMLChars.java[136-155]
- jablib/src/test/java/org/jabref/logic/bst/BstPreviewLayoutTest.java[134-141]
## Recommended Fix
Preserve commands that `HTMLChars` does not handle until `LatexToUnicodeFormatter` and `RemoveLatexCommandsFormatter` can process them. For example, configure `HTMLChars` to retain unknown commands verbatim, or convert only the formatting commands (`em`, `it`, `bf`, `sc`, `emph`, `textit`, `textbf`, `textsc`, `sup`, `sub`) to HTML using balanced-brace parsing and leave other commands to the existing pipeline. If converting math-font expressions before `HTMLChars` instead, avoid converting italic and bold text to mathematical letters. Restore the `unresolvableBracedMathIsKept` expectation to `O.&nbsp;Kopp. modulator.` and add a BST preview regression test for `\mathbb{F}`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Tip of the day
💡 Did you know, you can tweak Display settings with a live preview to see your comment before it ships

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@koppor
koppor marked this pull request as draft November 23, 2026 21:41
@github-actions github-actions Bot removed the status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers label Nov 23, 2026
HTMLChars now renders small caps, accepts a space before a formatting argument, and converts LaTeX inside formatted text, so the BST preview reuses it instead of its own converter. Escaped braces no longer end a group.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@subhramit subhramit added this to the 6.0 🍫🍯🌙 milestone Nov 23, 2026
@subhramit subhramit added dev: send-to-black-forest Port to the black-forest branch of JabRef/jabref-black-forest after merging (ADR-0073) component: libre-office labels Nov 23, 2026
subhramit
subhramit previously approved these changes Nov 23, 2026

@subhramit subhramit left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good
Added libre-office label as it also affects the BST preview in select style dialog.

# Conflicts:
#	jablib/src/main/java/org/jabref/logic/preview/BstPreviewLayout.java

koppor commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

🤖 Generated with Claude Code

Merged main into this branch to resolve the merge conflict.

Conflicting file: jablib/src/main/java/org/jabref/logic/preview/BstPreviewLayout.java — import block only. Resolved by taking main's package rename (org.jabref.logic.openoffice.style.BstStyle → org.jabref.logic.openoffice.bst.BstStyle) and keeping this PR's import set otherwise (HTMLChars added, RemoveTilde dropped, since the PR replaces the regex-based \emph/\textbf handling with HTMLChars).

CHANGELOG.md auto-merged; both entries of this PR are kept under Fixed.

The merge commit contains nothing beyond the conflict resolution. CI on this PR is the compile check.


Generated by Claude Code

@github-actions github-actions Bot added status: changes-required Pull requests that are not yet complete and removed component: libre-office status: changes-required Pull requests that are not yet complete labels Nov 24, 2026
@github-actions github-actions Bot removed the status: changes-required Pull requests that are not yet complete label Nov 24, 2026
@subhramit subhramit mentioned this pull request Nov 24, 2026
28 of 35 tasks
@subhramit
subhramit added this pull request to stack #17922 November 24, 2026 12:49
@koppor
koppor marked this pull request as ready for review November 26, 2026 13:46
@koppor
koppor enabled stacked auto-merge November 26, 2026 13:46
@github-actions github-actions Bot added the status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers label Nov 26, 2026
@koppor
koppor added this pull request to the merge queue Nov 26, 2026
@github-actions github-actions Bot added status: to-be-merged PRs which are accepted and should go into the merge-queue. and removed status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers labels Nov 26, 2026
Merged via the queue into main with commit 201bff7 Nov 26, 2026
90 of 94 checks passed
@koppor
koppor deleted the bst-preview-emph branch November 26, 2026 18:26
renovate-bot pushed a commit to renovate-bot/JabRef-_-jabref that referenced this pull request Nov 26, 2026
### Summary

Preserve supported nested LaTeX formatting in JStyle bibliographies sent
to LibreOffice/OpenOffice, without leaving inner commands visible, and
render spacing controls and literal ampersands correctly in HTML and
Writer output. Share the HTML/Writer conversion traversal while keeping
each formatter's normalization, character mappings, and markup
vocabulary distinct; public formatter APIs and registered layout names
remain unchanged.

This is the child of JabRef#17902. Its
useful escaped-brace `StringUtil` fix is inherited unchanged: this child
contains no `StringUtil` diff. BST rendering inside Writer continues to
use Pandoc; this patch fixes the JStyle path and shares its conversion
with HTML previews/layouts, not with the Pandoc pipeline.

The converter uses an explicit frame stack instead of recursion or
repeated argument rescans. Tests cover nested commands,
protection/literal braces, legacy switches, accents, normalization
differences, deep groups, and deep unknown-command arguments. This is an
architectural/correctness change, not a claim of benchmarked speedup.

Malformed-input recovery changes deliberately: escaped braces are
literal, supported commands without usable arguments emit no formatting,
and unfinished formatting scopes close at end of input. After BST
sanitizes unmatched braces, two malformed-title cases now retain HTML
entities or a recoverable small-caps scope rather than falling back to
plain Unicode. Both cases retain exact-output assertions. The malformed
HTML input `\{i}` now produces `{i`, not dotless i; valid `\{i\}`
produces `{i}`.

**Malformed-input recovery examples**

Outputs below are generated markup, not rendered text. BST rows show
only the title portion; the author prefix is unchanged.

| Context | Input | Old output (parent PR) | Current output | Recovery
rule / difference |
| --- | --- | --- | --- | --- |
| HTML, escaped opening brace and unmatched closing brace | `\{i}` |
`&imath;` (dotless i) | `{i` | The escaped opening brace is literal; the
unmatched structural closing brace is discarded. Previously this
incorrectly produced dotless i (`&imath;`). |
| HTML, valid escaped brace pair | `\{i\}` | `i\}` | `{i}` | Valid
reference case: both escaped braces remain literal. |
| HTML / Writer, formatting command without an argument | `\emph` |
`emph` | Empty string | Nothing is formatted and the command name does
not leak into output. |
| HTML / Writer, unfinished nested formatting | `\textit{a {\bf b` |
HTML: `<i>a <b>b</b></i>`; Writer: `<i>a {\bf b</i>` | `<i>a
<b>b</b></i>` | Close unfinished formatting scopes in reverse nesting
order, without inventing displayed braces. |
| BST preview, unmatched argument brace | `\textsc{L{\'o}pez` | `López.`
| `L&oacute;pez.` | After BST brace sanitization, recover the accent as
HTML. Previously the title was plain Unicode `López.`; the visible
letters are the same. |
| BST preview, unmatched legacy-switch group | `{\sc L{\'o}pez` |
`lópez.` | `<span style="font-variant: small-caps">l&oacute;pez.</span>`
| Recover the small-caps scope and close its tag. Previously the title
fell back to unstyled `lópez.`. |

### Legacy versus corrected behavior

These tests compare **generated markup**, not the characters ultimately
displayed. HTML entities are necessary representations, not inherently
bugs:

| Markup asserted by a test | Displayed result | Meaning |
| --- | --- | --- |
| `&amp;` | `&` | One literal ampersand |
| `&nbsp;` | A non-breaking space | A spacing character that prevents a
line break |
| `&copy;` | © | A copyright symbol |
| `&amp;amp;` | The literal text `&amp;` | Correct only when those five
characters are intended |

Existing `&nbsp;` expectations remain unchanged. Thin/medium/thick
spacing controls are not non-breaking-space commands, so they are not
all replaced with `&nbsp;`.

#### Ampersands

| Input characters (not Java string literals) | Legacy behavior |
Corrected behavior |
| --- | --- | --- |
| `&` | HTML displayed `&` | Both outputs display `&`, with literal
ampersands protected in markup |
| `\&` | Usually displayed `&` | Displays `&`, encoded once as `&amp;` |
| `\\&` (two backslashes, then ampersand) | HTML emitted `&amp;amp;`,
displaying the unwanted text `&amp;` | Emits `\&amp;`, displaying a
literal backslash followed by `&` |
| `\&copy;` | Writer could decode the intended literal text as © | Emits
`&amp;copy;`, displaying the literal text `&copy;` |
| `&copy;` already present in the source | Treated as an entity |
Remains an entity and displays © |
| `&{copy;}` | HTML protected the source ampersand; Writer could
assemble an entity | Emits `&amp;copy;`, displaying literal `&copy;`,
not © |

The double-escaping test passed before this follow-up because it
expected the legacy output. Qodo's claim that it broke an unchanged
assertion was incorrect, but preserving that assertion was not a reason
to keep the double-escaping behavior. The assertion now checks the
corrected output, and backslash runs from zero through six are tested
explicitly.

Ampersands are handled while traversing the input, rather than by
overlapping replacements before parsing or a blanket escape afterward.
This preserves backslash parity, distinguishes real source entities from
text assembled by removing groups, and protects escaped entity-looking
text until the renderer decodes it once. HTML's unsupported-accent
fallback also escapes literal ampersands because it bypasses normal text
emission.

Two source backslashes retain this converter's existing
**literal-backslash convention**. This change does not implement TeX's
line-breaking interpretation of `\\` or a complete TeX parser.

#### Spacing controls

| Input | Legacy HTML output displayed | Legacy Writer output displayed
| Corrected output in both dialects |
| --- | --- | --- | --- |
| `A\,B` | `A,B` | `AB` | `A` + U+2009 thin space + `B` |
| `A\:B` | `A:B` | `AB` | `A` + U+205F medium mathematical space + `B` |
| `A\;B` | `A;B` | `AB` | `A` + U+2005 four-per-em space + `B` |
| `A\!B` | `A!B` | `AB` | `AB`; unsupported negative spacing is omitted
|
| Plain `A,B` | `A,B` | `A,B` | Unchanged: `A,B` |

The initial shared-parser version introduced punctuation into Writer
output, including a ratio symbol for `\:`. Restoring legacy punctuation
in HTML and dropping every spacing instruction in Writer would preserve
incorrect/lossy outputs. Instead, positive spacing commands now produce
Unicode spacing characters; literal punctuation remains punctuation.

These widths are **font-dependent approximations**, not full TeX glue or
exact math-mode widths. In particular, U+2005 approximates thick
spacing, and the supported markup has no negative-spacing primitive.
Direct Unicode also avoids depending on HTML5-only named entities in
Writer's HTML4 decoder. Control symbols consume only themselves: in
`A\,{B}`, the group remains content rather than becoming an argument to
the comma command.

The implementation documents these decisions alongside the frame-stack,
argument/scope, malformed-input recovery, and bounded source-lookup
logic. Regression tests cover standalone and nested controls, following
groups, preserved protection braces, literal punctuation, source
entities, escaped entity-looking text, accent fallback, and real Writer
insertion/save/reopen.

### Related issues and pull requests

Stacked on JabRef#17902. The parent's
Checkstyle fix was pushed first as `53c6a3afd9`.

Searched JabRef/jabref and JabRef/jabref-koppor issues for “JStyle
nested formatting” and “LibreOffice textbf”; no confident matching issue
was found. No issue-closing claim is made.

### AI usage

Zed Agent with model `openai/gpt-6.1-sol` (GPT-6.1 Sol), including
delegated reviews and validation, assisted with implementation,
experiments, tests, documentation, and this description.

<details>
<summary>AI CHECKLIST.md walkthrough</summary>

# Code checklist

> [!IMPORTANT]
> **This is a mandatory final gate.** When the implementation is
finished and before you open a PR, work through **every** box below and
tick it. If a box cannot be ticked, fix the code first; mark a box `[/]`
only if the point genuinely does not apply.
>
> `AGENTS.md` describes how to write code *while* developing — this file
confirms the finished result. Do not skip the checklist and do not skip
individual points.

## 1. Code self-review

Read your own diff once, top to bottom, and confirm each point.

### Nullability and control flow

- [x] No `== null` / `!= null` checks — JSpecify annotations
(`@NullMarked`, `@Nullable`, `@NonNull`) used instead.
- [x] No `Objects.requireNonNull(...)` — nullability expressed via
JSpecify annotations.
- [x] New classes annotated with `@NullMarked`
(`org.jspecify.annotations.NullMarked`).
- [/] New packages annotated with `@NullMarked`
(`org.jspecify.annotations.NullMarked`).
- [x] `Optional` consumed with `ifPresent` / `ifPresentOrElse` / `map` /
`orElseThrow` — never `orElse(unusedValue)` nor an `isPresent()` +
`get()` block.
- [/] `StringUtil.isBlank(...)` used instead of `s == null ||
s.isBlank()`.

### Exceptions

- [/] No `catch (Exception e)` — only specific exceptions are caught.
- [/] No `throw new RuntimeException(...)` /
`IllegalStateException(...)` — these tear down the whole application.
- [/] Logged exceptions are passed as the **last** logger argument
(`LOGGER.info("...", e)`), not concatenated into the message string.

### Style and idioms

- [/] New `BibEntry` objects built with withers (`withField`, not
`setField`).
- [x] Modern Java used: `List.of()` / `Map.of()` / `Set.of()`,
`Path.of()`, `SequencedCollection` / `SequencedSet`, text blocks.
- [x] Regexes use a precompiled `Pattern.compile(...)` constant, not
`String.matches(...)`.
- [x] Keep alphabetical ordering when adding variables or enum items.
- [/] Background work uses `org.jabref.logic.util.BackgroundTask`, not
`new Thread()`.
- [x] No commented-out code, no trivial comments restating the code, no
AI-disclosure comments in source.
- [x] Markdown Javadoc (`///`) uses Markdown syntax, not JavaDoc inline
tags: `` `code` `` instead of `{@code}`, `[ClassName]` instead of
`{@link}`.

### User-facing text

- [/] All user-facing text localized (`Localization.lang` in Java, `%`
prefix in FXML).
- [/] Sentence case (not Title Case); no trailing `!`; labels do not end
with `:`.
- [/] Variance expressed with placeholders (`"...: %0"`), not string
concatenation.

### Security

- [/] User-controlled data (request params, entry fields, file contents)
is HTML-escaped before being written into any `text/html` response —
including exception/error messages, not just the success body (XSS).

### Tests

- [/] In case issue lists an example, this concrete example is covered
by a test case.
- [x] Behavior changes in `org.jabref.model` / `org.jabref.logic` have
added or updated tests.
- [x] Tests assert object contents (`assertEquals`), use plain JUnit
asserts (not AssertJ), have no `@DisplayName`, do not catch exceptions
(let them propagate so JUnit reports setup/teardown failures directly),
and use `@TempDir` instead of manual temp directories.
- [/] Fetcher tests hit the live endpoints — the remote API is not
mocked or stubbed (automated-review suggestions to mock it are rejected
on purpose).

## 2. Verification commands

Run in this order — cheapest first. Each must pass.

- [ ] `./gradlew :jablib:check` (or `./gradlew check` for all modules).
- [x] `./gradlew checkstyleMain checkstyleTest checkstyleJmh`.
- [x] `./gradlew modernizer`.
- [ ] `./gradlew --no-configuration-cache :rewriteDryRun` reports no
changes (run `./gradlew rewriteRun` to fix).
- [x] `./gradlew javadoc`.
- [x] `npx markdownlint-cli2 "docs/**/*.md" "*.md"` (only if Markdown
changed).
- [x] `npm ci && npm run textlint` reports no misspellings (only if
Markdown changed).
- [/] Only if formatting is still off after `rewriteRun`: `docker run -v
$(pwd):/github/workspace ghcr.io/leventebajczi/intellij-format:master
"*.java" "" ".idea/codeStyles/Project.xml"`.

## 3. Documentation

- [x] `CHANGELOG.md` entry added if the change is visible to the user
(end-user wording, no extra blank lines, sorted in next to existing
entries about the same component/feature). Link the issue if one exists;
link the PR only when no issue exists. Use `TODO` as the placeholder
when neither is known yet — never a fake number. No entry for fixes to
changes that were themselves introduced after the last release (feature
only in `## [Unreleased]`) — update the existing unreleased entry
instead if needed.
- [x] Searched [jabref/issues](https://github.com/JabRef/jabref/issues)
and
[jabref-koppor/issues](https://github.com/JabRef/jabref-koppor/issues)
for a related issue; linked only on a confident match, otherwise kept
`TODO` (no `closes`/`fixes` for merely-similar issues).
- [x] Requirement added to `docs/requirements/<area>.md` if the change
is a new feature or significant bug fix (skip for refactors, minor
fixes, and internal changes).
- [x] Developer documentation under `docs/` updated if behavior or
architecture changed.

## 4. Pull request

- [x] PR body built from `.github/PULL_REQUEST_TEMPLATE.md`, every
section filled.
- [x] All checklist items kept and marked `[x]`, `[ ]`, or `[/]`.
- [ ] "Steps to test" is a numbered list with a cropped screenshot of
the result for every visible change; no video (only allowed when another
program is involved, e.g. drag and drop or push to an external
application).
- [x] All HTML comments removed from the PR body.
- [x] PR created with `gh pr create --body-file <file>` (not `--body`).
- [ ] If `CHANGELOG.md` used a `TODO` placeholder (no issue confidently
identified yet — an existing issue link always stays), the PR was opened
as draft, the placeholder was replaced with the real PR-number link
after PR creation, committed and pushed, and only then was the PR marked
ready for review. If an issue is identified or created later, the link
is switched to the issue.

Checklist notes:

- No packages, dependencies, public APIs, user-facing UI strings,
background tasks, exception handlers, or HTTP response paths are
introduced. Existing HTML-like markup support is retained; the converter
is not an HTML sanitizer.
- Full-check completion, clean rewrite validation, interactive JabRef
testing, and screenshots remain open. Existing external/manual
requirements are not marked not-applicable just to complete the
checklist.
- The changelog placeholder was replaced with this PR's link and pushed
in `e1f17262e1`. The PR review state and contributor-owned checklist
declarations are preserved.
- Registered through native `gh stack link 17902 17921`:
JabRef/jabref Stack #17922. No rebase or force-push
was used.

</details>

### Checklist

- [x] I own the copyright of the code submitted and I license it under
the [MIT license](https://github.com/JabRef/jabref/blob/main/LICENSE)
- [x] If AI tools were used, I disclosed them in the "AI usage" section
and reviewed, understood, and take full ownership of all AI-generated
code
- [ ] I manually tested my changes in running JabRef (always required)
- [x] I added JUnit tests for changes (if applicable)
- [ ] I added screenshots in the PR description (if change is visible to
the user)
- [x] I added **one sentence (max 20 words)** to `CHANGELOG.md`
describing the change from the user's point of view (if the change is
visible to the user)
- [ ] I checked the [user documentation](https://docs.jabref.org/) for
up to dateness and submitted a pull request to our [user documentation
repository](https://github.com/JabRef/user-documentation/tree/main/en)

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
@jabref-machine

Copy link
Copy Markdown
Collaborator

Created backport PR for black-forest:

Please cherry-pick the changes locally and resolve any conflicts.

git fetch origin port-17902-to-black-forest
git worktree add --checkout .worktree/port-17902-to-black-forest port-17902-to-black-forest
cd .worktree/port-17902-to-black-forest
git reset --hard HEAD^
git cherry-pick -x 201bff7020f6d824d728e200dbdb461326c7de9e

Siedlerchr added a commit to dannys2603/jabref that referenced this pull request Nov 28, 2026
* main: (202 commits)
  New Crowdin updates (JabRef#17956)
  chore(deps): update dependency com.konghq:unirest-modules-gson to v4.12.4 (JabRef#17955)
  Let Renovate update JavaFX in the jabsrv launcher (JabRef#17954)
  chore(deps): update dependency com.konghq:unirest-modules-gson to v4.12.3 (JabRef#17953)
  Import the RIS serial number of books and chapters as ISBN (JabRef#17891)
  Share nested LaTeX conversion with Writer (JabRef#17921)
  Render BST preview italics and bold as text, not math letters (JabRef#17902)
  Chore(deps): Bump com.konghq:unirest-java-bom from 4.11.11 to 4.12.0 in /versions (JabRef#17951)
  Inject NativeDesktop into its callers and remove the deprecated static helpers (JabRef#17947)
  New Crowdin updates (JabRef#17945)
  Chore(deps): Bump org.graalvm.sdk:nativeimage from 25.5.5.0.3 to 25.6.5.1 in /versions (JabRef#17944)
  Chore(deps): Bump com.googlecode.plist:dd-plist from 1.30 to 1.31 in /versions (JabRef#17943)
  Chore(deps): Bump JetBrains/junie-github-action from 1.10.1 to 1.10.2 (JabRef#17942)
  Chore(deps): Bump softprops/action-gh-release from 3.0.3 to 3.0.4 (JabRef#17941)
  Chore(deps): Bump anthropics/claude-code-action from 1.0.286 to 1.0.289 (JabRef#17940)
  Chore(deps): Bump ruby/setup-ruby from 1.343.0 to 1.344.0 (JabRef#17939)
  Update dependency com.konghq:unirest-modules-gson to v4.12.0 (JabRef#17937)
  [Bot] Update SBOM files (JabRef#17934)
  Chore(deps): Bump jablib/src/main/resources/csl-styles from `af0aea3` to `7fa488b` (JabRef#17928)
  Chore(deps): Bump jablib/src/main/resources/csl-locales from `8bef426` to `21a175a` (JabRef#17927)
  ...
bhosale-mahesh pushed a commit to bhosale-mahesh/jabref that referenced this pull request Nov 29, 2026
…#17902)

### Summary

Entry previews with a BST style (e.g. `abbrv.bst`) showed italic and
bold text, such as journal names, as Unicode mathematical letters
(𝐵𝑟𝑖𝑡𝑖𝑠ℎ), which cannot be found by search or copied as text, and screen
readers read them letter by letter. They are now real italics and bold,
also when the emphasized text contains braces. The customized preview
additionally shows small caps and no longer shows LaTeX commands inside
emphasized text.

Analogies: the journal name used to be chocolate letters, pretty but
useless for search and screen readers; now it is plain text tilted like
a crescent moon, and finding it in the preview is as easy as finding
honey in a hive.

### Steps to test

1. In Preferences → Entry preview, add a `.bst` file such as `abbrv.bst`
and select it.
2. Select an article with a journal.
3. The journal name in the preview is italic, and searching the preview
for a word of it finds it.

![BST preview with italic
journal](https://raw.githubusercontent.com/JabRef/jabref-koppor/assets-bst-preview-emph/bst-preview-italic.png)

### Related issues and pull requests

Closes TODO

Triggered by github.com/palukku/pull/67 (hover citation in JabLS
showed the math letters).

### AI usage

Claude Code (model claude-opus-5-5), AIL3.

<details>
<summary>AI CHECKLIST.md walkthrough</summary>

#### 1. Code self-review

- [x] No `== null` / `!= null` checks — JSpecify annotations
(`@NullMarked`, `@Nullable`, `@NonNull`) used instead.
- [x] No `Objects.requireNonNull(...)` — nullability expressed via
JSpecify annotations.
- [/] New classes annotated with `@NullMarked`
(`org.jspecify.annotations.NullMarked`).
- [/] New packages annotated with `@NullMarked`
(`org.jspecify.annotations.NullMarked`).
- [/] `Optional` consumed with `ifPresent` / `ifPresentOrElse` / `map` /
`orElseThrow` — never `orElse(unusedValue)` nor an `isPresent()` +
`get()` block.
- [/] `StringUtil.isBlank(...)` used instead of `s == null ||
s.isBlank()`.
- [/] No `catch (Exception e)` — only specific exceptions are caught.
- [/] No `throw new RuntimeException(...)` /
`IllegalStateException(...)` — these tear down the whole application.
- [/] Logged exceptions are passed as the **last** logger argument
(`LOGGER.info("...", e)`), not concatenated into the message string.
- [/] New `BibEntry` objects built with withers (`withField`, not
`setField`).
- [/] Modern Java used: `List.of()` / `Map.of()` / `Set.of()`,
`Path.of()`, `SequencedCollection` / `SequencedSet`, text blocks.
- [/] Regexes use a precompiled `Pattern.compile(...)` constant, not
`String.matches(...)`.
- [/] Keep alphabetical ordering when adding variables or enum items.
- [/] Background work uses `org.jabref.logic.util.BackgroundTask`, not
`new Thread()`.
- [x] No commented-out code, no trivial comments restating the code, no
AI-disclosure comments in source.
- [x] Markdown Javadoc (`///`) uses Markdown syntax, not JavaDoc inline
tags: `` `code` `` instead of `{@code}`, `[ClassName]` instead of
`{@link}`.
- [/] All user-facing text localized (`Localization.lang` in Java, `%`
prefix in FXML).
- [/] Sentence case (not Title Case); no trailing `!`; labels do not end
with `:`.
- [/] Variance expressed with placeholders (`"...: %0"`), not string
concatenation.
- [/] User-controlled data (request params, entry fields, file contents)
is HTML-escaped before being written into any `text/html` response —
including exception/error messages, not just the success body (XSS).
- [x] In case issue lists an example, this concrete example is covered
by a test case.
- [x] Behavior changes in `org.jabref.model` / `org.jabref.logic` have
added or updated tests.
- [x] Tests assert object contents (`assertEquals`), use plain JUnit
asserts (not AssertJ), have no `@DisplayName`, do not catch exceptions
(let them propagate so JUnit reports setup/teardown failures directly),
and use `@TempDir` instead of manual temp directories.
- [/] Fetcher tests hit the live endpoints — the remote API is not
mocked or stubbed (automated-review suggestions to mock it are rejected
on purpose).

#### 2. Verification commands

- [ ] `./gradlew :jablib:check` (or `./gradlew check` for all modules).
- [x] `./gradlew checkstyleMain checkstyleTest checkstyleJmh`.
- [x] `./gradlew modernizer`.
- [x] `./gradlew --no-configuration-cache :rewriteDryRun` reports no
changes (run `./gradlew rewriteRun` to fix).
- [ ] `./gradlew javadoc`.
- [x] `npx markdownlint-cli2 "docs/**/*.md" "*.md"` (only if Markdown
changed).
- [/] `npm ci && npm run textlint` reports no misspellings (only if
Markdown changed).
- [/] Only if formatting is still off after `rewriteRun`: `docker run -v
$(pwd):/github/workspace ghcr.io/leventebajczi/intellij-format:master
"*.java" "" ".idea/codeStyles/Project.xml"`.

#### 3. Documentation

- [x] `CHANGELOG.md` entry added if the change is visible to the user
(end-user wording, no extra blank lines, sorted in next to existing
entries about the same component/feature). Link the issue if one exists;
link the PR only when no issue exists. Use `TODO` as the placeholder
when neither is known yet — never a fake number. No entry for fixes to
changes that were themselves introduced after the last release (feature
only in `## [Unreleased]`) — update the existing unreleased entry
instead if needed.
- [x] Searched [jabref/issues](https://github.com/JabRef/jabref/issues)
and
[jabref-koppor/issues](https://github.com/JabRef/jabref-koppor/issues)
for a related issue; linked only on a confident match, otherwise kept
`TODO` (no `closes`/`fixes` for merely-similar issues).
- [/] Requirement added to `docs/requirements/<area>.md` if the change
is a new feature or significant bug fix (skip for refactors, minor
fixes, and internal changes).
- [/] Developer documentation under `docs/` updated if behavior or
architecture changed.

#### 4. Pull request

- [x] PR body built from `.github/PULL_REQUEST_TEMPLATE.md`, every
section filled.
- [x] All checklist items kept and marked `[x]`, `[ ]`, or `[/]`.
- [x] "Steps to test" is a numbered list with a cropped screenshot of
the result for every visible change; no video (only allowed when another
program is involved, e.g. drag and drop or push to an external
application).
- [x] All HTML comments removed from the PR body.
- [x] PR created with `gh pr create --body-file <file>` (not `--body`).
- [x] If `CHANGELOG.md` used a `TODO` placeholder (no issue confidently
identified yet — an existing issue link always stays), the PR was opened
as draft, the placeholder was replaced with the real PR-number link
after PR creation, committed and pushed, and only then was the PR marked
ready for review. If an issue is identified or created later, the link
is switched to the issue.

</details>

### Checklist

- [x] I own the copyright of the code submitted and I license it under
the [MIT license](https://github.com/JabRef/jabref/blob/main/LICENSE)
- [x] If AI tools were used, I disclosed them in the "AI usage" section
and reviewed, understood, and take full ownership of all AI-generated
code
- [x] I manually tested my changes in running JabRef (always required)
- [x] I added JUnit tests for changes (if applicable)
- [x] I added screenshots in the PR description (if change is visible to
the user)
- [x] I added **one sentence (max 20 words)** to `CHANGELOG.md`
describing the change from the user's point of view (if the change is
visible to the user)
- [/] I checked the [user documentation](https://docs.jabref.org/) for
up to dateness and submitted a pull request to our [user documentation
repository](https://github.com/JabRef/user-documentation/tree/main/en)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: subhramit <subhramit.bb@live.in>
bhosale-mahesh pushed a commit to bhosale-mahesh/jabref that referenced this pull request Nov 29, 2026
### Summary

Preserve supported nested LaTeX formatting in JStyle bibliographies sent
to LibreOffice/OpenOffice, without leaving inner commands visible, and
render spacing controls and literal ampersands correctly in HTML and
Writer output. Share the HTML/Writer conversion traversal while keeping
each formatter's normalization, character mappings, and markup
vocabulary distinct; public formatter APIs and registered layout names
remain unchanged.

This is the child of JabRef#17902. Its
useful escaped-brace `StringUtil` fix is inherited unchanged: this child
contains no `StringUtil` diff. BST rendering inside Writer continues to
use Pandoc; this patch fixes the JStyle path and shares its conversion
with HTML previews/layouts, not with the Pandoc pipeline.

The converter uses an explicit frame stack instead of recursion or
repeated argument rescans. Tests cover nested commands,
protection/literal braces, legacy switches, accents, normalization
differences, deep groups, and deep unknown-command arguments. This is an
architectural/correctness change, not a claim of benchmarked speedup.

Malformed-input recovery changes deliberately: escaped braces are
literal, supported commands without usable arguments emit no formatting,
and unfinished formatting scopes close at end of input. After BST
sanitizes unmatched braces, two malformed-title cases now retain HTML
entities or a recoverable small-caps scope rather than falling back to
plain Unicode. Both cases retain exact-output assertions. The malformed
HTML input `\{i}` now produces `{i`, not dotless i; valid `\{i\}`
produces `{i}`.

**Malformed-input recovery examples**

Outputs below are generated markup, not rendered text. BST rows show
only the title portion; the author prefix is unchanged.

| Context | Input | Old output (parent PR) | Current output | Recovery
rule / difference |
| --- | --- | --- | --- | --- |
| HTML, escaped opening brace and unmatched closing brace | `\{i}` |
`&imath;` (dotless i) | `{i` | The escaped opening brace is literal; the
unmatched structural closing brace is discarded. Previously this
incorrectly produced dotless i (`&imath;`). |
| HTML, valid escaped brace pair | `\{i\}` | `i\}` | `{i}` | Valid
reference case: both escaped braces remain literal. |
| HTML / Writer, formatting command without an argument | `\emph` |
`emph` | Empty string | Nothing is formatted and the command name does
not leak into output. |
| HTML / Writer, unfinished nested formatting | `\textit{a {\bf b` |
HTML: `<i>a <b>b</b></i>`; Writer: `<i>a {\bf b</i>` | `<i>a
<b>b</b></i>` | Close unfinished formatting scopes in reverse nesting
order, without inventing displayed braces. |
| BST preview, unmatched argument brace | `\textsc{L{\'o}pez` | `López.`
| `L&oacute;pez.` | After BST brace sanitization, recover the accent as
HTML. Previously the title was plain Unicode `López.`; the visible
letters are the same. |
| BST preview, unmatched legacy-switch group | `{\sc L{\'o}pez` |
`lópez.` | `<span style="font-variant: small-caps">l&oacute;pez.</span>`
| Recover the small-caps scope and close its tag. Previously the title
fell back to unstyled `lópez.`. |

### Legacy versus corrected behavior

These tests compare **generated markup**, not the characters ultimately
displayed. HTML entities are necessary representations, not inherently
bugs:

| Markup asserted by a test | Displayed result | Meaning |
| --- | --- | --- |
| `&amp;` | `&` | One literal ampersand |
| `&nbsp;` | A non-breaking space | A spacing character that prevents a
line break |
| `&copy;` | © | A copyright symbol |
| `&amp;amp;` | The literal text `&amp;` | Correct only when those five
characters are intended |

Existing `&nbsp;` expectations remain unchanged. Thin/medium/thick
spacing controls are not non-breaking-space commands, so they are not
all replaced with `&nbsp;`.

#### Ampersands

| Input characters (not Java string literals) | Legacy behavior |
Corrected behavior |
| --- | --- | --- |
| `&` | HTML displayed `&` | Both outputs display `&`, with literal
ampersands protected in markup |
| `\&` | Usually displayed `&` | Displays `&`, encoded once as `&amp;` |
| `\\&` (two backslashes, then ampersand) | HTML emitted `&amp;amp;`,
displaying the unwanted text `&amp;` | Emits `\&amp;`, displaying a
literal backslash followed by `&` |
| `\&copy;` | Writer could decode the intended literal text as © | Emits
`&amp;copy;`, displaying the literal text `&copy;` |
| `&copy;` already present in the source | Treated as an entity |
Remains an entity and displays © |
| `&{copy;}` | HTML protected the source ampersand; Writer could
assemble an entity | Emits `&amp;copy;`, displaying literal `&copy;`,
not © |

The double-escaping test passed before this follow-up because it
expected the legacy output. Qodo's claim that it broke an unchanged
assertion was incorrect, but preserving that assertion was not a reason
to keep the double-escaping behavior. The assertion now checks the
corrected output, and backslash runs from zero through six are tested
explicitly.

Ampersands are handled while traversing the input, rather than by
overlapping replacements before parsing or a blanket escape afterward.
This preserves backslash parity, distinguishes real source entities from
text assembled by removing groups, and protects escaped entity-looking
text until the renderer decodes it once. HTML's unsupported-accent
fallback also escapes literal ampersands because it bypasses normal text
emission.

Two source backslashes retain this converter's existing
**literal-backslash convention**. This change does not implement TeX's
line-breaking interpretation of `\\` or a complete TeX parser.

#### Spacing controls

| Input | Legacy HTML output displayed | Legacy Writer output displayed
| Corrected output in both dialects |
| --- | --- | --- | --- |
| `A\,B` | `A,B` | `AB` | `A` + U+2009 thin space + `B` |
| `A\:B` | `A:B` | `AB` | `A` + U+205F medium mathematical space + `B` |
| `A\;B` | `A;B` | `AB` | `A` + U+2005 four-per-em space + `B` |
| `A\!B` | `A!B` | `AB` | `AB`; unsupported negative spacing is omitted
|
| Plain `A,B` | `A,B` | `A,B` | Unchanged: `A,B` |

The initial shared-parser version introduced punctuation into Writer
output, including a ratio symbol for `\:`. Restoring legacy punctuation
in HTML and dropping every spacing instruction in Writer would preserve
incorrect/lossy outputs. Instead, positive spacing commands now produce
Unicode spacing characters; literal punctuation remains punctuation.

These widths are **font-dependent approximations**, not full TeX glue or
exact math-mode widths. In particular, U+2005 approximates thick
spacing, and the supported markup has no negative-spacing primitive.
Direct Unicode also avoids depending on HTML5-only named entities in
Writer's HTML4 decoder. Control symbols consume only themselves: in
`A\,{B}`, the group remains content rather than becoming an argument to
the comma command.

The implementation documents these decisions alongside the frame-stack,
argument/scope, malformed-input recovery, and bounded source-lookup
logic. Regression tests cover standalone and nested controls, following
groups, preserved protection braces, literal punctuation, source
entities, escaped entity-looking text, accent fallback, and real Writer
insertion/save/reopen.

### Related issues and pull requests

Stacked on JabRef#17902. The parent's
Checkstyle fix was pushed first as `53c6a3afd9`.

Searched JabRef/jabref and JabRef/jabref-koppor issues for “JStyle
nested formatting” and “LibreOffice textbf”; no confident matching issue
was found. No issue-closing claim is made.

### AI usage

Zed Agent with model `openai/gpt-6.1-sol` (GPT-6.1 Sol), including
delegated reviews and validation, assisted with implementation,
experiments, tests, documentation, and this description.

<details>
<summary>AI CHECKLIST.md walkthrough</summary>

# Code checklist

> [!IMPORTANT]
> **This is a mandatory final gate.** When the implementation is
finished and before you open a PR, work through **every** box below and
tick it. If a box cannot be ticked, fix the code first; mark a box `[/]`
only if the point genuinely does not apply.
>
> `AGENTS.md` describes how to write code *while* developing — this file
confirms the finished result. Do not skip the checklist and do not skip
individual points.

## 1. Code self-review

Read your own diff once, top to bottom, and confirm each point.

### Nullability and control flow

- [x] No `== null` / `!= null` checks — JSpecify annotations
(`@NullMarked`, `@Nullable`, `@NonNull`) used instead.
- [x] No `Objects.requireNonNull(...)` — nullability expressed via
JSpecify annotations.
- [x] New classes annotated with `@NullMarked`
(`org.jspecify.annotations.NullMarked`).
- [/] New packages annotated with `@NullMarked`
(`org.jspecify.annotations.NullMarked`).
- [x] `Optional` consumed with `ifPresent` / `ifPresentOrElse` / `map` /
`orElseThrow` — never `orElse(unusedValue)` nor an `isPresent()` +
`get()` block.
- [/] `StringUtil.isBlank(...)` used instead of `s == null ||
s.isBlank()`.

### Exceptions

- [/] No `catch (Exception e)` — only specific exceptions are caught.
- [/] No `throw new RuntimeException(...)` /
`IllegalStateException(...)` — these tear down the whole application.
- [/] Logged exceptions are passed as the **last** logger argument
(`LOGGER.info("...", e)`), not concatenated into the message string.

### Style and idioms

- [/] New `BibEntry` objects built with withers (`withField`, not
`setField`).
- [x] Modern Java used: `List.of()` / `Map.of()` / `Set.of()`,
`Path.of()`, `SequencedCollection` / `SequencedSet`, text blocks.
- [x] Regexes use a precompiled `Pattern.compile(...)` constant, not
`String.matches(...)`.
- [x] Keep alphabetical ordering when adding variables or enum items.
- [/] Background work uses `org.jabref.logic.util.BackgroundTask`, not
`new Thread()`.
- [x] No commented-out code, no trivial comments restating the code, no
AI-disclosure comments in source.
- [x] Markdown Javadoc (`///`) uses Markdown syntax, not JavaDoc inline
tags: `` `code` `` instead of `{@code}`, `[ClassName]` instead of
`{@link}`.

### User-facing text

- [/] All user-facing text localized (`Localization.lang` in Java, `%`
prefix in FXML).
- [/] Sentence case (not Title Case); no trailing `!`; labels do not end
with `:`.
- [/] Variance expressed with placeholders (`"...: %0"`), not string
concatenation.

### Security

- [/] User-controlled data (request params, entry fields, file contents)
is HTML-escaped before being written into any `text/html` response —
including exception/error messages, not just the success body (XSS).

### Tests

- [/] In case issue lists an example, this concrete example is covered
by a test case.
- [x] Behavior changes in `org.jabref.model` / `org.jabref.logic` have
added or updated tests.
- [x] Tests assert object contents (`assertEquals`), use plain JUnit
asserts (not AssertJ), have no `@DisplayName`, do not catch exceptions
(let them propagate so JUnit reports setup/teardown failures directly),
and use `@TempDir` instead of manual temp directories.
- [/] Fetcher tests hit the live endpoints — the remote API is not
mocked or stubbed (automated-review suggestions to mock it are rejected
on purpose).

## 2. Verification commands

Run in this order — cheapest first. Each must pass.

- [ ] `./gradlew :jablib:check` (or `./gradlew check` for all modules).
- [x] `./gradlew checkstyleMain checkstyleTest checkstyleJmh`.
- [x] `./gradlew modernizer`.
- [ ] `./gradlew --no-configuration-cache :rewriteDryRun` reports no
changes (run `./gradlew rewriteRun` to fix).
- [x] `./gradlew javadoc`.
- [x] `npx markdownlint-cli2 "docs/**/*.md" "*.md"` (only if Markdown
changed).
- [x] `npm ci && npm run textlint` reports no misspellings (only if
Markdown changed).
- [/] Only if formatting is still off after `rewriteRun`: `docker run -v
$(pwd):/github/workspace ghcr.io/leventebajczi/intellij-format:master
"*.java" "" ".idea/codeStyles/Project.xml"`.

## 3. Documentation

- [x] `CHANGELOG.md` entry added if the change is visible to the user
(end-user wording, no extra blank lines, sorted in next to existing
entries about the same component/feature). Link the issue if one exists;
link the PR only when no issue exists. Use `TODO` as the placeholder
when neither is known yet — never a fake number. No entry for fixes to
changes that were themselves introduced after the last release (feature
only in `## [Unreleased]`) — update the existing unreleased entry
instead if needed.
- [x] Searched [jabref/issues](https://github.com/JabRef/jabref/issues)
and
[jabref-koppor/issues](https://github.com/JabRef/jabref-koppor/issues)
for a related issue; linked only on a confident match, otherwise kept
`TODO` (no `closes`/`fixes` for merely-similar issues).
- [x] Requirement added to `docs/requirements/<area>.md` if the change
is a new feature or significant bug fix (skip for refactors, minor
fixes, and internal changes).
- [x] Developer documentation under `docs/` updated if behavior or
architecture changed.

## 4. Pull request

- [x] PR body built from `.github/PULL_REQUEST_TEMPLATE.md`, every
section filled.
- [x] All checklist items kept and marked `[x]`, `[ ]`, or `[/]`.
- [ ] "Steps to test" is a numbered list with a cropped screenshot of
the result for every visible change; no video (only allowed when another
program is involved, e.g. drag and drop or push to an external
application).
- [x] All HTML comments removed from the PR body.
- [x] PR created with `gh pr create --body-file <file>` (not `--body`).
- [ ] If `CHANGELOG.md` used a `TODO` placeholder (no issue confidently
identified yet — an existing issue link always stays), the PR was opened
as draft, the placeholder was replaced with the real PR-number link
after PR creation, committed and pushed, and only then was the PR marked
ready for review. If an issue is identified or created later, the link
is switched to the issue.

Checklist notes:

- No packages, dependencies, public APIs, user-facing UI strings,
background tasks, exception handlers, or HTTP response paths are
introduced. Existing HTML-like markup support is retained; the converter
is not an HTML sanitizer.
- Full-check completion, clean rewrite validation, interactive JabRef
testing, and screenshots remain open. Existing external/manual
requirements are not marked not-applicable just to complete the
checklist.
- The changelog placeholder was replaced with this PR's link and pushed
in `e1f17262e1`. The PR review state and contributor-owned checklist
declarations are preserved.
- Registered through native `gh stack link 17902 17921`:
JabRef/jabref Stack #17922. No rebase or force-push
was used.

</details>

### Checklist

- [x] I own the copyright of the code submitted and I license it under
the [MIT license](https://github.com/JabRef/jabref/blob/main/LICENSE)
- [x] If AI tools were used, I disclosed them in the "AI usage" section
and reviewed, understood, and take full ownership of all AI-generated
code
- [ ] I manually tested my changes in running JabRef (always required)
- [x] I added JUnit tests for changes (if applicable)
- [ ] I added screenshots in the PR description (if change is visible to
the user)
- [x] I added **one sentence (max 20 words)** to `CHANGELOG.md`
describing the change from the user's point of view (if the change is
visible to the user)
- [ ] I checked the [user documentation](https://docs.jabref.org/) for
up to dateness and submitted a pull request to our [user documentation
repository](https://github.com/JabRef/user-documentation/tree/main/en)

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Siedlerchr added a commit to PedroSarmento2007/jabref that referenced this pull request Nov 29, 2026
* main: (35 commits)
  Fix author and editor name export in MODS format (JabRef#17936)
  Fix LaTeX conversion in exported PDF metadata (JabRef#17810)
  Fix preferences menu text (JabRef#17966)
  Skip forced full-text index merges on shutdown (JabRef#17961)
  Fix wrong bibo namespace in RDF export (JabRef#17842)
  New Crowdin updates (JabRef#17956)
  chore(deps): update dependency com.konghq:unirest-modules-gson to v4.12.4 (JabRef#17955)
  Let Renovate update JavaFX in the jabsrv launcher (JabRef#17954)
  chore(deps): update dependency com.konghq:unirest-modules-gson to v4.12.3 (JabRef#17953)
  Import the RIS serial number of books and chapters as ISBN (JabRef#17891)
  Share nested LaTeX conversion with Writer (JabRef#17921)
  Render BST preview italics and bold as text, not math letters (JabRef#17902)
  Chore(deps): Bump com.konghq:unirest-java-bom from 4.11.11 to 4.12.0 in /versions (JabRef#17951)
  Inject NativeDesktop into its callers and remove the deprecated static helpers (JabRef#17947)
  New Crowdin updates (JabRef#17945)
  Chore(deps): Bump org.graalvm.sdk:nativeimage from 25.5.5.0.3 to 25.6.5.1 in /versions (JabRef#17944)
  Chore(deps): Bump com.googlecode.plist:dd-plist from 1.30 to 1.31 in /versions (JabRef#17943)
  Chore(deps): Bump JetBrains/junie-github-action from 1.10.1 to 1.10.2 (JabRef#17942)
  Chore(deps): Bump softprops/action-gh-release from 3.0.3 to 3.0.4 (JabRef#17941)
  Chore(deps): Bump anthropics/claude-code-action from 1.0.286 to 1.0.289 (JabRef#17940)
  ...
Siedlerchr added a commit to gourprince222/jabref that referenced this pull request Nov 29, 2026
* main: (58 commits)
  Keep organization authors containing "and" intact in RIS export. (JabRef#17876)
  Fix author and editor name export in MODS format (JabRef#17936)
  Fix LaTeX conversion in exported PDF metadata (JabRef#17810)
  Fix preferences menu text (JabRef#17966)
  Skip forced full-text index merges on shutdown (JabRef#17961)
  Fix wrong bibo namespace in RDF export (JabRef#17842)
  New Crowdin updates (JabRef#17956)
  chore(deps): update dependency com.konghq:unirest-modules-gson to v4.12.4 (JabRef#17955)
  Let Renovate update JavaFX in the jabsrv launcher (JabRef#17954)
  chore(deps): update dependency com.konghq:unirest-modules-gson to v4.12.3 (JabRef#17953)
  Import the RIS serial number of books and chapters as ISBN (JabRef#17891)
  Share nested LaTeX conversion with Writer (JabRef#17921)
  Render BST preview italics and bold as text, not math letters (JabRef#17902)
  Chore(deps): Bump com.konghq:unirest-java-bom from 4.11.11 to 4.12.0 in /versions (JabRef#17951)
  Inject NativeDesktop into its callers and remove the deprecated static helpers (JabRef#17947)
  New Crowdin updates (JabRef#17945)
  Chore(deps): Bump org.graalvm.sdk:nativeimage from 25.5.5.0.3 to 25.6.5.1 in /versions (JabRef#17944)
  Chore(deps): Bump com.googlecode.plist:dd-plist from 1.30 to 1.31 in /versions (JabRef#17943)
  Chore(deps): Bump JetBrains/junie-github-action from 1.10.1 to 1.10.2 (JabRef#17942)
  Chore(deps): Bump softprops/action-gh-release from 3.0.3 to 3.0.4 (JabRef#17941)
  ...
@koppor koppor mentioned this pull request Dec 3, 2026
1 of 10 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

component: bst component: entry-preview component: export-or-save component: latex-file-support dev: send-to-black-forest Port to the black-forest branch of JabRef/jabref-black-forest after merging (ADR-0073) size: medium status: to-be-merged PRs which are accepted and should go into the merge-queue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants