| Shawn Pearce | 12c8fab | 2016-05-15 16:55:21 -0700 | [diff] [blame] | 1 | // 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 | |
| 15 | package com.google.gitiles.doc; |
| 16 | |
| 17 | import org.commonmark.Extension; |
| 18 | import org.commonmark.node.Block; |
| 19 | import org.commonmark.parser.Parser; |
| 20 | import org.commonmark.parser.Parser.ParserExtension; |
| 21 | import org.commonmark.parser.block.AbstractBlockParser; |
| 22 | import org.commonmark.parser.block.AbstractBlockParserFactory; |
| 23 | import org.commonmark.parser.block.BlockContinue; |
| 24 | import org.commonmark.parser.block.BlockStart; |
| 25 | import org.commonmark.parser.block.MatchedBlockParser; |
| 26 | import org.commonmark.parser.block.ParserState; |
| 27 | |
| 28 | /** CommonMark extension for {@code [TOC]}. */ |
| 29 | public 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 Frade | 21831b9 | 2022-12-01 21:54:21 -0800 | [diff] [blame] | 59 | CharSequence line = state.getLine().getContent(); |
| Shawn Pearce | 12c8fab | 2016-05-15 16:55:21 -0700 | [diff] [blame] | 60 | 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 | } |