All files / src/highlights highlights-utils.ts

100% Statements 47/47
100% Branches 13/13
100% Functions 2/2
100% Lines 47/47

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64    1x   1x   1x 22x 22x 22x 22x   22x   22x 2x 2x   22x 14x 14x   6x 6x 6x 6x 6x 6x   22x 4x 4x     22x 16x   2x 2x   16x 1x 1x 1x 1x 1x 16x   1x 1x 1x 1x 1x   20x 20x 20x 20x 20x 20x   20x 20x  
import * as vscode from "vscode";
import { HighlightCodeLineData } from "./highlights-models";
import { Logger } from "../logger";
 
const SEARCH_LINE_RADIUS = 10;
 
export function findActualLine(
    document: vscode.TextDocument,
    highlight: HighlightCodeLineData
): number | null {
    const logger = Logger.getInstance();
 
    const originalLine = highlight.codeLine - 1;
 
    if (originalLine < 0 || originalLine >= document.lineCount) {
        return null;
    }
 
    if (!highlight.anchorText) {
        return originalLine;
    }
 
    const searchRadius = SEARCH_LINE_RADIUS;
    const startLine = Math.max(0, originalLine - searchRadius);
    const endLine = Math.min(
        document.lineCount - 1,
        originalLine + searchRadius
    );
 
    if (isAnchorTextExists(document, originalLine, highlight.anchorText)) {
        return originalLine;
    }
 
    // Search nearby lines
    for (let i = startLine; i <= endLine; i++) {
        if (i === originalLine) {
            // Already checked
            continue;
        }
 
        if (isAnchorTextExists(document, i, highlight.anchorText)) {
            logger.debug(
                `Found anchor text (${highlight.anchorText}) at line ${i + 1} (originally ${highlight.codeLine})`
            );
            return i;
        }
    }
 
    logger.warn(
        `Could not find anchor text "${highlight.anchorText}" near line ${highlight.codeLine}`
    );
    return null;
}
 
function isAnchorTextExists(
    document: vscode.TextDocument,
    lineNumber: number,
    anchorText: string
): boolean {
    const lineText = document.lineAt(lineNumber).text;
    // Can lead to false positives, at the moment we can live with it.
    return lineText.includes(anchorText);
}