Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

RichTextLabel 中的 BBCode

前言

Label nodes are great for displaying basic text, but they have limitations. If you want to change the color of the text, or its alignment, you can only do that to the entire label. You can't make a part of the text have another color, or have a part of the text centered. To get around these limitations, you would use a RichTextLabel.

RichTextLabel allows for complex formatting of text using a markup syntax or the built-in API. It uses BBCodes for the markup syntax, a system of tags that designate formatting rules for a part of the text. You may be familiar with them if you ever used forums (also known as bulletin boards, hence the "BB" in "BBCode").

Unlike Label, RichTextLabel also comes with its own vertical scrollbar. This scrollbar is automatically displayed if the text does not fit within the control's size. The scrollbar can be disabled by unchecking the Scroll Active property in the RichTextLabel inspector.

Note that the BBCode tags can also be used to some extent in the XML source of the class reference. For more information, see 类参考入门.

参见

You can see how BBCode in RichTextLabel works in action using the Rich Text Label with BBCode demo project.

使用 BBCode

By default, RichTextLabel functions like a normal Label. It has the property_text property, which you can edit to have uniformly formatted text. To be able to use BBCode for rich text formatting, you need to turn on the BBCode mode by setting bbcode_enabled. After that, you can edit the text property using available tags. Both properties are located at the top of the inspector after selecting a RichTextLabel node.

../../_images/bbcode_in_richtextlabel_inspector.webp

For example, BBCode [color=green]test[/color] would render the word "test" with a green color.

../../_images/bbcode_in_richtextlabel_basic_example.webp

Most BBCodes consist of 3 parts: the opening tag, the content and the closing tag. The opening tag delimits the start of the formatted part, and can also carry some configuration options. Some opening tags, like the color one shown above, also require a value to work. Other opening tags may accept multiple options (separated by spaces within the opening tag). The closing tag delimits the end of the formatted part. In some cases, both the closing tag and the content can be omitted.

Unlike BBCode in HTML, leading/trailing whitespace is not removed by a RichTextLabel upon display. Duplicate spaces are also displayed as-is in the final output. This means that when displaying a code block in a RichTextLabel, you don't need to use a preformatted text tag.

[tag]content[/tag]
[tag=value]content[/tag]
[tag option1=value1 option2=value2]content[/tag]
[tag][/tag]
[tag]

备注

RichTextLabel doesn't support entangled BBCode tags. For example, instead of using:

[b]bold[i]bold italic[/b]italic[/i]

请使用:

[b]bold[i]bold italic[/i][/b][i]italic[/i]

安全地处理用户输入

In a scenario where users may freely input text (such as chat in a multiplayer game), you should make sure users cannot use arbitrary BBCode tags that will be parsed by RichTextLabel. This is to avoid inappropriate use of formatting, which can be problematic if [url] tags are handled by your RichTextLabel (as players may be able to create clickable links to phishing sites or similar).

Using RichTextLabel's [lb] and/or [rb] tags, we can replace the opening and/or closing brackets of any BBCode tag in a message with those escaped tags. This prevents users from using BBCode that will be parsed as tags – instead, the BBCode will be displayed as text.

Example of unescaped user input resulting in BBCode injection (2nd line) and escaped user input (3rd line)

Example of unescaped user input resulting in BBCode injection (2nd line) and escaped user input (3rd line)

创建一个 Node 节点并附加下面的脚本:

extends RichTextLabel

func _ready():
    append_chat_line("Player 1", "Hello world!")
    append_chat_line("Player 2", "Hello [color=red]BBCode injection[/color] (no escaping)!")
    append_chat_line_escaped("Player 2", "Hello [color=red]BBCode injection[/color] (with escaping)!")


# Returns escaped BBCode that won't be parsed by RichTextLabel as tags.
func escape_bbcode(bbcode_text):
    # We only need to replace opening brackets to prevent tags from being parsed.
    return bbcode_text.replace("[", "[lb]")


# Appends the user's message as-is, without escaping. This is dangerous!
func append_chat_line(username, message):
    append_text("%s: [color=green]%s[/color]\n" % [username, message])


# Appends the user's message with escaping.
# Remember to escape both the player name and message contents.
func append_chat_line_escaped(username, message):
    append_text("%s: [color=green]%s[/color]\n" % [escape_bbcode(username), escape_bbcode(message)])

剥离 BBCode 标签

For certain use cases, it can be desired to remove BBCode tags from the string. This is useful when displaying the RichTextLabel's text in another Control that does not support BBCode (such as a tooltip):

extends RichTextLabel

func _ready():
    var regex = RegEx.new()
    regex.compile("\\[.*?\\]")
    var text_without_tags = regex.sub(text, "", true)
    # `text_without_tags` contains the text with all BBCode tags removed.

备注

Removing BBCode tags entirely isn't advised for user input, as it can modify the displayed text without users understanding why part of their message was removed. Escaping user input should be preferred instead.

性能

In most cases, you can use BBCode directly as-is since text formatting is rarely a heavy task. However, with particularly large RichTextLabels (such as console logs spanning thousands of lines), you may encounter stuttering during gameplay when the RichTextLabel's text is updated.

There are several ways to alleviate this:

  • Use the append_text() function instead of appending to the text property. This function will only parse BBCode for the added text, rather than parsing BBCode from the entire text property.

  • Use push_[tag]() and pop() functions to add tags to RichTextLabel instead of using BBCode.

  • Enable the Threading > Threaded property in RichTextLabel. This won't speed up processing, but it will prevent the main thread from blocking, which avoids stuttering during gameplay. Only enable threading if it's actually needed in your project, as threading has some overhead.

使用 push_[标签]() 和 pop() 函数代替 BBCode

If you don't want to use BBCode for performance reasons, you can use functions provided by RichTextLabel to create formatting tags without writing BBCode in the text.

Every BBCode tag (including effects) has a push_[tag]() function (where [tag] is the tag's name). There are also a few convenience functions available, such as push_bold_italics() that combines both push_bold() and push_italics() into a single tag. See the RichTextLabel class reference for a complete list of push_[tag]() functions.

The pop() function is used to end any tag. Since BBCode is a tag stack, using pop() will close the most recently started tags first.

The following script will result in the same visual output as using BBCode [color=green]test [i]example[/i][/color]:

extends RichTextLabel

func _ready():
    append_text("BBCode ")  # Trailing space separates words from each other.
    push_color(Color.GREEN)
    append_text("test ")  # Trailing space separates words from each other.
    push_italics()
    append_text("example")
    pop()  # Ends the tag opened by `push_italics()`.
    pop()  # Ends the tag opened by `push_color()`.

警告

Do not set the text property directly when using formatting functions. Appending to the text property will erase all modifications made to the RichTextLabel using the append_text(), push_[tag]() and pop() functions.

参考

标签

示例

b
Makes {text} use the bold (or bold italics) font of RichTextLabel.

[b]{text}[/b]

i
Makes {text} use the italics (or bold italics) font of RichTextLabel.

[i]{text}[/i]

u
{text} 上显示下划线。

[u]{text}[/u]

s
{text} 上显示删除线。

[s]{text}[/s]

code
{text} 使用 RichTextLabel 的等宽字体。

[code]{text}[/code]

p
Adds new paragraph with {text}. Supports configuration options, see 段落选项.
[p]{text}[/p]
[p {options}]{text}[/p]
center
Makes {text} horizontally centered.
Same as [p align=center].

[center]{text}[/center]

left
Makes {text} horizontally left-aligned.
Same as [p align=left].

[left]{text}[/left]

right
Makes {text} horizontally right-aligned.
Same as [p align=right].

[right]{text}[/right]

fill
Makes {text} fill the full width of RichTextLabel.
Same as [p align=fill].

[fill]{text}[/fill]

indent
Indents {text} once. The indentation width is the same as with [ul] or [ol], but without a bullet point.

[indent]{text}[/indent]

url
Creates a hyperlink (underlined and clickable text). Can contain optional {text} or display {link} as is.
Must be handled with the "meta_clicked" signal to have an effect, see 处理 [url] 标签点击.
[url]{link}[/url]
[url={link}]{text}[/url]
hint
Creates a tooltip hint that is displayed when hovering the text with the mouse. Tooltip text should not be quoted (quotes will appear as-is in the tooltip otherwise).
[hint={tooltip text displayed on hover}]{text}[/hint]
img
Inserts an image from the {path} (can be any valid Texture2D resource).
If {width} is provided, the image will try to fit that width maintaining the aspect ratio.
If both {width} and {height} are provided, the image will be scaled to that size.
If {valign} configuration is provided, the image will try to align to the surrounding text, see 图像的垂直对齐.
Supports configuration options, see 图像选项.
[img]{path}[/img]
[img={width}]{path}[/img]
[img={width}x{height}]{path}[/img]
[img={valign}]{path}[/img]
[img {options}]{path}[/img]
font
Makes {text} use a font resource from the {path}.
Supports configuration options, see 字体选项.
[font={path}]{text}[/font]
[font {options}]{text}[/font]
font_size
Use custom font size for {text}.

[font_size={size}]{text}[/font_size]

dropcap
Use a different font size and color for {text}, while making the tag's contents span multiple lines if it's large enough.
A drop cap is typically one uppercase character, but [dropcap] supports containing multiple characters. margins values are comma-separated and can be positive, zero or negative. Negative top and bottom margins are particularly useful to allow the rest of the paragraph to display below the dropcap.

[dropcap font_size={size} color={color} margins={left},{top},{right},{bottom}]{text}[/dropcap]

opentype_features
{text} 启用自定义 OpenType 字体特性。{list} 中的特性必须以英文逗号分隔。
[opentype_features={list}]
{text}
[/opentype_features]
lang
Overrides the language for {text} that is set by the BiDi > Language property in RichTextLabel. {code} must be an ISO language code. This can be used to enforce the use of a specific script for a language without starting a new paragraph. Some font files may contain script-specific substitutes, in which case they will be used.

[lang={code}]{text}[/color]

color
Changes the color of {text}. Color must be provided by a common name (see 具名颜色) or using the HEX format (e.g. #ff00ff, see 十六进制颜色代码).

[color={code/name}]{text}[/color]

bgcolor
Draws the color behind {text}. This can be used to highlight text. Accepts same values as the color tag.

[bgcolor={code/name}]{text}[/bgcolor]

fgcolor
Draws the color in front of {text}. This can be used to "redact" text by using an opaque foreground color. Accepts same values as the color tag.

[fgcolor={code/name}]{text}[/fgcolor]

outline_size
Use custom font outline size for {text}.
[outline_size={size}]
{text}
[/outline_size]
outline_color
Use custom outline color for {text}. Accepts same values as the color tag.
[outline_color={code/name}]
{text}
[/outline_color]
table
Creates a table with the {number} of columns. Use the cell tag to define table cells.

[table={number}]{cells}[/table]

cell
Adds a cell with {text} to the table.
If {ratio} is provided, the cell will try to expand to that value proportionally to other cells and their ratio values.
Supports configuration options, see 单元格选项.
[cell]{text}[/cell]
[cell={ratio}]{text}[/cell]
[cell {options}]{text}[/cell]
ul
Adds an unordered list. List {items} must be provided by putting one item per line of text.
The bullet point can be customized using the {bullet} parameter, see 无序列表项目符号.
[ul]{items}[/ul]
[ul bullet={bullet}]{items}[/ul]
ol
Adds an ordered (numbered) list of the given {type} (see 有序列表类型). List {items} must be provided by putting one item per line of text.

[ol type={type}]{items}[/ol]

lb, rb
Adds [ and ] respectively. Allows escaping BBCode markup.
These are self-closing tags, which means you do not need to close them (and there is no [/lb] or [/rb] closing tag).
[lb]b[rb]text[lb]/b[rb] will display as [b]text[/b].
Several Unicode control characters can be added using their own self-closing tags.
This can result in easier maintenance compared to pasting those
control characters directly in the text.
[lrm] (left-to-right mark), [rlm] (right-to-left mark), [lre] (left-to-right embedding),
[rle] (right-to-left embedding), [lro] (left-to-right override), [rlo] (right-to-left override),
[pdf] (pop directional formatting), [alm] (Arabic letter mark), [lri] (left-to-right isolate),
[rli] (right-to-left isolate), [fsi] (first strong isolate), [pdi] (pop directional isolate),
[zwj] (zero-width joiner), [zwnj] (zero-width non-joiner), [wj] (word joiner),
[shy] (soft hyphen)

备注

Tags for bold ([b]) and italics ([i]) formatting work best if the appropriate custom fonts are set up in the RichTextLabelNode's theme overrides. If no custom bold or italic fonts are defined, faux bold and italic fonts will be generated by Godot. These fonts rarely look good in comparison to hand-made bold/italic font variants.

The monospaced ([code]) tag only works if a custom font is set up in the RichTextLabel node's theme overrides. Otherwise, monospaced text will use the regular font.

目前还没有用于控制文本垂直居中的BBCode标签.

Options can be skipped for all tags.

段落选项

  • align

    leftcenterrightfill

    默认

    left

    文本水平对齐。

  • bidi_overridest

    defaulturifileemaillistnonecustom

    默认

    default

    Structured text override.

  • directiondir

    ltrrtlauto

    默认

    继承

    Base BiDi direction.

  • languagelang

    ISO 语言代码。见 区域设置代码

    默认

    继承

    Locale override. Some font files may contain script-specific substitutes, in which case they will be used.

  • tab_stops

    List of floating-point numbers, e.g. 10.0,30.0

    默认

    Width of the space character in the font

    Overrides the