You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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?
Reacted by Adrian Hill, Armin Nabavi, Sadiinso, Erik Olesen, Roy Li, Ryan Thomas Lynch, ShenMian, Mr Beedell, Roke Julian Lockhart, Jerry, Max Rohrhirsch and 6 more
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),
)}
Reacted by Florian Vincent, Kevin Stephen, Pépe Hanisch, Jan Keller and 1um3n
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! ;-)
Reacted by victor-sm, nightingale-m, Dashie, Finley Ge, Jonas STIRNEMANN, Anis Lazaar, ShenMian, Lincoln Colling, Adrian Hill, Tianze Zhou and 7 more
Reacted by Anis Lazaar, Lincoln Colling, Tim Steenvoorden, Jay and Kevin Stephen
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
Reacted by willakat, Olivier Nicole, Victor Malov, Alex and Zongping Ding
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.
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.
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.
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:
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
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.
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:
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.
Reacted by Vitor do Nascimento, Neven Lukić, Ludovic Kuty and D Osinga
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.
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.
Reacted by allenzt, ⑆ Neved4 ⑈, Hong Jiarong, Frog Chen, Ludovic Kuty, Giorgio Mendieta, Yitong Zhao and Looky1173
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.
@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.
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!
@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:
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.
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.
@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:
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:
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):
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.
Reacted by Ole Mantei, Alex ANDRÉ, G. P. Müller and Julien Voisin
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):
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).
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:
Activity
[-]Line numbering for Raw Text / Code[/-][+]Feature Request: Line numbering for Raw Text / Code[/+]victor-sm commentedon Mar 26, 2023
@mpizenberg shared a solution on how to accomplish this. A native solution might still be nice, though.
mpizenberg commentedon Mar 26, 2023
Yep, this works for me, but I agree something more native would be nice :)
classabbyamp commentedon Apr 3, 2023
I cannot access this, could you share it directly or via a gist or similar?
mpizenberg commentedon Apr 3, 2023
Here you go: https://gist.github.com/mpizenberg/c6ed7bc3992ee5dfed55edce508080bb
mpizenberg commentedon Apr 3, 2023
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.
[-]Feature Request: Line numbering for Raw Text / Code[/-][+]Line numbering for Raw Text / Code[/+]willakat commentedon Apr 22, 2023
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.
Called as in this example:
Improvements welcome! ;-)
giltho commentedon Jun 9, 2023
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.reminstead ofcalc.modjneug commentedon Jul 26, 2023
Since line numbers are a thing outside of code (see #352 for example) I would like to see a general solution, like adding a
numberingoption toparor adding a#numbered[]element.Andrew15-5 commentedon Jul 26, 2023
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.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:
And the pretty frame like in
tcolorbox(from LaTeX) should not interfere with this layout issue.mainrs commentedon Jul 27, 2023
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.jneug commentedon Jul 27, 2023
Did you add a newline before the raw code? Like this:
Then
contentwill be asequenceand not arawelement. Try it without the newline:13 remaining items
Dherse commentedon Apr 2, 2024
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
jzbor commentedon Apr 2, 2024
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.jzbor commentedon Apr 6, 2024
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.linechanged 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:Andrew15-5 commentedon Apr 6, 2024
Here is an optimized version:
I'm not sure why you would need to use
math.mono()(I didn't even know such thing exists) for code block instead oftext(font: ...). Moreover, in an empty document that wrapper doesn't change anything.Andrew15-5 commentedon Apr 6, 2024
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.
laurmaedje commentedon Apr 8, 2024
It changed because
raw.linegives you access to thenumberandcount, so that you can trivially add the line number without having to redefine the wholerawshow rule.Example:
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.
Dherse commentedon Apr 8, 2024
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.
jjjenkinson commentedon Apr 26, 2024
I defined a function to show code. You can choose whether to show line numbers or not
Then you will get like this:

Astra3 commentedon May 8, 2024
I suggest a bit better solution than the one made by @laurmaedje, as it ignores non-block raw text.
kmlhpk commentedon Dec 3, 2024
@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.
Dherse commentedon Dec 3, 2024
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
placeevery 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!nboynick commentedon Feb 13, 2025
@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:
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.
Astra3 commentedon Feb 19, 2025
#2249 would have to be closed for an actual solution.
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:
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):
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.
dcangst commentedon Jul 15, 2026
Why not just use a box with a set width to fix the alignment?
Since
raw.linealso 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):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).
exflikt commentedon Nov 25, 2026
I found that the maximum width can be calculated outside
show raw.linerule and still get multi-digit alignment right, without usingcontextor offset: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.