com.vladsch.flexmark.ast.Paragraph Java Examples

The following examples show how to use com.vladsch.flexmark.ast.Paragraph. 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: 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 #2
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 #3
Source File: SmartFormat.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private String formatParagraph(Paragraph paragraph, int wrapLength) {
	String firstindent = paragraphIndent(paragraph);
	String indent = "";
	Block block = paragraph.getParent();
	if (block instanceof ListItem) {
		char[] chars = new char[firstindent.length()];
		Arrays.fill(chars, ' ');
		indent = new String(chars);
	} else if (block instanceof BlockQuote)
		indent = firstindent;

	// collect the paragraph text
	StringBuilder buf = new StringBuilder(paragraph.getTextLength());
	collectFormattableText(buf, paragraph);
	String text = buf.toString();

	// let addons protect text
	for (SmartFormatAddon addon : addons)
		text = addon.protect(text);

	// format the paragraph text
	text = formatText(text, wrapLength, indent, firstindent.length());

	// let addons unprotect text
	for (SmartFormatAddon hook : addons)
		text = hook.unprotect(text);

	return text;
}
 
Example #4
Source File: SmartFormat.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns the indent of the paragraph, which is the characters between
 * the start of the line and the first character of the paragraph.
 */
private String paragraphIndent(Paragraph paragraph) {
	int paraStartOffset = paragraph.getStartOffset();
	int paraLineStartOffset = paragraph.getDocument().getChars().startOfLine(paraStartOffset);
	return (paraStartOffset > paraLineStartOffset)
		? paragraph.getDocument().getChars().subSequence(paraLineStartOffset, paraStartOffset).toString()
		: "";
}
 
Example #5
Source File: MarkDownDocumentInterpreter.java    From camunda-bpm-swagger with Apache License 2.0 4 votes vote down vote up
String resolveText(final Node node) {
  return getOpChildNode(node, Paragraph.class)
    .map(childNode -> nodeToString(childNode, true))
    .orElse(null);
}
 
Example #6
Source File: SmartFormat.java    From markdown-writer-fx with BSD 2-Clause "Simplified" License 4 votes vote down vote up
void format(boolean formatSelectionOnly, String oldMarkdown) {
	Node markdownAST = editor.getMarkdownAST();
	if (markdownAST == null)
		return;

	// find paragraphs in old markdown
	HashSet<BasedSequence> oldParagraphs = new HashSet<>();
	if (oldMarkdown != null) {
		Node oldMarkdownAST = editor.parseMarkdown(oldMarkdown);
		NodeVisitor visitor = new NodeVisitor(Collections.emptyList()) {
			@Override
			public void visit(Node node) {
				if (node instanceof Paragraph || node instanceof HtmlBlock) {
					oldParagraphs.add(node.getChars());
				} else
					visitChildren(node);
			}
		};
		visitor.visit(oldMarkdownAST);
	}

	IndexRange selectedLinesRange = formatSelectionOnly ? editor.getSmartEdit().getSelectedLinesRange(false) : null;
	IndexRange selection = textArea.getSelection();
	int wrapLength = Options.getWrapLineLength();

	// find and format paragraphs
	List<Pair<Block, String>> formattedParagraphs = formatParagraphs(markdownAST, wrapLength, selectedLinesRange, oldParagraphs);
	if (formattedParagraphs.isEmpty())
		return;

	// replace text of formatted paragraphs
	MultiChangeBuilder<?, ?, ?> multiChange = textArea.createMultiChange(formattedParagraphs.size());
	for (Pair<Block, String> pair : formattedParagraphs) {
		Block paragraph = pair.getFirst();
		String newText = pair.getSecond();

		int startOffset = paragraph.getStartOffset();
		int endOffset = paragraph.getEndOffset();

		multiChange.replaceText(startOffset, endOffset, newText);
	}
	SmartEdit.commitMultiChange(textArea, multiChange);

	// make sure that selection is not out of bounds if text becomes shorter
	SmartEdit.selectRange(textArea, Math.min(selection.getStart(), textArea.getLength()), Math.min(selection.getEnd(), textArea.getLength()));
}
 
Example #7
Source File: UMLBlockQuote.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isParagraphEndWrappingDisabled(final Paragraph node) {
  return node == getLastChild() || node.getNext() instanceof UMLBlockQuote;
}
 
Example #8
Source File: UMLBlockQuote.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isParagraphStartWrappingDisabled(final Paragraph node) {
  return node == getFirstChild() || node.getPrevious() instanceof UMLBlockQuote;
}
 
Example #9
Source File: MarkdownParser.java    From sarl with Apache License 2.0 4 votes vote down vote up
/** Extract all the referencable objects from the given content.
 *
 * @param text the content to parse.
 * @return the referencables objects
 */
@SuppressWarnings("static-method")
protected ReferenceContext extractReferencableElements(String text) {
	final ReferenceContext context = new ReferenceContext();

	// Visit the links and record the transformations
	final MutableDataSet options = new MutableDataSet();
	final Parser parser = Parser.builder(options).build();
	final Node document = parser.parse(text);
	final Pattern pattern = Pattern.compile(SECTION_PATTERN_AUTONUMBERING);
	NodeVisitor visitor = new NodeVisitor(
			new VisitHandler<>(Paragraph.class, it -> {
				final CharSequence paragraphText = it.getContentChars();
				final Matcher matcher = pattern.matcher(paragraphText);
				if (matcher.find()) {
					final String number = matcher.group(2);
					final String title = matcher.group(3);
					final String key1 = computeHeaderId(number, title);
					final String key2 = computeHeaderId(null, title);
					context.registerSection(key1, key2, title);
				}
			}));
	visitor.visitChildren(document);

	final Pattern pattern1 = Pattern.compile(SECTION_PATTERN_TITLE_EXTRACTOR_WITHOUT_MD_PREFIX);
	visitor = new NodeVisitor(
			new VisitHandler<>(Heading.class, it -> {
				String key = it.getAnchorRefId();
				String title = it.getText().toString();
				// Sometimes, the title already contains the section number.
				// It should be removed.
				final Matcher matcher = pattern1.matcher(title);
				if (matcher.find()) {
					final String number = matcher.group(1);
					title = matcher.group(2);
					if (Strings.isEmpty(key)) {
						key = computeHeaderId(number, title);
					}
				}
				final String key2 = computeHeaderId(null, title);
				if (Strings.isEmpty(key)) {
					key = key2;
				}
				context.registerSection(key, key2, title);
			}));
	visitor.visitChildren(document);

	return context;
}