gobengo / distbin

distributed social pastebin using Activitypub

Home Page:https://distbin.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add lines number for source code

yalh76 opened this issue · comments

A decent enough solution might just be to write a fresh function that takes the result of highlighting the code (an input HTML string that is a <code> or its innerHTML, parses/rewrites it, then returns an HTML string that includes line numbers.
Use it here. https://github.com/gobengo/distbin/blob/master/src/distbin-html/an-activity.ts#L45

starting point:

const highlightedHtmlToLines = (html: string): Array<string> => html.split('\n'); // will probably need a more html-aware implementation
type HtmlString = string
type HtmlRewriter = (in: HtmlString ) => HtmlString ;
const addLineNumbers: HtmlRewriter = (highlightedCode: HtmlString): HtmlString => {
  const lines = highlightedHtmlToLines(highlightedCode)
  // two-column table with cells: lineNumber, actualLineHtml
  return `
  <table>
  ${
    lines
    .map((lineStr, lineIndex) => `
      <tr>
        <td class="lineNumber">${lineIndex}</td>
        <td class="lineOfCode>${lineStr}</td>
      </tr>`
    .join('\n')
  }
  </table>
  `
}