Skip to content

Commit

Permalink
Support ~~~ syntax in md
Browse files Browse the repository at this point in the history
Co-authored-by: Jakob Voss <voss@gbv.de>
  • Loading branch information
HwangTaehyun and nichtich authored Feb 27, 2023
1 parent 101b810 commit d6d19be
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 7 deletions.
51 changes: 50 additions & 1 deletion docs/markdown.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Markdown Scripts

It's possible to write scripts using markdown. Only code blocks will be executed
by zx.
by zx.

> You can run this markdown file:
>
Expand All @@ -14,6 +14,21 @@ await $`whoami`
await $`echo ${__dirname}`
```
~~~js
await $`whoami`
await $`echo ${__dirname}`
~~~

````js
await $`whoami`
await $`echo ${__dirname}`
````

~~~~js
await $`whoami`
await $`echo ${__dirname}`
~~~~

The `__filename` will be pointed to **markdown.md**:

```js
Expand All @@ -33,10 +48,44 @@ VAR=$(date)
echo "$VAR" | wc -c
```

~~~bash
VAR=$(date)
echo "$VAR" | wc -c
~~~

````bash
VAR=$(date)
echo "$VAR" | wc -c
````

~~~~bash
VAR=$(date)
echo "$VAR" | wc -c
~~~~

Other code blocks are ignored:

```css
body .hero {
margin: 42px;
}
```

~~~css
body .hero {
margin: 42px;
}
~~~

````css
body .hero {
margin: 42px;
}
````

~~~~css
body .hero {
margin: 42px;
}
~~~~

17 changes: 11 additions & 6 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,22 +187,27 @@ function transformMarkdown(buf: Buffer) {
const source = buf.toString()
const output = []
let state = 'root'
let sequence = ''
let match = ''
let prevLineIsEmpty = true
for (let line of source.split('\n')) {
switch (state) {
case 'root':
if (/^( {4}|\t)/.test(line) && prevLineIsEmpty) {
output.push(line)
state = 'tab'
} else if (/^```(js|javascript)$/.test(line)) {
} else if (/^(```+|~~~+)(js|javascript)$/.test(line)) {
output.push('')
state = 'js'
} else if (/^```(sh|bash)$/.test(line)) {
sequence = line.match(/^(```+|~~~+)(js|javascript)$/)![1]
} else if (/^(```+|~~~+)(sh|bash)$/.test(line)) {
output.push('await $`')
state = 'bash'
} else if (/^```.*$/.test(line)) {
sequence = line.match(/^(```+|~~~+)(sh|bash)$/)![1]
} else if (/^(```+|~~~+).*$/.test(line)) {
output.push('')
state = 'other'
sequence = line.match(/^(```+|~~~+)(.*)$/)![1]
} else {
prevLineIsEmpty = line === ''
output.push('// ' + line)
Expand All @@ -219,23 +224,23 @@ function transformMarkdown(buf: Buffer) {
}
break
case 'js':
if (/^```$/.test(line)) {
if (line === sequence) {
output.push('')
state = 'root'
} else {
output.push(line)
}
break
case 'bash':
if (/^```$/.test(line)) {
if (line === sequence) {
output.push('`')
state = 'root'
} else {
output.push(line)
}
break
case 'other':
if (/^```$/.test(line)) {
if (line === sequence) {
output.push('')
state = 'root'
} else {
Expand Down

0 comments on commit d6d19be

Please sign in to comment.