bbcode_in_richtextlabel.rst 34 KB

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