How to escape characters in Pango markup?
Asked Answered
S

3

13

My program has a gtk.TreeView which displays a gtk.ListStore. The gtk.ListStore contains strings like this:

"<span size='medium'><b>"+site_title+"</b></span>"+"\n"+URL

Where URL is (obviously) a URL string. Sometimes there are characters in URL that cause pango to fail to parse the markup.

Is there a way to escape URL as a whole so that pango will just ignore it so it will be displayed literally? If not, how should I "escape" special characters in URLs?

Sulphide answered 19/11, 2009 at 0:17 Comment(0)
P
2

You need to escape the values. I'm not sure what exact format Pango requires, but it looks like HTML and the cgi.escape function may be all you need.

import cgi
print "<span size='medium'><b>%s</b></span>\n%s" %
      (cgi.escape(site_title), cgi.escape(URL))
Pamper answered 19/11, 2009 at 2:43 Comment(0)
M
22

glib.markup_escape_text may be a more canonical approach when using GTK.

Montserrat answered 25/11, 2009 at 18:18 Comment(2)
In the latest version of PyGTK it appears to be gobject.markup_escape_textDaman
The link in the answer is broken; docs appear to be here: docs.gtk.org/glib/func.markup_escape_text.htmlPetunia
P
2

You need to escape the values. I'm not sure what exact format Pango requires, but it looks like HTML and the cgi.escape function may be all you need.

import cgi
print "<span size='medium'><b>%s</b></span>\n%s" %
      (cgi.escape(site_title), cgi.escape(URL))
Pamper answered 19/11, 2009 at 2:43 Comment(0)
T
0

//edit queue is full, so post here

GLib.markup_escape_text from PyGObject

demo

>>> from gi.repository import GLib
>>> GLib.markup_escape_text('abc \b \f < & >')
'abc &#x8; &#xc; &lt; &amp; &gt;'
>>> 

py api docs
https://lazka.github.io/pgi-docs/#GLib-2.0/functions.html#GLib.markup_escape_text https://pygobject.readthedocs.io

c api docs
https://docs.gtk.org/glib/func.markup_escape_text.html

Torrence answered 17/11, 2022 at 1:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.