@Override public Document process(Document document) { this.document = document; processBlock((StructuralNode) this.document); return this.document; }
private void processBlock(StructuralNode block) { List<StructuralNode> blocks = block.getBlocks(); for (int i = 0; i < blocks.size(); i++) { final StructuralNode currentBlock = blocks.get(i); if(currentBlock instanceof StructuralNode) { if ("paragraph".equals(currentBlock.getContext())) { List<String> lines = ((Block) currentBlock).getLines(); if (lines.size() > 0 && lines.get(0).startsWith("$")) { blocks.set(i, convertToTerminalListing((Block) currentBlock)); } } else { // It's not a paragraph, so recursively descent into the child node processBlock(currentBlock); } } } } public Block convertToTerminalListing(Block block) {
@Test public void a_treeprocessor_instance_should_be_executed_in_document() { JavaExtensionRegistry javaExtensionRegistry = this.asciidoctor.javaExtensionRegistry(); javaExtensionRegistry.treeprocessor(new TerminalCommandTreeprocessor(new HashMap<>())); String content = asciidoctor.convertFile( classpath.getResource("sample-with-terminal-command.ad"), options().toFile(false).get()); org.jsoup.nodes.Document doc = Jsoup.parse(content, "UTF-8"); Element contentElement = doc.getElementsByAttributeValue("class", "command").first(); assertThat(contentElement.text(), is("echo \"Hello, World!\"")); contentElement = doc.getElementsByAttributeValue("class", "command").last(); assertThat(contentElement.text(), is("gem install asciidoctor")); }
public Block convertToTerminalListing(Block block) { Map<String, Object> attributes = block.getAttributes(); attributes.put("role", "terminal"); StringBuilder resultLines = new StringBuilder(); List<String> lines = block.getLines(); for (String line : lines) { if (line.startsWith("$")) { resultLines.append("<span class=\"command\">") .append(line.substring(2, line.length())) .append("</span>"); } else { resultLines.append(line); } } return createBlock(this.document, "listing", Arrays.asList(resultLines.toString()), attributes, new HashMap<Object, Object>()); }
@Test public void a_treeprocessor_instance_should_be_executed_in_document() { this.asciidoctor.createGroup() .treeprocessor(new TerminalCommandTreeprocessor(new HashMap<String, Object>())) .register(); String content = asciidoctor.convertFile( classpath.getResource("sample-with-terminal-command.ad"), options().toFile(false).get()); org.jsoup.nodes.Document doc = Jsoup.parse(content, "UTF-8"); Element contentElement = doc.getElementsByAttributeValue("class", "command").first(); assertThat(contentElement.text(), is("echo \"Hello, World!\"")); contentElement = doc.getElementsByAttributeValue("class", "command").last(); assertThat(contentElement.text(), is("gem install asciidoctor")); }