How to Color Parts of Code Snippets?

Is there for method without a package for coloring parts of a coding block e.g.

```​
Enter a 24-hour time: 09:19
Closet departure time is 8:00, arriving at 10:16
```​

Outputs the text with no color. When I want to make 09:19 colored red. I cannot use the #text(fill: red) function as the text inside the backtics is treated as a string and the #raw() function accepts strings only. I am aware that I could break this block into lines and color that part only, but its a bit time consuming.

`Enter a 24-hour time:` #text(fill: red)[`09:19`] \
`Closet departure times is 8:00, arriving at 10:16`

Thank you for reading

1 Like

Hello,

Raw’s highlighting is set within the compiler. The only way to style it according to custom needs, would be to write a theme file.

If you are trying to copy raw’s font, you may want to try using a Sans Serif Font, e.g., DejaVu Sans Mono.

A quick hack is to use lang: "c".

#let s = "Enter a 24-hour time: 09:19
Closet departure time is 8:00, arriving at 10:16"
#let r = raw(s, lang: "c")

#repr(r)

#r

#s

#text(font: "DejaVu Sans Mono", size: 0.8em,  s)

Then you can use text’s styling to have colored times!

Maybe you could try using regex to specify what you want exactly:

#show regex("\d{1,2}:\d{2}"): set text(fill: red)

``
Enter a 24-hour time: 09:19
Closet departure time is 8:00, arriving at 10:16
``

Result

Thank you! I think my best bet is to use a mono-spaced font, so I can color parts of text based on my likings, since it isn’t about numbers. I want to color that part because in context it is inputed by user. Anyhow, if I want to use this method i.e. just using a mono-spaced font, can I make the text pre-formatted?

Using raw content

Mark the preferred part with a label:

#show <user-input>: set text(fill: red)

`Enter a 24-hour time:` `09:19` <user-input> \

`Closet departure times is 8:00, arriving at 10:16`

If you would like to use an external text, replace the fixed raw block ( `09:19` <user-input>) with #raw(input-text, block: false) <user-input>.

#show <user-input>: set text(fill: red)

#let text-input = "09:19"

`Enter a 24-hour time:` #raw(text-input, block: false) <user-input> \

`Closet departure times is 8:00, arriving at 10:16`

Simply Markup Mode

However, if you just want to use a mono-spaced font, then you should make a function to fill the text in different colors for simplicity.

#set text(font: "DejaVu Sans Mono")

#let user-input(s) = text(fill: red, s)

Enter a 24-hour time: #user-input[09:19] \
Closet departure time is 8:00, arriving at 10:16

Result

1 Like