From 9d2f177d5a15aa1970e7507a43d84ffdc2d2bedc Mon Sep 17 00:00:00 2001 From: Oliver Kopp Date: Mon, 23 Nov 2026 06:31:31 +0100 Subject: [PATCH 1/4] Render BST preview emphasis as HTML instead of math letters 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 --- CHANGELOG.md | 1 + .../logic/preview/BstPreviewLayout.java | 47 +++++++++---------- .../logic/bst/BstPreviewLayoutTest.java | 23 ++++++++- 3 files changed, 43 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fd98f1feccec..9db3d3b2633c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -76,6 +76,7 @@ Note that this project **does not** adhere to [Semantic Versioning](https://semv - We fixed an issue where clicking "Generate" in the AUX file import dialog before parsing caused an exception. - We fixed an issue where it was hard to distinguish between enabled/disabled status of search buttons in dark mode and added tooltips. [#11569](https://github.com/JabRef/jabref/issues/11569) - We fixed an issue where entries containing dollar signs, backslashes, or unset fields passed to `substring$` caused citation style preview and export to fail. [#12799](https://github.com/JabRef/jabref/issues/12799) +- We fixed an issue where BST entry previews showed italic and bold text as Unicode mathematical letters. TODO - We fixed an issue where citationcount, day, and dayfiled columns were sorted alphabetically instead of numerically. [#17459](https://github.com/JabRef/jabref/issues/17459) - We fixed an issue where searching or sorting the main table of a large library froze JabRef for seconds. [#17762](https://github.com/JabRef/jabref/pull/17762) - We fixed exports to RIS, CSV, HTML, and other template-based formats in native JabKit. [#17408](https://github.com/JabRef/jabref/issues/17408) diff --git a/jablib/src/main/java/org/jabref/logic/preview/BstPreviewLayout.java b/jablib/src/main/java/org/jabref/logic/preview/BstPreviewLayout.java index cc8ecf42dbd9..084598574ea7 100644 --- a/jablib/src/main/java/org/jabref/logic/preview/BstPreviewLayout.java +++ b/jablib/src/main/java/org/jabref/logic/preview/BstPreviewLayout.java @@ -40,14 +40,8 @@ public final class BstPreviewLayout implements PreviewLayout { private static final Pattern LATEX_COMMAND_PATTERN = Pattern.compile("(?m)^\\\\.*$"); private static final Pattern MULTIPLE_SPACES_PATTERN = Pattern.compile(" +"); - // LaTeX inline formatting → HTML. Italic and bold survive `LatexToUnicodeFormatter`, while - // `\textsc{...}` has to be converted earlier because it would otherwise be reduced to plain text. - private static final Pattern EMPH_PATTERN = Pattern.compile("\\\\emph\\{([^}]*?)}"); - private static final Pattern TEXTIT_PATTERN = Pattern.compile("\\\\textit\\{([^}]*?)}"); - private static final Pattern TEXTBF_PATTERN = Pattern.compile("\\\\textbf\\{([^}]*?)}"); - private static final Pattern GROUP_EM_PATTERN = Pattern.compile("\\{\\\\em\\s+([^}]*?)}"); - private static final Pattern GROUP_IT_PATTERN = Pattern.compile("\\{\\\\it\\s+([^}]*?)}"); - private static final Pattern GROUP_BF_PATTERN = Pattern.compile("\\{\\\\bf\\s+([^}]*?)}"); + private static final String SMALL_CAPS_OPEN = ""; + private static final String SPAN_CLOSE = ""; /// Matches a single LaTeX math command wrapped in the `{{$...$}}` form written by some /// exporters, e.g. `{{$\Sigma$}}`. Group 1 is the command without its leading backslash @@ -152,19 +146,11 @@ public String generatePreview(BibEntry originalEntry, BibDatabaseContext databas result = LATEX_COMMAND_PATTERN.matcher(result).replaceAll(""); // Remove some IEEEtran.bst output (resulting from a multiline \\providecommand) result = result.replace("#2}}", ""); - result = convertInlineSmallCapsToHtml(result); + result = convertInlineFormattingToHtml(result); // Have quotes right - and more result = new LatexToUnicodeFormatter().format(result); result = result.replace("``", "\""); result = result.replace("''", "\""); - // Convert LaTeX inline formatting to HTML before RemoveLatexCommandsFormatter strips them. - // \\emph{X} and {\\em X} forms (IEEEtran uses \\emph, abbrv uses {\\em}) - result = EMPH_PATTERN.matcher(result).replaceAll("$1"); - result = TEXTIT_PATTERN.matcher(result).replaceAll("$1"); - result = GROUP_EM_PATTERN.matcher(result).replaceAll("$1"); - result = GROUP_IT_PATTERN.matcher(result).replaceAll("$1"); - result = TEXTBF_PATTERN.matcher(result).replaceAll("$1"); - result = GROUP_BF_PATTERN.matcher(result).replaceAll("$1"); // Final cleanup result = new RemoveNewlinesFormatter().format(result); result = new RemoveLatexCommandsFormatter().format(result); @@ -173,12 +159,21 @@ public String generatePreview(BibEntry originalEntry, BibDatabaseContext databas return result; } - private static String convertInlineSmallCapsToHtml(String latex) { - String html = replaceCommandWithBalancedArgument(latex, "textsc"); - return replaceLegacySwitchWithBalancedArgument(html, "sc"); + /// Has to run before `LatexToUnicodeFormatter`, which would turn italic and bold into Unicode mathematical letters + /// (not searchable, read out letter by letter by screen readers) and reduce small caps to plain text. + /// Both the command form (`\\emph{X}`, used by IEEEtran) and the switch form (`{\\em X}`, used by abbrv) are converted. + private static String convertInlineFormattingToHtml(String latex) { + String html = replaceCommandWithBalancedArgument(latex, "textsc", SMALL_CAPS_OPEN, SPAN_CLOSE); + html = replaceLegacySwitchWithBalancedArgument(html, "sc", SMALL_CAPS_OPEN, SPAN_CLOSE); + html = replaceCommandWithBalancedArgument(html, "emph", "", ""); + html = replaceCommandWithBalancedArgument(html, "textit", "", ""); + html = replaceLegacySwitchWithBalancedArgument(html, "em", "", ""); + html = replaceLegacySwitchWithBalancedArgument(html, "it", "", ""); + html = replaceCommandWithBalancedArgument(html, "textbf", "", ""); + return replaceLegacySwitchWithBalancedArgument(html, "bf", "", ""); } - private static String replaceCommandWithBalancedArgument(String input, String command) { + private static String replaceCommandWithBalancedArgument(String input, String command, String openTag, String closeTag) { String commandPrefix = "\\" + command; StringBuilder output = new StringBuilder(input.length()); int index = 0; @@ -210,15 +205,15 @@ private static String replaceCommandWithBalancedArgument(String input, String co break; } - output.append("") + output.append(openTag) .append(input, contentStart, groupEnd) - .append(""); + .append(closeTag); index = groupEnd + 1; } return output.toString(); } - private static String replaceLegacySwitchWithBalancedArgument(String input, String command) { + private static String replaceLegacySwitchWithBalancedArgument(String input, String command, String openTag, String closeTag) { String legacyCommandPrefix = "{\\" + command; StringBuilder output = new StringBuilder(input.length()); int index = 0; @@ -248,9 +243,9 @@ private static String replaceLegacySwitchWithBalancedArgument(String input, Stri break; } - output.append("") + output.append(openTag) .append(input, contentStart, groupEnd) - .append(""); + .append(closeTag); index = groupEnd + 1; } return output.toString(); diff --git a/jablib/src/test/java/org/jabref/logic/bst/BstPreviewLayoutTest.java b/jablib/src/test/java/org/jabref/logic/bst/BstPreviewLayoutTest.java index 225030fc44f4..13306f7bf0c7 100644 --- a/jablib/src/test/java/org/jabref/logic/bst/BstPreviewLayoutTest.java +++ b/jablib/src/test/java/org/jabref/logic/bst/BstPreviewLayoutTest.java @@ -106,12 +106,31 @@ private static Stream generatePreviewHandlesInlineFormatting() { Arguments.of("\\textsc{L{\\'o}pez", "O.\u00a0Kopp. López."), Arguments.of("{\\sc L{\\'o}pez", "O.\u00a0Kopp. lópez."), + // Emphasis becomes HTML, not Unicode mathematical italic or bold letters + // abbrv lowercases titles, as BibTeX does inside {\\em ...} + Arguments.of("On {\\em Drosophila} genetics", "O.\u00a0Kopp. On drosophila genetics."), + Arguments.of("On \\emph{Drosophila} genetics", "O.\u00a0Kopp. On Drosophila genetics."), + Arguments.of("On \\textit{Drosophila} genetics", "O.\u00a0Kopp. On Drosophila genetics."), + Arguments.of("On \\textbf{Drosophila} genetics", "O.\u00a0Kopp. On Drosophila genetics."), + // Existing superscript and subscript rendering should remain unchanged Arguments.of("Proceedings of the 9\\textsuperscript{th} symposium", "O.\u00a0Kopp. Proceedings of the 9ᵗʰ symposium."), Arguments.of("{H\\textsubscript{2}O}", "O.\u00a0Kopp. H₂O.") ); } + @Test + void journalEmphasizedByBstIsRenderedItalic() throws URISyntaxException { + BstPreviewLayout bstPreviewLayout = new BstPreviewLayout(Path.of(BstPreviewLayoutTest.class.getResource("abbrv.bst").toURI())); + BibEntry entry = new BibEntry(StandardEntryType.Article) + .withField(StandardField.AUTHOR, "Karen A. Cooper") + .withField(StandardField.TITLE, "Cocoa and health: a decade of research") + .withField(StandardField.JOURNAL, "British Journal of Nutrition") + .withField(StandardField.YEAR, "2007"); + String preview = bstPreviewLayout.generatePreview(entry, bibDatabaseContext); + assertEquals("K.\u00a0A. Cooper. Cocoa and health: a decade of research. British Journal of Nutrition, 2007.", preview); + } + @Test void unresolvableBracedMathIsKept() throws URISyntaxException { BstPreviewLayout bstPreviewLayout = new BstPreviewLayout(Path.of(BstPreviewLayoutTest.class.getResource("abbrv.bst").toURI())); @@ -151,7 +170,7 @@ void generatePreviewResolvesXDataFields() throws URISyntaxException { String preview = bstPreviewLayout.generatePreview(book, context); - assertEquals("D.\u00a0E. Knuth. 𝑇ℎ𝑒 𝐵𝑜𝑜𝑘. Number\u00a01 in Computers and Typesetting. Addison-Wesley, Reading, MA, 1984.", preview); + assertEquals("D.\u00a0E. Knuth. The Book. Number\u00a01 in Computers and Typesetting. Addison-Wesley, Reading, MA, 1984.", preview); } @Test @@ -175,7 +194,7 @@ void generatePreviewIgnoresLibraryPreambleWhenResolvingXDataFields() throws URIS String preview = bstPreviewLayout.generatePreview(book, context); - assertEquals("D.\u00a0E. Knuth. 𝑇ℎ𝑒 𝐵𝑜𝑜𝑘. Number\u00a01 in Computers and Typesetting. Addison-Wesley, Reading, MA, 1984.", preview); + assertEquals("D.\u00a0E. Knuth. The Book. Number\u00a01 in Computers and Typesetting. Addison-Wesley, Reading, MA, 1984.", preview); } private static BibEntry getSliceTheoremPaper() { From 028631d78d415126ad6573f036f3354bc077c22e Mon Sep 17 00:00:00 2001 From: Oliver Kopp Date: Mon, 23 Nov 2026 06:32:08 +0100 Subject: [PATCH 2/4] Link PR in changelog Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9db3d3b2633c..8a0079dcb704 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -76,7 +76,7 @@ Note that this project **does not** adhere to [Semantic Versioning](https://semv - We fixed an issue where clicking "Generate" in the AUX file import dialog before parsing caused an exception. - We fixed an issue where it was hard to distinguish between enabled/disabled status of search buttons in dark mode and added tooltips. [#11569](https://github.com/JabRef/jabref/issues/11569) - We fixed an issue where entries containing dollar signs, backslashes, or unset fields passed to `substring$` caused citation style preview and export to fail. [#12799](https://github.com/JabRef/jabref/issues/12799) -- We fixed an issue where BST entry previews showed italic and bold text as Unicode mathematical letters. TODO +- We fixed an issue where BST entry previews showed italic and bold text as Unicode mathematical letters. [#17902](https://github.com/JabRef/jabref/pull/17902) - We fixed an issue where citationcount, day, and dayfiled columns were sorted alphabetically instead of numerically. [#17459](https://github.com/JabRef/jabref/issues/17459) - We fixed an issue where searching or sorting the main table of a large library froze JabRef for seconds. [#17762](https://github.com/JabRef/jabref/pull/17762) - We fixed exports to RIS, CSV, HTML, and other template-based formats in native JabKit. [#17408](https://github.com/JabRef/jabref/issues/17408) From df0f3e8ce15751ec74ba918e959e600f9f3407d5 Mon Sep 17 00:00:00 2001 From: Oliver Kopp Date: Mon, 23 Nov 2026 22:44:13 +0100 Subject: [PATCH 3/4] Convert BST preview LaTeX with HTMLChars 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 --- CHANGELOG.md | 1 + .../jabref/logic/layout/format/HTMLChars.java | 37 ++++- .../logic/preview/BstPreviewLayout.java | 140 +----------------- .../jabref/logic/util/strings/StringUtil.java | 6 + .../logic/bst/BstPreviewLayoutTest.java | 52 +++---- .../logic/layout/format/HTMLCharsTest.java | 12 +- .../logic/util/strings/StringUtilTest.java | 2 + 7 files changed, 85 insertions(+), 165 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a0079dcb704..90c6e436cf09 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -77,6 +77,7 @@ Note that this project **does not** adhere to [Semantic Versioning](https://semv - We fixed an issue where it was hard to distinguish between enabled/disabled status of search buttons in dark mode and added tooltips. [#11569](https://github.com/JabRef/jabref/issues/11569) - We fixed an issue where entries containing dollar signs, backslashes, or unset fields passed to `substring$` caused citation style preview and export to fail. [#12799](https://github.com/JabRef/jabref/issues/12799) - We fixed an issue where BST entry previews showed italic and bold text as Unicode mathematical letters. [#17902](https://github.com/JabRef/jabref/pull/17902) +- We fixed an issue where the customized entry preview ignored small caps and showed LaTeX commands inside emphasized text. [#17902](https://github.com/JabRef/jabref/pull/17902) - We fixed an issue where citationcount, day, and dayfiled columns were sorted alphabetically instead of numerically. [#17459](https://github.com/JabRef/jabref/issues/17459) - We fixed an issue where searching or sorting the main table of a large library froze JabRef for seconds. [#17762](https://github.com/JabRef/jabref/pull/17762) - We fixed exports to RIS, CSV, HTML, and other template-based formats in native JabKit. [#17408](https://github.com/JabRef/jabref/issues/17408) diff --git a/jablib/src/main/java/org/jabref/logic/layout/format/HTMLChars.java b/jablib/src/main/java/org/jabref/logic/layout/format/HTMLChars.java index 8a6a95256878..10a869f4b94c 100644 --- a/jablib/src/main/java/org/jabref/logic/layout/format/HTMLChars.java +++ b/jablib/src/main/java/org/jabref/logic/layout/format/HTMLChars.java @@ -2,6 +2,7 @@ import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.regex.Pattern; import org.jabref.logic.layout.ParamLayoutFormatter; @@ -20,6 +21,9 @@ public class HTMLChars implements ParamLayoutFormatter { /// - `&Hey` **Matched** private static final Pattern HTML_ENTITY_PATTERN = Pattern.compile("&(?!(?:[a-zA-Z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});)"); + // Declarations that apply to the rest of the enclosing group instead of taking an argument + private static final Set SWITCHES = Set.of("em", "it", "bf", "sc", "scshape"); + private boolean keepCurlyBraces = false; @Override @@ -31,7 +35,10 @@ public void setArgument(String arg) { @Override public String format(String inField) { - String field = normalizedField(inField); + return convert(normalizedField(inField)).replace("~", " "); // Replace any remaining ~ with   (non-breaking spaces) + } + + private String convert(String field) { StringBuilder sb = new StringBuilder(); StringBuilder currentCommand = null; @@ -50,7 +57,8 @@ public String format(String inField) { /* Close Command */ String command = currentCommand.toString(); String result = HTML_CHARS.get(command); - sb.append(Objects.requireNonNullElse(result, command)); + // A formatting command without argument formats nothing + sb.append(Objects.requireNonNullElse(result, getHTMLTag(command).isEmpty() ? command : "")); } escaped = true; incommand = true; @@ -112,13 +120,20 @@ public String format(String inField) { // command. // If so, handle. String tag = getHTMLTag(command); + // `\textsc {X}` is `\textsc{X}`; switches such as `{\em X}` instead apply to the rest of the group + int nextNonWhitespace = skipWhitespace(field, i); + if (!tag.isEmpty() && Character.isWhitespace(c) && !SWITCHES.contains(command) + && (nextNonWhitespace < field.length()) && (field.charAt(nextNonWhitespace) == '{')) { + i = nextNonWhitespace; + c = '{'; + } if (!tag.isEmpty()) { String part = StringUtil.getPart(field, i, true); if (this.keepCurlyBraces && (c == '{' || (c == '}'))) { i++; } i += part.length(); - sb.append('<').append(tag).append('>').append(part).append("'); + sb.append('<').append(tag).append('>').append(convert(part)).append("'); } else if (c == '{') { String argument = StringUtil.getPart(field, i, true); i += this.keepCurlyBraces ? argument.length() + 1 : argument.length(); @@ -172,7 +187,7 @@ public String format(String inField) { } } - return sb.toString().replace("~", " "); // Replace any remaining ~ with   (non-breaking spaces) + return sb.toString(); } private String normalizedField(String inField) { @@ -185,6 +200,14 @@ private String normalizedField(String inField) { .replaceAll("\\$([^$]*)\\$", this.keepCurlyBraces ? "\\\\{$1\\\\}" : "$1}"); } + private static int skipWhitespace(String field, int index) { + while ((index < field.length()) && Character.isWhitespace(field.charAt(index))) { + index++; + } + return index; + } + + /// Returns the opening tag without angle brackets; its first word is the element name private String getHTMLTag(String latexCommand) { String result = ""; switch (latexCommand) { @@ -203,6 +226,12 @@ private String getHTMLTag(String latexCommand) { case "bf": result = "b"; break; + // Small caps + case "textsc": + case "sc": + case "scshape": + result = "span style=\"font-variant: small-caps\""; + break; // Underline case "underline": result = "u"; diff --git a/jablib/src/main/java/org/jabref/logic/preview/BstPreviewLayout.java b/jablib/src/main/java/org/jabref/logic/preview/BstPreviewLayout.java index 084598574ea7..c655e46fb63e 100644 --- a/jablib/src/main/java/org/jabref/logic/preview/BstPreviewLayout.java +++ b/jablib/src/main/java/org/jabref/logic/preview/BstPreviewLayout.java @@ -14,9 +14,9 @@ import org.jabref.logic.cleanup.ConvertToBibtexCleanup; import org.jabref.logic.formatter.bibtexfields.RemoveNewlinesFormatter; import org.jabref.logic.l10n.Localization; +import org.jabref.logic.layout.format.HTMLChars; import org.jabref.logic.layout.format.LatexToUnicodeFormatter; import org.jabref.logic.layout.format.RemoveLatexCommandsFormatter; -import org.jabref.logic.layout.format.RemoveTilde; import org.jabref.logic.openoffice.style.BstStyle; import org.jabref.logic.util.StandardFileType; import org.jabref.model.database.BibDatabaseContext; @@ -40,9 +40,6 @@ public final class BstPreviewLayout implements PreviewLayout { private static final Pattern LATEX_COMMAND_PATTERN = Pattern.compile("(?m)^\\\\.*$"); private static final Pattern MULTIPLE_SPACES_PATTERN = Pattern.compile(" +"); - private static final String SMALL_CAPS_OPEN = ""; - private static final String SPAN_CLOSE = ""; - /// Matches a single LaTeX math command wrapped in the `{{$...$}}` form written by some /// exporters, e.g. `{{$\Sigma$}}`. Group 1 is the command without its leading backslash /// (`Sigma`). Reads as: `{{` `$` `\` (command) `$` `}}`. @@ -146,146 +143,21 @@ public String generatePreview(BibEntry originalEntry, BibDatabaseContext databas result = LATEX_COMMAND_PATTERN.matcher(result).replaceAll(""); // Remove some IEEEtran.bst output (resulting from a multiline \\providecommand) result = result.replace("#2}}", ""); - result = convertInlineFormattingToHtml(result); + // HTMLChars would turn line breaks into
+ result = new RemoveNewlinesFormatter().format(result); + // 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); // Have quotes right - and more result = new LatexToUnicodeFormatter().format(result); result = result.replace("``", "\""); result = result.replace("''", "\""); // Final cleanup - result = new RemoveNewlinesFormatter().format(result); result = new RemoveLatexCommandsFormatter().format(result); - result = new RemoveTilde().format(result); result = MULTIPLE_SPACES_PATTERN.matcher(result.trim()).replaceAll(" "); return result; } - /// Has to run before `LatexToUnicodeFormatter`, which would turn italic and bold into Unicode mathematical letters - /// (not searchable, read out letter by letter by screen readers) and reduce small caps to plain text. - /// Both the command form (`\\emph{X}`, used by IEEEtran) and the switch form (`{\\em X}`, used by abbrv) are converted. - private static String convertInlineFormattingToHtml(String latex) { - String html = replaceCommandWithBalancedArgument(latex, "textsc", SMALL_CAPS_OPEN, SPAN_CLOSE); - html = replaceLegacySwitchWithBalancedArgument(html, "sc", SMALL_CAPS_OPEN, SPAN_CLOSE); - html = replaceCommandWithBalancedArgument(html, "emph", "", ""); - html = replaceCommandWithBalancedArgument(html, "textit", "", ""); - html = replaceLegacySwitchWithBalancedArgument(html, "em", "", ""); - html = replaceLegacySwitchWithBalancedArgument(html, "it", "", ""); - html = replaceCommandWithBalancedArgument(html, "textbf", "", ""); - return replaceLegacySwitchWithBalancedArgument(html, "bf", "", ""); - } - - private static String replaceCommandWithBalancedArgument(String input, String command, String openTag, String closeTag) { - String commandPrefix = "\\" + command; - StringBuilder output = new StringBuilder(input.length()); - int index = 0; - while (index < input.length()) { - if (!input.startsWith(commandPrefix, index) || isEscaped(input, index)) { - output.append(input.charAt(index)); - index++; - continue; - } - - int commandEnd = index + commandPrefix.length(); - if ((commandEnd < input.length()) && Character.isLetter(input.charAt(commandEnd))) { - output.append(input.charAt(index)); - index++; - continue; - } - - int openingBrace = skipWhitespace(input, commandEnd); - if ((openingBrace >= input.length()) || (input.charAt(openingBrace) != '{')) { - output.append(input.charAt(index)); - index++; - continue; - } - - int contentStart = openingBrace + 1; - int groupEnd = findBalancedGroupEnd(input, contentStart); - if (groupEnd < 0) { - output.append(input, index, input.length()); - break; - } - - output.append(openTag) - .append(input, contentStart, groupEnd) - .append(closeTag); - index = groupEnd + 1; - } - return output.toString(); - } - - private static String replaceLegacySwitchWithBalancedArgument(String input, String command, String openTag, String closeTag) { - String legacyCommandPrefix = "{\\" + command; - StringBuilder output = new StringBuilder(input.length()); - int index = 0; - while (index < input.length()) { - if (!input.startsWith(legacyCommandPrefix, index)) { - output.append(input.charAt(index)); - index++; - continue; - } - - int commandEnd = index + legacyCommandPrefix.length(); - if ((commandEnd < input.length()) && Character.isLetter(input.charAt(commandEnd))) { - output.append(input.charAt(index)); - index++; - continue; - } - if ((commandEnd >= input.length()) || (!Character.isWhitespace(input.charAt(commandEnd)) && (input.charAt(commandEnd) != '}'))) { - output.append(input.charAt(index)); - index++; - continue; - } - - int contentStart = skipWhitespace(input, commandEnd); - int groupEnd = findBalancedGroupEnd(input, contentStart); - if (groupEnd < 0) { - output.append(input, index, input.length()); - break; - } - - output.append(openTag) - .append(input, contentStart, groupEnd) - .append(closeTag); - index = groupEnd + 1; - } - return output.toString(); - } - - private static int skipWhitespace(String input, int startIndex) { - int index = startIndex; - while ((index < input.length()) && Character.isWhitespace(input.charAt(index))) { - index++; - } - return index; - } - - private static int findBalancedGroupEnd(String input, int contentStart) { - int depth = 0; - for (int index = contentStart; index < input.length(); index++) { - char currentCharacter = input.charAt(index); - if (isEscaped(input, index)) { - continue; - } - if (currentCharacter == '{') { - depth++; - } else if (currentCharacter == '}') { - if (depth == 0) { - return index; - } - depth--; - } - } - return -1; - } - - private static boolean isEscaped(String input, int index) { - int backslashCount = 0; - for (int pos = index - 1; pos >= 0 && input.charAt(pos) == '\\'; pos--) { - backslashCount++; - } - return (backslashCount % 2) == 1; - } - /// Replaces `{{$\Cmd$}}` math expressions in all fields of the given entry by the corresponding /// Unicode character, wrapped in braces. The entry is modified in place, so it has to be a copy. /// diff --git a/jablib/src/main/java/org/jabref/logic/util/strings/StringUtil.java b/jablib/src/main/java/org/jabref/logic/util/strings/StringUtil.java index 9bcf769ca101..9227cb7e1293 100644 --- a/jablib/src/main/java/org/jabref/logic/util/strings/StringUtil.java +++ b/jablib/src/main/java/org/jabref/logic/util/strings/StringUtil.java @@ -104,6 +104,12 @@ public static String getPart(String text, int startIndex, boolean terminateOnEnd // end argument and leave whitespace for further processing break; } + if ((c == '\\') && ((index + 1) < text.length())) { + // Keep escaped characters together, so that `\{` and `\}` do not count as grouping + part.append(c).append(text.charAt(index + 1)); + index += 2; + continue; + } if ((c == '}') && (--count < 0)) { break; } else if (c == '{') { diff --git a/jablib/src/test/java/org/jabref/logic/bst/BstPreviewLayoutTest.java b/jablib/src/test/java/org/jabref/logic/bst/BstPreviewLayoutTest.java index 13306f7bf0c7..e68a9d6d1285 100644 --- a/jablib/src/test/java/org/jabref/logic/bst/BstPreviewLayoutTest.java +++ b/jablib/src/test/java/org/jabref/logic/bst/BstPreviewLayoutTest.java @@ -33,7 +33,7 @@ void generatePreviewForSimpleEntryUsingAbbr() throws URISyntaxException { BibEntry entry = new BibEntry().withField(StandardField.AUTHOR, "Oliver Kopp") .withField(StandardField.TITLE, "Thoughts on Development"); String preview = bstPreviewLayout.generatePreview(entry, bibDatabaseContext); - assertEquals("O.\u00a0Kopp. Thoughts on development.", preview); + assertEquals("O. Kopp. Thoughts on development.", preview); } @Test @@ -43,7 +43,7 @@ void generatePreviewForEntryWithMathFormulaInTitle() throws URISyntaxException { .withField(StandardField.AUTHOR, "Jane Doe") .withField(StandardField.TITLE, "Characterization of $\\alpha$"); String preview = bstPreviewLayout.generatePreview(entry, bibDatabaseContext); - assertEquals("J.\u00a0Doe. Characterization of α.", preview); + assertEquals("J. Doe. Characterization of α.", preview); } @Test @@ -53,21 +53,21 @@ void monthMayIsCorrectlyRendered() throws URISyntaxException { .withField(StandardField.TITLE, "Thoughts on Development") .withField(StandardField.MONTH, "#May#"); String preview = bstPreviewLayout.generatePreview(entry, bibDatabaseContext); - assertEquals("O.\u00a0Kopp. Thoughts on development, May.", preview); + assertEquals("O. Kopp. Thoughts on development, May.", preview); } @Test void generatePreviewForSliceTheoremPaperUsingAbbr() throws URISyntaxException { BstPreviewLayout bstPreviewLayout = new BstPreviewLayout(Path.of(BstPreviewLayoutTest.class.getResource("abbrv.bst").toURI())); String preview = bstPreviewLayout.generatePreview(getSliceTheoremPaper(), bibDatabaseContext); - assertEquals("T.\u00a0Diez. Slice theorem for fréchet group actions and covariant symplectic field theory. May 2014.", preview); + assertEquals("T. Diez. Slice theorem for fréchet group actions and covariant symplectic field theory. May 2014.", preview); } @Test void generatePreviewForSliceTheoremPaperUsingIEEE() throws URISyntaxException { BstPreviewLayout bstPreviewLayout = new BstPreviewLayout(Path.of(BstPreviewLayoutTest.class.getResource("IEEEtran.bst").toURI())); String preview = bstPreviewLayout.generatePreview(getSliceTheoremPaper(), bibDatabaseContext); - assertEquals("T.\u00a0Diez, \"Slice theorem for fréchet group actions and covariant symplectic field theory\" May 2014.", preview); + assertEquals("T. Diez, \"Slice theorem for fréchet group actions and covariant symplectic field theory\" May 2014.", preview); } @Test @@ -76,7 +76,7 @@ void mathSymbolsInBracedMathAreConvertedToUnicode() throws URISyntaxException { BibEntry entry = new BibEntry().withField(StandardField.AUTHOR, "Oliver Kopp") .withField(StandardField.TITLE, "{{$\\Sigma$}}{{$\\Delta$}} Modulator"); String preview = bstPreviewLayout.generatePreview(entry, bibDatabaseContext); - assertEquals("O.\u00a0Kopp. \u03a3\u0394 modulator.", preview); + assertEquals("O. Kopp. \u03a3\u0394 modulator.", preview); } @ParameterizedTest @@ -93,29 +93,29 @@ private static Stream generatePreviewHandlesInlineFormatting() { return Stream.of( // Small-caps forms that should be preserved in the preview output - Arguments.of("\\textsc{L{\\'o}pez}", "O.\u00a0Kopp. López."), - Arguments.of("{\\sc L{\\'o}pez}", "O.\u00a0Kopp. López."), - Arguments.of("\\textsc{Outer \\textsc{inner} text}", "O.\u00a0Kopp. Outer inner text."), + Arguments.of("\\textsc{L{\\'o}pez}", "O. Kopp. López."), + Arguments.of("{\\sc L{\\'o}pez}", "O. Kopp. López."), + Arguments.of("\\textsc{Outer \\textsc{inner} text}", "O. Kopp. Outer inner text."), // Parser edge cases that should still keep the surrounding small-caps span intact - Arguments.of("\\textsc {L{\\'o}pez}", "O.\u00a0Kopp. López."), - Arguments.of("\\textsc{A\\{B\\}C}", "O.\u00a0Kopp. ABC."), - Arguments.of("{\\scshape Lopez}", "O.\u00a0Kopp. Lopez."), + Arguments.of("\\textsc {L{\\'o}pez}", "O. Kopp. López."), + Arguments.of("\\textsc{A\\{B\\}C}", "O. Kopp. ABC."), + Arguments.of("{\\scshape Lopez}", "O. Kopp. Lopez."), // Malformed input should fall back to the existing preview pipeline without failing - Arguments.of("\\textsc{L{\\'o}pez", "O.\u00a0Kopp. López."), - Arguments.of("{\\sc L{\\'o}pez", "O.\u00a0Kopp. lópez."), + Arguments.of("\\textsc{L{\\'o}pez", "O. Kopp. López."), + Arguments.of("{\\sc L{\\'o}pez", "O. Kopp. lópez."), // Emphasis becomes HTML, not Unicode mathematical italic or bold letters // abbrv lowercases titles, as BibTeX does inside {\\em ...} - Arguments.of("On {\\em Drosophila} genetics", "O.\u00a0Kopp. On drosophila genetics."), - Arguments.of("On \\emph{Drosophila} genetics", "O.\u00a0Kopp. On Drosophila genetics."), - Arguments.of("On \\textit{Drosophila} genetics", "O.\u00a0Kopp. On Drosophila genetics."), - Arguments.of("On \\textbf{Drosophila} genetics", "O.\u00a0Kopp. On Drosophila genetics."), - - // Existing superscript and subscript rendering should remain unchanged - Arguments.of("Proceedings of the 9\\textsuperscript{th} symposium", "O.\u00a0Kopp. Proceedings of the 9ᵗʰ symposium."), - Arguments.of("{H\\textsubscript{2}O}", "O.\u00a0Kopp. H₂O.") + Arguments.of("On {\\em Drosophila} genetics", "O. Kopp. On drosophila genetics."), + Arguments.of("On \\emph{Drosophila} genetics", "O. Kopp. On Drosophila genetics."), + Arguments.of("On \\textit{Drosophila} genetics", "O. Kopp. On Drosophila genetics."), + Arguments.of("On \\textbf{Drosophila} genetics", "O. Kopp. On Drosophila genetics."), + + // Superscript and subscript become HTML + Arguments.of("Proceedings of the 9\\textsuperscript{th} symposium", "O. Kopp. Proceedings of the 9th symposium."), + Arguments.of("{H\\textsubscript{2}O}", "O. Kopp. H2O.") ); } @@ -128,7 +128,7 @@ void journalEmphasizedByBstIsRenderedItalic() throws URISyntaxException { .withField(StandardField.JOURNAL, "British Journal of Nutrition") .withField(StandardField.YEAR, "2007"); String preview = bstPreviewLayout.generatePreview(entry, bibDatabaseContext); - assertEquals("K.\u00a0A. Cooper. Cocoa and health: a decade of research. British Journal of Nutrition, 2007.", preview); + assertEquals("K. A. Cooper. Cocoa and health: a decade of research. British Journal of Nutrition, 2007.", preview); } @Test @@ -137,7 +137,7 @@ void unresolvableBracedMathIsKept() throws URISyntaxException { BibEntry entry = new BibEntry().withField(StandardField.AUTHOR, "Oliver Kopp") .withField(StandardField.TITLE, "{{$\\notacommand$}} Modulator"); String preview = bstPreviewLayout.generatePreview(entry, bibDatabaseContext); - assertEquals("O.\u00a0Kopp. modulator.", preview); + assertEquals("O. Kopp. notacommand modulator.", preview); } @Test @@ -170,7 +170,7 @@ void generatePreviewResolvesXDataFields() throws URISyntaxException { String preview = bstPreviewLayout.generatePreview(book, context); - assertEquals("D.\u00a0E. Knuth. The Book. Number\u00a01 in Computers and Typesetting. Addison-Wesley, Reading, MA, 1984.", preview); + assertEquals("D. E. Knuth. The TeX Book. Number 1 in Computers and Typesetting. Addison-Wesley, Reading, MA, 1984.", preview); } @Test @@ -194,7 +194,7 @@ void generatePreviewIgnoresLibraryPreambleWhenResolvingXDataFields() throws URIS String preview = bstPreviewLayout.generatePreview(book, context); - assertEquals("D.\u00a0E. Knuth. The Book. Number\u00a01 in Computers and Typesetting. Addison-Wesley, Reading, MA, 1984.", preview); + assertEquals("D. E. Knuth. The TeX Book. Number 1 in Computers and Typesetting. Addison-Wesley, Reading, MA, 1984.", preview); } private static BibEntry getSliceTheoremPaper() { diff --git a/jablib/src/test/java/org/jabref/logic/layout/format/HTMLCharsTest.java b/jablib/src/test/java/org/jabref/logic/layout/format/HTMLCharsTest.java index 59e75d9bf0f0..4e74a52dde1e 100644 --- a/jablib/src/test/java/org/jabref/logic/layout/format/HTMLCharsTest.java +++ b/jablib/src/test/java/org/jabref/logic/layout/format/HTMLCharsTest.java @@ -72,7 +72,17 @@ private static Stream provideLaTeXHighlightingFormattingData() { Arguments.of("hallo", "\\underline{hallo}"), Arguments.of("hallo", "\\sout{hallo}"), - Arguments.of("hallo", "\\texttt{hallo}") + Arguments.of("hallo", "\\texttt{hallo}"), + + Arguments.of("hallo", "\\textsc{hallo}"), + Arguments.of("hallo", "{\\sc hallo}"), + Arguments.of("hallo", "{\\scshape hallo}"), + Arguments.of("hallo", "\\textsc {hallo}"), + + Arguments.of("López", "\\emph{L{\\'o}pez}"), + Arguments.of("The TeX Book", "{\\em The {\\TeX} Book}"), + Arguments.of("a b c", "\\textbf{a \\textit{b} c}"), + Arguments.of("hallo", "\\textsc\\hallo") ); } diff --git a/jablib/src/test/java/org/jabref/logic/util/strings/StringUtilTest.java b/jablib/src/test/java/org/jabref/logic/util/strings/StringUtilTest.java index 8f2aadedcbe5..18d02911b10e 100644 --- a/jablib/src/test/java/org/jabref/logic/util/strings/StringUtilTest.java +++ b/jablib/src/test/java/org/jabref/logic/util/strings/StringUtilTest.java @@ -188,6 +188,8 @@ void stripBrackets(String expected, String input) { '', 'A closed mouth catches no }flies}', 25, false # Get the word from the end of the sentence bite, 'Barking dogs seldom bite', 19, true + # Escaped braces do not end the group + 'A\\{B\\}C', '{A\\{B\\}C} D', 0, true """) void getPart(String expected, String input, int startIndex, boolean forward) { assertEquals(expected, StringUtil.getPart(input, startIndex, forward)); From 53c6a3afd945772abd6aec54511425292c3e7a7b Mon Sep 17 00:00:00 2001 From: subhramit Date: Tue, 24 Nov 2026 17:26:43 +0530 Subject: [PATCH 4/4] Remove blank line from BST preview converter --- .../src/main/java/org/jabref/logic/layout/format/HTMLChars.java | 1 - 1 file changed, 1 deletion(-) diff --git a/jablib/src/main/java/org/jabref/logic/layout/format/HTMLChars.java b/jablib/src/main/java/org/jabref/logic/layout/format/HTMLChars.java index 10a869f4b94c..5e2019051d76 100644 --- a/jablib/src/main/java/org/jabref/logic/layout/format/HTMLChars.java +++ b/jablib/src/main/java/org/jabref/logic/layout/format/HTMLChars.java @@ -39,7 +39,6 @@ public String format(String inField) { } private String convert(String field) { - StringBuilder sb = new StringBuilder(); StringBuilder currentCommand = null;