Adiciona tinyblocks-syntax, tinyblocks-regex e tinyblocks-markdown (com testes)
This commit is contained in:
1 parent
c75d4be1c2
commit
a921f6574d
16 files changed
+1846
-4
No files matched your search
@@ -0,0 +1,28 @@
|
||||
# Makefile da library markdown (categoria "Markdown")
|
||||
CC := gcc
|
||||
BUILD := build
|
||||
|
||||
CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \
|
||||
-D_POSIX_C_SOURCE=200809L -I../../include -Iinclude
|
||||
|
||||
OBJ := $(BUILD)/tb_markdown.o
|
||||
LIB_A := $(BUILD)/libtinyblocks-markdown.a
|
||||
LIB_SO := $(BUILD)/libtinyblocks-markdown.so
|
||||
|
||||
.PHONY: all static shared clean
|
||||
all: static shared
|
||||
static: $(LIB_A)
|
||||
shared: $(LIB_SO)
|
||||
|
||||
$(OBJ): src/tb_markdown.c include/tb_markdown.h
|
||||
@mkdir -p $(BUILD)
|
||||
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||
|
||||
$(LIB_A): $(OBJ)
|
||||
ar rcs $@ $^
|
||||
|
||||
$(LIB_SO): $(OBJ)
|
||||
$(CC) -shared -o $@ $^
|
||||
|
||||
clean:
|
||||
$(RM) -r $(BUILD)
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* TinyBlocks - tb_markdown.h
|
||||
* Library tinyblocks-markdown: converte Markdown para HTML, XML ou SVG.
|
||||
* Independente do editor.
|
||||
*/
|
||||
#ifndef TINYBLOCKS_MARKDOWN_H
|
||||
#define TINYBLOCKS_MARKDOWN_H
|
||||
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
|
||||
TB_API const TinyBlocks_LibraryDescriptor* tb_markdown_get_library(void);
|
||||
|
||||
/* -- API C (resultados com malloc; libere com free) ---------------------- */
|
||||
TB_API char* tb_markdown_to_html(const char* md);
|
||||
TB_API char* tb_markdown_to_xml(const char* md);
|
||||
TB_API char* tb_markdown_to_svg(const char* md);
|
||||
|
||||
/* Variante do SVG com largura/fonte configuraveis. */
|
||||
TB_API char* tb_markdown_to_svg_opts(const char* md, int width, int font_size);
|
||||
|
||||
TB_API const char* tb_markdown_last_error(void);
|
||||
|
||||
#endif /* TINYBLOCKS_MARKDOWN_H */
|
||||
@@ -0,0 +1,15 @@
|
||||
# Metadados da library markdown. Lido pela UI/build sem recompilar o .so.
|
||||
[library]
|
||||
name = "tinyblocks-markdown"
|
||||
version = "1.0.0"
|
||||
category = "Markdown"
|
||||
description = "Converte Markdown para HTML, XML ou SVG"
|
||||
color = [96, 125, 139, 255]
|
||||
dark = [55, 71, 79, 255]
|
||||
|
||||
[build]
|
||||
sources = ["src/tb_markdown.c"]
|
||||
includes = ["include"]
|
||||
shared = "build/libtinyblocks-markdown.so"
|
||||
static = "build/libtinyblocks-markdown.a"
|
||||
depends = []
|
||||
@@ -0,0 +1,517 @@
|
||||
/*
|
||||
* TinyBlocks - tb_markdown.c
|
||||
* Categoria "Markdown": Markdown.ToHtml / ToXml / ToSvg.
|
||||
*
|
||||
* Parser por linhas -> lista de blocos (H1..H6, paragrafo, item de lista,
|
||||
* citacao, bloco de codigo, regra) -> serializacao para HTML, XML ou SVG.
|
||||
*/
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include <ctype.h>
|
||||
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
#include "tb_markdown.h"
|
||||
|
||||
static char s_err[160] = "";
|
||||
const char* tb_markdown_last_error(void) { return s_err; }
|
||||
|
||||
/* ---------------------------------------------------------------- Buffer */
|
||||
typedef struct { char* p; size_t n, cap; } Buf;
|
||||
static bool b_res(Buf* b, size_t extra) {
|
||||
if (b->n + extra + 1 <= b->cap) return true;
|
||||
size_t cap = b->cap ? b->cap : 128;
|
||||
while (cap < b->n + extra + 1) cap *= 2;
|
||||
char* p = (char*)realloc(b->p, cap);
|
||||
if (!p) return false;
|
||||
b->p = p; b->cap = cap; return true;
|
||||
}
|
||||
static bool b_put(Buf* b, const char* s, size_t n) {
|
||||
if (!b_res(b, n)) return false;
|
||||
memcpy(b->p + b->n, s, n); b->n += n; b->p[b->n] = 0; return true;
|
||||
}
|
||||
static bool b_str(Buf* b, const char* s) { return b_put(b, s, strlen(s)); }
|
||||
static bool b_ch(Buf* b, char c) { return b_put(b, &c, 1); }
|
||||
static bool b_fmt(Buf* b, const char* f, int v) {
|
||||
char tmp[48]; int n = snprintf(tmp, sizeof(tmp), f, v);
|
||||
return b_put(b, tmp, (size_t)(n > 0 ? n : 0));
|
||||
}
|
||||
static void b_esc(Buf* b, const char* s, size_t n) {
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
unsigned char c = (unsigned char)s[i];
|
||||
if (c == '&') b_str(b, "&");
|
||||
else if (c == '<') b_str(b, "<");
|
||||
else if (c == '>') b_str(b, ">");
|
||||
else if (c == '"') b_str(b, """);
|
||||
else b_ch(b, (char)c);
|
||||
}
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- Blocos */
|
||||
typedef enum { BLK_H, BLK_P, BLK_LI, BLK_CODE, BLK_QUOTE, BLK_HR } BlkKind;
|
||||
typedef struct {
|
||||
BlkKind kind;
|
||||
int level; /* heading */
|
||||
bool ordered; /* item de lista ordenada */
|
||||
int index; /* numero do item ordenado */
|
||||
char* text; /* conteudo (inline markdown) */
|
||||
char* lang; /* linguagem do bloco de codigo */
|
||||
} Blk;
|
||||
typedef struct { Blk* v; int n, cap; } Doc;
|
||||
|
||||
static Blk* doc_push(Doc* d, BlkKind k) {
|
||||
if (d->n == d->cap) {
|
||||
int cap = d->cap ? d->cap * 2 : 16;
|
||||
Blk* v = (Blk*)realloc(d->v, (size_t)cap * sizeof(Blk));
|
||||
if (!v) return NULL;
|
||||
d->v = v; d->cap = cap;
|
||||
}
|
||||
Blk* b = &d->v[d->n++];
|
||||
memset(b, 0, sizeof(*b));
|
||||
b->kind = k;
|
||||
return b;
|
||||
}
|
||||
static void doc_free(Doc* d) {
|
||||
for (int i = 0; i < d->n; i++) { free(d->v[i].text); free(d->v[i].lang); }
|
||||
free(d->v);
|
||||
d->v = NULL; d->n = d->cap = 0;
|
||||
}
|
||||
static char* dupn(const char* s, size_t n) {
|
||||
char* p = (char*)malloc(n + 1);
|
||||
if (!p) return NULL;
|
||||
memcpy(p, s, n); p[n] = 0; return p;
|
||||
}
|
||||
static void rtrim(char* s) { size_t n = strlen(s); while (n && (s[n-1]=='\n'||s[n-1]=='\r'||s[n-1]==' '||s[n-1]=='\t')) s[--n]=0; }
|
||||
static void ltrim_ptr(const char** p) { while (**p==' '||**p=='\t') (*p)++; }
|
||||
|
||||
static bool hr_line(const char* s) {
|
||||
int cnt = 0; char c0 = 0;
|
||||
for (; *s; s++) {
|
||||
if (*s == ' ' || *s == '\t') continue;
|
||||
if (!c0) c0 = *s;
|
||||
if (*s != c0) return false;
|
||||
cnt++;
|
||||
}
|
||||
return cnt >= 3 && (c0 == '-' || c0 == '*' || c0 == '_');
|
||||
}
|
||||
|
||||
static Doc* parse(const char* md) {
|
||||
Doc* d = (Doc*)calloc(1, sizeof(Doc));
|
||||
if (!d) return NULL;
|
||||
if (!md) md = "";
|
||||
const char* p = md;
|
||||
bool in_code = false;
|
||||
char code_lang[32] = "";
|
||||
Buf code = {0};
|
||||
Buf para = {0};
|
||||
bool para_active = false;
|
||||
|
||||
#define FLUSH_PARA() do { if (para_active) { Blk* b = doc_push(d, BLK_P); if (b) { b->text = dupn(para.p ? para.p : "", para.p ? strlen(para.p) : 0); } \
|
||||
free(para.p); para.p = NULL; para.n = para.cap = 0; para_active = false; } } while (0)
|
||||
|
||||
while (*p) {
|
||||
const char* nl = strchr(p, '\n');
|
||||
size_t len = nl ? (size_t)(nl - p) : strlen(p);
|
||||
char* line = dupn(p, len);
|
||||
if (!line) break;
|
||||
rtrim(line);
|
||||
const char* t = line;
|
||||
ltrim_ptr(&t);
|
||||
|
||||
if (!in_code && !strncmp(t, "```", 3)) {
|
||||
FLUSH_PARA();
|
||||
in_code = true;
|
||||
const char* lang = t + 3;
|
||||
ltrim_ptr(&lang);
|
||||
snprintf(code_lang, sizeof(code_lang), "%s", lang);
|
||||
free(line);
|
||||
if (!nl) break;
|
||||
p = nl + 1;
|
||||
continue;
|
||||
}
|
||||
if (in_code) {
|
||||
if (!strncmp(t, "```", 3)) {
|
||||
Blk* b = doc_push(d, BLK_CODE);
|
||||
if (b) { b->text = dupn(code.p ? code.p : "", code.p ? strlen(code.p) : 0);
|
||||
b->lang = dupn(code_lang, strlen(code_lang)); }
|
||||
free(code.p); code.p = NULL; code.n = code.cap = 0;
|
||||
in_code = false;
|
||||
} else {
|
||||
b_put(&code, line, strlen(line));
|
||||
b_ch(&code, '\n');
|
||||
}
|
||||
free(line);
|
||||
if (!nl) break;
|
||||
p = nl + 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!*t) { FLUSH_PARA(); free(line); if (!nl) break; p = nl + 1; continue; }
|
||||
|
||||
int h = 0;
|
||||
while (t[h] == '#' && h < 6) h++;
|
||||
if (h > 0 && (t[h] == ' ' || t[h] == 0)) {
|
||||
FLUSH_PARA();
|
||||
const char* body = t + h; ltrim_ptr(&body);
|
||||
Blk* b = doc_push(d, BLK_H);
|
||||
if (b) { b->level = h; b->text = dupn(body, strlen(body)); }
|
||||
free(line); if (!nl) break; p = nl + 1; continue;
|
||||
}
|
||||
if (hr_line(t)) {
|
||||
FLUSH_PARA();
|
||||
doc_push(d, BLK_HR);
|
||||
free(line); if (!nl) break; p = nl + 1; continue;
|
||||
}
|
||||
if (*t == '>') {
|
||||
FLUSH_PARA();
|
||||
const char* body = t + 1; ltrim_ptr(&body);
|
||||
Blk* b = doc_push(d, BLK_QUOTE);
|
||||
if (b) b->text = dupn(body, strlen(body));
|
||||
free(line); if (!nl) break; p = nl + 1; continue;
|
||||
}
|
||||
if ((t[0] == '-' || t[0] == '*' || t[0] == '+') && (t[1] == ' ' || t[1] == 0)) {
|
||||
FLUSH_PARA();
|
||||
const char* body = t + 1; ltrim_ptr(&body);
|
||||
Blk* b = doc_push(d, BLK_LI);
|
||||
if (b) { b->ordered = false; b->text = dupn(body, strlen(body)); }
|
||||
free(line); if (!nl) break; p = nl + 1; continue;
|
||||
}
|
||||
if (isdigit((unsigned char)t[0])) {
|
||||
const char* q = t;
|
||||
while (isdigit((unsigned char)*q)) q++;
|
||||
if ((*q == '.' || *q == ')') && (q[1] == ' ' || q[1] == 0)) {
|
||||
FLUSH_PARA();
|
||||
const char* body = q + 1; ltrim_ptr(&body);
|
||||
Blk* b = doc_push(d, BLK_LI);
|
||||
if (b) { b->ordered = true; b->index = atoi(t); b->text = dupn(body, strlen(body)); }
|
||||
free(line); if (!nl) break; p = nl + 1; continue;
|
||||
}
|
||||
}
|
||||
/* paragrafo (linhas consecutivas unidas por espaco) */
|
||||
if (para_active) b_ch(¶, ' ');
|
||||
b_str(¶, t);
|
||||
para_active = true;
|
||||
free(line);
|
||||
if (!nl) break;
|
||||
p = nl + 1;
|
||||
}
|
||||
if (in_code && code.p) {
|
||||
Blk* b = doc_push(d, BLK_CODE);
|
||||
if (b) b->text = dupn(code.p, strlen(code.p));
|
||||
free(code.p); code.p = NULL;
|
||||
}
|
||||
FLUSH_PARA();
|
||||
free(para.p);
|
||||
#undef FLUSH_PARA
|
||||
return d;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- Inline */
|
||||
/* Serializa inline markdown para HTML (xml=false) ou XML (xml=true). */
|
||||
static void inline_out(Buf* b, const char* s, bool xml) {
|
||||
const char* bold0 = xml ? "<bold>" : "<strong>";
|
||||
const char* bold1 = xml ? "</bold>" : "</strong>";
|
||||
const char* it0 = xml ? "<italic>" : "<em>";
|
||||
const char* it1 = xml ? "</italic>" : "</em>";
|
||||
while (*s) {
|
||||
if (s[0] == '*' && s[1] == '*') {
|
||||
const char* e = strstr(s + 2, "**");
|
||||
if (e) {
|
||||
char* mid = dupn(s + 2, (size_t)(e - (s + 2)));
|
||||
b_str(b, bold0); inline_out(b, mid ? mid : "", xml); b_str(b, bold1);
|
||||
free(mid); s = e + 2; continue;
|
||||
}
|
||||
}
|
||||
if (s[0] == '`') {
|
||||
const char* e = strchr(s + 1, '`');
|
||||
if (e) { b_str(b, "<code>"); b_esc(b, s + 1, (size_t)(e - (s + 1))); b_str(b, "</code>"); s = e + 1; continue; }
|
||||
}
|
||||
if (s[0] == '!' && s[1] == '[') {
|
||||
const char* close = strchr(s + 2, ']');
|
||||
if (close && close[1] == '(') {
|
||||
const char* rp = strchr(close + 2, ')');
|
||||
if (rp) {
|
||||
b_str(b, xml ? "<image src=\"" : "<img alt=\"");
|
||||
if (!xml) { b_esc(b, s + 2, (size_t)(close - (s + 2))); b_str(b, "\" src=\""); }
|
||||
b_esc(b, close + 2, (size_t)(rp - (close + 2)));
|
||||
if (xml) b_str(b, "\" alt=\"");
|
||||
if (xml) b_esc(b, s + 2, (size_t)(close - (s + 2)));
|
||||
b_str(b, xml ? "\"/>" : "\">");
|
||||
s = rp + 1; continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (s[0] == '[') {
|
||||
const char* close = strchr(s + 1, ']');
|
||||
if (close && close[1] == '(') {
|
||||
const char* rp = strchr(close + 2, ')');
|
||||
if (rp) {
|
||||
b_str(b, xml ? "<link href=\"" : "<a href=\"");
|
||||
b_esc(b, close + 2, (size_t)(rp - (close + 2)));
|
||||
b_str(b, "\">");
|
||||
{ char* mid = dupn(s + 1, (size_t)(close - (s + 1)));
|
||||
inline_out(b, mid, xml); free(mid); }
|
||||
b_str(b, xml ? "</link>" : "</a>");
|
||||
s = rp + 1; continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ((s[0] == '*' || s[0] == '_')) {
|
||||
char q = s[0];
|
||||
const char* e = strchr(s + 1, q);
|
||||
if (e && e > s + 1) {
|
||||
b_str(b, it0);
|
||||
{ char* mid = dupn(s + 1, (size_t)(e - (s + 1)));
|
||||
inline_out(b, mid, xml); free(mid); }
|
||||
b_str(b, it1);
|
||||
s = e + 1; continue;
|
||||
}
|
||||
}
|
||||
if (s[0] == '&') { b_str(b, "&"); s++; continue; }
|
||||
if (s[0] == '<') { b_str(b, "<"); s++; continue; }
|
||||
if (s[0] == '>') { b_str(b, ">"); s++; continue; }
|
||||
b_ch(b, s[0]); s++;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ HTML */
|
||||
char* tb_markdown_to_html(const char* md) {
|
||||
s_err[0] = 0;
|
||||
Doc* d = parse(md);
|
||||
if (!d) { snprintf(s_err, sizeof(s_err), "sem memoria"); return NULL; }
|
||||
Buf b = {0};
|
||||
bool in_ul = false, in_ol = false;
|
||||
for (int i = 0; i < d->n; i++) {
|
||||
Blk* k = &d->v[i];
|
||||
bool is_li = k->kind == BLK_LI;
|
||||
if (!is_li && (in_ul || in_ol)) {
|
||||
b_str(&b, in_ul ? "</ul>\n" : "</ol>\n"); in_ul = in_ol = false;
|
||||
}
|
||||
switch (k->kind) {
|
||||
case BLK_H:
|
||||
b_fmt(&b, "<h%d>", k->level); inline_out(&b, k->text ? k->text : "", false); b_fmt(&b, "</h%d>\n", k->level);
|
||||
break;
|
||||
case BLK_P:
|
||||
b_str(&b, "<p>"); inline_out(&b, k->text ? k->text : "", false); b_str(&b, "</p>\n");
|
||||
break;
|
||||
case BLK_QUOTE:
|
||||
b_str(&b, "<blockquote>"); inline_out(&b, k->text ? k->text : "", false); b_str(&b, "</blockquote>\n");
|
||||
break;
|
||||
case BLK_CODE:
|
||||
b_str(&b, "<pre><code");
|
||||
if (k->lang && k->lang[0]) { b_str(&b, " class=\"language-"); b_esc(&b, k->lang, strlen(k->lang)); b_str(&b, "\""); }
|
||||
b_str(&b, ">"); b_esc(&b, k->text ? k->text : "", k->text ? strlen(k->text) : 0); b_str(&b, "</code></pre>\n");
|
||||
break;
|
||||
case BLK_HR:
|
||||
b_str(&b, "<hr>\n");
|
||||
break;
|
||||
case BLK_LI:
|
||||
if (k->ordered) { if (!in_ol) { b_str(&b, "<ol>\n"); in_ol = true; } }
|
||||
else { if (!in_ul) { b_str(&b, "<ul>\n"); in_ul = true; } }
|
||||
b_str(&b, "<li>"); inline_out(&b, k->text ? k->text : "", false); b_str(&b, "</li>\n");
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (in_ul) b_str(&b, "</ul>\n");
|
||||
if (in_ol) b_str(&b, "</ol>\n");
|
||||
doc_free(d); free(d);
|
||||
return b.p;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------- XML */
|
||||
char* tb_markdown_to_xml(const char* md) {
|
||||
s_err[0] = 0;
|
||||
Doc* d = parse(md);
|
||||
if (!d) { snprintf(s_err, sizeof(s_err), "sem memoria"); return NULL; }
|
||||
Buf b = {0};
|
||||
b_str(&b, "<markdown>\n");
|
||||
bool in_list = false; bool list_ordered = false;
|
||||
for (int i = 0; i < d->n; i++) {
|
||||
Blk* k = &d->v[i];
|
||||
bool is_li = k->kind == BLK_LI;
|
||||
if (!is_li && in_list) { b_str(&b, "</list>\n"); in_list = false; }
|
||||
switch (k->kind) {
|
||||
case BLK_H:
|
||||
b_str(&b, "<heading level=\""); b_fmt(&b, "%d", k->level); b_str(&b, "\">");
|
||||
inline_out(&b, k->text ? k->text : "", true); b_str(&b, "</heading>\n");
|
||||
break;
|
||||
case BLK_P:
|
||||
b_str(&b, "<paragraph>"); inline_out(&b, k->text ? k->text : "", true); b_str(&b, "</paragraph>\n");
|
||||
break;
|
||||
case BLK_QUOTE:
|
||||
b_str(&b, "<quote>"); inline_out(&b, k->text ? k->text : "", true); b_str(&b, "</quote>\n");
|
||||
break;
|
||||
case BLK_CODE:
|
||||
b_str(&b, "<code");
|
||||
if (k->lang && k->lang[0]) { b_str(&b, " lang=\""); b_esc(&b, k->lang, strlen(k->lang)); b_str(&b, "\""); }
|
||||
b_str(&b, ">"); b_esc(&b, k->text ? k->text : "", k->text ? strlen(k->text) : 0); b_str(&b, "</code>\n");
|
||||
break;
|
||||
case BLK_HR:
|
||||
b_str(&b, "<rule/>\n");
|
||||
break;
|
||||
case BLK_LI:
|
||||
if (!in_list) {
|
||||
b_str(&b, "<list ordered=\""); b_str(&b, k->ordered ? "true" : "false"); b_str(&b, "\">\n");
|
||||
in_list = true; list_ordered = k->ordered;
|
||||
}
|
||||
(void)list_ordered;
|
||||
b_str(&b, "<item>"); inline_out(&b, k->text ? k->text : "", true); b_str(&b, "</item>\n");
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (in_list) b_str(&b, "</list>\n");
|
||||
b_str(&b, "</markdown>");
|
||||
doc_free(d); free(d);
|
||||
return b.p;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------- SVG */
|
||||
char* tb_markdown_to_svg_opts(const char* md, int width, int font_size) {
|
||||
s_err[0] = 0;
|
||||
if (width < 80) width = 640;
|
||||
if (font_size < 6) font_size = 16;
|
||||
Doc* d = parse(md);
|
||||
if (!d) { snprintf(s_err, sizeof(s_err), "sem memoria"); return NULL; }
|
||||
|
||||
int pad = 16;
|
||||
int line_h = (int)(font_size * 1.5);
|
||||
int y = pad + font_size;
|
||||
Buf body = {0};
|
||||
char num[24];
|
||||
for (int i = 0; i < d->n; i++) {
|
||||
Blk* k = &d->v[i];
|
||||
int fs = font_size;
|
||||
bool bold = false, mono = false, italic = false;
|
||||
int indent = 0;
|
||||
const char* prefix = "";
|
||||
int bullet_r = 0; /* raio do marcador de lista */
|
||||
switch (k->kind) {
|
||||
case BLK_H:
|
||||
fs = font_size + (7 - k->level) * 4;
|
||||
if (fs < font_size) fs = font_size;
|
||||
bold = true;
|
||||
y += (fs - font_size) / 2;
|
||||
break;
|
||||
case BLK_P: break;
|
||||
case BLK_QUOTE: italic = true; indent = 14; break;
|
||||
case BLK_CODE: mono = true; indent = 14; break;
|
||||
case BLK_HR: break;
|
||||
case BLK_LI: indent = 12; bullet_r = (fs / 5) + 1; break;
|
||||
}
|
||||
if (k->kind == BLK_HR) {
|
||||
b_fmt(&body, " <line x1=\"%d\" y1=\"", pad);
|
||||
b_fmt(&body, "%d", y - fs / 2);
|
||||
b_str(&body, "\" x2=\"");
|
||||
b_fmt(&body, "%d", width - pad);
|
||||
b_str(&body, "\" y2=\"");
|
||||
b_fmt(&body, "%d", y - fs / 2);
|
||||
b_str(&body, "\" stroke=\"#cccccc\" stroke-width=\"1\"/>\n");
|
||||
y += line_h / 2;
|
||||
continue;
|
||||
}
|
||||
if (bullet_r) {
|
||||
b_str(&body, " <circle cx=\"");
|
||||
b_fmt(&body, "%d", pad + indent);
|
||||
b_str(&body, "\" cy=\"");
|
||||
b_fmt(&body, "%d", y - fs / 3);
|
||||
b_str(&body, "\" r=\"");
|
||||
b_fmt(&body, "%d", bullet_r);
|
||||
b_str(&body, "\" fill=\"#555555\"/>\n");
|
||||
}
|
||||
const char* txt = k->text ? k->text : "";
|
||||
if (k->kind == BLK_LI && k->ordered) {
|
||||
snprintf(num, sizeof(num), "%d. ", k->index);
|
||||
prefix = num;
|
||||
}
|
||||
b_str(&body, " <text x=\"");
|
||||
b_fmt(&body, "%d", pad + indent + (k->kind == BLK_LI ? 14 : 0));
|
||||
b_str(&body, "\" y=\"");
|
||||
b_fmt(&body, "%d", y);
|
||||
b_str(&body, "\" font-family=\"");
|
||||
b_str(&body, mono ? "monospace" : "sans-serif");
|
||||
b_str(&body, "\" font-size=\"");
|
||||
b_fmt(&body, "%d", fs);
|
||||
b_str(&body, "\"");
|
||||
if (bold) b_str(&body, " font-weight=\"bold\"");
|
||||
if (italic) b_str(&body, " font-style=\"italic\"");
|
||||
b_str(&body, " fill=\"#");
|
||||
b_str(&body, k->kind == BLK_QUOTE ? "666666" : (mono ? "333333" : "111111"));
|
||||
b_str(&body, "\">");
|
||||
b_esc(&body, prefix, strlen(prefix));
|
||||
/* texto simples (sem marcadores inline) */
|
||||
for (const char* p = txt; *p; p++) {
|
||||
if (*p == '*' || *p == '`') continue;
|
||||
b_esc(&body, p, 1);
|
||||
}
|
||||
b_str(&body, "</text>\n");
|
||||
y += (fs > font_size ? line_h + (fs - font_size) : line_h);
|
||||
}
|
||||
int height = y + pad;
|
||||
|
||||
Buf out = {0};
|
||||
b_str(&out, "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"");
|
||||
b_fmt(&out, "%d", width);
|
||||
b_str(&out, "\" height=\"");
|
||||
b_fmt(&out, "%d", height);
|
||||
b_str(&out, "\" viewBox=\"0 0 ");
|
||||
b_fmt(&out, "%d", width);
|
||||
b_ch(&out, ' ');
|
||||
b_fmt(&out, "%d", height);
|
||||
b_str(&out, "\">\n");
|
||||
b_str(&out, " <rect width=\"100%\" height=\"100%\" fill=\"#ffffff\"/>\n");
|
||||
b_str(&out, body.p ? body.p : "");
|
||||
b_str(&out, "</svg>");
|
||||
free(body.p);
|
||||
doc_free(d); free(d);
|
||||
return out.p;
|
||||
}
|
||||
|
||||
char* tb_markdown_to_svg(const char* md) { return tb_markdown_to_svg_opts(md, 640, 16); }
|
||||
|
||||
/* ---------------------------------------------------------------- Blocos */
|
||||
static const char* in_text(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) {
|
||||
TinyBlocks_Value v = tb_block_get_input(self, rt, i);
|
||||
return (v.kind == TB_VALUE_TEXT && v.as.text) ? v.as.text : "";
|
||||
}
|
||||
static void eval_html(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
char* s = tb_markdown_to_html(in_text(self, rt, 0));
|
||||
tb_block_set_output(self, 0, tb_value_text(s ? s : "")); free(s); self->dirty = false;
|
||||
}
|
||||
static void eval_xml(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
char* s = tb_markdown_to_xml(in_text(self, rt, 0));
|
||||
tb_block_set_output(self, 0, tb_value_text(s ? s : "")); free(s); self->dirty = false;
|
||||
}
|
||||
static void eval_svg(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
char* s = tb_markdown_to_svg(in_text(self, rt, 0));
|
||||
tb_block_set_output(self, 0, tb_value_text(s ? s : "")); free(s); self->dirty = false;
|
||||
}
|
||||
|
||||
static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name,
|
||||
const TinyBlocks_SlotDesc* in, uint32_t ni,
|
||||
const TinyBlocks_SlotDesc* out, uint32_t no,
|
||||
void (*fn)(TinyBlocks_Block*, TinyBlocks*)) {
|
||||
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, out, no, fn);
|
||||
return t && tb_library_add(lib, &t->base);
|
||||
}
|
||||
|
||||
static bool markdown_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||
static const TinyBlocks_Category cat = {
|
||||
"Markdown",
|
||||
{ 96/255.f, 125/255.f, 139/255.f, 1.f},
|
||||
{ 55/255.f, 71/255.f, 79/255.f, 1.f},
|
||||
};
|
||||
tb_library_set_category(lib, &cat);
|
||||
static const TinyBlocks_SlotDesc in_md[] = {{"markdown", TB_VALUE_TEXT}};
|
||||
static const TinyBlocks_SlotDesc out_text[] = {{"texto", TB_VALUE_TEXT}};
|
||||
return reg(rt, lib, "Markdown.ToHtml", in_md, 1, out_text, 1, eval_html)
|
||||
&& reg(rt, lib, "Markdown.ToXml", in_md, 1, out_text, 1, eval_xml)
|
||||
&& reg(rt, lib, "Markdown.ToSvg", in_md, 1, out_text, 1, eval_svg);
|
||||
}
|
||||
|
||||
TINYBLOCKS_DEFINE_LIBRARY(markdown, "tinyblocks-markdown", "1.0.0", markdown_init, NULL)
|
||||
|
||||
const TinyBlocks_LibraryDescriptor* tb_markdown_get_library(void) {
|
||||
return &_tb_lib_desc_markdown;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
# Makefile da library regex (categoria "Regex")
|
||||
CC := gcc
|
||||
BUILD := build
|
||||
|
||||
CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \
|
||||
-D_POSIX_C_SOURCE=200809L -I../../include -Iinclude
|
||||
|
||||
OBJ := $(BUILD)/tb_regex.o
|
||||
LIB_A := $(BUILD)/libtinyblocks-regex.a
|
||||
LIB_SO := $(BUILD)/libtinyblocks-regex.so
|
||||
|
||||
.PHONY: all static shared clean
|
||||
all: static shared
|
||||
static: $(LIB_A)
|
||||
shared: $(LIB_SO)
|
||||
|
||||
$(OBJ): src/tb_regex.c include/tb_regex.h
|
||||
@mkdir -p $(BUILD)
|
||||
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||
|
||||
$(LIB_A): $(OBJ)
|
||||
ar rcs $@ $^
|
||||
|
||||
$(LIB_SO): $(OBJ)
|
||||
$(CC) -shared -o $@ $^
|
||||
|
||||
clean:
|
||||
$(RM) -r $(BUILD)
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* TinyBlocks - tb_regex.h
|
||||
* Library tinyblocks-regex: expressoes regulares (POSIX ERE) para busca,
|
||||
* substituicao e divisao de texto. Independente do editor.
|
||||
*/
|
||||
#ifndef TINYBLOCKS_REGEX_H
|
||||
#define TINYBLOCKS_REGEX_H
|
||||
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
|
||||
TB_API const TinyBlocks_LibraryDescriptor* tb_regex_get_library(void);
|
||||
|
||||
/* -- API C --------------------------------------------------------------- */
|
||||
|
||||
/* Verdadeiro se o padrao casa em algum ponto do texto. */
|
||||
TB_API bool tb_regex_test(const char* text, const char* pattern);
|
||||
/* Verdadeiro se o padrao casa o texto inteiro (ancorado). */
|
||||
TB_API bool tb_regex_match(const char* text, const char* pattern);
|
||||
|
||||
/* Primeiro casamento (malloc; libere com free) ou NULL. */
|
||||
TB_API char* tb_regex_find(const char* text, const char* pattern);
|
||||
/* Grupo i do primeiro casamento (0 = casamento inteiro). */
|
||||
TB_API char* tb_regex_group(const char* text, const char* pattern, int group);
|
||||
/* Quantidade de grupos de captura do padrao (-1 em erro). */
|
||||
TB_API int tb_regex_group_count(const char* text, const char* pattern);
|
||||
/* Numero de casamentos. */
|
||||
TB_API int tb_regex_count(const char* text, const char* pattern);
|
||||
|
||||
/* Substitui todas as ocorrencias. Em `repl`, $0..$9 inserem os grupos e
|
||||
* $$ insere um '$'. Devolve texto (malloc). */
|
||||
TB_API char* tb_regex_replace(const char* text, const char* pattern, const char* repl);
|
||||
|
||||
/* Divide o texto pelos casamentos; devolve vetor de strings terminado por
|
||||
* NULL (libere cada item e o vetor). */
|
||||
TB_API char** tb_regex_split(const char* text, const char* pattern, int* out_count);
|
||||
TB_API void tb_regex_free_list(char** list);
|
||||
|
||||
TB_API const char* tb_regex_last_error(void);
|
||||
|
||||
#endif /* TINYBLOCKS_REGEX_H */
|
||||
@@ -0,0 +1,15 @@
|
||||
# Metadados da library regex. Lido pela UI/build sem recompilar o .so.
|
||||
[library]
|
||||
name = "tinyblocks-regex"
|
||||
version = "1.0.0"
|
||||
category = "Regex"
|
||||
description = "Expressoes regulares: busca, grupo, substituicao e divisao"
|
||||
color = [69, 90, 100, 255]
|
||||
dark = [38, 50, 56, 255]
|
||||
|
||||
[build]
|
||||
sources = ["src/tb_regex.c"]
|
||||
includes = ["include"]
|
||||
shared = "build/libtinyblocks-regex.so"
|
||||
static = "build/libtinyblocks-regex.a"
|
||||
depends = []
|
||||
@@ -0,0 +1,318 @@
|
||||
/*
|
||||
* TinyBlocks - tb_regex.c
|
||||
* Categoria "Regex": Regex.Test / Match / Find / Group / Count / Replace /
|
||||
* Split, sobre POSIX ERE (<regex.h>).
|
||||
*/
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include <regex.h>
|
||||
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
#include <tinyblocks/tb_json_block.h>
|
||||
#include "tb_regex.h"
|
||||
|
||||
#define MAX_GROUPS 32
|
||||
|
||||
static char s_err[200] = "";
|
||||
const char* tb_regex_last_error(void) { return s_err; }
|
||||
|
||||
static bool compile(regex_t* re, const char* pattern) {
|
||||
s_err[0] = 0;
|
||||
if (!pattern) pattern = "";
|
||||
int rc = regcomp(re, pattern, REG_EXTENDED);
|
||||
if (rc != 0) {
|
||||
char msg[160];
|
||||
regerror(rc, re, msg, sizeof(msg));
|
||||
snprintf(s_err, sizeof(s_err), "%s", msg);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool tb_regex_test(const char* text, const char* pattern) {
|
||||
regex_t re;
|
||||
if (!compile(&re, pattern)) return false;
|
||||
bool ok = regexec(&re, text ? text : "", 0, NULL, 0) == 0;
|
||||
regfree(&re);
|
||||
return ok;
|
||||
}
|
||||
|
||||
bool tb_regex_match(const char* text, const char* pattern) {
|
||||
/* Ancora o padrao com ^( ... )$ usando grupos nao-capturantes de ERE. */
|
||||
if (!pattern) pattern = "";
|
||||
size_t n = strlen(pattern);
|
||||
char* anch = (char*)malloc(n + 8);
|
||||
if (!anch) return false;
|
||||
anch[0] = '^'; anch[1] = '('; memcpy(anch + 2, pattern, n);
|
||||
anch[n + 2] = ')'; anch[n + 3] = '$'; anch[n + 4] = 0;
|
||||
bool ok = tb_regex_test(text, anch);
|
||||
free(anch);
|
||||
return ok;
|
||||
}
|
||||
|
||||
char* tb_regex_find(const char* text, const char* pattern) {
|
||||
regex_t re;
|
||||
if (!compile(&re, pattern)) return NULL;
|
||||
regmatch_t m;
|
||||
char* out = NULL;
|
||||
if (regexec(&re, text ? text : "", 1, &m, 0) == 0 && m.rm_so >= 0) {
|
||||
size_t len = (size_t)(m.rm_eo - m.rm_so);
|
||||
out = (char*)malloc(len + 1);
|
||||
if (out) { memcpy(out, text + m.rm_so, len); out[len] = 0; }
|
||||
}
|
||||
regfree(&re);
|
||||
return out;
|
||||
}
|
||||
|
||||
char* tb_regex_group(const char* text, const char* pattern, int group) {
|
||||
if (group < 0 || group >= MAX_GROUPS) { snprintf(s_err, sizeof(s_err), "grupo fora do intervalo"); return NULL; }
|
||||
regex_t re;
|
||||
if (!compile(&re, pattern)) return NULL;
|
||||
regmatch_t m[MAX_GROUPS];
|
||||
char* out = NULL;
|
||||
if (regexec(&re, text ? text : "", MAX_GROUPS, m, 0) == 0 &&
|
||||
m[group].rm_so >= 0) {
|
||||
size_t len = (size_t)(m[group].rm_eo - m[group].rm_so);
|
||||
out = (char*)malloc(len + 1);
|
||||
if (out) { memcpy(out, text + m[group].rm_so, len); out[len] = 0; }
|
||||
}
|
||||
regfree(&re);
|
||||
return out;
|
||||
}
|
||||
|
||||
int tb_regex_group_count(const char* text, const char* pattern) {
|
||||
regex_t re;
|
||||
if (!compile(&re, pattern)) return -1;
|
||||
(void)text;
|
||||
int n = (int)re.re_nsub; /* numero de subexpressoes */
|
||||
regfree(&re);
|
||||
return n;
|
||||
}
|
||||
|
||||
int tb_regex_count(const char* text, const char* pattern) {
|
||||
regex_t re;
|
||||
if (!compile(&re, pattern)) return -1;
|
||||
const char* p = text ? text : "";
|
||||
regmatch_t m;
|
||||
int count = 0;
|
||||
while (*p && regexec(&re, p, 1, &m, 0) == 0) {
|
||||
count++;
|
||||
if (m.rm_eo == m.rm_so) { p++; if (!*p) break; }
|
||||
else p += m.rm_eo;
|
||||
}
|
||||
regfree(&re);
|
||||
return count;
|
||||
}
|
||||
|
||||
/* --- Expansao do substituto -------------------------------------------- */
|
||||
typedef struct { char* p; size_t n, cap; } Buf;
|
||||
static bool b_res(Buf* b, size_t extra) {
|
||||
if (b->n + extra + 1 <= b->cap) return true;
|
||||
size_t cap = b->cap ? b->cap : 64;
|
||||
while (cap < b->n + extra + 1) cap *= 2;
|
||||
char* p = (char*)realloc(b->p, cap);
|
||||
if (!p) return false;
|
||||
b->p = p; b->cap = cap; return true;
|
||||
}
|
||||
static bool b_put(Buf* b, const char* s, size_t n) {
|
||||
if (!b_res(b, n)) return false;
|
||||
memcpy(b->p + b->n, s, n); b->n += n; b->p[b->n] = 0; return true;
|
||||
}
|
||||
|
||||
static void expand(Buf* out, const char* repl, const char* text, regmatch_t* m) {
|
||||
for (const char* p = repl; *p; p++) {
|
||||
if (*p == '$' && p[1] == '$') { b_put(out, "$", 1); p++; continue; }
|
||||
if (*p == '$' && p[1] >= '0' && p[1] <= '9') {
|
||||
int g = p[1] - '0';
|
||||
if (m[g].rm_so >= 0) b_put(out, text + m[g].rm_so, (size_t)(m[g].rm_eo - m[g].rm_so));
|
||||
p++;
|
||||
continue;
|
||||
}
|
||||
b_put(out, p, 1);
|
||||
}
|
||||
}
|
||||
|
||||
char* tb_regex_replace(const char* text, const char* pattern, const char* repl) {
|
||||
regex_t re;
|
||||
if (!compile(&re, pattern)) return NULL;
|
||||
if (!text) text = "";
|
||||
if (!repl) repl = "";
|
||||
Buf out = {0};
|
||||
const char* p = text;
|
||||
regmatch_t m[MAX_GROUPS];
|
||||
while (*p && regexec(&re, p, MAX_GROUPS, m, 0) == 0) {
|
||||
b_put(&out, p, (size_t)m[0].rm_so);
|
||||
expand(&out, repl, p, m);
|
||||
if (m[0].rm_eo == m[0].rm_so) {
|
||||
b_put(&out, p, 1);
|
||||
p++;
|
||||
if (!*p) break;
|
||||
} else {
|
||||
p += m[0].rm_eo;
|
||||
}
|
||||
}
|
||||
if (*p) b_put(&out, p, strlen(p));
|
||||
regfree(&re);
|
||||
if (!out.p) { out.p = (char*)malloc(1); if (out.p) out.p[0] = 0; }
|
||||
return out.p;
|
||||
}
|
||||
|
||||
char** tb_regex_split(const char* text, const char* pattern, int* out_count) {
|
||||
if (out_count) *out_count = 0;
|
||||
regex_t re;
|
||||
if (!compile(&re, pattern)) return NULL;
|
||||
if (!text) text = "";
|
||||
size_t cap = 8, n = 0;
|
||||
char** list = (char**)malloc(cap * sizeof(char*));
|
||||
if (!list) { regfree(&re); return NULL; }
|
||||
const char* p = text;
|
||||
regmatch_t m;
|
||||
for (;;) {
|
||||
if (*p && regexec(&re, p, 1, &m, 0) == 0) {
|
||||
size_t len = (size_t)m.rm_so;
|
||||
char* item = (char*)malloc(len + 1);
|
||||
if (!item) break;
|
||||
memcpy(item, p, len); item[len] = 0;
|
||||
if (n + 2 > cap) { cap *= 2; list = (char**)realloc(list, cap * sizeof(char*)); }
|
||||
list[n++] = item;
|
||||
if (m.rm_eo == m.rm_so) {
|
||||
if (!p[m.rm_so]) { p += m.rm_so; break; }
|
||||
/* casa vazio: emite 1 char e continua */
|
||||
char* one = (char*)malloc(2);
|
||||
one[0] = p[m.rm_so]; one[1] = 0;
|
||||
list[n++] = one;
|
||||
p += m.rm_so + 1;
|
||||
} else {
|
||||
p += m.rm_eo;
|
||||
}
|
||||
} else {
|
||||
size_t len = strlen(p);
|
||||
char* item = (char*)malloc(len + 1);
|
||||
if (!item) break;
|
||||
memcpy(item, p, len); item[len] = 0;
|
||||
if (n + 1 > cap) { cap += 1; list = (char**)realloc(list, cap * sizeof(char*)); }
|
||||
list[n++] = item;
|
||||
break;
|
||||
}
|
||||
}
|
||||
regfree(&re);
|
||||
list[n] = NULL;
|
||||
if (out_count) *out_count = (int)n;
|
||||
return list;
|
||||
}
|
||||
|
||||
void tb_regex_free_list(char** list) {
|
||||
if (!list) return;
|
||||
for (int i = 0; list[i]; i++) free(list[i]);
|
||||
free(list);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- Blocos */
|
||||
static const char* in_text(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) {
|
||||
TinyBlocks_Value v = tb_block_get_input(self, rt, i);
|
||||
return (v.kind == TB_VALUE_TEXT && v.as.text) ? v.as.text : "";
|
||||
}
|
||||
static double in_real(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) {
|
||||
TinyBlocks_Value v = tb_block_get_input(self, rt, i);
|
||||
if (v.kind == TB_VALUE_REAL) return v.as.real;
|
||||
if (v.kind == TB_VALUE_INTEGER) return (double)v.as.integer;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void eval_test(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
bool ok = tb_regex_test(in_text(self, rt, 0), in_text(self, rt, 1));
|
||||
tb_block_set_output(self, 0, tb_value_integer(ok ? 1 : 0));
|
||||
self->dirty = false;
|
||||
}
|
||||
static void eval_match(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
bool ok = tb_regex_match(in_text(self, rt, 0), in_text(self, rt, 1));
|
||||
tb_block_set_output(self, 0, tb_value_integer(ok ? 1 : 0));
|
||||
self->dirty = false;
|
||||
}
|
||||
static void eval_find(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
char* s = tb_regex_find(in_text(self, rt, 0), in_text(self, rt, 1));
|
||||
tb_block_set_output(self, 0, tb_value_text(s ? s : ""));
|
||||
free(s);
|
||||
self->dirty = false;
|
||||
}
|
||||
static void eval_group(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
char* s = tb_regex_group(in_text(self, rt, 0), in_text(self, rt, 1), (int)in_real(self, rt, 2));
|
||||
tb_block_set_output(self, 0, tb_value_text(s ? s : ""));
|
||||
free(s);
|
||||
self->dirty = false;
|
||||
}
|
||||
static void eval_count(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
tb_block_set_output(self, 0, tb_value_integer(tb_regex_count(in_text(self, rt, 0), in_text(self, rt, 1))));
|
||||
self->dirty = false;
|
||||
}
|
||||
static void eval_groups(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
tb_block_set_output(self, 0, tb_value_integer(tb_regex_group_count("", in_text(self, rt, 1))));
|
||||
self->dirty = false;
|
||||
}
|
||||
static void eval_replace(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
char* s = tb_regex_replace(in_text(self, rt, 0), in_text(self, rt, 1), in_text(self, rt, 2));
|
||||
tb_block_set_output(self, 0, tb_value_text(s ? s : ""));
|
||||
free(s);
|
||||
self->dirty = false;
|
||||
}
|
||||
static void eval_split(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
int n = 0;
|
||||
char** parts = tb_regex_split(in_text(self, rt, 0), in_text(self, rt, 1), &n);
|
||||
TinyBlocks_JsonValue* arr = tb_json_array();
|
||||
if (arr) {
|
||||
for (int i = 0; parts && parts[i]; i++) {
|
||||
TinyBlocks_JsonValue* s = tb_json_string(parts[i]);
|
||||
if (s) { tb_json_array_push(arr, s); tb_json_release(s); }
|
||||
}
|
||||
tb_block_set_output(self, 0, tb_value_json(arr));
|
||||
tb_json_release(arr);
|
||||
} else {
|
||||
tb_block_set_output(self, 0, tb_value_text(""));
|
||||
}
|
||||
tb_regex_free_list(parts);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name,
|
||||
const TinyBlocks_SlotDesc* in, uint32_t ni,
|
||||
const TinyBlocks_SlotDesc* out, uint32_t no,
|
||||
void (*fn)(TinyBlocks_Block*, TinyBlocks*)) {
|
||||
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, out, no, fn);
|
||||
return t && tb_library_add(lib, &t->base);
|
||||
}
|
||||
|
||||
static bool regex_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||
static const TinyBlocks_Category cat = {
|
||||
"Regex",
|
||||
{ 69/255.f, 90/255.f, 100/255.f, 1.f},
|
||||
{ 38/255.f, 50/255.f, 56/255.f, 1.f},
|
||||
};
|
||||
tb_library_set_category(lib, &cat);
|
||||
|
||||
static const TinyBlocks_SlotDesc two[] = {{"texto", TB_VALUE_TEXT}, {"padrao", TB_VALUE_TEXT}};
|
||||
static const TinyBlocks_SlotDesc three[] = {{"texto", TB_VALUE_TEXT}, {"padrao", TB_VALUE_TEXT}, {"com", TB_VALUE_TEXT}};
|
||||
static const TinyBlocks_SlotDesc grp[] = {{"texto", TB_VALUE_TEXT}, {"padrao", TB_VALUE_TEXT}, {"grupo", TB_VALUE_REAL}};
|
||||
static const TinyBlocks_SlotDesc pat[] = {{"padrao", TB_VALUE_TEXT}};
|
||||
static const TinyBlocks_SlotDesc out_text[] = {{"texto", TB_VALUE_TEXT}};
|
||||
static const TinyBlocks_SlotDesc out_bool[] = {{"verdadeiro", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc out_int[] = {{"numero", TB_VALUE_INTEGER}};
|
||||
static const TinyBlocks_SlotDesc out_list[] = {{"lista", TB_VALUE_JSON}};
|
||||
|
||||
return reg(rt, lib, "Regex.Test", two, 2, out_bool, 1, eval_test)
|
||||
&& reg(rt, lib, "Regex.Match", two, 2, out_bool, 1, eval_match)
|
||||
&& reg(rt, lib, "Regex.Find", two, 2, out_text, 1, eval_find)
|
||||
&& reg(rt, lib, "Regex.Group", grp, 3, out_text, 1, eval_group)
|
||||
&& reg(rt, lib, "Regex.Count", two, 2, out_int, 1, eval_count)
|
||||
&& reg(rt, lib, "Regex.Groups", pat, 1, out_int, 1, eval_groups)
|
||||
&& reg(rt, lib, "Regex.Replace", three, 3, out_text, 1, eval_replace)
|
||||
&& reg(rt, lib, "Regex.Split", two, 2, out_list, 1, eval_split);
|
||||
}
|
||||
|
||||
TINYBLOCKS_DEFINE_LIBRARY(regex, "tinyblocks-regex", "1.0.0", regex_init, NULL)
|
||||
|
||||
const TinyBlocks_LibraryDescriptor* tb_regex_get_library(void) {
|
||||
return &_tb_lib_desc_regex;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
# Makefile da library syntax (categoria "Sintaxe")
|
||||
CC := gcc
|
||||
BUILD := build
|
||||
|
||||
CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \
|
||||
-D_POSIX_C_SOURCE=200809L -I../../include -Iinclude
|
||||
|
||||
OBJ := $(BUILD)/tb_syntax.o
|
||||
LIB_A := $(BUILD)/libtinyblocks-syntax.a
|
||||
LIB_SO := $(BUILD)/libtinyblocks-syntax.so
|
||||
|
||||
.PHONY: all static shared clean
|
||||
all: static shared
|
||||
static: $(LIB_A)
|
||||
shared: $(LIB_SO)
|
||||
|
||||
$(OBJ): src/tb_syntax.c include/tb_syntax.h
|
||||
@mkdir -p $(BUILD)
|
||||
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||
|
||||
$(LIB_A): $(OBJ)
|
||||
ar rcs $@ $^
|
||||
|
||||
$(LIB_SO): $(OBJ)
|
||||
$(CC) -shared -o $@ $^
|
||||
|
||||
clean:
|
||||
$(RM) -r $(BUILD)
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* TinyBlocks - tb_syntax.h
|
||||
* Library tinyblocks-syntax: realce de sintaxe (syntax highlight) de um texto
|
||||
* em varias linguagens, devolvendo o texto colorido em XML.
|
||||
* Independente do editor.
|
||||
*
|
||||
* O XML gerado tem a forma:
|
||||
* <code lang="c">
|
||||
* <line><t type="kw" color="#c678dd">int</t> <t type="id" color="#9cdcfe">x</t>...</line>
|
||||
* ...
|
||||
* </code>
|
||||
* Cada linha do texto vira um elemento <line>; os trechos viram <t> com o tipo
|
||||
* do token e a cor (#rrggbb). Texto fora de tokens vira <t type="plain">.
|
||||
*/
|
||||
#ifndef TINYBLOCKS_SYNTAX_H
|
||||
#define TINYBLOCKS_SYNTAX_H
|
||||
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
|
||||
TB_API const TinyBlocks_LibraryDescriptor* tb_syntax_get_library(void);
|
||||
|
||||
/* -- API C --------------------------------------------------------------- */
|
||||
|
||||
/* Realca `text` como `lang` e devolve XML (malloc; libere com free). */
|
||||
TB_API char* tb_syntax_highlight(const char* text, const char* lang);
|
||||
|
||||
/* Realca `text` como um trecho de codigo C numa unica linha (sem <line>),
|
||||
* util para assinaturas/hover. Devolve XML (malloc). */
|
||||
TB_API char* tb_syntax_highlight_inline(const char* text, const char* lang);
|
||||
|
||||
/* Numero de linguagens conhecidas e o nome normalizado da i-esima. */
|
||||
TB_API int tb_syntax_language_count(void);
|
||||
TB_API const char* tb_syntax_language_name(int i);
|
||||
|
||||
/* Cor (#rrggbb) associada a um tipo de token ("kw", "str", "cmt", ...). */
|
||||
TB_API const char* tb_syntax_type_color(const char* type);
|
||||
|
||||
/* Normaliza um nome/extensao de linguagem ("py" -> "python"); nunca NULL. */
|
||||
TB_API const char* tb_syntax_normalize_lang(const char* lang);
|
||||
|
||||
TB_API const char* tb_syntax_last_error(void);
|
||||
|
||||
#endif /* TINYBLOCKS_SYNTAX_H */
|
||||
@@ -0,0 +1,15 @@
|
||||
# Metadados da library syntax. Lido pela UI/build sem recompilar o .so.
|
||||
[library]
|
||||
name = "tinyblocks-syntax"
|
||||
version = "1.0.0"
|
||||
category = "Sintaxe"
|
||||
description = "Realca sintaxe de codigo e devolve XML colorido"
|
||||
color = [255, 152, 0, 255]
|
||||
dark = [230, 119, 0, 255]
|
||||
|
||||
[build]
|
||||
sources = ["src/tb_syntax.c"]
|
||||
includes = ["include"]
|
||||
shared = "build/libtinyblocks-syntax.so"
|
||||
static = "build/libtinyblocks-syntax.a"
|
||||
depends = []
|
||||
@@ -0,0 +1,499 @@
|
||||
/*
|
||||
* TinyBlocks - tb_syntax.c
|
||||
* Categoria "Sintaxe": Syntax.Highlight / Syntax.Languages / Syntax.Color.
|
||||
* Tokenizador simples (keyword/string/comment/number/preproc/punct) que
|
||||
* devolve o texto colorido em XML.
|
||||
*/
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include <ctype.h>
|
||||
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
#include "tb_syntax.h"
|
||||
|
||||
static char s_err[160] = "";
|
||||
const char* tb_syntax_last_error(void) { return s_err; }
|
||||
|
||||
/* ---------------------------------------------------------------- Buffer */
|
||||
typedef struct { char* p; size_t n, cap; } Buf;
|
||||
|
||||
static bool b_reserve(Buf* b, size_t extra) {
|
||||
if (b->n + extra + 1 <= b->cap) return true;
|
||||
size_t cap = b->cap ? b->cap : 128;
|
||||
while (cap < b->n + extra + 1) cap *= 2;
|
||||
char* p = (char*)realloc(b->p, cap);
|
||||
if (!p) return false;
|
||||
b->p = p; b->cap = cap;
|
||||
return true;
|
||||
}
|
||||
static bool b_raw(Buf* b, const char* s, size_t n) {
|
||||
if (!b_reserve(b, n)) return false;
|
||||
memcpy(b->p + b->n, s, n); b->n += n; b->p[b->n] = 0; return true;
|
||||
}
|
||||
static bool b_str(Buf* b, const char* s) { return b_raw(b, s, strlen(s)); }
|
||||
static bool b_ch(Buf* b, char c) { return b_raw(b, &c, 1); }
|
||||
|
||||
static void b_esc(Buf* b, const char* s, size_t n) {
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
char c = s[i];
|
||||
if (c == '&') b_str(b, "&");
|
||||
else if (c == '<') b_str(b, "<");
|
||||
else if (c == '>') b_str(b, ">");
|
||||
else b_ch(b, c);
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- Token tip */
|
||||
typedef enum { T_PLAIN, T_KW, T_TYPE, T_STR, T_NUM, T_CMT, T_PRE,
|
||||
T_FN, T_OP, T_PUNC, T_ID } TK;
|
||||
|
||||
static const char* tk_name(TK k) {
|
||||
switch (k) {
|
||||
case T_KW: return "kw";
|
||||
case T_TYPE: return "type";
|
||||
case T_STR: return "str";
|
||||
case T_NUM: return "num";
|
||||
case T_CMT: return "cmt";
|
||||
case T_PRE: return "pre";
|
||||
case T_FN: return "fn";
|
||||
case T_OP: return "op";
|
||||
case T_PUNC: return "punc";
|
||||
case T_ID: return "id";
|
||||
default: return "plain";
|
||||
}
|
||||
}
|
||||
static const char* tk_color(TK k) {
|
||||
switch (k) {
|
||||
case T_KW: return "#c678dd";
|
||||
case T_TYPE: return "#e5c07b";
|
||||
case T_STR: return "#98c379";
|
||||
case T_NUM: return "#d19a66";
|
||||
case T_CMT: return "#7f848e";
|
||||
case T_PRE: return "#e06c75";
|
||||
case T_FN: return "#61afef";
|
||||
case T_OP: return "#56b6c2";
|
||||
case T_PUNC: return "#abb2bf";
|
||||
case T_ID: return "#9cdcfe";
|
||||
default: return "#d4d4d4";
|
||||
}
|
||||
}
|
||||
|
||||
const char* tb_syntax_type_color(const char* type) {
|
||||
if (!type) return tk_color(T_PLAIN);
|
||||
if (!strcmp(type, "kw")) return tk_color(T_KW);
|
||||
if (!strcmp(type, "type")) return tk_color(T_TYPE);
|
||||
if (!strcmp(type, "str")) return tk_color(T_STR);
|
||||
if (!strcmp(type, "num")) return tk_color(T_NUM);
|
||||
if (!strcmp(type, "cmt")) return tk_color(T_CMT);
|
||||
if (!strcmp(type, "pre")) return tk_color(T_PRE);
|
||||
if (!strcmp(type, "fn")) return tk_color(T_FN);
|
||||
if (!strcmp(type, "op")) return tk_color(T_OP);
|
||||
if (!strcmp(type, "punc")) return tk_color(T_PUNC);
|
||||
if (!strcmp(type, "id")) return tk_color(T_ID);
|
||||
return tk_color(T_PLAIN);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ Linguagens */
|
||||
typedef struct {
|
||||
const char* name;
|
||||
const char* aliases; /* separados por espaco */
|
||||
const char* line_cmt; /* NULL = nenhum */
|
||||
bool block_cmt; /* C-style */
|
||||
bool preproc; /* '#' no inicio da linha */
|
||||
bool quotes; /* ' e " */
|
||||
const char* keywords;
|
||||
const char* types;
|
||||
const char* builtins;
|
||||
} Lang;
|
||||
|
||||
#define KW_C \
|
||||
"auto break case const continue default do else enum extern for goto if " \
|
||||
"inline register restrict return sizeof static struct switch typedef " \
|
||||
"union volatile while _Bool _Static_assert"
|
||||
#define TY_C \
|
||||
"char double float int long short signed unsigned void size_t ssize_t " \
|
||||
"int8_t int16_t int32_t int64_t uint8_t uint16_t uint32_t uint64_t " \
|
||||
"uintptr_t ptrdiff_t bool FILE va_list"
|
||||
#define BI_C \
|
||||
"printf fprintf sprintf snprintf malloc calloc realloc free memcpy memset " \
|
||||
"strlen strcmp strcpy memmove abs fabs sqrt pow sin cos floor ceil fopen " \
|
||||
"fclose fread fwrite fgets fputs remove rename"
|
||||
|
||||
#define KW_PY \
|
||||
"and as assert async await break class continue def del elif else except " \
|
||||
"finally for from global if import in is lambda nonlocal not or pass raise " \
|
||||
"return try while with yield"
|
||||
#define TY_PY \
|
||||
"int float complex bool str bytes list tuple dict set frozenset object " \
|
||||
"type None True False self"
|
||||
#define BI_PY \
|
||||
"print len range str int float list dict set tuple sum min max abs open " \
|
||||
"enumerate zip map filter sorted type isinstance getattr setattr append"
|
||||
|
||||
#define KW_JS \
|
||||
"var let const function return if else for while do break continue class " \
|
||||
"new delete typeof instanceof in of this super extends import export from " \
|
||||
"default try catch finally throw async await yield switch case null " \
|
||||
"undefined true false"
|
||||
#define TY_JS \
|
||||
"Object Array String Number Boolean Symbol Promise Map Set Date RegExp"
|
||||
#define BI_JS \
|
||||
"console log alert parseInt parseFloat JSON stringify require"
|
||||
|
||||
#define KW_TOML "true false"
|
||||
#define KW_MD ""
|
||||
|
||||
static Lang L_C = { "c", "c h cpp cc cxx hpp c++ objc", "//", true, true, true,
|
||||
KW_C, TY_C, BI_C };
|
||||
static Lang L_PY = { "python", "py python python3", "#", false, false, true,
|
||||
KW_PY, TY_PY, BI_PY };
|
||||
static Lang L_JS = { "javascript", "js javascript mjs node", "//", true, false, true,
|
||||
KW_JS, TY_JS, BI_JS };
|
||||
static Lang L_JSON = { "json", "json", NULL, false, false, true,
|
||||
"true false null", "", "" };
|
||||
static Lang L_TOML = { "toml", "toml ini cfg", "#", false, false, true,
|
||||
KW_TOML, "", "" };
|
||||
static Lang L_XML = { "xml", "xml html htm svg xhtml", NULL, true, false, true,
|
||||
"", "", "" };
|
||||
static Lang L_MD = { "markdown", "md markdown mkd", NULL, false, false, true,
|
||||
KW_MD, "", "" };
|
||||
static Lang L_TXT = { "texto", "txt text plain log", NULL, false, false, false,
|
||||
"", "", "" };
|
||||
|
||||
static Lang* LANGS[] = { &L_C, &L_PY, &L_JS, &L_JSON, &L_TOML, &L_XML, &L_MD, &L_TXT };
|
||||
#define NLANGS ((int)(sizeof(LANGS)/sizeof(LANGS[0])))
|
||||
|
||||
int tb_syntax_language_count(void) { return NLANGS; }
|
||||
const char* tb_syntax_language_name(int i) {
|
||||
if (i < 0 || i >= NLANGS) return "texto";
|
||||
return LANGS[i]->name;
|
||||
}
|
||||
|
||||
const char* tb_syntax_normalize_lang(const char* lang) {
|
||||
if (!lang || !*lang) return "texto";
|
||||
/* Aceita nome de linguagem ou caminho com extensao: usa o que vem
|
||||
* depois do ultimo '.'. */
|
||||
const char* src = lang;
|
||||
const char* dot = strrchr(lang, '.');
|
||||
if (dot && dot[1]) src = dot + 1;
|
||||
char buf[32]; size_t n = 0;
|
||||
for (const char* p = src; *p && n < sizeof(buf)-1; p++)
|
||||
buf[n++] = (char)tolower((unsigned char)*p);
|
||||
buf[n] = 0;
|
||||
if (!buf[0]) return "texto";
|
||||
for (int i = 0; i < NLANGS; i++) {
|
||||
const char* a = LANGS[i]->aliases;
|
||||
size_t al = strlen(LANGS[i]->name);
|
||||
for (const char* p = a; p && *p; ) {
|
||||
while (*p == ' ') p++;
|
||||
const char* s = p;
|
||||
while (*p && *p != ' ') p++;
|
||||
size_t l = (size_t)(p - s);
|
||||
if (l == n && !strncmp(s, buf, l)) return LANGS[i]->name;
|
||||
}
|
||||
if (al == n && !strncmp(LANGS[i]->name, buf, n)) return LANGS[i]->name;
|
||||
}
|
||||
return "texto";
|
||||
}
|
||||
|
||||
static Lang* lang_find(const char* lang) {
|
||||
const char* nm = tb_syntax_normalize_lang(lang);
|
||||
for (int i = 0; i < NLANGS; i++)
|
||||
if (!strcmp(LANGS[i]->name, nm)) return LANGS[i];
|
||||
return &L_TXT;
|
||||
}
|
||||
|
||||
static bool word_in(const char* list, const char* w, size_t n) {
|
||||
if (!list || !*list) return false;
|
||||
const char* p = list;
|
||||
while (*p) {
|
||||
while (*p == ' ') p++;
|
||||
const char* s = p;
|
||||
while (*p && *p != ' ') p++;
|
||||
if ((size_t)(p - s) == n && !strncmp(s, w, n)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- Emissao */
|
||||
static bool emit(Buf* b, TK k, const char* s, size_t n, bool inline_mode) {
|
||||
(void)inline_mode;
|
||||
if (n == 0) return true;
|
||||
b_str(b, "<t type=\"");
|
||||
b_str(b, tk_name(k));
|
||||
b_str(b, "\" color=\"");
|
||||
b_str(b, tk_color(k));
|
||||
b_str(b, "\">");
|
||||
b_esc(b, s, n);
|
||||
b_str(b, "</t>");
|
||||
return true;
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------- Tokenizadores */
|
||||
static bool is_id_start(int c) { return isalpha(c) || c == '_'; }
|
||||
static bool is_id_char(int c) { return isalnum(c) || c == '_'; }
|
||||
static bool is_op(int c) {
|
||||
return strchr("+-*/%=!<>&|^~?:.", c) != NULL;
|
||||
}
|
||||
static bool is_punc(int c) { return strchr("(){}[];,@", c) != NULL; }
|
||||
|
||||
static void tok_c_like(Buf* b, const char* s, Lang* L, bool inline_mode) {
|
||||
size_t i = 0, n = strlen(s);
|
||||
bool line_start = true;
|
||||
while (i < n) {
|
||||
char c = s[i];
|
||||
if (c == '\n') { b_ch(b, '\n'); i++; line_start = true; continue; }
|
||||
if (c == ' ' || c == '\t' || c == '\r') { b_ch(b, c); i++; continue; }
|
||||
if (line_start && L->preproc && c == '#') {
|
||||
size_t j = i; while (j < n && s[j] != '\n') j++;
|
||||
emit(b, T_PRE, s + i, j - i, inline_mode); i = j; line_start = false; continue;
|
||||
}
|
||||
if (L->block_cmt && c == '/' && i + 1 < n && s[i+1] == '*') {
|
||||
size_t j = i + 2; while (j + 1 < n && !(s[j] == '*' && s[j+1] == '/')) j++;
|
||||
j = (j + 1 < n) ? j + 2 : n;
|
||||
emit(b, T_CMT, s + i, j - i, inline_mode); i = j; line_start = false; continue;
|
||||
}
|
||||
if (L->line_cmt && !strncmp(s + i, L->line_cmt, strlen(L->line_cmt))) {
|
||||
size_t j = i; while (j < n && s[j] != '\n') j++;
|
||||
emit(b, T_CMT, s + i, j - i, inline_mode); i = j; continue;
|
||||
}
|
||||
if (c == '"' || (L->quotes && c == '\'')) {
|
||||
char q = c; size_t j = i + 1;
|
||||
while (j < n && s[j] != q) { if (s[j] == '\\' && j + 1 < n) j++; j++; }
|
||||
if (j < n) j++;
|
||||
emit(b, T_STR, s + i, j - i, inline_mode); i = j; line_start = false; continue;
|
||||
}
|
||||
if (isdigit((unsigned char)c) || (c == '.' && i + 1 < n && isdigit((unsigned char)s[i+1]))) {
|
||||
size_t j = i;
|
||||
while (j < n && (isalnum((unsigned char)s[j]) || s[j] == '.' || s[j] == '_' ||
|
||||
s[j] == 'x' || s[j] == 'X')) j++;
|
||||
emit(b, T_NUM, s + i, j - i, inline_mode); i = j; line_start = false; continue;
|
||||
}
|
||||
if (is_id_start((unsigned char)c)) {
|
||||
size_t j = i;
|
||||
while (j < n && is_id_char((unsigned char)s[j])) j++;
|
||||
size_t wl = j - i;
|
||||
TK k;
|
||||
if (word_in(L->keywords, s + i, wl)) k = T_KW;
|
||||
else if (word_in(L->types, s + i, wl)) k = T_TYPE;
|
||||
else if (word_in(L->builtins, s + i, wl)) k = T_FN;
|
||||
else {
|
||||
size_t jj = j; while (jj < n && (s[jj] == ' ' || s[jj] == '\t')) jj++;
|
||||
k = (jj < n && s[jj] == '(') ? T_FN : T_ID;
|
||||
}
|
||||
emit(b, k, s + i, wl, inline_mode); i = j; line_start = false; continue;
|
||||
}
|
||||
if (is_op((unsigned char)c)) {
|
||||
size_t j = i; while (j < n && is_op((unsigned char)s[j])) j++;
|
||||
emit(b, T_OP, s + i, j - i, inline_mode); i = j; line_start = false; continue;
|
||||
}
|
||||
if (is_punc((unsigned char)c)) {
|
||||
emit(b, T_PUNC, s + i, 1, inline_mode); i++; line_start = false; continue;
|
||||
}
|
||||
b_ch(b, c); i++; line_start = false;
|
||||
}
|
||||
}
|
||||
|
||||
/* XML/HTML: trata tags <nome attr="valor"> e comentarios <!-- --> */
|
||||
static void tok_xml(Buf* b, const char* s, bool inline_mode) {
|
||||
size_t i = 0, n = strlen(s);
|
||||
while (i < n) {
|
||||
if (!strncmp(s + i, "<!--", 4)) {
|
||||
size_t j = i + 4; while (j + 2 < n && strncmp(s + j, "-->", 3)) j++;
|
||||
j = (j + 2 < n) ? j + 3 : n;
|
||||
emit(b, T_CMT, s + i, j - i, inline_mode); i = j; continue;
|
||||
}
|
||||
if (s[i] == '<') {
|
||||
size_t j = i;
|
||||
emit(b, T_PUNC, s + j, 1, inline_mode); j++;
|
||||
if (j < n && s[j] == '/') { emit(b, T_PUNC, s + j, 1, inline_mode); j++; }
|
||||
size_t ns = j;
|
||||
while (j < n && (isalnum((unsigned char)s[j]) || s[j] == '-' || s[j] == ':' || s[j] == '_')) j++;
|
||||
if (j > ns) emit(b, T_TYPE, s + ns, j - ns, inline_mode);
|
||||
while (j < n && s[j] != '>') {
|
||||
if (s[j] == '"' || s[j] == '\'') {
|
||||
char q = s[j]; size_t k = j + 1;
|
||||
while (k < n && s[k] != q) k++;
|
||||
if (k < n) k++;
|
||||
emit(b, T_STR, s + j, k - j, inline_mode); j = k;
|
||||
} else if (is_id_start((unsigned char)s[j])) {
|
||||
size_t k = j; while (k < n && is_id_char((unsigned char)s[k])) k++;
|
||||
emit(b, T_ID, s + j, k - j, inline_mode); j = k;
|
||||
} else if (s[j] == '=' || s[j] == '/') {
|
||||
emit(b, T_OP, s + j, 1, inline_mode); j++;
|
||||
} else if (s[j] == ' ' || s[j] == '\t' || s[j] == '\n') {
|
||||
b_ch(b, s[j]); j++;
|
||||
} else { b_ch(b, s[j]); j++; }
|
||||
}
|
||||
if (j < n) { emit(b, T_PUNC, s + j, 1, inline_mode); j++; }
|
||||
i = j; continue;
|
||||
}
|
||||
if (s[i] == '&') {
|
||||
size_t j = i + 1; while (j < n && s[j] != ';' && j - i < 12) j++;
|
||||
if (j < n && s[j] == ';') j++;
|
||||
emit(b, T_NUM, s + i, j - i, inline_mode); i = j; continue;
|
||||
}
|
||||
b_ch(b, s[i]); i++;
|
||||
}
|
||||
}
|
||||
|
||||
/* Markdown: titulos, listas, citacoes, codigo, links, enfase. */
|
||||
static void tok_md(Buf* b, const char* s, bool inline_mode) {
|
||||
size_t i = 0, n = strlen(s);
|
||||
bool bol = true;
|
||||
while (i < n) {
|
||||
if (s[i] == '\n') { b_ch(b, '\n'); i++; bol = true; continue; }
|
||||
if (bol) {
|
||||
if (s[i] == '#') {
|
||||
size_t j = i; while (j < n && s[j] == '#') j++;
|
||||
emit(b, T_KW, s + i, j - i, inline_mode);
|
||||
size_t k = j; while (k < n && s[k] != '\n') k++;
|
||||
emit(b, T_TYPE, s + j, k - j, inline_mode);
|
||||
i = k; bol = false; continue;
|
||||
}
|
||||
if (s[i] == '>' || s[i] == '-' || s[i] == '*' || s[i] == '+') {
|
||||
size_t j = i; while (j < n && (s[j] == s[i] || s[j] == ' ')) j++;
|
||||
emit(b, T_OP, s + i, j - i, inline_mode); i = j; bol = false; continue;
|
||||
}
|
||||
if (isdigit((unsigned char)s[i])) {
|
||||
size_t j = i; while (j < n && (isdigit((unsigned char)s[j]) || s[j] == '.' || s[j] == ')')) j++;
|
||||
emit(b, T_OP, s + i, j - i, inline_mode); i = j; bol = false; continue;
|
||||
}
|
||||
bol = false;
|
||||
}
|
||||
if (s[i] == '`') {
|
||||
size_t j = i + 1; while (j < n && s[j] != '`' && s[j] != '\n') j++;
|
||||
if (j < n && s[j] == '`') j++;
|
||||
emit(b, T_STR, s + i, j - i, inline_mode); i = j; continue;
|
||||
}
|
||||
if (s[i] == '*' || s[i] == '_') {
|
||||
size_t j = i; while (j < n && (s[j] == '*' || s[j] == '_')) j++;
|
||||
emit(b, T_OP, s + i, j - i, inline_mode); i = j; continue;
|
||||
}
|
||||
if (s[i] == '[') {
|
||||
size_t j = i; int depth = 0;
|
||||
while (j < n && s[j] != '\n') {
|
||||
if (s[j] == '[') depth++;
|
||||
else if (s[j] == ']') { depth--; if (depth == 0) { j++; break; } }
|
||||
j++;
|
||||
}
|
||||
emit(b, T_FN, s + i, j - i, inline_mode); i = j; continue;
|
||||
}
|
||||
b_ch(b, s[i]); i++;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- Render */
|
||||
char* tb_syntax_highlight_inline(const char* text, const char* lang) {
|
||||
s_err[0] = 0;
|
||||
if (!text) text = "";
|
||||
Lang* L = lang_find(lang);
|
||||
/* inline: uma unica linha (quebras viram espacos) */
|
||||
char* tmp = (char*)malloc(strlen(text) + 1);
|
||||
if (!tmp) { snprintf(s_err, sizeof(s_err), "sem memoria"); return NULL; }
|
||||
size_t k = 0;
|
||||
for (const char* p = text; *p; p++) tmp[k++] = (*p == '\n') ? ' ' : *p;
|
||||
tmp[k] = 0;
|
||||
Buf b = {0};
|
||||
if (L == &L_XML) tok_xml(&b, tmp, true);
|
||||
else if (L == &L_MD) tok_md(&b, tmp, true);
|
||||
else tok_c_like(&b, tmp, L, true);
|
||||
free(tmp);
|
||||
return b.p;
|
||||
}
|
||||
|
||||
char* tb_syntax_highlight(const char* text, const char* lang) {
|
||||
s_err[0] = 0;
|
||||
/* divide por linhas e tokeniza cada uma (tokenizador pede string terminada) */
|
||||
Lang* L = lang_find(lang);
|
||||
Buf b = {0};
|
||||
char hdr[96];
|
||||
snprintf(hdr, sizeof(hdr), "<code lang=\"%s\">\n", L->name);
|
||||
b_str(&b, hdr);
|
||||
const char* p = text ? text : "";
|
||||
size_t n = strlen(p);
|
||||
size_t i = 0;
|
||||
while (i <= n) {
|
||||
const char* nl = strchr(p + i, '\n');
|
||||
size_t len = nl ? (size_t)(nl - (p + i)) : n - i;
|
||||
char* line = (char*)malloc(len + 1);
|
||||
if (!line) { free(b.p); snprintf(s_err, sizeof(s_err), "sem memoria"); return NULL; }
|
||||
memcpy(line, p + i, len); line[len] = 0;
|
||||
b_str(&b, "<line>");
|
||||
if (L == &L_XML) tok_xml(&b, line, false);
|
||||
else if (L == &L_MD) tok_md(&b, line, false);
|
||||
else tok_c_like(&b, line, L, false);
|
||||
b_str(&b, "</line>\n");
|
||||
free(line);
|
||||
if (!nl) break;
|
||||
i = (size_t)(nl - p) + 1;
|
||||
}
|
||||
b_str(&b, "</code>");
|
||||
return b.p;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- Blocos */
|
||||
static const char* in_text(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) {
|
||||
TinyBlocks_Value v = tb_block_get_input(self, rt, i);
|
||||
return (v.kind == TB_VALUE_TEXT && v.as.text) ? v.as.text : "";
|
||||
}
|
||||
|
||||
static void eval_highlight(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
char* x = tb_syntax_highlight(in_text(self, rt, 0), in_text(self, rt, 1));
|
||||
tb_block_set_output(self, 0, tb_value_text(x ? x : ""));
|
||||
free(x);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_inline(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
char* x = tb_syntax_highlight_inline(in_text(self, rt, 0), in_text(self, rt, 1));
|
||||
tb_block_set_output(self, 0, tb_value_text(x ? x : ""));
|
||||
free(x);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_languages(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
(void)rt;
|
||||
Buf b = {0};
|
||||
for (int i = 0; i < NLANGS; i++) {
|
||||
if (i) b_str(&b, ", ");
|
||||
b_str(&b, LANGS[i]->name);
|
||||
}
|
||||
tb_block_set_output(self, 0, tb_value_text(b.p ? b.p : ""));
|
||||
free(b.p);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name,
|
||||
const TinyBlocks_SlotDesc* in, uint32_t ni,
|
||||
const TinyBlocks_SlotDesc* out, uint32_t no,
|
||||
void (*fn)(TinyBlocks_Block*, TinyBlocks*)) {
|
||||
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, out, no, fn);
|
||||
return t && tb_library_add(lib, &t->base);
|
||||
}
|
||||
|
||||
static bool syntax_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||
static const TinyBlocks_Category cat = {
|
||||
"Sintaxe",
|
||||
{ 255/255.f, 152/255.f, 0/255.f, 1.f},
|
||||
{ 230/255.f, 119/255.f, 0/255.f, 1.f},
|
||||
};
|
||||
tb_library_set_category(lib, &cat);
|
||||
|
||||
static const TinyBlocks_SlotDesc hl_in[] = {{"texto", TB_VALUE_TEXT}, {"linguagem", TB_VALUE_TEXT}};
|
||||
static const TinyBlocks_SlotDesc out_text_s[] = {{"xml", TB_VALUE_TEXT}};
|
||||
static const TinyBlocks_SlotDesc out_list_s[] = {{"linguagens", TB_VALUE_TEXT}};
|
||||
|
||||
return reg(rt, lib, "Syntax.Highlight", hl_in, 2, out_text_s, 1, eval_highlight)
|
||||
&& reg(rt, lib, "Syntax.Inline", hl_in, 2, out_text_s, 1, eval_inline)
|
||||
&& reg(rt, lib, "Syntax.Languages", NULL, 0, out_list_s, 1, eval_languages);
|
||||
}
|
||||
|
||||
TINYBLOCKS_DEFINE_LIBRARY(syntax, "tinyblocks-syntax", "1.0.0", syntax_init, NULL)
|
||||
|
||||
const TinyBlocks_LibraryDescriptor* tb_syntax_get_library(void) {
|
||||
return &_tb_lib_desc_syntax;
|
||||
}
|
||||
Reference in new issue
Block a user