Skip to content

Commit

Permalink
Merge d7b556b into 8403d71
Browse files Browse the repository at this point in the history
  • Loading branch information
StephanoGeorge committed Jul 27, 2022
2 parents 8403d71 + d7b556b commit 28791bb
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,5 +83,6 @@ noremap <buffer> <F6> <Esc>:%!npx md-padding<CR>
### 代码注释
代码格式化不是本仓库的功能之一,请使用对应语言的 prettifier。但代码中的注释会被当做 Markdown 正文来格式化,目前支持这些语言的注释:

- cpp, c, java, javascript, typescript, csharp
- cpp, c, java, javascript, typescript, csharp, go
- sql
- bash, python, ruby
39 changes: 39 additions & 0 deletions src/parser/parse-code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,22 @@ type documentParser = (content: string) => Document

const parsers = {
cpp: cpp,
'c++': cpp,
c: cpp,
java: cpp,
javascript: cpp,
js: cpp,
csharp: cpp,
'c#': cpp,
typescript: cpp,
ts: cpp,
go: cpp,
sql: sql,
bash: bash,
shell: bash,
sh: bash,
python: bash,
py: bash,
ruby: bash
}

Expand Down Expand Up @@ -53,6 +62,36 @@ function * cpp (code: string, parseMarkdown: documentParser) {
}
}

function * sql (code: string, parseMarkdown: documentParser) {
let i = 0; let prevI = 0
const N = code.length
while (i < N) {
const c2 = code.substr(i, 2)
if (c2 === '--') {
const j = code.indexOf('\n', i)
const end = j === -1 ? N : j
if (i + 2 > prevI) {
yield new Raw(code.slice(prevI, i + 2))
}
yield parseMarkdown(code.slice(i + 2, end))
prevI = i = end
} else if (c2 === '/*') {
const j = code.indexOf('*/', i)
const end = j === -1 ? N : j
if (i + 2 > prevI) {
yield new Raw(code.slice(prevI, i + 2))
}
yield parseMarkdown(code.slice(i + 2, end))
prevI = i = end
} else {
i++
}
}
if (prevI < N) {
yield new Raw(code.slice(prevI, N))
}
}

function * bash (code: string, parseMarkdown: documentParser) {
let i = 0; let prevI = 0
const N = code.length
Expand Down
5 changes: 5 additions & 0 deletions test/transformers/pad-markdown.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ describe('padding()', () => {
const output = 'sample: \n```javascript\n/**\n * @param {string} s 字符串 s\n * @return {string}\n */\nvar longestPalindrome = function(s) {}\n```'
expect(padMarkdown(input)).toEqual(output)
})
it('should pad line comment in sql', () => {
const input = 'sample: \n```sql\nSELECT * FROM USER; -- 查找所有USER\n```'
const output = 'sample: \n```sql\nSELECT * FROM USER; -- 查找所有 USER\n```'
expect(padMarkdown(input)).toEqual(output)
})
it('should pad block comment in bash', () => {
const input = 'sample: \n```bash\necho X11就很好 # X11就很好\n```'
const output = 'sample: \n```bash\necho X11就很好 # X11 就很好\n```'
Expand Down

0 comments on commit 28791bb

Please sign in to comment.