org.conqat.lib.commons.markup.MarkdownCodeBlockFinder Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of teamscale-lib-commons Show documentation
Show all versions of teamscale-lib-commons Show documentation
Provides common utility functions
package org.conqat.lib.commons.markup;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* Class for processing a markdown file's content and finding the starting lines of code blocks.
* Code blocks are surrounded by a pair of delimiters (triple back ticks {@code ```}) and can
* optionally specify a language for syntax highlighting. This language is then defined in the line
* of the opening delimiter. Example for markdown file's content with a code block:
*
*
* {@code
* This is a code block:
* ``` java
* int a = 1;
* if (condition) {
* doSomething();
* }
* ```
* }
*
*/
public class MarkdownCodeBlockFinder {
/**
* Contains the line content and line number for the starting line of a code block in a markdown
* file.
*/
public static class CodeBlockStartLine {
private final String lineContent;
private final int lineNumber;
private CodeBlockStartLine(String lineContent, int lineNumber) {
this.lineContent = lineContent;
this.lineNumber = lineNumber;
}
public String getLineContent() {
return lineContent;
}
public int getLineNumber() {
return lineNumber;
}
}
/**
* Returns the start lines for each code block in the markdown file's content.
*/
public static List findCodeBlockStartLines(@NonNull String fileContent) {
List codeBlockStartLines = new ArrayList<>();
Scanner sc = new Scanner(fileContent);
int currentLineNumber = 0;
boolean nextDelimiterIsStartOfCodeBlock = true;
while (sc.hasNextLine()) {
currentLineNumber++;
String currentLine = sc.nextLine();
if (currentLine.startsWith(MarkupUtils.CODE_BLOCK_DELIMITER)) {
if (nextDelimiterIsStartOfCodeBlock) {
codeBlockStartLines.add(new CodeBlockStartLine(currentLine, currentLineNumber));
}
nextDelimiterIsStartOfCodeBlock = !nextDelimiterIsStartOfCodeBlock;
}
}
sc.close();
return codeBlockStartLines;
}
}