Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Include code from scripts inside Markdown documents #407

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
33 changes: 28 additions & 5 deletions src/reader/markdown.jl
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
function parse_markdown(document_body; is_pandoc = false)
header_text, document_body, offset = separate_header_text(document_body)
header = parse_header(header_text)
code_start, code_end = if is_pandoc
code_start, code_end, code_script = if is_pandoc
r"^<<(?<options>.*?)>>=\s*$",
r"^@\s*$"
r"^@\s*$",
r"a^" # match nothing TODO
else
r"^[`~]{3}(\{?)julia\s*([;,]?)\s*(?<options>.*?)(\}|\s*)$",
r"^[`~]{3}\s*$"
r"^[`~]{3}\s*$",
r"^[`~]{1}(?<options>js\s.*?)[`~]{1}"
end
return header, parse_markdown_body(document_body, code_start, code_end, offset)
return header, parse_markdown_body(document_body, code_start, code_end, code_script, offset)
end

# headers
Expand Down Expand Up @@ -46,7 +48,7 @@ end
# body
# ----

function parse_markdown_body(document_body, code_start, code_end, offset)
function parse_markdown_body(document_body, code_start, code_end, code_script, offset)
lines = split(document_body, '\n')

state = :doc
Expand All @@ -61,6 +63,7 @@ function parse_markdown_body(document_body, code_start, code_end, offset)
chunks = WeaveChunk[]
for (line_no, line) in enumerate(lines)
m = match(code_start, line)
sm = match(code_script, line)
if !isnothing(m) && state === :doc
state = :code

Expand All @@ -76,6 +79,26 @@ function parse_markdown_body(document_body, code_start, code_end, offset)
continue
end

if !isnothing(sm) && state === :doc
option_string = isnothing(sm[:options]) ? "" : strip(sm[:options])
options = parse_options(option_string)
haskey(options, :label) && (options[:name] = options[:label])
haskey(options, :name) || (options[:name] = nothing)

isempty(strip(content)) || push!(chunks, DocChunk(content, doc_no += 1, start_line))

script_path = abspath(options[:js].first)
script_lines = split(read(script_path, String), "\n")
indices = options[:js].second

content = join(script_lines[indices], "\n")
push!(chunks, CodeChunk(content, code_no += 1, start_line, option_string, options))

start_line = line_no + offset
content = ""
continue
end

if occursin(code_end, line) && state === :code
push!(chunks, CodeChunk(content, code_no += 1, start_line, option_string, options))

Expand Down