blob: 24eabe082aa236d61a7628c1bb0e08ee63754a64 [file] [log] [blame]
Shawn Pearce12c8fab2016-05-15 16:55:21 -07001// Copyright (C) 2016 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package com.google.gitiles.doc;
16
17import org.commonmark.Extension;
18import org.commonmark.node.Block;
19import org.commonmark.parser.Parser;
20import org.commonmark.parser.Parser.ParserExtension;
21import org.commonmark.parser.block.AbstractBlockParser;
22import org.commonmark.parser.block.AbstractBlockParserFactory;
23import org.commonmark.parser.block.BlockContinue;
24import org.commonmark.parser.block.BlockStart;
25import org.commonmark.parser.block.MatchedBlockParser;
26import org.commonmark.parser.block.ParserState;
27
28/** CommonMark extension for {@code [TOC]}. */
29public class TocExtension implements ParserExtension {
30 public static Extension create() {
31 return new TocExtension();
32 }
33
34 private TocExtension() {}
35
36 @Override
37 public void extend(Parser.Builder builder) {
38 builder.customBlockParserFactory(new TocParserFactory());
39 }
40
41 private static class TocParser extends AbstractBlockParser {
42 private final TocBlock block = new TocBlock();
43
44 @Override
45 public Block getBlock() {
46 return block;
47 }
48
49 @Override
50 public BlockContinue tryContinue(ParserState parserState) {
51 return BlockContinue.none();
52 }
53 }
54
55 private static class TocParserFactory extends AbstractBlockParserFactory {
56 @Override
57 public BlockStart tryStart(ParserState state, MatchedBlockParser matched) {
58 if (state.getIndent() == 0) {
Ivan Frade21831b92022-12-01 21:54:21 -080059 CharSequence line = state.getLine().getContent();
Shawn Pearce12c8fab2016-05-15 16:55:21 -070060 int s = state.getNextNonSpaceIndex();
61 if ("[TOC]".contentEquals(line.subSequence(s, line.length()))) {
62 return BlockStart.of(new TocParser()).atIndex(line.length());
63 }
64 }
65 return BlockStart.none();
66 }
67 }
68}