Skip to content

Commit

Permalink
Converter with line num support
Browse files Browse the repository at this point in the history
  • Loading branch information
harshad1 committed Aug 12, 2023
1 parent 892cdf4 commit 7ae90c2
Show file tree
Hide file tree
Showing 9 changed files with 46 additions and 46 deletions.
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,8 +563,9 @@ public void onFsViewerConfig(GsFileBrowserOptions.Options dopt) {
return true;
}
case R.id.action_line_numbers: {
_appSettings.setLineNumbersEnabled(!_appSettings.isLineNumbersEnabled());
_hlEditor.setLineNumbersEnabled(_appSettings.isLineNumbersEnabled());
final boolean newState = !_hlEditor.getLineNumbersEnabled();
_appSettings.setDocumentLineNumbersEnabled(_document.getPath(), newState);
_hlEditor.setLineNumbersEnabled(newState);
_hlEditor.invalidate();
updateMenuToggleStates(0);
return true;
Expand Down Expand Up @@ -758,7 +759,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
24 changes: 10 additions & 14 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,12 +98,12 @@ 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();
Expand All @@ -121,21 +122,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 +181,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();

if (_appSettings.isLineNumbersEnabled()) {
if (lineNum) {
// Add code blocks Line numbers extension
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,7 +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" : ""));
final String xt = getViewHlPrismIncludes(GsContextUtils.instance.isDarkModeEnabled(context) ? "-tomorrow" : "", lineNum);
head += xt;

// 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
Expand Down Expand Up @@ -324,7 +325,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 +361,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
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

0 comments on commit 7ae90c2

Please sign in to comment.