Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 22 additions & 49 deletions packages/api-model/src/doc/elixir.ts
Original file line number Diff line number Diff line change
@@ -1,63 +1,36 @@
import { parseMarkdownDocFull, type ParsedMarkdownDoc } from './markdown.ts'
import { fromMarkdown } from 'mdast-util-from-markdown'
import { parseMarkdownDocFull, type MarkdownDocLine, type ParsedMarkdownDoc } from './markdown.ts'

const FENCE = /^\s*(`{3,}|~{3,})/
const PROMPT = /^\s*(?:iex(?:\(\d+\))?|\.\.\.(?:\(\d+\))?)>/
const INDENTED = /^(?: {4}| {0,3}\t)/m
/** ExDoc's admonition: `> #### Heading {: .warning}`. */
const ADMONITION = /^>\s*#{1,6}\s+(.*?)\s*\{:\s*\.(warning|error|info|tip|neutral)\s*\}\s*$/
const ADMONITION_KIND: Record<string, string> = { warning: 'WARNING', error: 'CAUTION', info: 'NOTE', tip: 'TIP', neutral: 'NOTE' }

const indentOf = (line: string) => /^ */.exec(line)![0].length
/** Use Markdown's block boundaries so paragraph and list continuation stays in prose. */
function indentedExamples(raw: string): MarkdownDocLine[] {
const lines = raw.split('\n')
if (!INDENTED.test(raw)) return lines

/**
* An `iex>` doctest is an indented block in ExDoc's Markdown, and the shared
* parser reads only fenced code. Fence it, keeping the prompts: a doctest is a
* session, and its expected results are the lines without a prompt.
*
* A block belongs to the doctest it starts, so the blank lines inside a run of
* `iex>` expressions do not end it; the first unindented or unprompted line
* after a blank one does.
*/
function fenceDoctests(lines: string[]): string[] {
const out: string[] = []
let fence: string | undefined
for (let i = 0; i < lines.length; i++) {
const line = lines[i]!
const opening = FENCE.exec(line)
if (fence) {
// A closing fence repeats the opening character at least as many times and carries no info string.
if (opening && opening[1]![0] === fence[0] && opening[1]!.length >= fence.length && !line.replace(/^\s*[`~]+/, '').trim()) fence = undefined
out.push(line)
continue
}
if (opening) { fence = opening[1]!; out.push(line); continue }
if (indentOf(line) >= 4 && PROMPT.test(line)) {
const base = indentOf(line)
const block: string[] = []
while (i < lines.length) {
const next = lines[i]!
if (next.trim() && indentOf(next) < base) break
if (!next.trim()) {
// A blank line continues the session only while another prompt follows.
const following = lines.slice(i + 1).find((entry) => entry.trim())
if (!following || indentOf(following) < base || !PROMPT.test(following)) break
}
block.push(next.slice(Math.min(base, indentOf(next))))
i++
}
i--
out.push('```elixir', ...block, '```')
continue
}
out.push(line)
const out: MarkdownDocLine[] = []
let cursor = 0
for (const node of fromMarkdown(raw).children) {
if (node.type !== 'code' || !node.position) continue
const first = node.position.start.line - 1
if (!INDENTED.test(lines[first]!)) continue
out.push(...lines.slice(cursor, first), { code: node.value })
cursor = node.position.end.line
}
out.push(...lines.slice(cursor))
return out
}

/** Rewrite ExDoc admonitions as the GitHub alerts the shared parser lifts into callouts. */
function alertAdmonitions(lines: string[]): string[] {
const out: string[] = []
function alertAdmonitions(lines: MarkdownDocLine[]): MarkdownDocLine[] {
const out: MarkdownDocLine[] = []
let fence = false
for (const line of lines) {
if (typeof line !== 'string') { out.push(line); continue }
if (FENCE.test(line)) fence = !fence
const match = fence ? null : ADMONITION.exec(line)
if (!match) { out.push(line); continue }
Expand All @@ -67,8 +40,8 @@ function alertAdmonitions(lines: string[]): string[] {
return out
}

/** ExDoc Markdown: fenced and indented `iex>` examples, `## Examples` sections and `{: .warning}` admonitions. */
/** ExDoc Markdown with fenced and indented examples, example sections and admonitions. */
export function parseElixirDoc(raw: string): ParsedMarkdownDoc {
const lines = alertAdmonitions(fenceDoctests(raw.replaceAll('\r\n', '\n').split('\n')))
return parseMarkdownDocFull(lines.join('\n'), 'elixir')
const lines = alertAdmonitions(indentedExamples(raw.replaceAll('\r\n', '\n')))
return parseMarkdownDocFull(lines, 'elixir')
}
31 changes: 20 additions & 11 deletions packages/api-model/src/doc/markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,8 +169,10 @@ export function parseMarkdownDoc(raw: string, defaultLang = 'text'): DocBlock {
return parseMarkdownDocFull(raw, defaultLang).doc
}

export function parseMarkdownDocFull(raw: string, defaultLang = 'text'): ParsedMarkdownDoc {
const lines = raw.split('\n')
export type MarkdownDocLine = string | { code: string }

export function parseMarkdownDocFull(raw: string | MarkdownDocLine[], defaultLang = 'text'): ParsedMarkdownDoc {
const lines = typeof raw === 'string' ? raw.split('\n') : raw
const prose: string[] = []
const examples: { lang: string; code: string; intro?: string }[] = []

Expand Down Expand Up @@ -210,20 +212,27 @@ export function parseMarkdownDocFull(raw: string, defaultLang = 'text'): ParsedM
tag = undefined
}

const addExample = (lang: string, code: string) => {
examples.push({
lang,
code: code.replace(/\s+$/, ''),
intro: pending.join(' ').replace(/\s+/g, ' ').trim() || undefined,
})
pending = []
}

for (const line of lines) {
if (typeof line !== 'string') {
closeQuote()
addExample(defaultLang, line.code)
continue
}
const fenced = FENCE.exec(line)
if (fence) {
if (fenced) {
const open = fence
examples.push({
lang: open.lang || defaultLang,
code: (defaultLang === 'rust' && (!open.lang || open.lang === 'rust') ? rustdocVisible(open.code) : open.code)
.map((l) => l.slice(open.indent))
.join('\n')
.replace(/\s+$/, ''),
intro: pending.join(' ').replace(/\s+/g, ' ').trim() || undefined,
})
pending = []
const code = defaultLang === 'rust' && (!open.lang || open.lang === 'rust') ? rustdocVisible(open.code) : open.code
addExample(open.lang || defaultLang, code.map((l) => l.slice(open.indent)).join('\n'))
fence = undefined
continue
}
Expand Down
30 changes: 30 additions & 0 deletions packages/api-model/test/elixir.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,36 @@ describe('ExDoc Markdown', () => {
expect(doc.body ?? '').not.toContain('iex>')
})

it('keeps a plain indented example together with its blank line and callback indentation', () => {
const code = [
'alias LibTmux.Server',
'',
'Server.with_owned(options, fn server ->',
' Server.snapshot!(server)',
'end)',
].join('\n')
const indented = code.split('\n').map((line) => line ? ` ${line}` : '').join('\n')
const { doc } = parseElixirDoc(`Runs a function.\n\n${indented}\n\nThe server stops when the call returns.`)
expect(doc.examples).toEqual([{ lang: 'elixir', code, intro: undefined }])
expect(doc.body).toBe('The server stops when the call returns.')
})

it('keeps indented paragraphs in Markdown prose', () => {
const { doc } = parseElixirDoc([
'Summary.',
'',
'A paragraph with a',
' continuation.',
'',
'- A list item.',
'',
' A second paragraph in the list item.',
].join('\n'))
expect(doc.examples).toBeUndefined()
expect(doc.body).toContain(' continuation.')
expect(doc.body).toContain(' A second paragraph in the list item.')
})

it('leaves a fenced block alone and treats a bare fence as Elixir', () => {
const { doc } = parseElixirDoc('Summary.\n\n```\nServer.new(socket: "/tmp/tmux")\n```\n')
expect(doc.examples).toEqual([{ lang: 'elixir', code: 'Server.new(socket: "/tmp/tmux")', intro: undefined }])
Expand Down
2 changes: 1 addition & 1 deletion site/src/data/api/elixir.json

Large diffs are not rendered by default.

23 changes: 23 additions & 0 deletions site/test/api-prose.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'
import { readFileSync } from 'node:fs'
import { fromMarkdown } from 'mdast-util-from-markdown'
import { API_MODELS, createApiIndex } from '../src/lib/api-models'
import { pinnedSource } from '../src/lib/api-source-pages'
import { symbolMarkdown } from '../src/lib/symbol-markdown'
import { SymbolIndex, tokenizeDoc } from '@libtmux/api-model/reference'
import { parseApiProse } from '@libtmux/api-model/reference'
Expand All @@ -13,6 +14,28 @@ import config from '../ec.config.mjs'
import { codeLang } from '../src/lib/highlight'

describe('shared API prose blocks', () => {
it('exports the owned-server callback in one Elixir code block', () => {
const model = API_MODELS.elixir!
const symbol = model.symbols.find((entry) => entry.id === 'LibTmux.Server.with_owned/2')!
const source = pinnedSource('elixir', symbol.source.file)!
expect(source.revision).toBe(symbol.source.revision)
// The EEP-48 line names @doc. Its closing heredoc sets the Markdown indentation.
const lines = source.content.split('\n').slice(symbol.source.line)
const end = lines.findIndex((line) => line.trim() === '"""')
expect(end).toBeGreaterThan(0)
const indent = lines[end]!.indexOf('"""')
const doc = lines.slice(0, end).map((line) => line.slice(indent)).join('\n')
const expected = fromMarkdown(doc).children.filter((node) => node.type === 'code')
expect(expected).toHaveLength(1)
expect(expected[0]!.value).toContain('Server.with_owned(')

const blocks = fromMarkdown(symbolMarkdown({ model, symbol })).children.filter((node) => node.type === 'code')
const callbacks = blocks.filter((block) => block.value.includes('Server.with_owned('))
expect(callbacks.map(({ lang, value }) => ({ lang, value }))).toEqual([
{ lang: 'elixir', value: expected[0]!.value },
])
})

it('routes ExDoc guides from nested symbol pages and keeps section fragments', () => {
const model = API_MODELS.elixir!
const version = '0.1.3'
Expand Down
Loading