Diff options
authorBryce Kwon <bryce@brycekwon.com>
committerBryce Kwon <bryce@brycekwon.com>
commit
parent
tree
download
Map the markup characters to entities in one place
-rw-r--r--source/html.c62
1 file changed, 34 insertions, 28 deletions
diff --git a/source/html.c b/source/html.c
index 437a0ae..7ad4642 100644
--- a/source/html.c
+++ b/source/html.c
@@ -218,6 +218,24 @@ void html_vtxtf(const char *format, va_list ap)
strbuf_release(&sb);
}
+/*
+ * The entity for a character that page text would otherwise read as markup, or
+ * NULL for any other character.
+ */
+static const char *txt_entity(int c)
+{
+ switch (c) {
+ case '<':
+ return "&lt;";
+ case '>':
+ return "&gt;";
+ case '&':
+ return "&amp;";
+ default:
+ return NULL;
+ }
+}
+
void html_txt(const char *txt)
{
if (txt)
@@ -234,15 +252,11 @@ ssize_t html_ntxt(const char *txt, size_t len)
left = (ssize_t)len;
while (p && *p && left--) {
- int c = *p;
- if (c == '<' || c == '>' || c == '&') {
+ const char *entity = txt_entity(*p);
+
+ if (entity) {
html_raw(txt, p - txt);
- if (c == '>')
- html("&gt;");
- else if (c == '<')
- html("&lt;");
- else if (c == '&')
- html("&amp;");
+ html(entity);
txt = p + 1;
}
p++;
@@ -308,16 +322,10 @@ void html_blob_txt(const char *txt, size_t len)
const char *p;
for (p = txt; p < end; p++) {
- const char *entity = NULL, *esc = NULL;
+ const char *entity = txt_entity(*p), *esc = NULL;
size_t width = 1;
- if (*p == '<')
- entity = "&lt;";
- else if (*p == '>')
- entity = "&gt;";
- else if (*p == '&')
- entity = "&amp;";
- else
+ if (!entity)
esc = html_line_break_escape(p, end, &width);
if (!entity && !esc)
continue;
@@ -355,19 +363,17 @@ void html_attr(const char *txt)
const char *p = txt;
while (p && *p) {
- int c = *p;
- if (c == '<' || c == '>' || c == '\'' || c == '\"' || c == '&') {
+ const char *entity;
+
+ if (*p == '\'')
+ entity = "&#x27;";
+ else if (*p == '"')
+ entity = "&quot;";
+ else
+ entity = txt_entity(*p);
+ if (entity) {
html_raw(txt, p - txt);
- if (c == '>')
- html("&gt;");
- else if (c == '<')
- html("&lt;");
- else if (c == '\'')
- html("&#x27;");
- else if (c == '"')
- html("&quot;");
- else if (c == '&')
- html("&amp;");
+ html(entity);
txt = p + 1;
}
p++;