Skip to content

Line numbering for Raw Text / Code #344

Closed

Description

@nightingale-m

Currently, there is no way to set line numbers for Raw Text / Code. It would also be cool to be able to specify which number it starts from.

Perhaps specify this in the parameter numbering, which defaults to none but can be changed to integer?

Activity

  1. changed the title [-]Line numbering for Raw Text / Code[/-] [+]Feature Request: Line numbering for Raw Text / Code[/+] on Mar 26, 2023
  2. victor-sm commented on Mar 26, 2023

    @victor-sm

    @mpizenberg shared a solution on how to accomplish this. A native solution might still be nice, though.

  3. mpizenberg commented on Mar 26, 2023

    @mpizenberg
    Sponsor

    Yep, this works for me, but I agree something more native would be nice :)

  4. added
    feature request
    text
    on Apr 1, 2023
  5. classabbyamp commented on Apr 3, 2023

    @classabbyamp
    Contributor

    @mpizenberg shared a solution on how to accomplish this

    I cannot access this, could you share it directly or via a gist or similar?

  6. mpizenberg commented on Apr 3, 2023

    @mpizenberg
    Sponsor

    Goal: being able to add line numbers, which are correct even in case of long lines that need wrapping.

    Strategy: duplicate the code block, once for getting the line numbers correct, and the other for syntax highlighting. The idea is to split lines and prefix each line with its line number such that line wrapping should be respected.

    #show raw.where(block: true): it => { set par(justify: false); grid(
      columns: (100%, 100%),
      column-gutter: -100%,
      block(width: 100%, inset: 1em, for i, line in it.text.split("\n") {
        box(width: 0pt, align(right, str(i + 1) + h(2em)))
        hide(line)
        linebreak()
      }),
      block(radius: 1em, fill: luma(246), width: 100%, inset: 1em, it),
    )}
    
  7. changed the title [-]Feature Request: Line numbering for Raw Text / Code[/-] [+]Line numbering for Raw Text / Code[/+] on Apr 4, 2023
  8. willakat commented on Apr 22, 2023

    @willakat

    Hi,
    I was missing some of the features from lstlistings and put this together to start learning typst. Posting it here in case it can help someone or even maybe serve to help spark a "native" typst feature.

    #let code(
        caption: none,             // content of caption bubble (string, none)
        bgcolor: rgb("#fefae0"),   // back ground color (color)
        strokecolor: 1pt + maroon, // frame color (color)
        hlcolor: auto,             // color to use for highlighted lines (auto, color)
        width: 100%,
        radius: 3pt,
        inset: 5pt,
        numbers: false,            // show line numbers (boolean)
        stepnumber: 1,             // only number lines divisible by stepnumber (integer)
        numberfirstline: false,    // if the firstline isn't divisible by stepnumber, force it to be numbered anyway (boolean)
        numberstyle: auto,         // style function to apply to line numbers (auto, style)
        firstnumber: 1,            // number of the first line (integer)
        highlight: none,           // line numbers to highlight (none, array of integer)
        content
    ) = {
        if type(hlcolor) == "auto" {
            hlcolor = bgcolor.darken(10%)
        }
        if type(highlight) == "none" {
            highlight = ()
        }
        block(
            width: width,
            fill: bgcolor,
            stroke: strokecolor,
            radius: radius,
            inset: inset,
            clip: false,
            {
                // Draw the caption bubble if a caption was set
                if caption != none {
                    style(styles => {
                        let caption_block = block(width: auto,
                                inset: inset,
                                radius: radius,
                                fill: bgcolor,
                                stroke: strokecolor,
                                h(.5em) + caption + h(.5em))
                        place(
                            top + left,
                            dx: 0em,
                            dy: -(measure(caption_block, styles).height / 2 + inset),
                            caption_block 
                        )
                    })
                    // skip some vertical space to avoid the caption overlapping with
                    // the beginning of the content
                    v(.6em)
                }
    
                let (columns, align, make_row) = {
                    if numbers {
                        // line numbering requested
                        if type(numberstyle) == "auto" {
                            numberstyle = text.with(style: "italic", 
                                                    slashed-zero: true, 
                                                    size: .6em)
                        }
                        ( ( auto, 1fr ),
                          ( right + horizon, left ),
                          e => {
                            let (i, l) = e
                            let n = i + firstnumber
                            let n_str = if (calc.mod(n, stepnumber) == 0) or (numberfirstline and i == 0) { numberstyle(str(n)) } else { none }
                            (n_str + h(.5em), raw(lang: content.lang, l))
                          }
                        )
                   } else {
                        ( ( 1fr, ),
                          ( left, ),
                          e => {
                            let (i, l) = e
                            raw( lang:content.lang, l)
                          }
                        )
                    }
                }
                table(
                    stroke:none,
                    columns: columns,
                    rows: (auto,),
                    gutter: 0pt,
                    inset: 2pt,
                    align: (col, _) => align.at(col),
                    fill: (c, row) => if (row / 2 + firstnumber) in highlight { hlcolor } else { none },
                    ..content
                        .text
                        .split("\n")
                        .enumerate()
                        .map(make_row)
                        .flatten()
                        .map(c => if c.has("text") and c.text == "" { v(1em) } else { c })
                )
            }
        )
    }
    

    Called as in this example:

    #code( 
        // firstnumber:306,
        // stepnumber:1,
        stepnumber:5,
        // numberfirstline: true,
        numbers: true,
        caption: "Code: example.py",
        highlight: (1, 5, 308)
    )[```python
    # Python in a code box
    a = 1
    
    def add_one(v):
        return v + 1
    ```]
    

    Improvements welcome! ;-)

  9. giltho commented on Jun 9, 2023

    @giltho

    For anyone who comes here looking at using the solution above, it's beautiful, but there's been a change in API it seems:
    use calc.rem instead of calc.mod

  10. jneug commented on Jul 26, 2023

    @jneug

    Since line numbers are a thing outside of code (see #352 for example) I would like to see a general solution, like adding a numbering option to par or adding a #numbered[] element.

  11. Andrew15-5 commented on Jul 26, 2023

    @Andrew15-5
    Contributor

    I would like to see a general solution

    I've commented in the #352, and the there is at least one problem — where to put line numbers? In the allowed area or outside the margins?

    For #352 it seems that outside the margins is the way to go.

    Although I haven't used line numbers with minted (from LaTeX) that much, I think that for raw text the numbers could go either way (outside/inside the margins). This is because the raw text line numbers appear only on a fraction of the whole document, meaning that somewhere (generally) the left margin would shift back and forth as the raw text is added in the document.

    |margin|
    |      |This is normal paragraph. And here is the code:
    |      |
    |     1|command1
    |     2|command2
    

    Since somewhere the document requirements can state the specific margins throughout the whole document, it is necessary to be able to typeset the raw text inside the allowed area:

    |margin|
    |      |This is normal paragraph. And here is the code:
    |      |
    |      |1 command1
    |      |2 command2
    

    And the pretty frame like in tcolorbox (from LaTeX) should not interfere with this layout issue.

  12. mainrs commented on Jul 27, 2023

    @mainrs

    ..content
    .text
    .split("\n")

    This does not work for me. I get the following error message: content does not contain field "text" and no default value was specified. I'm using typst 0.6.0.

  13. jneug commented on Jul 27, 2023

    @jneug

    This does not work for me. I get the following error message: content does not contain field "text" and no default value was specified. I'm using typst 0.6.0.

    Did you add a newline before the raw code? Like this:

    #code()[
    ```
    Some code
    ```
    ]

    Then content will be a sequence and not a raw element. Try it without the newline:

    #code()[```
    Some code
    ```]
  14. 13 remaining items

  15. Dherse commented on Apr 2, 2024

    @Dherse
    Contributor

    I think that a very basic system could be supported, but I don't know how much value it would add🤔I agree that Typst is great because you don't need a billion package, but I think that some packages are to be expected in areas that are too opinionated to be built-in

  16. jzbor commented on Apr 2, 2024

    @jzbor

    but I think that some packages are to be expected in areas that are too opinionated to be built-in

    Yes but this also applies to syntax highlighting in general which is supported and enabled by default. In comparison I think line numbering is a rather basic and uncontroversial feature.
    Given that typst already seems to implement this feature (via raw.line) I think it would be nice to also expose it in a user-friendly way.

  17. jzbor commented on Apr 6, 2024

    @jzbor

    Hi,
    I think this issue should be re-opened or declared wont-fix, as it has not actually been implemented. Correct me if I get something wrong, but from my perspective nothing has changed except from a custom API for an out-of-tree package that has been implemented. Also please note, this does not mean that I have any issue with the codly package itself, I just think it does not directly resolve this issue.

    As for show rules, I am not even sure if raw.line changed anything. If so it does not become clear from the documentation. For anybody interested in actually having line-numbers in vanilla Typst, this is the show-rule I ended up with:

      show raw.where(block: true): it => [
        #let nlines = it.lines.len()
        #table(columns: (auto, auto), align: (right, left), inset: 0.0em, gutter: 0.5em, stroke: none,
          ..it.lines.enumerate().map(((i, line)) => (math.mono(text(gray)[#(i + 1)]), line)).flatten()
        )
      ]
    
  18. Andrew15-5 commented on Apr 6, 2024

    @Andrew15-5
    Contributor

    Here is an optimized version:

    #let style-number(number) = text(gray)[#number]
    #show raw.where(block: true): it => grid(
      columns: 2,
      align: (right, left),
      gutter: 0.5em,
      ..it.lines
        .enumerate()
        .map(((i, line)) => (style-number(i + 1), line))
        .flatten()
    )

    I'm not sure why you would need to use math.mono() (I didn't even know such thing exists) for code block instead of text(font: ...). Moreover, in an empty document that wrapper doesn't change anything.

  19. Andrew15-5 commented on Apr 6, 2024

    @Andrew15-5
    Contributor

    I think a better way to go about things is to create a new issue and describe what is missing and what kind of API is desirable.

  20. laurmaedje commented on Apr 8, 2024

    @laurmaedje
    Member

    As for show rules, I am not even sure if raw.line changed anything. If so it does not become clear from the documentation. For anybody interested in actually having line-numbers in vanilla Typst, this is the show-rule I ended up with.

    It changed because raw.line gives you access to the number and count, so that you can trivially add the line number without having to redefine the whole raw show rule.

    Example:

    #show raw.line: it => {
      text(fill: gray)[#it.number]
      h(1em)
      it.body
    }
    
    ```rust
    fn main() {
        println!("Hello World!")
    }
    ```

    Any "even more built-in" way would be way less customizable and barely shorter. But I think a simple example like the one above should definitely be added to the docs.

  21. Dherse commented on Apr 8, 2024

    @Dherse
    Contributor

    And it keeps multi-line formatting correct if you want to do more advanced formatting (like putting lines in a table, etc.) something which was either very difficult or nearly impossible before.

  22. jjjenkinson commented on Apr 26, 2024

    @jjjenkinson

    I defined a function to show code. You can choose whether to show line numbers or not

      #let codeblock(body, caption: none, lineNum:false) = {
        if lineNum {
          show raw.where(block:true): it =>{
            set par(justify: false)
            block(fill: luma(240),inset: 0.3em,radius: 0.3em,
              // grid size: N*2
              grid(
                columns: 2,
                align: left+top,
                column-gutter: 0.5em,
                stroke: (x,y) => if x==0 {( right: (paint:gray, dash:"densely-dashed") )},
                inset: 0.3em,
                ..it.lines.map((line) => (str(line.number), line.body)).flatten()
              )
            )
          }
          figure(body, caption: caption, kind: "code", supplement: "Code")
        }
        else{
          figure(body, caption: caption, kind: "code", supplement: "Code")
        }
      }

    Then you will get like this:
    屏幕截图_20240426_192652

  23. Astra3 commented on May 8, 2024

    @Astra3
    Contributor

    I suggest a bit better solution than the one made by @laurmaedje, as it ignores non-block raw text.

    #show raw.where(block: true): code => {
      show raw.line: line => {
        text(fill: gray)[#line.number]
        h(1em)
        line.body
      }
      code
    }
  24. kmlhpk commented on Dec 3, 2024

    @kmlhpk

    I suggest a bit better solution than the one made by @laurmaedje, as it ignores non-block raw text.

    #show raw.where(block: true): code => {
      show raw.line: line => {
        text(fill: gray)[#line.number]
        h(1em)
        line.body
      }
      code
    }

    @Astra3 is there an easy way to make this text non-selectable? Say if someone wanted to copy and paste an entire code block at once from the resultant PDF, but without including the line numbers.

  25. Dherse commented on Dec 3, 2024

    @Dherse
    Contributor

    Hey @kmlhpk, I am the author of Codly, a popular package for extending the functionality of raw blocks. Unfortunately, it's not possible to make text non-selectable, AFAIK. In the first version of codly, I used to manually place every number after the lines, which kind of worked (since they would be selectable after), but it's brittle and buggy. But if you do find a solution that works, I am all ears!

  26. nboynick commented on Feb 13, 2025

    @nboynick

    I suggest a bit better solution than the one made by @laurmaedje, as it ignores non-block raw text.

    #show raw.where(block: true): code => {
      show raw.line: line => {
        text(fill: gray)[#line.number]
        h(1em)
        line.body
      }
      code
    }

    @Astra3 Maybe you would know better how to do this, but I was running into the issue that from line 10 onwards everything was slightly off, so I modified your code slightly to include extra spacing before the lines for numbers 1-9:

    #show raw.where(block: true): code => {
      show raw.line: line => {
        if line.number < 10 {
          text(fill: gray)[$"  "$#line.number]
        } else {
          text(fill: gray)[#line.number]
        }
        h(1em)
        line.body
      }
      code
    }

    I however also have no idea why it was only working with two spaces for me even though I assume that everything in raw is being rendered using a monospace font which means a single space should make up the difference for a single digit. Perhaps this has to do with me using the math mode to render the spaces. Just using a space in the content block was cutting it away however.

  27. Astra3 commented on Feb 19, 2025

    @Astra3
    Contributor

    Hey @kmlhpk, I am the author of Codly, a popular package for extending the functionality of raw blocks. Unfortunately, it's not possible to make text non-selectable, AFAIK. In the first version of codly, I used to manually place every number after the lines, which kind of worked (since they would be selectable after), but it's brittle and buggy. But if you do find a solution that works, I am all ears!

    #2249 would have to be closed for an actual solution.

    I suggest a bit better solution than the one made by @laurmaedje, as it ignores non-block raw text.

    #show raw.where(block: true): code => {
      show raw.line: line => {
        text(fill: gray)[#line.number]
        h(1em)
        line.body
      }
      code
    }

    @Astra3 Maybe you would know better how to do this, but I was running into the issue that from line 10 onwards everything was slightly off, so I modified your code slightly to include extra spacing before the lines for numbers 1-9:

    #show raw.where(block: true): code => {
      show raw.line: line => {
        if line.number < 10 {
          text(fill: gray)[$"  "$#line.number]
        } else {
          text(fill: gray)[#line.number]
        }
        h(1em)
        line.body
      }
      code
    }

    I however also have no idea why it was only working with two spaces for me even though I assume that everything in raw is being rendered using a monospace font which means a single space should make up the difference for a single digit. Perhaps this has to do with me using the math mode to render the spaces. Just using a space in the content block was cutting it away however.

    The numbers are aligned the same way the text is and there is no logic that is looking ahead at the line numbers. So if there is a larger number than one space, each line after that is offset by one character. Instead of math mode you can use tilda (unbreakable space) for each empty character, like so:

    #show raw.where(block: true): code => {
      show raw.line: line => {
        if line.number < 10 {
          text(fill: gray)[~#line.number]
        } else {
          text(fill: gray)[#line.number]
        }
        h(1em)
        line.body
      }
      code
    }

    That will fail on the 100th line, so perhaps a better way might be to use a grid. I came up with something like this is (inspired by the original @mpizenberg's usage of grid):

    #show raw.where(block: true): code => {
      grid(
        columns: (auto, auto),
        column-gutter: 1em,
        row-gutter: par.leading,
        align: (right, raw.align),
        ..for line in code.lines {
          (
            text(fill: gray)[#line.number],
            line.body,
          )
        },
      )
    }

    It replaces every raw block with a grid of two columns, filled in with a for loop array, first column having line numbers aligned to the right and the second column aligned to raw block's requested align. It's very convoluted and if I saw it as an example in the docs for implementing line numbers, I'd be honestly scared away. It's imo worth considering reopening this issue, as the scripting solution isn't as straightforward as it was supposed to be (or just using Codly, as mentioned; and it is the solution I support).

    To my knowledge it is not possible to "expand" grid items from a show rule, so a show rule cannot be used for filling the grid and a for loop has to be used instead.

  28. dcangst commented on Jul 15, 2026

    @dcangst

    Why not just use a box with a set width to fix the alignment?

    Since raw.line also gives you the total number of lines in count you can measure the space needed (I am not sure if I did the context thing right/optimal, that still confuses me every time):

    #show raw.where(block: true): code => {
      show raw.line: line => {
        context {
          let max-width = measure([#line.count]).width
          box(width: max-width, align(right, text(fill: gray)[#line.number]))
          h(1em)
          line.body
        }
      }
      code
    }

    However, to make all code blocks look the same i usually don't bother and just set a fixed width for a document/project (possibly also adjusting sizing such that 80/120 (or whatever column count the project uses) fits on a line).

  29. exflikt commented on Nov 25, 2026

    @exflikt

    I found that the maximum width can be calculated outside show raw.line rule and still get multi-digit alignment right, without using context or offset:

    #show raw.where(block: true): body => {
       let max-width = calc.floor(calc.log(body.lines.len(), base: 10.0)) * 1em
       show raw.line: it => {
          box(width: max-width, align(right, text(fill: gray)[#it.number]))
          h(1em)
          it.body
       }
       body
    }

    This does not address the line wrapping issue though, so I'd rather use @Astra3's solution if I find line number/body overlap too annoying.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature requesttext

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions