nihdoc

WIP markup parser (txt -> html)
git clone git://git.alexkarle.com.com/blag
Log | Files | Refs | README | LICENSE

commit f64a1a60edde970676a54e31fbc333c58ea38893 (patch)
parent 8765abd72c999a0b626bfb0e80bb9f97e3bb8329
Author: Alex Karle <alex@alexkarle.com>
Date:   Thu, 23 Dec 2021 20:32:50 -0500

refactor: Condense all inline format edits into helper

Italics, bold, and code all have the same flow (minus the fact that the
first two have no effect in code). By abstracting that flow into a
helper, it cuts the complexity of the core switch a bit!

Diffstat:
Mblag.c | 54+++++++++++++++++-------------------------------------
1 file changed, 17 insertions(+), 37 deletions(-)

diff --git a/blag.c b/blag.c @@ -27,6 +27,7 @@ enum Link { }; typedef struct State { + int c; enum Block in; enum Link in_link; int hlvl; @@ -111,10 +112,22 @@ void handle_lf(state *s) { } } +int toggle_format(state *s, char *fmt, int enabled, int allow_in_code) { + if ((allow_in_code || !s->in_code) && s->in_link != URL_PARSE && s->in != CODE) { + maybe_startp(s); + printf("<%s%s>", enabled ? "/" : "", fmt); + return !enabled; + } else { + putesc(s->c); + } + return enabled; +} + int parse() { /* Mini state machine (home grown spaghetti code) */ int c; state s = { + .c = 0, .in = NONE, .in_link = NOL, .hlvl = 0, @@ -133,7 +146,7 @@ int parse() { }; while ((c = getchar()) != EOF) { - /* printf("\n>> c: %d lastc: %d started: %d indent: %d\n", c, s.lastc, s.linestarted, s.indent); */ + s.c = c; /* store for helpers */ /* Handle Escapes before all else */ if (s.escape) { @@ -199,46 +212,13 @@ int parse() { } break; case '`': - if (s.in_link != URL_PARSE && s.in != CODE) { - maybe_startp(&s); - if (s.in_code) { - printf("</code>"); - s.in_code = 0; - } else { - printf("<code>"); - s.in_code = 1; - } - } else { - putesc(c); - } + s.in_code = toggle_format(&s, "code", s.in_code, 1); break; case '*': - if (!s.in_code && s.in_link != URL_PARSE && s.in != CODE) { - maybe_startp(&s); - if (s.in_bold) { - printf("</strong>"); - s.in_bold = 0; - } else { - printf("<strong>"); - s.in_bold = 1; - } - } else { - putesc(c); - } + s.in_bold = toggle_format(&s, "strong", s.in_bold, 0); break; case '_': - if (!s.in_code && s.in_link != URL_PARSE && s.in != CODE) { - maybe_startp(&s); - if (s.in_ital) { - printf("</em>"); - s.in_ital = 0; - } else { - printf("<em>"); - s.in_ital = 1; - } - } else { - putesc(c); - } + s.in_ital = toggle_format(&s, "em", s.in_ital, 0); break; case '\t': case '>':