Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ 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. [#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)
Expand Down
37 changes: 33 additions & 4 deletions jablib/src/main/java/org/jabref/logic/layout/format/HTMLChars.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<String> SWITCHES = Set.of("em", "it", "bf", "sc", "scshape");

private boolean keepCurlyBraces = false;

@Override
Expand All @@ -31,7 +35,10 @@ public void setArgument(String arg) {

@Override
public String format(String inField) {
String field = normalizedField(inField);
return convert(normalizedField(inField)).replace("~", "&nbsp;"); // Replace any remaining ~ with &nbsp; (non-breaking spaces)
}

private String convert(String field) {

StringBuilder sb = new StringBuilder();
StringBuilder currentCommand = null;
Expand All @@ -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;
Expand Down Expand Up @@ -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("</").append(tag).append('>');
sb.append('<').append(tag).append('>').append(convert(part)).append("</").append(tag.split(" ")[0]).append('>');
} else if (c == '{') {
String argument = StringUtil.getPart(field, i, true);
i += this.keepCurlyBraces ? argument.length() + 1 : argument.length();
Expand Down Expand Up @@ -172,7 +187,7 @@ public String format(String inField) {
}
}

return sb.toString().replace("~", "&nbsp;"); // Replace any remaining ~ with &nbsp; (non-breaking spaces)
return sb.toString();
}

private String normalizedField(String inField) {
Expand All @@ -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) {
Expand All @@ -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";
Expand Down
145 changes: 6 additions & 139 deletions jablib/src/main/java/org/jabref/logic/preview/BstPreviewLayout.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -40,15 +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(" +");

// 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+([^}]*?)}");

/// 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) `$` `}}`.
Expand Down Expand Up @@ -152,145 +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 = convertInlineSmallCapsToHtml(result);
// HTMLChars would turn line breaks into <br>
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("''", "\"");
// 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("<i>$1</i>");
result = TEXTIT_PATTERN.matcher(result).replaceAll("<i>$1</i>");
result = GROUP_EM_PATTERN.matcher(result).replaceAll("<i>$1</i>");
result = GROUP_IT_PATTERN.matcher(result).replaceAll("<i>$1</i>");
result = TEXTBF_PATTERN.matcher(result).replaceAll("<b>$1</b>");
result = GROUP_BF_PATTERN.matcher(result).replaceAll("<b>$1</b>");
// 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;
}

private static String convertInlineSmallCapsToHtml(String latex) {
String html = replaceCommandWithBalancedArgument(latex, "textsc");
return replaceLegacySwitchWithBalancedArgument(html, "sc");
}

private static String replaceCommandWithBalancedArgument(String input, String command) {
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("<span style=\"font-variant: small-caps\">")
.append(input, contentStart, groupEnd)
.append("</span>");
index = groupEnd + 1;
}
return output.toString();
}

private static String replaceLegacySwitchWithBalancedArgument(String input, String command) {
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("<span style=\"font-variant: small-caps\">")
.append(input, contentStart, groupEnd)
.append("</span>");
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.
///
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 == '{') {
Expand Down
Loading
Loading