Fall back to plain text if syntax highlighting fails. (#854)

[HotFix] Fall back to plain text if syntax highlighting fails.

upstream issue: https://github.com/noties/Prism4j/issues/8

Reviewed-on: https://codeberg.org/gitnex/GitNex/pulls/854
Reviewed-by: 6543 <6543@noreply.codeberg.org>
Co-Authored-By: opyale <opyale@noreply.codeberg.org>
Co-Committed-By: opyale <opyale@noreply.codeberg.org>
This commit is contained in:
opyale 2021-03-30 00:31:26 +02:00 committed by 6543
parent a848cabcda
commit 3e5fca4f52
1 changed files with 19 additions and 11 deletions

View File

@ -93,22 +93,30 @@ public class SyntaxHighlightedArea extends LinearLayout {
}
public void setContent(@NonNull String source, @NonNull String extension) {
if(source.length() > 0) {
if(source.length() > 0) {
linesView.setLineCount(AppUtil.getLineCount(source));
MainGrammarLocator mainGrammarLocator = MainGrammarLocator.getInstance();
Prism4jSyntaxHighlight prism4jSyntaxHighlight = Prism4jSyntaxHighlight.create(new Prism4j(mainGrammarLocator), prism4jTheme, MainGrammarLocator.DEFAULT_FALLBACK_LANGUAGE);
try {
CharSequence highlightedSource = prism4jSyntaxHighlight.highlight(mainGrammarLocator.fromExtension(extension), source);
MainGrammarLocator mainGrammarLocator = MainGrammarLocator.getInstance();
Prism4j prism4j = new Prism4j(mainGrammarLocator);
if(highlightedSource.charAt(highlightedSource.length() - 1) == '\n') {
// Removes a line break which is probably added by Prism4j but not actually present in the source.
// This line should be altered in case this gets fixed.
sourceView.setText(highlightedSource.subSequence(0, highlightedSource.length() - 1));
}
else {
sourceView.setText(highlightedSource);
CharSequence highlightedSource = Prism4jSyntaxHighlight.create(prism4j, prism4jTheme, MainGrammarLocator.DEFAULT_FALLBACK_LANGUAGE)
.highlight(mainGrammarLocator.fromExtension(extension), source);
if(highlightedSource.charAt(highlightedSource.length() - 1) == '\n') {
// Removes a line break which is probably added by Prism4j but not actually present in the source.
// This line should be altered in case this gets fixed.
sourceView.setText(highlightedSource.subSequence(0, highlightedSource.length() - 1));
}
else {
sourceView.setText(highlightedSource);
}
} catch(Throwable ignored) {
// Fall back to plaintext if something fails
sourceView.setText(source);
}
}
}