Skip to content

Commit

Permalink
add include-code pandoc filter
Browse files Browse the repository at this point in the history
  • Loading branch information
prakaa committed Jul 8, 2023
1 parent c3a3110 commit 7a9df69
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
3 changes: 3 additions & 0 deletions _quarto.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
project:
type: website

filters:
- filters/include-code-files.lua

website:
title: "CEEM Gists"
favicon: assets/ceem_logo.png
Expand Down
62 changes: 62 additions & 0 deletions filters/include-code-files.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
--- include-code-files.lua – filter to include code from source files
---
--- Copyright: © 2020 Bruno BEAUFILS
--- License: MIT – see LICENSE file for details

--- Dedent a line
local function dedent (line, n)
return line:sub(1,n):gsub(" ","") .. line:sub(n+1)
end

--- Filter function for code blocks
local function transclude (cb)
if cb.attributes.include then
local content = ""
local fh = io.open(cb.attributes.include)
if not fh then
io.stderr:write("Cannot open file " .. cb.attributes.include .. " | Skipping includes\n")
else
local number = 1
local start = 1

-- change hyphenated attributes to PascalCase
for i,pascal in pairs({"startLine", "endLine"})
do
local hyphen = pascal:gsub("%u", "-%0"):lower()
if cb.attributes[hyphen] then
cb.attributes[pascal] = cb.attributes[hyphen]
cb.attributes[hyphen] = nil
end
end

if cb.attributes.startLine then
cb.attributes.startFrom = cb.attributes.startLine
start = tonumber(cb.attributes.startLine)
end
for line in fh:lines ("L")
do
if cb.attributes.dedent then
line = dedent(line, cb.attributes.dedent)
end
if number >= start then
if not cb.attributes.endLine or number <= tonumber(cb.attributes.endLine) then
content = content .. line
end
end
number = number + 1
end
fh:close()
end
-- remove key-value pair for used keys
cb.attributes.include = nil
cb.attributes.startLine = nil
cb.attributes.endLine = nil
cb.attributes.dedent = nil
-- return final code block
return pandoc.CodeBlock(content, cb.attr)
end
end

return {
{ CodeBlock = transclude }
}

0 comments on commit 7a9df69

Please sign in to comment.