From b9b546bced5eae0d3c63c6bb8ee30d434239ae37 Mon Sep 17 00:00:00 2001 From: MichaelHatherly Date: Thu, 8 Feb 2024 13:20:08 +0000 Subject: [PATCH] Fix #30, correct YAML handling in cells Support full YAML syntax rather than just single line key/value pairs. --- src/server.jl | 62 +++++++++++++---------------------- test/testsets/cell_options.jl | 15 ++++++++- 2 files changed, 36 insertions(+), 41 deletions(-) diff --git a/src/server.jl b/src/server.jl index eaa231f..224e49f 100644 --- a/src/server.jl +++ b/src/server.jl @@ -607,53 +607,35 @@ function process_cell_source(source::AbstractString) end function extract_cell_options(source::AbstractString; file::AbstractString, line::Integer) - function error_message(io::IO, msg::AbstractString) - print(io, " ") - printstyled(IOContext(io, :color => true), "← $msg"; color = :red, bold = true) - end - prefix = "#| " - options = Dict{String,Any}() - - msg = IOBuffer() - errors = false - + yaml = IOBuffer() + none = true for line in eachline(IOBuffer(source)) - print(msg, line) if startswith(line, prefix) _, rest = split(line, prefix; limit = 2) - rest = lstrip(rest) - if isempty(rest) - error_message(msg, "blank line") - errors = true - else - try - option = YAML.load(rest) - if isa(option, Dict) - merge!(options, option) - else - error_message(msg, "invalid syntax") - errors = true - end - catch error - error_message(msg, string(error)) - errors = true - end - end + println(yaml, rest) + none = false end - println(msg) end - if errors - error(""" - Error parsing cell attributes: - - $(file):$(line) - ```{julia} - $(rstrip(String(take!(msg)))) - ``` - """) + if none + return Dict{String,Any}() + else + seekstart(yaml) + options = try + YAML.load(yaml) + catch + msg = """ + Error parsing cell attributes at $(file):$(line): + + ```{julia} + $source + ``` + """ + error(msg) + end + isa(options, Dict) || error("Cell attributes must be a dictionary.") + return options end - return options end """ diff --git a/test/testsets/cell_options.jl b/test/testsets/cell_options.jl index c90b892..c7ebf51 100644 --- a/test/testsets/cell_options.jl +++ b/test/testsets/cell_options.jl @@ -28,6 +28,19 @@ end line = 1, ) == Dict("valid" => true) + text = """ + ```{julia} + #| multiline: + #| - 1 + #| - 2 + ``` + """ + @test QuartoNotebookRunner.extract_cell_options( + text; + file = "file.qmd", + line = 1, + ) == Dict("multiline" => [1, 2]) + text = """ ```{julia} #| valid: true @@ -68,7 +81,7 @@ end server = QuartoNotebookRunner.Server() buffer = IOBuffer() - @test_throws_message "Error parsing cell attributes" QuartoNotebookRunner.run!( + @test_throws_message "Cell attributes must be a dictionary." QuartoNotebookRunner.run!( server, notebook; output = buffer,