Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Line numbers improvements #2090

Merged
merged 45 commits into from
Sep 11, 2023
Merged
Show file tree
Hide file tree
Changes from 40 commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
ab04552
add line numbers support
Jun 5, 2023
33b3d78
fix bug in calculating width of max line number
Jun 6, 2023
af10f41
remove 3 strings of non english translations, update licenses_3rd_par…
Jun 6, 2023
a4c7161
Bugfix: Mermaid code cannot be rendered when line numbers enabled
Jun 18, 2023
488f476
Optimized code
Jun 23, 2023
3dd82a4
Bugfix: Line numbers cannot behave well with bigger headings enabled
Jun 23, 2023
e5069a5
perf(line numbers): drawing line numbers only near the visible area
Jun 27, 2023
a0579cc
fix(line numbers): ClassCastException when disable line wrapping
Jun 27, 2023
289cfb8
rework line number settings
gsantner Jul 9, 2023
e118cd0
automatic code reformat, add license notice for flexmark extension
gsantner Jul 9, 2023
d480f9a
supress lint due checked with getLineCount
gsantner Jul 9, 2023
40077ac
todo.txt improvement
gsantner Jul 9, 2023
a7fdd30
feat(line numbers): align line numbers text to the right; minor perfo…
Jul 15, 2023
bc83846
refactor(line numbers): minor improvements
Jul 17, 2023
dbe456b
perf(line numbers): performance improvements
Jul 17, 2023
57d5935
refactor(line numbers): minor improvements
Jul 19, 2023
4cbee78
refactor(line numbers): minor improvements
Jul 20, 2023
8d62124
Token for inserting selection
harshad1 Aug 4, 2023
7ecb268
Ignoring token in new file dialog
harshad1 Aug 4, 2023
35692bf
Tweaks
harshad1 Aug 4, 2023
c899628
refactor(line numbers): minor improvements
Aug 6, 2023
4900610
Merge remote-tracking branch 'coworker/line_numbers_support' into loc…
harshad1 Aug 6, 2023
b75fdfb
perf(line numbers): added support for iterating from the first visibl…
Aug 8, 2023
7901b7f
Merge remote-tracking branch 'guang-lin/line_numbers_support' into lo…
harshad1 Aug 11, 2023
dc1c9f1
Reworked line numbers for some simplicity
harshad1 Aug 11, 2023
892cdf4
Fixes, per file
harshad1 Aug 11, 2023
7ae90c2
Converter with line num support
harshad1 Aug 12, 2023
7faa0db
GetChars made faster
harshad1 Aug 12, 2023
c7b0cd7
Many small tweaks
harshad1 Aug 13, 2023
8f18b61
Unrelated fix for matching directories too
harshad1 Aug 13, 2023
d38bef6
Rework single pass line numbering
harshad1 Aug 14, 2023
a52a559
fix conflicts
Aug 15, 2023
a778a5e
perf(line numbers): avoided unnecessary loops and moved the codes to …
Aug 15, 2023
6fd55c7
removed System.err.println(i);
Aug 15, 2023
f3f3fab
fix(line numbers): incorrect adjustment of the gutter width
Aug 15, 2023
5930692
fix(line numbers): corrected calculation of max line number
Aug 16, 2023
31f0d37
perf(line numbers): added line track and reduced frequency of updatin…
Aug 16, 2023
0691123
fix(line numbers): display problems in todo.txt and bigger headings
Aug 16, 2023
51ad175
refactor(line numbers): minor improvements
Aug 16, 2023
a6712c1
perf(line numbers): changed the way to call the method to stop drawing
Aug 17, 2023
26f33c1
perf(line numbers): some improvements based on the suggestions
Aug 24, 2023
a7cf4fb
fix(line numbers): argument 'text' might be null
Aug 24, 2023
34d46ac
docs(line numbers): correct the comments
Aug 25, 2023
1205e0d
refactor(line numbers): add margin to recalculate the start line
Aug 29, 2023
9a13a64
fix(line numbers): solve lag update to border of the gutter
Aug 29, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
_hlEditor.setTextColor(_appSettings.getEditorForegroundColor());
_hlEditor.setGravity(_appSettings.isEditorStartEditingInCenter() ? Gravity.CENTER : Gravity.NO_GRAVITY);
_hlEditor.setHighlightingEnabled(_appSettings.getDocumentHighlightState(_document.getPath(), _hlEditor.getText()));
_hlEditor.setLineNumbersEnabled(_appSettings.isLineNumbersEnabled());
_hlEditor.setLineNumbersEnabled(_appSettings.getDocumentLineNumbersEnabled(_document.getPath()));
_hlEditor.setAutoFormatEnabled(_appSettings.getDocumentAutoFormatEnabled(_document.getPath()));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Do not need to send contents to accessibility
Expand Down Expand Up @@ -459,7 +459,7 @@ public boolean onOptionsItemSelected(@NonNull final MenuItem item) {
if (saveDocument(false)) {
TextConverterBase converter = FormatRegistry.getFormat(_document.getFormat(), activity, _document).getConverter();
_cu.shareText(getActivity(),
converter.convertMarkup(getTextString(), getActivity(), false, _document.getFile()),
converter.convertMarkup(getTextString(), getActivity(), false, _hlEditor.getLineNumbersEnabled(), _document.getFile()),
"text/" + (item.getItemId() == R.id.action_share_html ? "html" : "plain")
);
}
Expand Down Expand Up @@ -563,9 +563,9 @@ public void onFsViewerConfig(GsFileBrowserOptions.Options dopt) {
return true;
}
case R.id.action_line_numbers: {
_appSettings.setLineNumbersEnabled(!_appSettings.isLineNumbersEnabled());
_hlEditor.setLineNumbersEnabled(_appSettings.isLineNumbersEnabled());
_hlEditor.invalidate();
final boolean newState = !_hlEditor.getLineNumbersEnabled();
_appSettings.setDocumentLineNumbersEnabled(_document.getPath(), newState);
_hlEditor.setLineNumbersEnabled(newState);
updateMenuToggleStates(0);
return true;
}
Expand Down Expand Up @@ -758,7 +758,7 @@ private boolean isDisplayedAtMainActivity() {

public void updateViewModeText() {
final String text = getTextString();
_format.getConverter().convertMarkupShowInWebView(_document, text, getActivity(), _webView, _nextConvertToPrintMode);
_format.getConverter().convertMarkupShowInWebView(_document, text, getActivity(), _webView, _nextConvertToPrintMode, _hlEditor.getLineNumbersEnabled());
}

public void setViewModeVisibility(boolean show) {
Expand Down
31 changes: 13 additions & 18 deletions app/src/main/java/net/gsantner/markor/format/TextConverterBase.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import net.gsantner.markor.model.Document;
import net.gsantner.opoc.format.GsTextUtils;
import net.gsantner.opoc.util.GsContextUtils;
import net.gsantner.opoc.util.GsFileUtils;

import java.io.File;
import java.util.Date;
Expand Down Expand Up @@ -97,19 +98,18 @@ public TextConverterBase() {
* @param webView The WebView content to be shown in
* @return Copy of converted html
*/
public String convertMarkupShowInWebView(Document document, String content, Activity context, WebView webView, boolean isExportInLightMode) {
public String convertMarkupShowInWebView(Document document, String content, Activity context, WebView webView, boolean lightMode, boolean lineNum) {
String html;
try {
html = convertMarkup(content, context, isExportInLightMode, document.getFile());
html = convertMarkup(content, context, lightMode, lineNum, document.getFile());
} catch (Exception e) {
html = "Please report at project issue tracker: " + e.toString();
html = "Please report at project issue tracker: " + e;
}

String baseFolder = ApplicationObject.settings().getNotebookDirectory().getAbsolutePath();
if (document.getFile().getParentFile() != null) {
baseFolder = document.getFile().getParent();
String baseFolder = document.getFile().getParent();
if (baseFolder == null) {
baseFolder = "file://" + baseFolder + "/";
}
baseFolder = "file://" + baseFolder + "/";
webView.loadDataWithBaseURL(baseFolder, html, getContentType(), UTF_CHARSET, null);

// When TOKEN_TEXT_CONVERTER_MAX_ZOOM_OUT_BY_DEFAULT is contained in text zoom out as far possible
Expand All @@ -121,21 +121,16 @@ public String convertMarkupShowInWebView(Document document, String content, Acti
return html;
}

protected String getFileExtension(File file) {
if (file == null) {
return "";
}
return (file.getName().contains(".") ? file.getName().substring(file.getName().lastIndexOf(".")) : "").toLowerCase();
}

/**
* Convert markup text to target format
*
* @param markup Markup text
* @param context Android Context
* @param markup Markup text
* @param context Android Context
* @param lightMode
* @param lineNum
* @return html as String
*/
public abstract String convertMarkup(String markup, Context context, boolean isExportInLightMode, File file);
public abstract String convertMarkup(String markup, Context context, boolean lightMode, boolean lineNum, File file);

protected String putContentIntoTemplate(Context context, String content, boolean isExportInLightMode, File file, String onLoadJs, String head) {
final String contentLower = content.toLowerCase();
Expand Down Expand Up @@ -185,7 +180,7 @@ protected String putContentIntoTemplate(Context context, String content, boolean
.replace(TOKEN_ACCENT_COLOR, GsTextUtils.colorToHexString(ContextCompat.getColor(context, R.color.accent)))
.replace(TOKEN_TEXT_DIRECTION, _appSettings.isRenderRtl() ? "right" : "left")
.replace(TOKEN_FONT, font)
.replace(TOKEN_TEXT_CONVERTER_CSS_CLASS, "format-" + getClass().getSimpleName().toLowerCase().replace("textconverter", "").replace("converter", "") + " fileext-" + getFileExtension(file).replace(".", ""))
.replace(TOKEN_TEXT_CONVERTER_CSS_CLASS, "format-" + getClass().getSimpleName().toLowerCase().replace("textconverter", "").replace("converter", "") + " fileext-" + GsFileUtils.getFilenameExtension(file).replace(".", ""))
.replace(TOKEN_POST_TODAY_DATE, DateFormat.getDateFormat(context).format(new Date()))
.replace(TOKEN_FILEURI_VIEWED_FILE, (file != null ? Uri.fromFile(file.getAbsoluteFile()).toString() : "file:///dummy").replace("'", "\\'").replace("\"", "\\\""));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public class AsciidocTextConverter extends TextConverterBase {
public static final String HTML_ASCIIDOCJS_DARK_CSS_INCLUDE = "file:///android_asset/asciidoc/dark.css";

@Override
public String convertMarkup(String markup, Context context, boolean isExportInLightMode, File file) {
public String convertMarkup(String markup, Context context, boolean lightMode, boolean lineNum, File file) {
String converted = "<div id=\"asciidoc_content\"></div>\n";
String onLoadJs = "var textBase64 = `" +
//convert a text to base64 to simplify supporting special characters
Expand All @@ -52,10 +52,10 @@ public String convertMarkup(String markup, Context context, boolean isExportInLi
//standalone : true - to generate header 1 (= title) in the page. if don't do that - title will be absent.
//nofooter: true - to don't generate footer (Last updated ...). if don't do that and use standalone : true - the page will have that footer.
"var html = asciidoctor.convert(utf8PlainText, {standalone : true, attributes : {nofooter: true, stylesheet: \"" +
(isExportInLightMode ? HTML_ASCIIDOCJS_DEFAULT_CSS_INCLUDE : HTML_ASCIIDOCJS_DARK_CSS_INCLUDE)
(lightMode ? HTML_ASCIIDOCJS_DEFAULT_CSS_INCLUDE : HTML_ASCIIDOCJS_DARK_CSS_INCLUDE)
+ "\"}});\n" +
"document.getElementById(\"asciidoc_content\").innerHTML = html;";
return putContentIntoTemplate(context, converted, isExportInLightMode, file, onLoadJs, HTML_ASCIIDOCJS_JS_INCLUDE);
return putContentIntoTemplate(context, converted, lightMode, file, onLoadJs, HTML_ASCIIDOCJS_JS_INCLUDE);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public class EmbedBinaryTextConverter extends TextConverterBase {

@SuppressWarnings({"ConstantConditions", "StringConcatenationInLoop"})
@Override
public String convertMarkup(String markup, Context context, boolean isExportInLightMode, File file) {
public String convertMarkup(String markup, Context context, boolean lightMode, boolean lineNum, File file) {
String converted = "", onLoadJs = "", head = "";
if (file == null) {
return "";
Expand Down Expand Up @@ -152,7 +152,7 @@ public String convertMarkup(String markup, Context context, boolean isExportInLi
}

converted += HTML101_BODY_END;
return putContentIntoTemplate(context, converted, isExportInLightMode, file, onLoadJs, head);
return putContentIntoTemplate(context, converted, lightMode, file, onLoadJs, head);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import com.opencsv.CSVReaderBuilder;
import com.opencsv.ICSVParser;

import net.gsantner.markor.format.TextConverterBase;
import net.gsantner.markor.format.markdown.MarkdownTextConverter;

import java.io.BufferedReader;
Expand All @@ -33,17 +34,17 @@
* Part of Markor-Architecture implementing Preview/Export for csv.
* <p>
* Converts csv to md and let
* {@link MarkdownTextConverter#convertMarkup(String, Context, boolean, File)}
* {@link TextConverterBase#convertMarkup(String, Context, boolean, boolean, File)}
* do the rest.
* <p>
* This way csv columns may contain md expressions like bold text.
*/
@SuppressWarnings("WeakerAccess")
public class CsvTextConverter extends MarkdownTextConverter {
@Override
public String convertMarkup(String csvMarkup, Context context, boolean isExportInLightMode, File file) {
public String convertMarkup(String csvMarkup, Context context, boolean lightMode, boolean lineNum, File file) {
String mdMarkup = Csv2MdTable.toMdTable(csvMarkup);
return super.convertMarkup(mdMarkup, context, isExportInLightMode, file);
return super.convertMarkup(mdMarkup, context, lightMode, lineNum, file);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,19 +157,20 @@ public class MarkdownTextConverter extends TextConverterBase {
//########################

@Override
public String convertMarkup(String markup, Context context, boolean isExportInLightMode, File file) {
public String convertMarkup(String markup, Context context, boolean lightMode, boolean lineNum, File file) {
String converted = "", onLoadJs = "", head = "";

MutableDataSet options = new MutableDataSet();
final MutableDataSet options = new MutableDataSet();

if (_appSettings.isLineNumbersEnabled()) {
if (lineNum) {
// Add code blocks Line numbers extension
ArrayList<Extension> extensions = new ArrayList<>(flexmarkExtensions);
final ArrayList<Extension> extensions = new ArrayList<>(flexmarkExtensions);
extensions.add(LineNumbersExtension.create());
options.set(Parser.EXTENSIONS, extensions);
} else {
options.set(Parser.EXTENSIONS, flexmarkExtensions);
}

options.set(Parser.SPACE_IN_LINK_URLS, true); // allow links like [this](some filename with spaces.md)
//options.set(HtmlRenderer.SOFT_BREAK, "<br />\n"); // Add linefeed to html break
options.set(EmojiExtension.USE_IMAGE_TYPE, EmojiImageType.UNICODE_ONLY); // Use unicode (OS/browser images)
Expand Down Expand Up @@ -273,8 +274,7 @@ public String convertMarkup(String markup, Context context, boolean isExportInLi
}

// Enable View (block) code syntax highlighting
final String xt = getViewHlPrismIncludes((GsContextUtils.instance.isDarkModeEnabled(context) ? "-tomorrow" : ""));
head += xt;
head += getViewHlPrismIncludes(GsContextUtils.instance.isDarkModeEnabled(context) ? "-tomorrow" : "", lineNum);

// Jekyll: Replace {{ site.baseurl }} with ..--> usually used in Jekyll blog _posts folder which is one folder below repository root, for reference to e.g. pictures in assets folder
markup = markup.replace("{{ site.baseurl }}", "..").replace(TOKEN_SITE_DATE_JEKYLL, TOKEN_POST_TODAY_DATE);
Expand All @@ -296,11 +296,9 @@ public String convertMarkup(String markup, Context context, boolean isExportInLi
fmaText = HTML_FRONTMATTER_CONTAINER_S + fmaText + HTML_FRONTMATTER_CONTAINER_E + "\n";
}


////////////
// Markup parsing - afterwards = HTML
converted = flexmarkRenderer.withOptions(options).render(flexmarkParser.parse(markup));
converted = fmaText + converted;
converted = fmaText + flexmarkRenderer.withOptions(options).render(flexmarkParser.parse(markup));

// After render changes: Fixes for Footnotes (converter creates footnote + <br> + ref#(click) --> remove line break)
if (converted.contains("footnote-")) {
Expand All @@ -324,7 +322,7 @@ public String convertMarkup(String markup, Context context, boolean isExportInLi
}

// Deliver result
return putContentIntoTemplate(context, converted, isExportInLightMode, file, onLoadJs, head);
return putContentIntoTemplate(context, converted, lightMode, file, onLoadJs, head);
}

private static final Pattern linkPattern = Pattern.compile("\\[(.*?)\\]\\((.*?)(\\s+\".*\")?\\)");
Expand Down Expand Up @@ -360,13 +358,13 @@ private String escapeSpacesInLink(final String markup) {
}

@SuppressWarnings({"StringConcatenationInsideStringBufferAppend"})
private String getViewHlPrismIncludes(final String themeName) {
private String getViewHlPrismIncludes(final String themeName, final boolean lineNum) {
final StringBuilder sb = new StringBuilder(1000);
sb.append(CSS_PREFIX + "prism/themes/prism" + themeName + ".min.css" + CSS_POSTFIX);
sb.append(JS_PREFIX + "prism/prism.js" + JS_POSTFIX);
sb.append(JS_PREFIX + "prism/plugins/autoloader/prism-autoloader.min.js" + JS_POSTFIX);

if (_appSettings.isLineNumbersEnabled()) {
if (lineNum) {
sb.append(CSS_PREFIX + "prism/plugins/line-numbers/prism-line-numbers.css" + CSS_POSTFIX);
sb.append(JS_PREFIX + "prism/plugins/line-numbers/prism-line-numbers.min.js" + JS_POSTFIX);
}
Expand Down Expand Up @@ -424,4 +422,4 @@ private String replaceTokens(final String markup, final Map<String, List<String>

return markupReplaced;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public class PlaintextTextConverter extends TextConverterBase {
//########################

@Override
public String convertMarkup(String markup, Context context, boolean isExportInLightMode, File file) {
public String convertMarkup(String markup, Context context, boolean lightMode, boolean lineNum, File file) {
String converted = "", onLoadJs = "", head = "";
final String extWithDot = GsFileUtils.getFilenameExtension(file);
String tmp;
Expand All @@ -65,20 +65,20 @@ public String convertMarkup(String markup, Context context, boolean isExportInLi
converted += markup;
} else if (extWithDot.matches(EmbedBinaryTextConverter.EXT_MATCHES_M3U_PLAYLIST)) {
// Playlist: Load in Embed-Binary view-mode
return FormatRegistry.CONVERTER_EMBEDBINARY.convertMarkup(markup, context, isExportInLightMode, file);
return FormatRegistry.CONVERTER_EMBEDBINARY.convertMarkup(markup, context, lightMode, lineNum, file);
} else if (EXT_CODE_HL.contains(extWithDot) || (this instanceof KeyValueTextConverter)) {
// Source code: Load in Markdown view-mode & utilize code block highlighting
final String hlLang = extWithDot.replace(".sh", ".bash").replace(".", "");
markup = String.format(Locale.ROOT, "```%s\n%s\n```", hlLang, markup);
return FormatRegistry.CONVERTER_MARKDOWN.convertMarkup(markup, context, isExportInLightMode, file);
return FormatRegistry.CONVERTER_MARKDOWN.convertMarkup(markup, context, lightMode, lineNum, file);
} else {
///////////////////////////////////////////
// Whatever else show in plaintext <pre> block
converted = HTML100_BODY_PRE_BEGIN
+ TextUtilsCompat.htmlEncode(markup)
+ HTML101_BODY_PRE_END;
}
return putContentIntoTemplate(context, converted, isExportInLightMode, file, onLoadJs, head);
return putContentIntoTemplate(context, converted, lightMode, file, onLoadJs, head);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,12 @@ public class TodoTxtTextConverter extends TextConverterBase {
//########################

@Override
public String convertMarkup(String markup, Context context, boolean isExportInLightMode, File file) {
public String convertMarkup(String markup, Context context, boolean lightMode, boolean lineNum, File file) {
String converted = "", onLoadJs = "", head = "";
converted = HTML100_BODY_PRE_BEGIN
+ parse(TextUtilsCompat.htmlEncode(markup))
+ HTML101_BODY_PRE_END;
return putContentIntoTemplate(context, converted, isExportInLightMode, file, onLoadJs, head);
return putContentIntoTemplate(context, converted, lightMode, file, onLoadJs, head);
}

private String parse(String str) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,25 +35,26 @@ public class WikitextTextConverter extends TextConverterBase {
/**
* First, convert Wikitext to regular Markor markdown. Then, calls the regular converter.
*
* @param markup Markup text
* @param context Android Context
* @param isExportInLightMode True if the light theme is to apply.
* @param file The file to convert.
* @param markup Markup text
* @param context Android Context
* @param lightMode True if the light theme is to apply.
* @param lineNum
* @param file The file to convert.
* @return HTML text
*/
@Override
public String convertMarkup(String markup, Context context, boolean isExportInLightMode, File file) {
public String convertMarkup(String markup, Context context, boolean lightMode, boolean lineNum, File file) {
String contentWithoutHeader = markup.replaceFirst(WikitextSyntaxHighlighter.ZIMHEADER.toString(), "");
StringBuilder markdownContent = new StringBuilder();

for (String line : contentWithoutHeader.split("\\r\\n|\\r|\\n")) {
String markdownEquivalentLine = getMarkdownEquivalentLine(context, file, line, isExportInLightMode);
String markdownEquivalentLine = getMarkdownEquivalentLine(context, file, line, lightMode);
markdownContent.append(markdownEquivalentLine);
markdownContent.append(" "); // line breaks must be made explicit in markdown by two spaces
markdownContent.append(String.format("%n"));
}

return FormatRegistry.CONVERTER_MARKDOWN.convertMarkup(markdownContent.toString(), context, isExportInLightMode, file);
return FormatRegistry.CONVERTER_MARKDOWN.convertMarkup(markdownContent.toString(), context, lightMode, lineNum, file);
}

private String getMarkdownEquivalentLine(final Context context, final File file, String wikitextLine, final boolean isExportInLightMode) {
Expand Down
Loading
Loading