How to use lines-and-columns - 8 common examples

To help you get started, we’ve selected a few lines-and-columns examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github decaffeinate / decaffeinate / src / utils / resolveToPatchError.ts View on Github external
export default function resolveToPatchError(err: any, content: string, stageName: string): PatchError | null {
  const makePatchError = (start: number, end: number, source: string): PatchError =>
    new PatchError(`${stageName} failed to parse: ${err.message}`, source, start, end);

  if (err.pos) {
    // Handle JavaScript parse errors.
    let { pos } = err;
    if (pos === content.length) {
      pos--;
    }
    return makePatchError(pos, pos + 1, content);
  } else if (err.syntaxError) {
    // Handle CoffeeScript parse errors.
    const { location } = err.syntaxError;
    const lineMap = new LinesAndColumns(content);
    const firstIndex = lineMap.indexForLocation({ line: location.first_line, column: location.first_column });
    let lastIndex = lineMap.indexForLocation({ line: location.last_line, column: location.last_column });
    if (firstIndex !== null) {
      if (lastIndex === null) {
        lastIndex = firstIndex + 1;
      } else {
        lastIndex++;
      }
      return makePatchError(firstIndex, lastIndex, content);
    }
  }
  return null;
}
github decaffeinate / decaffeinate / src / utils / CodeContext.ts View on Github external
constructor(readonly source: string) {
    this.linesAndColumns = new LinesAndColumns(source);
  }
github planbcoding / vscode-react-refactor / src / lib / code-actions / extract-jsx.ts View on Github external
const getIndexesForSelection = (
    documentText: string,
    selectionOrRange: vscode.Selection
): number[] => {
    const lines = new LinesAndColumns(documentText);
    const { start, end } = selectionOrRange;
    const startIndex = lines.indexForLocation({
        line: start.line,
        column: start.character
    });
    let endIndex = lines.indexForLocation({
        line: end.line,
        column: end.character
    });
    return [startIndex, endIndex];
};
github alangpierce / sucrase / src / util / formatTokens.ts View on Github external
export default function formatTokens(code: string, tokens: Array): string {
  if (tokens.length === 0) {
    return "";
  }

  const tokenKeys = Object.keys(tokens[0]).filter(
    (k) => k !== "type" && k !== "value" && k !== "start" && k !== "end" && k !== "loc",
  );
  const typeKeys = Object.keys(tokens[0].type).filter((k) => k !== "label" && k !== "keyword");

  const headings = ["Location", "Label", "Raw", ...tokenKeys, ...typeKeys];

  const lines = new LinesAndColumns(code);
  const rows = [headings, ...tokens.map(getTokenComponents)];
  const padding = headings.map(() => 0);
  for (const components of rows) {
    for (let i = 0; i < components.length; i++) {
      padding[i] = Math.max(padding[i], components[i].length);
    }
  }
  return rows
    .map((components) => components.map((component, i) => component.padEnd(padding[i])).join(" "))
    .join("\n");

  function getTokenComponents(token: Token): Array {
    const raw = code.slice(token.start, token.end);
    return [
      formatRange(token.start, token.end),
      formatTokenType(token.type),
github decaffeinate / decaffeinate / src / utils / PatchError.ts View on Github external
static prettyPrint(error: PatchError): string {
    const { source, message } = error;
    let { start, end } = error;
    start = Math.min(Math.max(start, 0), source.length);
    end = Math.min(Math.max(end, start), source.length);
    const lineMap = new LinesAndColumns(source);
    const startLoc = lineMap.locationForIndex(start);
    const endLoc = lineMap.locationForIndex(end);

    if (!startLoc || !endLoc) {
      throw new Error(`unable to find locations for range: [${start}, ${end})`);
    }

    const displayStartLine = Math.max(0, startLoc.line - 2);
    const displayEndLine = endLoc.line + 2;

    const rows: Array> = [];

    for (let line = displayStartLine; line <= displayEndLine; line++) {
      const startOfLine = lineMap.indexForLocation({ line, column: 0 });
      let endOfLine = lineMap.indexForLocation({ line: line + 1, column: 0 });
      if (startOfLine === null) {
github sindresorhus / parse-json / index.js View on Github external
return JSON.parse(string, reviver);
		} catch (error) {
			fallback(string, reviver);
			throw error;
		}
	} catch (error) {
		error.message = error.message.replace(/\n/g, '');
		const indexMatch = error.message.match(/in JSON at position (\d+) while parsing near/);

		const jsonError = new JSONError(error);
		if (filename) {
			jsonError.fileName = filename;
		}

		if (indexMatch && indexMatch.length > 0) {
			const lines = new LinesAndColumns(string);
			const index = Number(indexMatch[1]);
			const location = lines.locationForIndex(index);

			const codeFrame = codeFrameColumns(
				string,
				{start: {line: location.line + 1, column: location.column + 1}},
				{highlightCode: true}
			);

			jsonError.codeFrame = codeFrame;
		}

		throw jsonError;
	}
};
github Munter / subfont / lib / subsetFonts.js View on Github external
if (char === '\t' || char === '\n') {
            continue;
          }

          const codePoint = char.codePointAt(0);

          const isMissing = !characterSet.includes(codePoint);

          if (isMissing) {
            let location;
            const charIdx = htmlAsset.text.indexOf(char);

            if (charIdx === -1) {
              location = `${htmlAsset.urlOrDescription} (generated content)`;
            } else {
              const position = new LinesAndColumns(
                htmlAsset.text
              ).locationForIndex(charIdx);
              location = `${htmlAsset.urlOrDescription}:${position.line +
                1}:${position.column + 1}`;
            }

            missingGlyphsErrors.push({
              codePoint,
              char,
              htmlAsset,
              fontUsage,
              location
            });
          }
        }
      }
github assetgraph / assetgraph / lib / transforms / subsetFonts.js View on Github external
if (char === '\t' || char === '\n') {
              continue;
            }

            const codePoint = char.codePointAt(0);

            const isMissing = !characterSet.includes(codePoint);

            if (isMissing) {
              let location;
              const charIdx = htmlAsset.text.indexOf(char);

              if (charIdx === -1) {
                location = `${htmlAsset.urlOrDescription} (generated content)`;
              } else {
                const position = new LinesAndColumns(
                  htmlAsset.text
                ).locationForIndex(charIdx);
                location = `${htmlAsset.urlOrDescription}:${position.line +
                  1}:${position.column + 1}`;
              }

              missingGlyphsErrors.push({
                codePoint,
                char,
                htmlAsset,
                fontUsage,
                location
              });
            }
          }
        }

lines-and-columns

Maps lines and columns to character offsets and back.

MIT
Latest version published 6 months ago

Package Health Score

72 / 100
Full package analysis

Popular lines-and-columns functions