com.vladsch.flexmark.ast.Node Java Examples

The following examples show how to use com.vladsch.flexmark.ast.Node. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TwitterNodePostProcessor.java    From MarkdownView with Apache License 2.0 6 votes vote down vote up
@Override
public void process(NodeTracker state, Node node) {
    if (node instanceof Link) {
        Node previous = node.getPrevious();

        if (previous instanceof Text) {
            final BasedSequence chars = previous.getChars();

            //Se o nó anterior termina com '#' e é seguido pelo Link
            if (chars.endsWith("#") && chars.isContinuedBy(node.getChars())) {
                //Remove o caractere '#' do nó anterior.
                previous.setChars(chars.subSequence(0, chars.length() - 1));
                Twitter videoLink = new Twitter((Link) node);
                videoLink.takeChildren(node);
                node.unlink();
                previous.insertAfter(videoLink);
                state.nodeRemoved(node);
                state.nodeAddedWithChildren(videoLink);
            }
        }
    }
}
 
Example #2
Source File: DocumentParser.java    From camunda-bpm-swagger with Apache License 2.0 6 votes vote down vote up
@SneakyThrows
public HashMap<String, Node> parse(final String fileContents) {
  final Node document = parser.parse(fileContents);
  final ReversiblePeekingIterable<Node> children = document.getChildren();
  final Stack<String> headingStack = new Stack<>();
  final HashMap<String, Node> documentTree = new HashMap<>();
  Paragraph subDocument = new Paragraph();
  documentTree.put("#", subDocument);
  for (final Node next : children) {
    final Optional<Paragraph> newSubDocument = resolveHeading(next)
      .map((Heading heading) -> {
        pushHeading(headingStack, heading);
        final String headingTitle = getHeadingTitle(headingStack);
        final Paragraph subDoc = new Paragraph();
        documentTree.put(headingTitle, subDoc);
        return subDoc;
      });
    if (newSubDocument.isPresent()) {
      subDocument = newSubDocument.get();
    }
    else {
      subDocument.appendChild(next);
    }
  }
  return documentTree;
}
 
Example #3
Source File: MarkdownEditorPane.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void textChanged(String newText) {
	if (borderPane.getBottom() != null) {
		findReplacePane.removeListener(findHitsChangeListener);
		findReplacePane.textChanged();
		findReplacePane.addListener(findHitsChangeListener);
	}

	if (isReadOnly())
		newText = "";

	Node astRoot = parseMarkdown(newText);

	if (Options.isShowImagesEmbedded())
		EmbeddedImage.replaceImageSegments(textArea, astRoot, getParentPath());

	applyHighlighting(astRoot);

	markdownText.set(newText);
	markdownAST.set(astRoot);
}
 
Example #4
Source File: VideoLinkNodePostProcessor.java    From MarkdownView with Apache License 2.0 6 votes vote down vote up
@Override
public void process(NodeTracker state, Node node) {
    if (node instanceof Link) {
        Node previous = node.getPrevious();

        if (previous instanceof Text) {
            final BasedSequence chars = previous.getChars();

            //Se o nó anterior termina com '@' e é seguido pelo Link
            if (chars.endsWith("@") && chars.isContinuedBy(node.getChars())) {
                //Remove o caractere '@' do nó anterior.
                previous.setChars(chars.subSequence(0, chars.length() - 1));
                VideoLink videoLink = new VideoLink((Link) node);
                videoLink.takeChildren(node);
                node.unlink();
                previous.insertAfter(videoLink);
                state.nodeRemoved(node);
                state.nodeAddedWithChildren(videoLink);
            }
        }
    }
}
 
Example #5
Source File: SmartFormat.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Collects the text of a single paragraph.
 *
 * Replaces:
 *   - tabs with spaces
 *   - newlines with spaces (may occur in Code nodes)
 *   - soft line breaks with spaces
 *   - hard line breaks with special marker characters
 *   - spaces and tabs in special nodes, that should not formatted, with marker characters
 */
private void collectFormattableText(StringBuilder buf, Node node) {
	for (Node n = node.getFirstChild(); n != null; n = n.getNext()) {
		if (n instanceof Text) {
			buf.append(n.getChars().toString().replace('\t', ' ').replace('\n', ' '));
		} else if (n instanceof DelimitedNode) {
			// italic, bold and code
			buf.append(((DelimitedNode) n).getOpeningMarker());
			collectFormattableText(buf, n);
			buf.append(((DelimitedNode) n).getClosingMarker());
		} else if (n instanceof SoftLineBreak) {
			buf.append(' ');
		} else if (n instanceof HardLineBreak) {
			buf.append(' ').append(n.getChars().startsWith("\\")
				? HARD_LINE_BREAK_BACKSLASH : HARD_LINE_BREAK_SPACES).append(' ');
		} else {
			// other text that should be not wrapped or formatted
			buf.append(protectWhitespace(n.getChars().toString()));
		}
	}
}
 
Example #6
Source File: FlexmarkPreviewRenderer.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public List<Range> findSequences(int startOffset, int endOffset) {
	ArrayList<Range> sequences = new ArrayList<>();

	Node astRoot = toAstRoot();
	if (astRoot == null)
		return sequences;

	NodeVisitor visitor = new NodeVisitor(Collections.emptyList()) {
		@Override
		public void visit(Node node) {
			BasedSequence chars = node.getChars();
			if (isInSequence(startOffset, endOffset, chars))
				sequences.add(new Range(chars.getStartOffset(), chars.getEndOffset()));

			for (BasedSequence segment : node.getSegments()) {
				if (isInSequence(startOffset, endOffset, segment))
					sequences.add(new Range(segment.getStartOffset(), segment.getEndOffset()));
			}

			visitChildren(node);
		}
	};
	visitor.visit(astRoot);
	return sequences;
}
 
Example #7
Source File: FlexmarkPreviewRenderer.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void update(String markdownText, Node astRoot, Path path) {
	assert markdownText != null;
	assert astRoot != null;

	if (this.astRoot == astRoot)
		return;

	this.markdownText = markdownText;
	this.astRoot = astRoot;
	this.path = path;

	astRoot2 = null;
	htmlPreview = null;
	htmlSource = null;
	ast = null;
}
 
Example #8
Source File: SmartEdit.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private List<Node> findIndentableNodesAtSelection() {
	if (!indentNodes)
		return Collections.emptyList();

	return findNodesAtSelectedLines((start, end, node) -> {
		if (!(node instanceof ListItem))
			return false;

		// match only if one non-ListBlock child is in range
		for (Node child : node.getChildren()) {
			if (isInNode(start, end, child) && !(child instanceof ListBlock))
				return true;
		}
		return false;
	}, false, false);
}
 
Example #9
Source File: DocumentationGenerator.java    From TestingApp with Apache License 2.0 6 votes vote down vote up
public String getInstructionsAsHTML() {
    MutableDataSet options = new MutableDataSet();

    // uncomment to set optional extensions
    //options.set(Parser.EXTENSIONS, Arrays.asList(TablesExtension.create(), StrikethroughExtension.create()));

    // uncomment to convert soft-breaks to hard breaks
    options.set(HtmlRenderer.SOFT_BREAK, "<br />\n");

    Parser parser = Parser.builder(options).build();
    HtmlRenderer renderer = HtmlRenderer.builder(options).build();

    String markdown = getInstructionsAsMarkdown();

    // You can re-use parser and renderer instances
    Node document = parser.parse(markdown);
    return renderer.render(document);
}
 
Example #10
Source File: SmartEdit.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void indentNodes(List<Node> nodes, boolean right) {
	StringBuilder buf = new StringBuilder();
	for (int i = 0; i < nodes.size(); i++) {
		Node node = nodes.get(i);
		if (i > 0)
			buf.append(textArea.getText(nodes.get(i - 1).getEndOffset(), node.getStartOffset()));

		// indent list items
		if (node instanceof ListItem) {
			String str = node.getChars().toString();
			str = indentText(str, right);
			buf.append(str);
		}
	}

	int start = nodes.get(0).getStartOffset();
	int end = nodes.get(nodes.size() - 1).getEndOffset();

	IndentSelection isel = rememberIndentSelection();
	replaceText(textArea, start, end, buf.toString());
	selectAfterIndent(isel);
}
 
Example #11
Source File: MarkdownPreviewPane.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public MarkdownPreviewPane() {
	pane.getStyleClass().add("preview-pane");

	previewContext = new PreviewContext() {
		@Override public Renderer getRenderer() { return activeRenderer; }
		@Override public String getMarkdownText() { return markdownText.get(); }
		@Override public Node getMarkdownAST() { return markdownAST.get(); }
		@Override public Path getPath() { return path.get(); }
		@Override public IndexRange getEditorSelection() { return editorSelection.get(); }
	};

	path.addListener((observable, oldValue, newValue) -> update() );
	markdownText.addListener((observable, oldValue, newValue) -> update() );
	markdownAST.addListener((observable, oldValue, newValue) -> update() );
	scrollY.addListener((observable, oldValue, newValue) -> scrollY());
	editorSelection.addListener((observable, oldValue, newValue) -> editorSelectionChanged());

	Options.additionalCSSProperty().addListener(new WeakChangeListener<String>(
		(observable, oldValue, newValue) -> update()));
}
 
Example #12
Source File: MarkdownResource.java    From sling-whiteboard with Apache License 2.0 6 votes vote down vote up
@Override
public boolean consume(Node n, Map<String, Object> p) {
	AbstractYamlFrontMatterVisitor vis = new AbstractYamlFrontMatterVisitor();
	vis.visit(n);
	if ( vis.getData().isEmpty() )
		return false;
	
	for ( Map.Entry<String, List<String>> entry : vis.getData().entrySet() ) {
		if ( entry.getValue().size() == 1)
			p.put(entry.getKey(), entry.getValue().get(0));
		else
			p.put(entry.getKey(), entry.getValue().toArray(new String[0]));
	}
		
	
	return true;
}
 
Example #13
Source File: MarkdownHandler.java    From 1Rramp-Android with MIT License 6 votes vote down vote up
public static String getHtmlFromMarkdown(String md){
  MutableDataSet options = new MutableDataSet();

  // uncomment to set optional extensions
  //options.set(Parser.EXTENSIONS, Arrays.asList(TablesExtension.create(), StrikethroughExtension.create()));

  // uncomment to convert soft-breaks to hard breaks
  //options.set(HtmlRenderer.SOFT_BREAK, "<br />\n");

  Parser parser = Parser.builder(options).build();
  HtmlRenderer renderer = HtmlRenderer.builder(options).build();
  Node document = parser.parse(md);
  String html = renderer.render(document);
  //do some more formatting
  html = RegexUtils.replaceMarkdownImage(html);
  html = RegexUtils.replacePlainImageLinks(html);
  return html;
}
 
Example #14
Source File: DefaultMarkdownManager.java    From onedev with MIT License 5 votes vote down vote up
@Override
public String render(String markdown) {
	List<Extension> extensions = new ArrayList<>();
	extensions.add(AnchorLinkExtension.create());
	extensions.add(TablesExtension.create());
	extensions.add(TaskListExtension.create());
	extensions.add(DefinitionExtension.create());
	extensions.add(TocExtension.create());
	extensions.add(AutolinkExtension.create());
	extensions.addAll(contributedExtensions);

	MutableDataHolder options = new MutableDataSet()
			.set(HtmlRenderer.GENERATE_HEADER_ID, true)
			.set(AnchorLinkExtension.ANCHORLINKS_SET_NAME, true)
			.set(AnchorLinkExtension.ANCHORLINKS_WRAP_TEXT, false)
			.set(AnchorLinkExtension.ANCHORLINKS_TEXT_PREFIX, "<span class='header-anchor'></span>")
			.set(Parser.SPACE_IN_LINK_URLS, true)
			.setFrom(ParserEmulationProfile.GITHUB_DOC)
			.set(TablesExtension.COLUMN_SPANS, false)
			.set(TablesExtension.APPEND_MISSING_COLUMNS, true)
			.set(TablesExtension.DISCARD_EXTRA_COLUMNS, true)
			.set(TablesExtension.HEADER_SEPARATOR_COLUMN_MATCH, true)
			.set(Parser.EXTENSIONS, extensions);

	Parser parser = Parser.builder(options).build();

	HtmlRenderer htmlRenderer = HtmlRenderer.builder(options).build();
	
	Node document = parser.parse(markdown);
	return htmlRenderer.render(document);
}
 
Example #15
Source File: MarkdownResource.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
@Override
public boolean consume(Node n, Map<String, Object> p) {
	if ( n instanceof Heading ) {
		Heading h = (Heading) n;
		if ( h.getLevel() == 1 ) {
			p.put("jcr:title", h.getText().toString());
			return true;
		}
	}
	return false;
}
 
Example #16
Source File: FlexmarkPreviewRenderer.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private Node toAstRoot() {
	if (!addons.iterator().hasNext())
		return astRoot; // no addons --> use AST from editor

	if (astRoot2 == null)
		astRoot2 = parseMarkdown(markdownText);
	return astRoot2;
}
 
Example #17
Source File: FlexmarkPreviewRenderer.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private String printTree() {
	Node astRoot = toAstRoot();
	if (astRoot == null)
		return "";

	StringBuilder buf = new StringBuilder(100);
	printNode(buf, "", astRoot);
	return buf.toString().replace(Node.SPLICE, "...");
}
 
Example #18
Source File: FlexmarkPreviewRenderer.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void printNode(StringBuilder buf, String indent, Node node) {
	buf.append(indent);
	node.astString(buf, true);
	printAttributes(buf, node);
	buf.append('\n');

	indent += "    ";
	for (Node child = node.getFirstChild(); child != null; child = child.getNext())
		printNode(buf, indent, child);
}
 
Example #19
Source File: AbstractDocumentInterpreter.java    From camunda-bpm-swagger with Apache License 2.0 5 votes vote down vote up
Node resolveNode(Stack<Class> classes, Node node) {
  if (node == null)
    return null;
  if (classes.isEmpty())
    return node;
  Class type = classes.pop();
  return resolveNode(classes, node.getFirstChildAny(type));
}
 
Example #20
Source File: WikiFormatter.java    From webdsl with Apache License 2.0 5 votes vote down vote up
public static String wikiFormat(String text, boolean useHardWraps, String rootUrl){
    	try {
            Node document = MARKDOWN_PARSER.parse( text );
            HtmlRenderer renderer = getHTMLRenderer(rootUrl, useHardWraps);
            return renderer.render(document);
//            		 + "<!--end-->"; //This forces an unclosed HTML-comment in the rendered output to be closed. This fixes the issue where commonmark may escape a closing `-->` when a blank line exists in the HTML comment.  
//    		return processor.markdownToHtml( processVerbatim(text), getLinkRenderer( rootUrl ) );
    	} catch (Exception e) {
			Logger.error(e);
			return errorMessage(text);
		}
    }
 
Example #21
Source File: MarkdownEditorPane.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 5 votes vote down vote up
Node parseMarkdown(String text) {
	if (parser == null) {
		parser = Parser.builder()
			.extensions(MarkdownExtensions.getFlexmarkExtensions(Options.getMarkdownRenderer()))
			.build();
	}
	return parser.parse(text);
}
 
Example #22
Source File: MarkdownEditorPane.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void applyHighlighting(Node astRoot) {
	List<ExtraStyledRanges> extraStyledRanges = findReplacePane.hasHits()
		? Arrays.asList(
			new ExtraStyledRanges("hit", findReplacePane.getHits()),
			new ExtraStyledRanges("hit-active", Arrays.asList(findReplacePane.getActiveHit())))
		: null;

	MarkdownSyntaxHighlighter.highlight(textArea, astRoot, extraStyledRanges);
}
 
Example #23
Source File: SmartFormat.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 5 votes vote down vote up
List<Pair<Block, String>> formatParagraphs(Node markdownAST, int wrapLength, IndexRange selection, HashSet<BasedSequence> oldParagraphs) {
	ArrayList<Pair<Block, String>> formattedParagraphs = new ArrayList<>();
	NodeVisitor visitor = new NodeVisitor(Collections.emptyList()) {
		@Override
		public void visit(Node node) {
			if (node instanceof Paragraph || node instanceof HtmlBlock) {
				if (selection != null && !isNodeSelected(node, selection))
					return;

				if (oldParagraphs != null && oldParagraphs.contains(node.getChars()))
					return; // ignore unmodified paragraphs

				String newText = (node instanceof Paragraph)
					? formatParagraph((Paragraph) node, wrapLength)
					: formatHtmlBlock((HtmlBlock) node, wrapLength);

				// append trailing line separator (if necessary)
				if (node.getChars().endsWith("\n"))
					newText += "\n";

				if (!node.getChars().equals(newText, false))
					formattedParagraphs.add(new Pair<>((Block) node, newText));
			} else
				visitChildren(node);
		}
	};
	visitor.visit(markdownAST);
	return formattedParagraphs;
}
 
Example #24
Source File: SmartEdit.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void tabPressed(KeyEvent e) {
	List<Node> nodes;
	if (!(nodes = findIndentableNodesAtSelection()).isEmpty())
		indentNodes(nodes, true);
	else if (isIndentSelection())
		indentSelectedLines(true);
	else {
		// Note: not using replaceSelection(MarkdownTextArea, String) to allow undo merging in this case
		textArea.replaceSelection("\t");
		textArea.requestFollowCaret();
	}
}
 
Example #25
Source File: SmartEdit.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void shiftTabPressed(KeyEvent e) {
	List<Node> nodes;
	if (!(nodes = findIndentableNodesAtSelection()).isEmpty())
		indentNodes(nodes, false);
	else
		indentSelectedLines(false);
}
 
Example #26
Source File: SmartEdit.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void insertDelimited(Class<? extends Node> cls, String openCloseMarker, String hint) {
	List<? extends Node> nodes = findNodesAtSelection((s, e, n) -> cls.isInstance(n), false, false);
	if (nodes.size() > 0) {
		// there is delimited text in current selection --> change them to plain text
		if (nodes.size() == 1 && hint.equals(((DelimitedNode)nodes.get(0)).getText().toString())) {
			// delete node including hint text
			Node node = nodes.get(0);
			deleteText(textArea, node.getStartOffset(), node.getEndOffset());
		} else
			removeDelimiters(nodes);
	} else
		surroundSelectionInCode(openCloseMarker, hint);
}
 
Example #27
Source File: SmartEdit.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private <T extends Node> void removeDelimiters(List<T> nodes) {
	StringBuilder buf = new StringBuilder();
	for (int i = 0; i < nodes.size(); i++) {
		T node = nodes.get(i);
		if (i > 0)
			buf.append(textArea.getText(nodes.get(i - 1).getEndOffset(), node.getStartOffset()));
		buf.append(((DelimitedNode)node).getText());
	}

	int start = nodes.get(0).getStartOffset();
	int end = nodes.get(nodes.size() - 1).getEndOffset();
	replaceText(textArea, start, end, buf.toString());
	selectRange(textArea, start, start + buf.length());
}
 
Example #28
Source File: SmartEdit.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Find single node that completely encloses the current selection and match a predicate.
 */
private <T extends Node> T findNodeAtSelection(FindNodePredicate predicate) {
	IndexRange selection = textArea.getSelection();
	int start = selection.getStart();
	int end = selection.getEnd();
	List<T> nodes = findNodes(start, end, predicate, false, false);
	if (nodes.size() != 1)
		return null;

	T node = nodes.get(0);
	BasedSequence text = (node instanceof DelimitedNode) ? ((DelimitedNode)node).getText() : node.getChars();
	return (start >= text.getStartOffset() && end <= text.getEndOffset()) ? node : null;
}
 
Example #29
Source File: SmartEdit.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Find all nodes that are within the given range and match a predicate.
 */
private <T> List<T> findNodes(int start, int end, FindNodePredicate predicate, boolean allowNested, boolean deepest) {
	Node markdownAST = editor.getMarkdownAST();
	if (markdownAST == null)
		return Collections.emptyList();

	ArrayList<T> nodes = new ArrayList<>();
	NodeVisitor visitor = new NodeVisitor(Collections.emptyList()) {
		@SuppressWarnings("unchecked")
		@Override
		public void visit(Node node) {
			if (isInNode(start, end, node) && predicate.test(start, end, node)) {
				if (deepest) {
					int oldNodesSize = nodes.size();
					visitChildren(node);

					// add only if no other child was added
					if (nodes.size() == oldNodesSize)
						nodes.add((T) node);
					return;
				}

				nodes.add((T) node);

				if (!allowNested)
					return; // do not visit children
			}

			visitChildren(node);
		}
	};
	visitor.visit(markdownAST);
	return nodes;
}
 
Example #30
Source File: Markdown2HtmlUtil.java    From plumemo with Apache License 2.0 5 votes vote down vote up
/**
 * Markdownz转为Html
 * @param content
 * @return
 */
public static String html(String content){

    MutableDataSet options = new MutableDataSet();
    options.setFrom(ParserEmulationProfile.MARKDOWN);
    options.set(Parser.EXTENSIONS, Arrays.asList(new Extension[]{TablesExtension.create()}));
    Parser parser = Parser.builder(options).build();
    HtmlRenderer renderer = HtmlRenderer.builder(options).build();
    Node document = parser.parse(content);

    return renderer.render(document);
}