Add support for better bold/italic formatting

This commit is contained in:
Konstantin Nazarov 2021-08-01 22:40:37 +01:00
parent d97f7044ed
commit f00a95c6a3
Signed by: knazarov
GPG key ID: 4CFE0A42FA409C22
3 changed files with 52 additions and 24 deletions

View file

@ -21,7 +21,7 @@ Here's a list of supported markdown primitives
- Headers
- Paragraphs
- Text formatting: bold
- Text formatting: bold/italic
- Code blocks
- Blockquotes
- Lists, both bulleted and numbered

View file

@ -240,20 +240,34 @@ function escape_text(str) {
return str;
}
function extract_emphasis(str, i, sstr, arr, num, c) {
function extract_emphasis(str, i, sstr) {
sstr=substr(str, i, length(str) - i + 1);
c = ""
if (match(sstr, /^\*{1,3}[^\*]/)) {
c = "*";
if (match(sstr, /^\*[^\*]+\*/) ||
match(sstr, /^\*\*[^\*]+\*\*/) ||
match(sstr, /^\*\*\*[^\*]+\*\*\*/) ||
match(sstr, /^_[^_]+_/) ||
match(sstr, /^__[^_]+__/) ||
match(sstr, /^___[^_]+___/))
return substr(str, i, RLENGTH);
return "";
}
function parse_emphasis(str, i) {
match(str, /^[\*_]{1,3}/);
num = RLENGTH;
}
if (match(sstr, /^_{1,3}[^_]/)) {
c = "_";
num = RLENGTH;
if (num == 1) {
return "<em>" parse_line(substr(str, 2, length(str) - 2)) "</em>";
}
if (num == 2) {
return "<strong>" parse_line(substr(str, 3, length(str) - 4)) "</strong>";
}
if (num == 3) {
return "<strong><em>" parse_line(substr(str, 4, length(str) - 6)) "</em></strong>";
}
return "";
}
function parse_line(str, result, end, i, c) {
@ -262,17 +276,10 @@ function parse_line(str, result, end, i, c) {
for (i=1; i<=length(str); i++) {
c = substr(str, i, 1);
if (c == "*" && is_token(str, i, "**")){
end = find(str, "**", i+2);
if (end != 0) {
result = result "<strong>" parse_line(substr(str, i+2, end - i - 2)) "</strong>";
i = end+1;
}
else {
result = result "**";
i++;
}
if ((c == "*" || c == "_") && extract_emphasis(str, i) != ""){
emphasis = extract_emphasis(str, i);
result = result parse_emphasis(emphasis)
i = i + length(emphasis) - 1;
}
else if (c == "`" && is_token(str, i, "```")) {
end = find(str, "```", i+3);

21
test.sh
View file

@ -103,10 +103,31 @@ underlined header 2
<h2>underlined header 2</h2>
EOF
check <<-EOF
*italic*
_italic_
---
<p><em>italic</em></p>
<p><em>italic</em></p>
EOF
check <<-EOF
**bold**
__bold__
---
<p><strong>bold</strong></p>
<p><strong>bold</strong></p>
EOF
check <<-EOF
***bold italic***
___bold italic___
---
<p><strong><em>bold italic</em></strong></p>
<p><strong><em>bold italic</em></strong></p>
EOF
check <<-EOF