How can one substitute variables in raw blocks?

Hi all,

New to Typst, so sorry if this is a rather obvious/silly question.
As I understand it, is it possible to perform variable substitutions in raw blocks, like

#import "@preview/codly:1.2.0": *
#import "@preview/codly-languages:0.1.1": *
#show: codly-init.with()

#let version = "1.0"

#codly(enabled: true, number-format: none)
```bash
#!/bin/bash

# How could I replace $version?
echo $version

```

Thanks in advance
Brgds

By using the #raw function instead of the shorthand form of it:

```<lang>
...
```

versus

#raw(lang: "lang", "...")

you can include variables into the text:

#import "@preview/codly:1.2.0": *
#import "@preview/codly-languages:0.1.1": *
#show: codly-init.with()

#let version = "1.0"

#codly(enabled: true, number-format: none)
#raw(block: true,
     "#!/bin/bash
echo " + version, // must be at column 0 (else adds spaces)
     lang: "bash"
)

image

Hope that helps :)

you can use crudo to help yourself with that. An alternative approach that fails here would be using a show rule.

#let version = "1.0"
#let code = ```bash
#!/bin/bash

# How could I replace $version?
echo $version

```

= No substitution

#code

= Substitution (attempt) using `show`

#{
  show "$version": version
  code
}

= Substitution using `crudo`

#import "@preview/crudo:0.1.1"
#crudo.map(code, line => line.replace("$version", version))

= Substitution using `crudo`, ignoring comments

#import "@preview/crudo:0.1.1"
#crudo.map(code, line => {
  if line.trim().starts-with("#") { return line }
  line.replace("$version", version)
})

The substitution attempt using show only succeeds in the comment because the $version in the actual code is parsed as two separate tokens (for syntax highlighting purposes). Replacing $version with e.g. VERSION should fix that, though.

Alternatively, Crudo allows you to treat raw blocks more like arrays of strings (lines) that content elements. In particular, crudo.map() will replace each line with the result of the function, which can then replace stuff. Since it’s line-by-line, you can easily check if you’re in a comment line, just in case you want to only replace the code occurrences of the version.

1 Like

Thank you for your replies. Marked as solved.