bbcode_in_richtextlabel.rst 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  1. .. _doc_bbcode_in_richtextlabel:
  2. BBCode in RichTextLabel
  3. =======================
  4. Introduction
  5. ------------
  6. :ref:`class_Label` nodes are great for displaying basic text, but they have limitations.
  7. If you want to change the color of the text, or its alignment, you can only do that to
  8. the entire label. You can't make a part of the text have another color, or have a part
  9. of the text centered. To get around these limitations, you would use a :ref:`class_RichTextLabel`.
  10. :ref:`class_RichTextLabel` allows for complex formatting of text using a markup syntax or
  11. the built-in API. It uses BBCodes for the markup syntax, a system of tags that designate
  12. formatting rules for a part of the text. You may be familiar with them if you ever used
  13. forums (also known as `bulletin boards`, hence the "BB" in "BBCode").
  14. Unlike Label, RichTextLabel also comes with its own vertical scrollbar. This
  15. scrollbar is automatically displayed if the text does not fit within the
  16. control's size. The scrollbar can be disabled by unchecking the
  17. **Scroll Active** property in the RichTextLabel inspector.
  18. Note that the BBCode tags can also be used to some extent in the XML source of
  19. the class reference. For more information, see :ref:`doc_class_reference_primer`.
  20. .. seealso::
  21. You can see how BBCode in RichTextLabel works in action using the
  22. `Rich Text Label with BBCode demo project <https://github.com/godotengine/godot-demo-projects/tree/master/gui/rich_text_bbcode>`__.
  23. Using BBCode
  24. ------------
  25. By default, :ref:`class_RichTextLabel` functions like a normal :ref:`class_Label`.
  26. It has the :ref:`property_text <class_RichTextLabel_property_text>` property, which you can
  27. edit to have uniformly formatted text. To be able to use BBCode for rich text formatting,
  28. you need to turn on the BBCode mode by setting :ref:`bbcode_enabled <class_RichTextLabel_property_bbcode_enabled>`.
  29. After that, you can edit the :ref:`text <class_RichTextLabel_property_text>`
  30. property using available tags. Both properties are located at the top of the inspector
  31. after selecting a RichTextLabel node.
  32. .. image:: img/bbcode_in_richtextlabel_inspector.webp
  33. For example, ``BBCode [color=green]test[/color]`` would render the word "test" with
  34. a green color.
  35. .. image:: img/bbcode_in_richtextlabel_basic_example.webp
  36. Most BBCodes consist of 3 parts: the opening tag, the content and the closing
  37. tag. The opening tag delimits the start of the formatted part, and can also
  38. carry some configuration options. Some opening tags, like the ``color`` one
  39. shown above, also require a value to work. Other opening tags may accept
  40. multiple options (separated by spaces within the opening tag). The closing tag
  41. delimits the end of the formatted part. In some cases, both the closing tag and
  42. the content can be omitted.
  43. Unlike BBCode in HTML, leading/trailing whitespace is not removed by a
  44. RichTextLabel upon display. Duplicate spaces are also displayed as-is in the
  45. final output. This means that when displaying a code block in a RichTextLabel,
  46. you don't need to use a preformatted text tag.
  47. .. code-block:: none
  48. [tag]content[/tag]
  49. [tag=value]content[/tag]
  50. [tag option1=value1 option2=value2]content[/tag]
  51. [tag][/tag]
  52. [tag]
  53. .. note::
  54. RichTextLabel doesn't support entangled BBCode tags. For example, instead of
  55. using:
  56. ::
  57. [b]bold[i]bold italic[/b]italic[/i]
  58. Use:
  59. ::
  60. [b]bold[i]bold italic[/i][/b][i]italic[/i]
  61. .. _doc_bbcode_in_richtextlabel_handling_user_input_safely:
  62. Handling user input safely
  63. --------------------------
  64. In a scenario where users may freely input text (such as chat in a multiplayer
  65. game), you should make sure users cannot use arbitrary BBCode tags that will be
  66. parsed by RichTextLabel. This is to avoid inappropriate use of formatting, which
  67. can be problematic if ``[url]`` tags are handled by your RichTextLabel (as players
  68. may be able to create clickable links to phishing sites or similar).
  69. Using RichTextLabel's ``[lb]`` and/or ``[rb]`` tags, we can replace the opening and/or
  70. closing brackets of any BBCode tag in a message with those escaped tags. This
  71. prevents users from using BBCode that will be parsed as tags – instead, the
  72. BBCode will be displayed as text.
  73. .. figure:: img/bbcode_in_richtextlabel_escaping_user_input.webp
  74. :align: center
  75. :alt: Example of unescaped user input resulting in BBCode injection (2nd line) and escaped user input (3rd line)
  76. Example of unescaped user input resulting in BBCode injection (2nd line) and escaped user input (3rd line)
  77. The above image was created using the following script:
  78. ::
  79. extends RichTextLabel
  80. func _ready():
  81. append_chat_line("Player 1", "Hello world!")
  82. append_chat_line("Player 2", "Hello [color=red]BBCode injection[/color] (no escaping)!")
  83. append_chat_line_escaped("Player 2", "Hello [color=red]BBCode injection[/color] (with escaping)!")
  84. # Returns escaped BBCode that won't be parsed by RichTextLabel as tags.
  85. func escape_bbcode(bbcode_text):
  86. # We only need to replace opening brackets to prevent tags from being parsed.
  87. return bbcode_text.replace("[", "[lb]")
  88. # Appends the user's message as-is, without escaping. This is dangerous!
  89. func append_chat_line(username, message):
  90. append_text("%s: [color=green]%s[/color]\n" % [username, message])
  91. # Appends the user's message with escaping.
  92. # Remember to escape both the player name and message contents.
  93. func append_chat_line_escaped(username, message):
  94. append_text("%s: [color=green]%s[/color]\n" % [escape_bbcode(username), escape_bbcode(message)])
  95. Stripping BBCode tags
  96. ---------------------
  97. For certain use cases, it can be desired to remove BBCode tags from the string.
  98. This is useful when displaying the RichTextLabel's text in another Control that
  99. does not support BBCode (such as a tooltip):
  100. .. code::
  101. extends RichTextLabel
  102. func _ready():
  103. var regex = RegEx.new()
  104. regex.compile("\\[.*?\\]")
  105. var text_without_tags = regex.sub(text, "", true)
  106. # `text_without_tags` contains the text with all BBCode tags removed.
  107. .. note::
  108. Removing BBCode tags entirely isn't advised for user input, as it can
  109. modify the displayed text without users understanding why part of their
  110. message was removed.
  111. :ref:`Escaping user input <doc_bbcode_in_richtextlabel_handling_user_input_safely>`
  112. should be preferred instead.
  113. Performance
  114. -----------
  115. In most cases, you can use BBCode directly as-is since text formatting is rarely
  116. a heavy task. However, with particularly large RichTextLabels (such as console
  117. logs spanning thousands of lines), you may encounter stuttering during gameplay
  118. when the RichTextLabel's text is updated.
  119. There are several ways to alleviate this:
  120. - Use the ``append_text()`` function instead of appending to the ``text``
  121. property. This function will only parse BBCode for the added text, rather than
  122. parsing BBCode from the entire ``text`` property.
  123. - Use ``push_[tag]()`` and ``pop()`` functions to add tags to RichTextLabel instead of
  124. using BBCode.
  125. - Enable the **Threading > Threaded** property in RichTextLabel. This won't
  126. speed up processing, but it will prevent the main thread from blocking, which
  127. avoids stuttering during gameplay. Only enable threading if it's actually
  128. needed in your project, as threading has some overhead.
  129. .. _doc_bbcode_in_richtextlabel_use_functions:
  130. Using push_[tag]() and pop() functions instead of BBCode
  131. --------------------------------------------------------
  132. If you don't want to use BBCode for performance reasons, you can use functions
  133. provided by RichTextLabel to create formatting tags without writing BBCode in
  134. the text.
  135. Every BBCode tag (including effects) has a ``push_[tag]()`` function (where
  136. ``[tag]`` is the tag's name). There are also a few convenience functions
  137. available, such as ``push_bold_italics()`` that combines both ``push_bold()``
  138. and ``push_italics()`` into a single tag. See the
  139. :ref:`RichTextLabel class reference <class_RichTextLabel>` for a complete list of
  140. ``push_[tag]()`` functions.
  141. The ``pop()`` function is used to end *any* tag. Since BBCode is a tag *stack*,
  142. using ``pop()`` will close the most recently started tags first.
  143. The following script will result in the same visual output as using
  144. ``BBCode [color=green]test [i]example[/i][/color]``:
  145. ::
  146. extends RichTextLabel
  147. func _ready():
  148. append_text("BBCode ") # Trailing space separates words from each other.
  149. push_color(Color.GREEN)
  150. append_text("test ") # Trailing space separates words from each other.
  151. push_italics()
  152. append_text("example")
  153. pop() # Ends the tag opened by `push_italics()`.
  154. pop() # Ends the tag opened by `push_color()`.
  155. .. warning::
  156. Do **not** set the ``text`` property directly when using formatting functions.
  157. Appending to the ``text`` property will erase all modifications made to the
  158. RichTextLabel using the ``append_text()``, ``push_[tag]()`` and ``pop()``
  159. functions.
  160. Reference
  161. ---------
  162. .. list-table::
  163. :class: wrap-normal
  164. :width: 100%
  165. :widths: 60 40
  166. * - Tag
  167. - Example
  168. * - | **b**
  169. | Makes ``{text}`` use the bold (or bold italics) font of ``RichTextLabel``.
  170. - ``[b]{text}[/b]``
  171. * - | **i**
  172. | Makes ``{text}`` use the italics (or bold italics) font of ``RichTextLabel``.
  173. - ``[i]{text}[/i]``
  174. * - | **u**
  175. | Makes ``{text}`` underlined.
  176. - ``[u]{text}[/u]``
  177. * - | **s**
  178. | Makes ``{text}`` strikethrough.
  179. - ``[s]{text}[/s]``
  180. * - | **code**
  181. | Makes ``{text}`` use the mono font of ``RichTextLabel``.
  182. - ``[code]{text}[/code]``
  183. * - | **p**
  184. | Adds new paragraph with ``{text}``. Supports configuration options,
  185. see :ref:`doc_bbcode_in_richtextlabel_paragraph_options`.
  186. - | ``[p]{text}[/p]``
  187. | ``[p {options}]{text}[/p]``
  188. * - | **center**
  189. | Makes ``{text}`` horizontally centered.
  190. | Same as ``[p align=center]``.
  191. - ``[center]{text}[/center]``
  192. * - | **left**
  193. | Makes ``{text}`` horizontally left-aligned.
  194. | Same as ``[p align=left]``.
  195. - ``[left]{text}[/left]``
  196. * - | **right**
  197. | Makes ``{text}`` horizontally right-aligned.
  198. | Same as ``[p align=right]``.
  199. - ``[right]{text}[/right]``
  200. * - | **fill**
  201. | Makes ``{text}`` fill the full width of ``RichTextLabel``.
  202. | Same as ``[p align=fill]``.
  203. - ``[fill]{text}[/fill]``
  204. * - | **indent**
  205. | Indents ``{text}`` once.
  206. The indentation width is the same as with ``[ul]`` or ``[ol]``, but without a bullet point.
  207. - ``[indent]{text}[/indent]``
  208. * - | **url**
  209. | Creates a hyperlink (underlined and clickable text). Can contain optional
  210. ``{text}`` or display ``{link}`` as is.
  211. | **Must be handled with the "meta_clicked" signal to have an effect,** see :ref:`doc_bbcode_in_richtextlabel_handling_url_tag_clicks`.
  212. - | ``[url]{link}[/url]``
  213. | ``[url={link}]{text}[/url]``
  214. * - | **hint**
  215. | Creates a tooltip hint that is displayed when hovering the text with the mouse.
  216. Tooltip text should not be quoted (quotes will appear as-is in the tooltip otherwise).
  217. - | ``[hint={tooltip text displayed on hover}]{text}[/hint]``
  218. * - | **img**
  219. | Inserts an image from the ``{path}`` (can be any valid :ref:`class_Texture2D` resource).
  220. | If ``{width}`` is provided, the image will try to fit that width maintaining
  221. the aspect ratio.
  222. | If both ``{width}`` and ``{height}`` are provided, the image will be scaled
  223. to that size.
  224. | If ``{valign}`` configuration is provided, the image will try to align to the
  225. surrounding text, see :ref:`doc_bbcode_in_richtextlabel_image_alignment`.
  226. | Supports configuration options, see :ref:`doc_bbcode_in_richtextlabel_image_options`.
  227. - | ``[img]{path}[/img]``
  228. | ``[img={width}]{path}[/img]``
  229. | ``[img={width}x{height}]{path}[/img]``
  230. | ``[img={valign}]{path}[/img]``
  231. | ``[img {options}]{path}[/img]``
  232. * - | **font**
  233. | Makes ``{text}`` use a font resource from the ``{path}``.
  234. | Supports configuration options, see :ref:`doc_bbcode_in_richtextlabel_font_options`.
  235. - | ``[font={path}]{text}[/font]``
  236. | ``[font {options}]{text}[/font]``
  237. * - | **font_size**
  238. | Use custom font size for ``{text}``.
  239. - ``[font_size={size}]{text}[/font_size]``
  240. * - | **dropcap**
  241. | Use a different font size and color for ``{text}``, while making the tag's contents
  242. span multiple lines if it's large enough.
  243. | A `drop cap <https://www.computerhope.com/jargon/d/dropcap.htm>`__ is typically one
  244. uppercase character, but ``[dropcap]`` supports containing multiple characters.
  245. ``margins`` values are comma-separated and can be positive, zero or negative.
  246. Negative top and bottom margins are particularly useful to allow the rest of
  247. the paragraph to display below the dropcap.
  248. - ``[dropcap font_size={size} color={color} margins={left},{top},{right},{bottom}]{text}[/dropcap]``
  249. * - | **opentype_features**
  250. | Enables custom OpenType font features for ``{text}``. Features must be provided as
  251. a comma-separated ``{list}``.
  252. - | ``[opentype_features={list}]``
  253. | ``{text}``
  254. | ``[/opentype_features]``
  255. * - | **lang**
  256. | Overrides the language for ``{text}`` that is set by the **BiDi > Language** property
  257. in :ref:`class_RichTextLabel`. ``{code}`` must be an ISO :ref:`language code <doc_locales>`.
  258. This can be used to enforce the use of a specific script for a language without
  259. starting a new paragraph. Some font files may contain script-specific substitutes,
  260. in which case they will be used.
  261. - ``[lang={code}]{text}[/color]``
  262. * - | **color**
  263. | Changes the color of ``{text}``. Color must be provided by a common name (see
  264. :ref:`doc_bbcode_in_richtextlabel_named_colors`) or using the HEX format (e.g.
  265. ``#ff00ff``, see :ref:`doc_bbcode_in_richtextlabel_hex_colors`).
  266. - ``[color={code/name}]{text}[/color]``
  267. * - | **bgcolor**
  268. | Draws the color behind ``{text}``. This can be used to highlight text.
  269. Accepts same values as the ``color`` tag.
  270. - ``[bgcolor={code/name}]{text}[/bgcolor]``
  271. * - | **fgcolor**
  272. | Draws the color in front of ``{text}``. This can be used to "redact" text by using
  273. an opaque foreground color. Accepts same values as the ``color`` tag.
  274. - ``[fgcolor={code/name}]{text}[/fgcolor]``
  275. * - | **outline_size**
  276. | Use custom font outline size for ``{text}``.
  277. - | ``[outline_size={size}]``
  278. | ``{text}``
  279. | ``[/outline_size]``
  280. * - | **outline_color**
  281. | Use custom outline color for ``{text}``. Accepts same values as the ``color`` tag.
  282. - | ``[outline_color={code/name}]``
  283. | ``{text}``
  284. | ``[/outline_color]``
  285. * - | **table**
  286. | Creates a table with the ``{number}`` of columns. Use the ``cell`` tag to define
  287. table cells.
  288. - ``[table={number}]{cells}[/table]``
  289. * - | **cell**
  290. | Adds a cell with ``{text}`` to the table.
  291. | If ``{ratio}`` is provided, the cell will try to expand to that value proportionally
  292. to other cells and their ratio values.
  293. | Supports configuration options, see :ref:`doc_bbcode_in_richtextlabel_cell_options`.
  294. - | ``[cell]{text}[/cell]``
  295. | ``[cell={ratio}]{text}[/cell]``
  296. | ``[cell {options}]{text}[/cell]``
  297. * - | **ul**
  298. | Adds an unordered list. List ``{items}`` must be provided by putting one item per
  299. line of text.
  300. | The bullet point can be customized using the ``{bullet}`` parameter,
  301. see :ref:`doc_bbcode_in_richtextlabel_unordered_list_bullet`.
  302. - | ``[ul]{items}[/ul]``
  303. | ``[ul bullet={bullet}]{items}[/ul]``
  304. * - | **ol**
  305. | Adds an ordered (numbered) list of the given ``{type}`` (see :ref:`doc_bbcode_in_richtextlabel_list_types`).
  306. List ``{items}`` must be provided by putting one item per line of text.
  307. - ``[ol type={type}]{items}[/ol]``
  308. * - | **lb**, **rb**
  309. | Adds ``[`` and ``]`` respectively. Allows escaping BBCode markup.
  310. | These are self-closing tags, which means you do not need to close them
  311. (and there is no ``[/lb]`` or ``[/rb]`` closing tag).
  312. - | ``[lb]b[rb]text[lb]/b[rb]`` will display as ``[b]text[/b]``.
  313. * - | Several Unicode control characters can be added using their own self-closing tags.
  314. | This can result in easier maintenance compared to pasting those
  315. | control characters directly in the text.
  316. - | ``[lrm]`` (left-to-right mark), ``[rlm]`` (right-to-left mark), ``[lre]`` (left-to-right embedding),
  317. | ``[rle]`` (right-to-left embedding), ``[lro]`` (left-to-right override), ``[rlo]`` (right-to-left override),
  318. | ``[pdf]`` (pop directional formatting), ``[alm]`` (Arabic letter mark), ``[lri]`` (left-to-right isolate),
  319. | ``[rli]`` (right-to-left isolate), ``[fsi]`` (first strong isolate), ``[pdi]`` (pop directional isolate),
  320. | ``[zwj]`` (zero-width joiner), ``[zwnj]`` (zero-width non-joiner), ``[wj]`` (word joiner),
  321. | ``[shy]`` (soft hyphen)
  322. .. note::
  323. Tags for bold (``[b]``) and italics (``[i]``) formatting work best if the
  324. appropriate custom fonts are set up in the RichTextLabelNode's theme
  325. overrides. If no custom bold or italic fonts are defined,
  326. `faux bold and italic fonts <https://fonts.google.com/knowledge/glossary/faux_fake_pseudo_synthesized>`__
  327. will be generated by Godot. These fonts rarely look good in comparison to hand-made bold/italic font variants.
  328. The monospaced (``[code]``) tag **only** works if a custom font is set up in
  329. the RichTextLabel node's theme overrides. Otherwise, monospaced text will use the regular font.
  330. There are no BBCode tags to control vertical centering of text yet.
  331. Options can be skipped for all tags.
  332. .. _doc_bbcode_in_richtextlabel_paragraph_options:
  333. Paragraph options
  334. ~~~~~~~~~~~~~~~~~
  335. - **align**
  336. +-----------+--------------------------------------------+
  337. | `Values` | ``left``, ``center``, ``right``, ``fill`` |
  338. +-----------+--------------------------------------------+
  339. | `Default` | ``left`` |
  340. +-----------+--------------------------------------------+
  341. Text horizontal alignment.
  342. - **bidi_override**, **st**
  343. +-----------+---------------------------------------------------------------------------+
  344. | `Values` | ``default``, ``uri``, ``file``, ``email``, ``list``, ``none``, ``custom`` |
  345. +-----------+---------------------------------------------------------------------------+
  346. | `Default` | ``default`` |
  347. +-----------+---------------------------------------------------------------------------+
  348. Structured text override.
  349. - **direction**, **dir**
  350. +-----------+--------------------------------------------+
  351. | `Values` | ``ltr``, ``rtl``, ``auto`` |
  352. +-----------+--------------------------------------------+
  353. | `Default` | Inherit |
  354. +-----------+--------------------------------------------+
  355. Base BiDi direction.
  356. - **language**, **lang**
  357. +-----------+--------------------------------------------+
  358. | `Values` | ISO language codes. See :ref:`doc_locales` |
  359. +-----------+--------------------------------------------+
  360. | `Default` | Inherit |
  361. +-----------+--------------------------------------------+
  362. Locale override. Some font files may contain script-specific substitutes, in which case they will be used.
  363. - **tab_stops**
  364. +-----------+----------------------------------------------------+
  365. | `Values` | List of floating-point numbers, e.g. ``10.0,30.0`` |
  366. +-----------+----------------------------------------------------+
  367. | `Default` | Width of the space character in the font |
  368. +-----------+----------------------------------------------------+
  369. Overrides the horizontal offsets for each tab character. When the end of the
  370. list is reached, the tab stops will loop over. For example, if you set
  371. ``tab_stops`` to ``10.0,30.0``, the first tab will be at ``10`` pixels, the
  372. second tab will be at ``10 + 30 = 40`` pixels, and the third tab will be at
  373. ``10 + 30 + 10 = 50`` pixels from the origin of the RichTextLabel.
  374. .. _doc_bbcode_in_richtextlabel_handling_url_tag_clicks:
  375. Handling ``[url]`` tag clicks
  376. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  377. By default, ``[url]`` tags do nothing when clicked. This is to allow flexible use
  378. of ``[url]`` tags rather than limiting them to opening URLs in a web browser.
  379. To handle clicked ``[url]`` tags, connect the ``RichTextLabel`` node's
  380. :ref:`meta_clicked <class_RichTextLabel_signal_meta_clicked>` signal to a script function.
  381. For example, the following method can be connected to ``meta_clicked`` to open
  382. clicked URLs using the user's default web browser::
  383. # This assumes RichTextLabel's `meta_clicked` signal was connected to
  384. # the function below using the signal connection dialog.
  385. func _richtextlabel_on_meta_clicked(meta):
  386. # `meta` is not guaranteed to be a String, so convert it to a String
  387. # to avoid script errors at run-time.
  388. OS.shell_open(str(meta))
  389. For more advanced use cases, it's also possible to store JSON in an ``[url]``
  390. tag's option and parse it in the function that handles the ``meta_clicked`` signal.
  391. For example:
  392. .. code-block:: none
  393. [url={"example": "value"}]JSON[/url]
  394. .. _doc_bbcode_in_richtextlabel_image_options:
  395. Image options
  396. ~~~~~~~~~~~~~
  397. - **color**
  398. +-----------+--------------------------------------------+
  399. | `Values` | Color name or color in HEX format |
  400. +-----------+--------------------------------------------+
  401. | `Default` | Inherit |
  402. +-----------+--------------------------------------------+
  403. Color tint of the image (modulation).
  404. - **height**
  405. +-----------+--------------------------------------------+
  406. | `Values` | Number in pixels |
  407. +-----------+--------------------------------------------+
  408. | `Default` | Inherit |
  409. +-----------+--------------------------------------------+
  410. Target height of the image.
  411. - **width**
  412. +-----------+--------------------------------------------+
  413. | `Values` | Number in pixels |
  414. +-----------+--------------------------------------------+
  415. | `Default` | Inherit |
  416. +-----------+--------------------------------------------+
  417. Target width of the image.
  418. - **region**
  419. +-----------+--------------------------------------------+
  420. | `Values` | x,y,width,height in pixels |
  421. +-----------+--------------------------------------------+
  422. | `Default` | Inherit |
  423. +-----------+--------------------------------------------+
  424. Region rect of the image. This can be used to display a single image from a spritesheet.
  425. .. _doc_bbcode_in_richtextlabel_image_alignment:
  426. Image vertical alignment
  427. ~~~~~~~~~~~~~~~~~~~~~~~~
  428. When a vertical alignment value is provided with the ``[img]`` tag the image
  429. will try to align itself against the surrounding text. Alignment is performed
  430. using a vertical point of the image and a vertical point of the text. There are
  431. 3 possible points on the image (``top``, ``center``, and ``bottom``) and 4
  432. possible points on the text (``top``, ``center``, ``baseline``, and ``bottom``),
  433. which can be used in any combination.
  434. To specify both points, use their full or short names as a value of the image tag:
  435. .. code-block:: none
  436. [img=top,bottom]
  437. [img=center,center]
  438. You can also specify just one value (``top``, ``center``, or ``bottom``) to make
  439. use of a corresponding preset (``top-top``, ``center-center``, and ``bottom-bottom``
  440. respectively).
  441. Short names for the values are ``t`` (``top``), ``c`` (``center``), ``l`` (``baseline``),
  442. and ``b`` (``bottom``).
  443. .. _doc_bbcode_in_richtextlabel_font_options:
  444. Font options
  445. ~~~~~~~~~~~~
  446. - **name**, **n**
  447. +-----------+--------------------------------------------+
  448. | `Values` | A valid Font resource path. |
  449. +-----------+--------------------------------------------+
  450. | `Default` | Inherit |
  451. +-----------+--------------------------------------------+
  452. Font resource path.
  453. - **size**, **s**
  454. +-----------+--------------------------------------------+
  455. | `Values` | Number in pixels. |
  456. +-----------+--------------------------------------------+
  457. | `Default` | Inherit |
  458. +-----------+--------------------------------------------+
  459. Custom font size.
  460. .. _doc_bbcode_in_richtextlabel_named_colors:
  461. Named colors
  462. ~~~~~~~~~~~~
  463. For tags that allow specifying a color by name you can use names of the constants from
  464. the built-in :ref:`class_Color` class. Named classes can be specified in a number of
  465. styles using different casings: ``DARK_RED``, ``DarkRed``, and ``darkred`` will give
  466. the same exact result.
  467. .. _doc_bbcode_in_richtextlabel_hex_colors:
  468. Hexadecimal color codes
  469. ~~~~~~~~~~~~~~~~~~~~~~~
  470. For opaque RGB colors, any valid 6-digit hexadecimal code is supported, e.g.
  471. ``[color=#ffffff]white[/color]``. Shorthand RGB color codes such as ``#6f2``
  472. (equivalent to ``#66ff22``) are also supported.
  473. For transparent RGB colors, any RGBA 8-digit hexadecimal code can be used,
  474. e.g. ``[color=#ffffff88]translucent white[/color]``. Note that the alpha channel
  475. is the **last** component of the color code, not the first one. Short RGBA
  476. color codes such as ``#6f28`` (equivalent to ``#66ff2288``) are supported as well.
  477. .. _doc_bbcode_in_richtextlabel_cell_options:
  478. Cell options
  479. ~~~~~~~~~~~~
  480. - **expand**
  481. +-----------+--------------------------------------------+
  482. | `Values` | Integer number |
  483. +-----------+--------------------------------------------+
  484. | `Default` | 1 |
  485. +-----------+--------------------------------------------+
  486. Cell expansion ratio. This defines which cells will try to expand to
  487. proportionally to other cells and their expansion ratios.
  488. - **border**
  489. +-----------+--------------------------------------------+
  490. | `Values` | Color name or color in HEX format |
  491. +-----------+--------------------------------------------+
  492. | `Default` | Inherit |
  493. +-----------+--------------------------------------------+
  494. Cell border color.
  495. - **bg**
  496. +-----------+--------------------------------------------+
  497. | `Values` | Color name or color in HEX format |
  498. +-----------+--------------------------------------------+
  499. | `Default` | Inherit |
  500. +-----------+--------------------------------------------+
  501. Cell background color. For alternating odd/even row backgrounds,
  502. you can use ``bg=odd_color,even_color``.
  503. .. _doc_bbcode_in_richtextlabel_unordered_list_bullet:
  504. Unordered list bullet
  505. ~~~~~~~~~~~~~~~~~~~~~
  506. By default, the ``[ul]`` tag uses the ``U+2022`` "Bullet" Unicode glyph as the
  507. bullet character. This behavior is similar to web browsers. The bullet character
  508. can be customized using ``[ul bullet={bullet}]``. If provided, this ``{bullet}``
  509. parameter must be a *single* character with no enclosing quotes (for example,
  510. ``[bullet=*]``). Additional characters are ignored. The bullet character's
  511. width does not affect the list's formatting.
  512. See `Bullet (typography) on Wikipedia <https://en.wikipedia.org/wiki/Bullet_(typography)>`__
  513. for a list of common bullet characters that you can paste directly in the ``bullet`` parameter.
  514. .. _doc_bbcode_in_richtextlabel_list_types:
  515. Ordered list types
  516. ~~~~~~~~~~~~~~~~~~
  517. Ordered lists can be used to automatically mark items with numbers
  518. or letters in ascending order. This tag supports the following
  519. type options:
  520. - ``1`` - Numbers, using language specific numbering system if possible.
  521. - ``a``, ``A`` - Lower and upper case Latin letters.
  522. - ``i``, ``I`` - Lower and upper case Roman numerals.
  523. Text effects
  524. ------------
  525. BBCode can also be used to create different text effects that can optionally be
  526. animated. Five customizable effects are provided out of the box, and you can
  527. easily create your own. By default, animated effects will pause
  528. :ref:`when the SceneTree is paused <doc_pausing_games>`. You can change this
  529. behavior by adjusting the RichTextLabel's **Process > Mode** property.
  530. All examples below mention the default values for options in the listed tag format.
  531. .. note::
  532. Text effects that move characters' position may result in characters being
  533. clipped by the RichTextLabel node bounds.
  534. You can resolve this by disabling **Control > Layout > Clip Contents** in
  535. the inspector after selecting the RichTextLabel node, or ensuring there is
  536. enough margin added around the text by using line breaks above and below the
  537. line using the effect.
  538. Pulse
  539. ~~~~~
  540. .. image:: img/bbcode_in_richtextlabel_effect_pulse.webp
  541. Pulse creates an animated pulsing effect that multiplies each character's
  542. opacity and color. It can be used to bring attention to specific text. Its tag
  543. format is ``[pulse freq=1.0 color=#ffffff40 ease=-2.0]{text}[/pulse]``.
  544. ``freq`` controls the frequency of the half-pulsing cycle (higher is faster). A
  545. full pulsing cycle takes ``2 * (1.0 / freq)`` seconds. ``color`` is the target
  546. color multiplier for blinking. The default mostly fades out text, but not
  547. entirely. ``ease`` is the easing function exponent to use. Negative values
  548. provide in-out easing, which is why the default is ``-2.0``.
  549. Wave
  550. ~~~~
  551. .. image:: img/bbcode_in_richtextlabel_effect_wave.webp
  552. Wave makes the text go up and down. Its tag format is
  553. ``[wave amp=50.0 freq=5.0 connected=1]{text}[/wave]``.
  554. ``amp`` controls how high and low the effect goes, and ``freq`` controls how
  555. fast the text goes up and down. A ``freq`` value of ``0`` will result in no
  556. visible waves, and negative ``freq`` values won't display any waves either. If
  557. ``connected`` is ``1`` (default), glyphs with ligatures will be moved together.
  558. If ``connected`` is ``0``, each glyph is moved individually even if they are
  559. joined by ligatures. This can work around certain rendering issues with font
  560. ligatures.
  561. Tornado
  562. ~~~~~~~
  563. .. image:: img/bbcode_in_richtextlabel_effect_tornado.webp
  564. Tornado makes the text move around in a circle. Its tag format is
  565. ``[tornado radius=10.0 freq=1.0 connected=1]{text}[/tornado]``.
  566. ``radius`` is the radius of the circle that controls the offset, ``freq`` is how
  567. fast the text moves in a circle. A ``freq`` value of ``0`` will pause the
  568. animation, while negative ``freq`` will play the animation backwards. If
  569. ``connected`` is ``1`` (default), glyphs with ligatures will be moved together.
  570. If ``connected`` is ``0``, each glyph is moved individually even if they are
  571. joined by ligatures. This can work around certain rendering issues with font
  572. ligatures.
  573. Shake
  574. ~~~~~
  575. .. image:: img/bbcode_in_richtextlabel_effect_shake.webp
  576. Shake makes the text shake. Its tag format is
  577. ``[shake rate=20.0 level=5 connected=1]{text}[/shake]``.
  578. ``rate`` controls how fast the text shakes, ``level`` controls how far the text
  579. is offset from the origin. If ``connected`` is ``1`` (default), glyphs with
  580. ligatures will be moved together. If ``connected`` is ``0``, each glyph is moved
  581. individually even if they are joined by ligatures. This can work around certain
  582. rendering issues with font ligatures.
  583. Fade
  584. ~~~~
  585. .. image:: img/bbcode_in_richtextlabel_effect_fade.webp
  586. Fade creates a static fade effect that multiplies each character's opacity.
  587. Its tag format is ``[fade start=4 length=14]{text}[/fade]``.
  588. ``start`` controls the starting position of the falloff relative to where the fade
  589. command is inserted, ``length`` controls over how many characters should the fade
  590. out take place.
  591. Rainbow
  592. ~~~~~~~
  593. .. image:: img/bbcode_in_richtextlabel_effect_rainbow.webp
  594. Rainbow gives the text a rainbow color that changes over time. Its tag format is
  595. ``[rainbow freq=1.0 sat=0.8 val=0.8]{text}[/rainbow]``.
  596. ``freq`` is the number of full rainbow cycles per second, ``sat`` is the
  597. saturation of the rainbow, ``val`` is the value of the rainbow. A ``freq`` value
  598. of ``0`` will pause the animation, while negative ``freq`` will play the
  599. animation backwards.
  600. Font outlines are *not* affected by the rainbow effect (they keep their original color).
  601. Existing font colors are overridden by the rainbow effect. However, CanvasItem's
  602. **Modulate** and **Self Modulate** properties will affect how the rainbow effect
  603. looks, as modulation multiplies its final colors.
  604. Custom BBCode tags and text effects
  605. -----------------------------------
  606. You can extend the :ref:`class_RichTextEffect` resource type to create your own custom
  607. BBCode tags. Create a new script file that extends the :ref:`class_RichTextEffect` resource type
  608. and give the script a ``class_name`` so that the effect can be selected in the inspector.
  609. Add the ``@tool`` annotation to your GDScript file if you wish to have these custom effects
  610. run within the editor itself. The RichTextLabel does not need to have a script attached,
  611. nor does it need to be running in ``tool`` mode. The new effect can be registered in
  612. the Inspector by adding it to the **Markup > Custom Effects** array, or in code with the
  613. :ref:`install_effect() <class_RichTextLabel_method_install_effect>` method:
  614. .. figure:: img/bbcode_in_richtextlabel_selecting_custom_richtexteffect.webp
  615. :align: center
  616. :alt: Selecting a custom RichTextEffect after saving a script that extends RichTextEffect with a ``class_name``
  617. Selecting a custom RichTextEffect after saving a script that extends RichTextEffect with a ``class_name``
  618. .. warning::
  619. If the custom effect is not registered within the RichTextLabel's
  620. **Markup > Custom Effects** property, no effect will be visible and the original
  621. tag will be left as-is.
  622. There is only one function that you need to extend: ``_process_custom_fx(char_fx)``.
  623. Optionally, you can also provide a custom BBCode identifier simply by adding a member
  624. name ``bbcode``. The code will check the ``bbcode`` property automatically or will
  625. use the name of the file to determine what the BBCode tag should be.
  626. ``_process_custom_fx``
  627. ~~~~~~~~~~~~~~~~~~~~~~
  628. This is where the logic of each effect takes place and is called once per glyph
  629. during the draw phase of text rendering. This passes in a :ref:`class_CharFXTransform`
  630. object, which holds a few variables to control how the associated glyph is rendered:
  631. - ``identity`` specifies which custom effect is being processed. You should use that for
  632. code flow control.
  633. - ``outline`` is ``true`` if effect is called for drawing text outline.
  634. - ``range`` tells you how far into a given custom effect block you are in as an
  635. index.
  636. - ``elapsed_time`` is the total amount of time the text effect has been running.
  637. - ``visible`` will tell you whether the glyph is visible or not and will also allow you
  638. to hide a given portion of text.
  639. - ``offset`` is an offset position relative to where the given glyph should render under
  640. normal circumstances.
  641. - ``color`` is the color of a given glyph.
  642. - ``glyph_index`` and ``font`` is glyph being drawn and font data resource used to draw it.
  643. - Finally, ``env`` is a :ref:`class_Dictionary` of parameters assigned to a given custom
  644. effect. You can use :ref:`get() <class_Dictionary_method_get>` with an optional default value
  645. to retrieve each parameter, if specified by the user. For example ``[custom_fx spread=0.5
  646. color=#FFFF00]test[/custom_fx]`` would have a float ``spread`` and Color ``color``
  647. parameters in its ``env`` Dictionary. See below for more usage examples.
  648. The last thing to note about this function is that it is necessary to return a boolean
  649. ``true`` value to verify that the effect processed correctly. This way, if there's a problem
  650. with rendering a given glyph, it will back out of rendering custom effects entirely until
  651. the user fixes whatever error cropped up in their custom effect logic.
  652. Here are some examples of custom effects:
  653. Ghost
  654. ~~~~~
  655. ::
  656. @tool
  657. extends RichTextEffect
  658. class_name RichTextGhost
  659. # Syntax: [ghost freq=5.0 span=10.0][/ghost]
  660. # Define the tag name.
  661. var bbcode = "ghost"
  662. func _process_custom_fx(char_fx):
  663. # Get parameters, or use the provided default value if missing.
  664. var speed = char_fx.env.get("freq", 5.0)
  665. var span = char_fx.env.get("span", 10.0)
  666. var alpha = sin(char_fx.elapsed_time * speed + (char_fx.range.x / span)) * 0.5 + 0.5
  667. char_fx.color.a = alpha
  668. return true
  669. Matrix
  670. ~~~~~~
  671. ::
  672. @tool
  673. extends RichTextEffect
  674. class_name RichTextMatrix
  675. # Syntax: [matrix clean=2.0 dirty=1.0 span=50][/matrix]
  676. # Define the tag name.
  677. var bbcode = "matrix"
  678. # Gets TextServer for retrieving font information.
  679. func get_text_server():
  680. return TextServerManager.get_primary_interface()
  681. func _process_custom_fx(char_fx):
  682. # Get parameters, or use the provided default value if missing.
  683. var clear_time = char_fx.env.get("clean", 2.0)
  684. var dirty_time = char_fx.env.get("dirty", 1.0)
  685. var text_span = char_fx.env.get("span", 50)
  686. var value = char_fx.glyph_index
  687. var matrix_time = fmod(char_fx.elapsed_time + (char_fx.range.x / float(text_span)), \
  688. clear_time + dirty_time)
  689. matrix_time = 0.0 if matrix_time < clear_time else \
  690. (matrix_time - clear_time) / dirty_time
  691. if matrix_time > 0.0:
  692. value = int(1 * matrix_time * (126 - 65))
  693. value %= (126 - 65)
  694. value += 65
  695. char_fx.glyph_index = get_text_server().font_get_glyph_index(char_fx.font, 1, value, 0)
  696. return true
  697. This will add a few new BBCode commands, which can be used like so:
  698. .. code-block:: none
  699. [center][ghost]This is a custom [matrix]effect[/matrix][/ghost] made in
  700. [pulse freq=5.0 height=2.0][pulse color=#00FFAA freq=2.0]GDScript[/pulse][/pulse].[/center]