From f64a1a60edde970676a54e31fbc333c58ea38893 Mon Sep 17 00:00:00 2001 From: Alex Karle Date: Thu, 23 Dec 2021 20:32:50 -0500 Subject: [PATCH] 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! --- blag.c | 54 +++++++++++++++++------------------------------------- 1 file changed, 17 insertions(+), 37 deletions(-) diff --git a/blag.c b/blag.c index 7b845d6..561fc0a 100644 --- 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(""); - s.in_code = 0; - } else { - printf(""); - 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(""); - s.in_bold = 0; - } else { - printf(""); - 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(""); - s.in_ital = 0; - } else { - printf(""); - s.in_ital = 1; - } - } else { - putesc(c); - } + s.in_ital = toggle_format(&s, "em", s.in_ital, 0); break; case '\t': case '>': -- libgit2 1.1.1