Skip to content

Instantly share code, notes, and snippets.

@tarleb
Last active January 19, 2024 17:52
Show Gist options
  • Save tarleb/a0f41adfa7b0e5a9be441e945f843299 to your computer and use it in GitHub Desktop.
Save tarleb/a0f41adfa7b0e5a9be441e945f843299 to your computer and use it in GitHub Desktop.
Emulating org-mode's :noexport: behavior for Markdown.
--[[
Remove all subtrees whose headlines contain class `noexport`.
License: MIT
Copyright: © Albert Krewinkel
]]
-- pandoc.utils.make_sections exists since pandoc 2.8
PANDOC_VERSION:must_be_at_least {2,8}
local utils = require 'pandoc.utils'
-- Returns true iff a div is a section div.
local function is_section_div (div)
return div.t == 'Div'
and div.classes[1] == 'section'
and div.attributes.number
end
-- Returns the header element of a section, or nil if the argument is not a
-- section.
local function section_header (div)
if not div.t == 'Div' then return nil end
local header = div.content and div.content[1]
local is_header = is_section_div(div)
and header
and header.t == 'Header'
return is_header and header or nil
end
--- Remove remaining section divs
local function flatten_sections (div)
local header = section_header(div)
if not header then
return nil
else
header.identifier = div.identifier
div.content[1] = header
return div.content
end
end
function drop_noexport_sections (div)
if div.classes:includes('noexport') then
return {}
end
end
--- Setup the document for further processing by wrapping all
--- sections in Div elements.
function setup_document (doc)
local sections = utils.make_sections(false, nil, doc.blocks)
return pandoc.Pandoc(sections, doc.meta)
end
return {
{Pandoc = setup_document},
{Div = drop_noexport_sections},
{Div = flatten_sections}
}
@tarleb
Copy link
Author

tarleb commented May 27, 2020

Mark headers with {.noexport} to exclude them from the final document:

# First

First paragraph.

# This is an internal note {.noexport}

## with subsections

And words. If only a few.

# Third

## Yet more

This is more content.

Running pandoc --lua-filter=noexport-subtrees.lua test.md gives

<h1 id="first">First</h1>
<p>First paragraph.</p>
<h1 id="third">Third</h1>
<h2 id="yet-more">Yet more</h2>
<p>This is more content.</p>

@whyboris
Copy link

whyboris commented Jan 5, 2024

Thank you for this ❤️ it works beautifully 🥳

I do believe the first line should not have a space between the -- and the [[

The script errored on my machine until I changed it to:

--[[

@tarleb
Copy link
Author

tarleb commented Jan 19, 2024

Thank you @whyboris! I removed the space.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment