MCPcopy Create free account
hub / github.com/cortex-js/compute-engine / highlightCodeBlock

Function highlightCodeBlock

src/common/syntax-highlighter.ts:356–418  ·  view source on GitHub ↗
(
  code: string,
  lineStart: number | undefined = 1,
  markIndicator?: string,
  grammar?: SyntaxGrammar
)

Source from the content-addressed store, hash-verified

354 * gutter with line numbers and an optional highlighted line
355 */
356export function highlightCodeBlock(
357 code: string,
358 lineStart: number | undefined = 1,
359 markIndicator?: string,
360 grammar?: SyntaxGrammar
361): StyledBlock {
362 // Split the mark into a line and column range
363 // e.g 14:3-14 -> { line: 14, colStart: 3, colEnd: 14 }
364 let markLine = 0;
365 let markCol = '';
366 if (markIndicator) {
367 let lineStr = '';
368 [lineStr, markCol] = markIndicator.split(':');
369 markLine = parseInt(lineStr);
370 }
371
372 // Split the code into lines
373 const sourceLines = code.split('\n');
374
375 // Parse each line
376 const lines = sourceLines.map((line) => renderCode(parseCode(line, grammar)));
377
378 if (lineStart === undefined) {
379 // Concatenate the lines into a single block without a gutter
380 const content = lines.flatMap((line) => [...line, { content: '\n' }]);
381 return { tag: 'block', spans: content };
382 }
383
384 // Turn the lines into a StyleBlock
385 const lastLine = lineStart + sourceLines.length - 1;
386 const maxDigits = lastLine.toString().length;
387
388 // Return a StyleBlock with a gutter including line numbers
389
390 const content: StyledSpan[] = lines.flatMap((line, i) => {
391 const lineNo = lineStart + i;
392 if (lineNo === markLine) {
393 return [
394 {
395 content: `\n${lineNo.toString().padStart(maxDigits, ' ')} `,
396 weight: 'normal',
397 ...DEFAULT_THEME.mark,
398 },
399 {
400 content: `\u2503`,
401 ...DEFAULT_THEME.mark_indicator,
402 },
403 ...mark(line, markCol),
404 ];
405 } else {
406 const lineNoStr = `\n${lineNo.toString().padStart(maxDigits, ' ')}`;
407 return [
408 { content: lineNoStr, weight: 'thin' },
409 { content: ' \u2502 ', fg: 'white' }, // U+2502 Thin vertical line
410 ...line,
411 ];
412 }
413 });

Callers

nothing calls this directly

Calls 5

renderCodeFunction · 0.85
markFunction · 0.85
parseCodeFunction · 0.70
mapMethod · 0.65
toStringMethod · 0.65

Tested by

no test coverage detected