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

Make headline dialog work in view mode #2206

Merged
merged 15 commits into from
Mar 27, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -703,7 +703,6 @@ private boolean isWrapped() {
}

private void setHorizontalScrollMode(final boolean wrap) {

final Context context = getContext();
if (context != null && _hlEditor != null && isWrapped() != wrap) {

Expand Down Expand Up @@ -864,7 +863,7 @@ public void onAnimationEnd(Animator animation) {

@Override
protected void onToolbarClicked(View v) {
if (!_isPreviewVisible && _format != null) {
if (_format != null) {
_format.getActions().runTitleClick();
}
}
Expand Down Expand Up @@ -892,7 +891,7 @@ public Document getDocument() {
return _document;
}

public WebView getWebview() {
public WebView getWebView() {
return _webView;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,7 @@ public Map<String, ActionItem> getActiveActionMap() {
final List<ActionItem> actionList = getActionList();
final List<String> keyList = getActiveActionKeys();

final Map<String, ActionItem> map = new HashMap<String, ActionItem>();

final Map<String, ActionItem> map = new HashMap<>();
for (int i = 0; i < actionList.size(); i++) {
map.put(keyList.get(i), actionList.get(i));
}
Expand Down Expand Up @@ -251,7 +250,6 @@ private List<String> loadActionPreference(final String suffix) {
* @return List of Action Item keys in order specified by preferences
*/
public List<String> getActionOrder() {

final Set<String> order = new LinkedHashSet<>(loadActionPreference(ORDER_SUFFIX));

// Handle the case where order was stored without suffix. i.e. before this release.
Expand Down Expand Up @@ -532,7 +530,6 @@ private static void runRegexReplaceAction(final Editable editable, final List<Re
Selection.setSelection(editable, newSelStart, newSelEnd);
}


protected void runSurroundAction(final String delim) {
runSurroundAction(delim, delim, true);
}
Expand Down Expand Up @@ -737,7 +734,11 @@ protected final boolean runCommonAction(final @StringRes int action) {
return true;
}
case R.string.abid_common_web_jump_to_table_of_contents: {
_webView.loadUrl("javascript:document.getElementsByClassName('toc')[0].scrollIntoView();");
if (_appSettings.isMarkdownTableOfContentsEnabled()) {
_webView.loadUrl("javascript:document.getElementsByClassName('toc')[0].scrollIntoView();");
} else {
runTitleClick();
}
return true;
}
case R.string.abid_common_view_file_in_other_app: {
Expand Down Expand Up @@ -841,15 +842,13 @@ public ActionItem setRepeatable(boolean repeatable) {
}

public static void moveLineSelectionBy1(final HighlightingEditor hlEditor, final boolean isUp) {

final Editable text = hlEditor.getText();

final int[] sel = TextViewUtils.getSelection(hlEditor);
final int linesStart = TextViewUtils.getLineStart(text, sel[0]);
final int linesEnd = TextViewUtils.getLineEnd(text, sel[1]);

if ((isUp && linesStart > 0) || (!isUp && linesEnd < text.length())) {

final CharSequence lines = text.subSequence(linesStart, linesEnd);

final int altStart = isUp ? TextViewUtils.getLineStart(text, linesStart - 1) : linesEnd + 1;
Expand Down Expand Up @@ -893,7 +892,6 @@ private String rstr(@StringRes int resKey) {
}

public void runSpecialKeyAction() {

// Needed to prevent selection from being overwritten on refocus
final int[] sel = TextViewUtils.getSelection(_hlEditor);
_hlEditor.clearFocus();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,7 @@ public String convertMarkupShowInWebView(
final Activity context,
final WebView webView,
final boolean lightMode,
final boolean lineNum
) {
final boolean lineNum) {
String html;
try {
html = convertMarkup(content, context, lightMode, lineNum, document.getFile());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ private void insertTableRow(int cols, boolean isHeaderEnabled) {
@Override
public boolean runTitleClick() {
final Matcher m = MarkdownReplacePatternGenerator.PREFIX_ATX_HEADING.matcher("");
MarkorDialogFactory.showHeadlineDialog(getActivity(), _hlEditor, _disabledHeadings, (text, start, end) -> {
MarkorDialogFactory.showHeadlineDialog(getActivity(), _hlEditor, _webView, _disabledHeadings, (text, start, end) -> {
if (m.reset(text.subSequence(start, end)).find()) {
return m.end(2) - m.start(2) - 1;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,10 @@
import com.vladsch.flexmark.ext.yaml.front.matter.AbstractYamlFrontMatterVisitor;
import com.vladsch.flexmark.ext.yaml.front.matter.YamlFrontMatterExtension;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.html.renderer.HeaderIdGenerator;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.superscript.SuperscriptExtension;
import com.vladsch.flexmark.util.ast.Document;
import com.vladsch.flexmark.util.builder.Extension;
import com.vladsch.flexmark.util.options.MutableDataSet;

Expand Down Expand Up @@ -153,17 +155,23 @@ public class MarkdownTextConverter extends TextConverterBase {
public static final HtmlRenderer flexmarkRenderer = HtmlRenderer.builder().extensions(flexmarkExtensions).build();

//########################
//## Methods
//## Others
//########################
private static String toDashChars = " -_"; // See HtmlRenderer.HEADER_ID_GENERATOR_TO_DASH_CHARS.getFrom(document)
private static final Pattern linkPattern = Pattern.compile("\\[(.*?)\\]\\((.*?)(\\s+\".*\")?\\)");


//########################
//## Methods
//########################
@Override
public String convertMarkup(String markup, Context context, boolean lightMode, boolean enableLineNumbers, File file) {
String converted = "", onLoadJs = "", head = "";
String converted, onLoadJs = "", head = "";
final MutableDataSet options = new MutableDataSet();

options.set(Parser.EXTENSIONS, flexmarkExtensions);

options.set(Parser.SPACE_IN_LINK_URLS, true); // allow links like [this](some filename with spaces.md)
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

Expand Down Expand Up @@ -198,7 +206,7 @@ public String convertMarkup(String markup, Context context, boolean lightMode, b
head += CSS_PRESENTATION_BEAMER;
}

// Frontmatter
// Front matter
String fmaText = "";
final List<String> fmaAllowedAttributes = _appSettings.getMarkdownShownYamlFrontMatterKeys();
Map<String, List<String>> fma = Collections.EMPTY_MAP;
Expand Down Expand Up @@ -293,7 +301,8 @@ public String convertMarkup(String markup, Context context, boolean lightMode, b

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

// After render changes: Fixes for Footnotes (converter creates footnote + <br> + ref#(click) --> remove line break)
if (converted.contains("footnote-")) {
Expand Down Expand Up @@ -329,14 +338,15 @@ public String convertMarkup(String markup, Context context, boolean lightMode, b
return putContentIntoTemplate(context, converted, lightMode, file, onLoadJs, head);
}

private static final Pattern linkPattern = Pattern.compile("\\[(.*?)\\]\\((.*?)(\\s+\".*\")?\\)");
public static String generateHeaderId(String headerText) {
return HeaderIdGenerator.generateId(headerText, toDashChars, false, false);
}

private String escapeSpacesInLink(final String markup) {
final Matcher matcher = linkPattern.matcher(markup);
if (!matcher.find()) {
return markup;
}

// 1) Walk through the text till finding a link in markdown syntax
// 2) Add all text-before-link to buffer
// 3) Extract [title](link to somehere)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ public static String createWikitextHeaderAndTitleContents(String fileNameWithout
@Override
public boolean runTitleClick() {
final Matcher m = WikitextSyntaxHighlighter.HEADING.matcher("");
MarkorDialogFactory.showHeadlineDialog(getActivity(), _hlEditor, _disabledHeadings, (text, start, end) -> {
MarkorDialogFactory.showHeadlineDialog(getActivity(), _hlEditor, _webView, _disabledHeadings, (text, start, end) -> {
if (m.reset(text.subSequence(start, end)).find()) {
return 7 - (m.end(2) - m.start(2));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import android.util.Pair;
import android.view.Gravity;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
Expand All @@ -39,6 +40,7 @@
import net.gsantner.markor.ApplicationObject;
import net.gsantner.markor.R;
import net.gsantner.markor.format.FormatRegistry;
import net.gsantner.markor.format.markdown.MarkdownTextConverter;
import net.gsantner.markor.format.todotxt.TodoTxtBasicSyntaxHighlighter;
import net.gsantner.markor.format.todotxt.TodoTxtFilter;
import net.gsantner.markor.format.todotxt.TodoTxtTask;
Expand Down Expand Up @@ -792,9 +794,9 @@ private static class Heading {
public static void showHeadlineDialog(
final Activity activity,
final EditText edit,
final WebView webView,
final Set<Integer> disabled,
final GsCallback.r3<Integer, CharSequence, Integer, Integer> headingLevel
) {
final GsCallback.r3<Integer, CharSequence, Integer, Integer> headingLevel) {
// Get all headings and their levels
final CharSequence text = edit.getText();
final List<Heading> headings = new ArrayList<>();
Expand All @@ -819,12 +821,19 @@ public static void showHeadlineDialog(
dopt.titleText = R.string.table_of_contents;
dopt.searchHintText = R.string.search;
dopt.isSearchEnabled = true;
dopt.neutralButtonText = R.string.filter;
dopt.isSoftInputVisible = false;
dopt.isDismissOnItemSelected = false;
dopt.isSaveItemPositionEnabled = true;

dopt.positionCallback = result -> {
final int index = filtered.get(result.get(0));
TextViewUtils.selectLines(edit, headings.get(index).line);
String header = headings.get(index).str;
String id = MarkdownTextConverter.generateHeaderId(header.substring(header.lastIndexOf('#') + 1).trim());
webView.loadUrl("javascript:document.getElementById('" + id + "').scrollIntoView();");
};

dopt.neutralButtonText = R.string.filter;
dopt.neutralButtonCallback = (dialog) -> {
final DialogOptions dopt2 = new DialogOptions();
dopt2.preSelected = GsCollectionUtils.indices(levels, l -> !disabled.contains(l));
Expand All @@ -850,7 +859,11 @@ public static void showHeadlineDialog(
};
GsSearchOrCustomTextDialog.showMultiChoiceDialogWithSearchFilterUI(activity, dopt2);
};
dopt.gravity = Gravity.TOP;

dopt.portraitAspectRatio = new float[]{0.95f, 0.8f};
dopt.landscapeAspectRatio = new float[]{0.7f, 0.95f};
dopt.gravity = Gravity.CENTER;
guanglinn marked this conversation as resolved.
Show resolved Hide resolved

GsSearchOrCustomTextDialog.showMultiChoiceDialogWithSearchFilterUI(activity, dopt);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ private AlertDialog.Builder makeDialog(final File basedir, final boolean allowCr

if (pos == 3) { // Jekyll
prefix = TodoTxtTask.DATEF_YYYY_MM_DD.format(new Date()) + "-";
} else if (pos == 9) { //ZettelKasten
} else if (pos == 9) { // ZettelKasten
prefix = new SimpleDateFormat("yyyyMMddHHmm", Locale.ROOT).format(new Date()) + "-";
}
if (!TextUtils.isEmpty(prefix) && !fileNameEdit.getText().toString().startsWith(prefix)) {
Expand Down Expand Up @@ -325,7 +325,7 @@ private String getTemplateByPos(
" line\";2059-12-24\n";
}
case 12: {
// orgmode
// Org-mode
return "OrgMode Reference\n" + "* Headline\n" + "** Nested headline\n" + "*** Deeper\n" + "\n" + "* Basic markup\n" + "This is the general building block for org-mode navigation.\n" + "- _underscores let you underline things_\n" + "- *stars add emphasis*\n" + "- /slashes are italics/\n" + "- +pluses are strikethrough+\n" + "- =equal signs are verbatim text=\n" + "- ~tildes can also be used~\n" + "\n" + "* List\n" + "** Unordered List\n" + "- Item 1\n" + "- Item 2\n" + " - Subitem 2.1\n" + " - Subitem 2.2\n" + "** Ordered List\n" + "1. First Item\n" + "2. Second Item\n" + " 1. Subitem 2.1\n" + " 2. Subitem 2.2\n" + "- [X] Completed Task\n" + "- [ ] Uncompleted Task\n" + "** Nested List\n" + " - Item A\n" + " - Subitem A.1\n" + " - Subitem A.2\n" + " - Item B\n" + "\n" + "* Tables\n" + "\n" + "| First Name | Last Name | Years using Emacs |\n" + "|----------------------------+---------------------+-------------------|\n" + "| Lee | Hinman | 5 |\n" + "| Mike | Hunsinger | 2 |\n" + "| Daniel | Glauser | 4 |\n" + "| Really-long-first-name-guy | long-last-name-pers | 1 |\n" + "\n" + "* Org-mode links\n" + "\n" + "#+BEGIN_SRC fundamental\n" + "[[http://google.com/][Google]]\n" + "#+END_SRC\n" + "\n" + "[[./images/pic1.png]]\n" + "\n" + "\n" + "* TODO List\n" + "** TODO This is a task that needs doing\n" + "** TODO Another todo task\n" + "- [ ] sub task one\n" + "- [X] sub task two\n" + "- [ ] sub task three\n" + "** DONE I've already finished this one\n" + "*** CANCELLED learn todos\n" + " CLOSED: [2023-10-16 Mon 08:39]\n" + "\n" + "* Code\n" + "#+BEGIN_LaTeX\n" + "$a + b$\n" + "#+END_LaTeX\n" + "\n" + "#+BEGIN_SRC emacs-lisp\n" + "(defun my/function ()\n" + " \"docstring\"\n" + " (interactive)\n" + " (progn\n" + " (+ 1 1)\n" + " (message \"Hi\")))\n" + "#+END_SRC\n" + "\n";
}
}
Expand Down
Loading
Loading