question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Document Line Numbers Snippet

See original GitHub issue

Hey there!

Would be cool to add a small stub to the Readme to document adding line numbers either via either of the following methods:

Would the prism-react-renderer team be open to this?


CodeSandbox version

import React from 'react'
import styled from 'styled-components'
import Highlight, { defaultProps } from 'prism-react-renderer'
import theme from 'prism-react-renderer/themes/nightOwl'

const exampleCode = `
(function someDemo() {
  var test = "Hello World!";
  console.log(test);
})();

return () => <App />;
`.trim()

const LineNo = styled.span`
  display: inline-block;
  width: 2em;
  user-select: none;
  opacity: 0.3;
`

const Pre = styled.pre`
  text-align: left;
  margin: 1em 0;
  padding: 0.5em;

  & .token-line {
    line-height: 1.3em;
    height: 1.3em;
  }
`

const Basic = () => (
  <Highlight {...defaultProps} theme={theme} code={exampleCode} language="jsx">
    {({ className, style, tokens, getLineProps, getTokenProps }) => (
      <Pre className={className} style={style}>
        {tokens.map((line, i) => (
          <div {...getLineProps({ line, key: i })}>
            <LineNo>{i + 1}</LineNo>
            {line.map((token, key) => <span {...getTokenProps({ token, key })} />)}
          </div>
        ))}
      </Pre>
    )}
  </Highlight>
)

export default Basic

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:2
  • Comments:9 (6 by maintainers)

github_iconTop GitHub Comments

2reactions
huy-nguyencommented, Nov 26, 2019

I tried @karlhorky’s solution and encounter a problem. It looks like the last element of tokens is an empty line that looks like this:

[{types: ["plaint"], content: "", empty: true}]

If you don’t add line numbering, this last line is not visible. However, the addition of the <LineNo/> React element causes this line to always be visible, leading to one extra empty line always showing up in every code block. My solution was to add a conditional check for for this empty line and also remove the styling for .token-line inside the Pre styled-component, so here’s how my solution looks (without the dynamic line number offset):

import React from 'react'
import styled from 'styled-components'
import Highlight, { defaultProps } from 'prism-react-renderer'
import theme from 'prism-react-renderer/themes/nightOwl'

const exampleCode = `
(function someDemo() {
  var test = "Hello World!";
  console.log(test);
})();

return () => <App />;
`.trim()

const LineNo = styled.span`
  display: inline-block;
  width: 2em;
  user-select: none;
  opacity: 0.3;
`

const Pre = styled.pre`
  text-align: left;
  margin: 1em 0;
  padding: 0.5em;
`

const Basic = () => (
  <Highlight {...defaultProps} theme={theme} code={exampleCode} language="jsx">
    {({ className, style, tokens, getLineProps, getTokenProps }) => (
      <Pre className={className} style={style}>
        {tokens.map((line, i) => {
            // Remove the last empty line:
            let lineNumberElem;
            if (
              line.length === 1 &&
              line[0].empty === true &&
              i === tokens.length - 1
            ) {
              lineNumberElem = null;
            } else {
              lineNumberElem = <LineNo>{i + 1}</LineNo>;
            }

            return (
              <div key={i} {...getLineProps({ line, key: i })}>
                {lineNumberElem}
                {line.map((token, key) => (
                  <span key={key} {...getTokenProps({ token, key })} />
                ))}
              </div>
            );
          })}
      </Pre>
    )}
  </Highlight>
)

export default Basic

I didn’t add it here but it’s also helpful to change the LineNo to display: inline-flex; justify-content: flex-end; padding-right: 0.5rem; to make line numbers right-align, which looks better instead of the jagged right edge with the original formatting.

1reaction
karlhorkycommented, Apr 27, 2020

Working on a PR now.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Formatting code with line numbers - microsoft word - Super User
Formatting code with line numbers · Go to "insert" tab, click "object" button (it's on the right) · Choose "openDocument Text": it will...
Read more >
Add or remove line numbers - Microsoft Support
Click Select in the Editing group on the Home tab, and then click Select All. Or press CTRL+A.
Read more >
Adding Line Numbers in MS Word to Specific Sections of Text
To apply line numbers to a specific section, insert section breaks in the document. Place the cursor at the beginning sentence/word of text...
Read more >
Code Snippets — Display Line Numbers - Elegant
reStructuredText and Markdown have directives that generate line numbers for code blocks. Use them to display line numbers in code snippets.
Read more >
5.7 Line numbers for code blocks (*) | R Markdown Cookbook
5.7 Line numbers for code blocks (*) ... For revealjs's revealjs_presentation output format (El Hattab and Allaire 2017), you may also need to...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found