1 package eu.svjatoslav.sixth.core.document;
3 import eu.svjatoslav.commons.string.tokenizer.InvalidSyntaxException;
4 import eu.svjatoslav.commons.string.tokenizer.Tokenizer;
5 import eu.svjatoslav.commons.string.tokenizer.TokenizerMatch;
6 import eu.svjatoslav.sixth.core.document.text.FormattedText;
8 import static eu.svjatoslav.commons.string.tokenizer.Terminator.TerminationStrategy.PRESERVE;
9 import static eu.svjatoslav.sixth.core.document.Helper.*;
10 import static eu.svjatoslav.sixth.core.document.text.FormattedText.fromOrg;
12 public class Document {
13 public final Heading rootHeading = new Heading( null , 0, null);
14 private Heading currentHeading = rootHeading;
16 public Heading createHeading(FormattedText name, int targetLevel){
17 if (currentHeading.level == (targetLevel - 1)){
18 Heading newHeading = new Heading(name, targetLevel, currentHeading);
19 currentHeading.addChild(newHeading);
20 currentHeading = newHeading;
24 if (currentHeading.level > (targetLevel - 1)){
25 currentHeading = currentHeading.parent;
26 return createHeading(name, targetLevel);
29 Heading missingIntermediate = new Heading(fromOrg("<noname>"), currentHeading.level + 1, currentHeading);
30 currentHeading.addChild(missingIntermediate);
31 currentHeading = missingIntermediate;
32 return createHeading(name, targetLevel);
35 public Heading getCurrentHeading(){
36 return currentHeading;
39 private void parseHeading(TokenizerMatch token) throws InvalidSyntaxException {
40 String[] headingSections = token.getRegExpGroups();
41 int level = headingSections[0].length();
42 String title = headingSections[1];
43 createHeading(fromOrg(title), level);
46 public void parse(String fileContentsAsString) throws InvalidSyntaxException {
47 final Tokenizer tokenizer = new Tokenizer(fileContentsAsString);
50 // "*** Example Heading 1234"
51 tokenizer.addTerminator(PRESERVE, "(\\*+)[ \\t](.*)\\r?\\n", TG_HEADING);
53 // Org list. Examples:
56 tokenizer.addTerminator(PRESERVE, "([ \\t]*)(\\+|-)[ \\t]+(.*)?\\r?\\n", TG_LIST);
59 tokenizer.addTerminator(PRESERVE, "([ \\t]+)(\\*)[ \\t]+(.*)?\\r?\\n", TG_LIST);
62 // "#+OPTIONS: H:20 num:20"
63 tokenizer.addTerminator(PRESERVE, "#\\+.+:.*\\r?\\n", TG_DOCUMENT_PROPERTY);
66 tokenizer.addTerminator(PRESERVE,".*\\r?\\n", TG_NORMAL_TEXT);
69 while (tokenizer.hasMoreContent()) {
70 final TokenizerMatch tm = tokenizer.getNextToken();
72 if (tm.isGroup(TG_HEADING)){
77 currentHeading.parse(tm);