aboutsummaryrefslogtreecommitdiff
path: root/_extensions/ruc-play/semantic-markdown/semantic-markdown.lua
blob: c4669f017940d3248b25b709b572ddafd3a86feb (plain)
  1. --- semantic-markdown - Pandoc plugin to process semantic hints
  2. ---
  3. --- SPDX-FileCopyrightText: 2025 Jonas Smedegaard <dr@jones.dk>
  4. --- SPDX-License-Identifier: GPL-3.0-or-later
  5. ---
  6. --- ## Examples
  7. ---
  8. --- Ideally, this text:
  9. ---
  10. --- ```Markdown+RDF
  11. --- Simple ontological annotation:
  12. --- [This]{foaf:depiction} is not a pipe.
  13. ---
  14. --- Nested, mixed-use and custom-namespaced annotations:
  15. --- [[Ceci]{foaf:depiction} n'est pas une pipe.]{lang=fr bibo:Quote}
  16. ---
  17. --- {bibo}: http://purl.org/ontology/bibo/
  18. --- ```
  19. ---
  20. --- ...should with this filter be transformed to this text:
  21. ---
  22. --- ```Markdown
  23. --- ---
  24. --- turtle: |
  25. --- @prefix bibo: http://purl.org/ontology/bibo/
  26. ---
  27. --- _:001 a foaf:depiction .
  28. --- _:002 a foaf:depiction .
  29. --- _:003 a bibo:Quote .
  30. --- ---
  31. --- Simple ontological annotation:
  32. --- This is not a pipe.
  33. ---
  34. --- Nested, mixed-use and custom-namespaced annotations:
  35. --- [Ceci n'est pas une pipe.]{lang=fr}
  36. --- ```
  37. ---
  38. --- When target document format is html,
  39. --- this filter should ideally produce RDFa 1.1 Lite or Core data.
  40. --- (Lite is *not* a subset of Core as it deviates slightly).
  41. ---
  42. --- * v0.0.1
  43. --- * initial release
  44. ---
  45. --- @version 0.0.1
  46. --- @see <https://source.jones.dk/semantic-markdown/about/>
  47. --- @see <https://moodle.ruc.dk/course/view.php?id=23505>
  48. --- @see <https://www.w3.org/TR/rdfa-primer/#using-rdfa>
  49. --- @see <https://www.ctrl.blog/entry/rdfa-link-attributes.html>
  50. -- TODO: maybe use topdown traversal
  51. -- * order of declaring annotations might matter (but should not)
  52. -- * might enable simpler functions and/or faster processing
  53. -- @see <https://pandoc.org/lua-filters.html#topdown-traversal>
  54. -- ensure stable character classes independent of system locale
  55. -- @see <https://pandoc.org/lua-filters.html#common-pitfalls>
  56. os.setlocale 'C'
  57. --- pseudo-enum table to track parser enclosure state
  58. --- @see <https://stackoverflow.com/a/70529481/18619283>
  59. local Enclosure = {
  60. NONE = "0",
  61. BRACKETED = "1",
  62. BRACKETED_DONE = "2",
  63. BRACED = "3",
  64. }
  65. -- TODO: cover non-ASCII Unicode characters
  66. -- @see <https://www.lua.org/manual/5.4/manual.html#6.5>
  67. --- curie_prefix - CURIE prefix component as set of chars
  68. --- @see <https://www.w3.org/TR/2010/NOTE-curie-20101216/>
  69. local _name_start_char = "A-Z_a-z"
  70. local _name_char = _name_start_char.."-0-9"
  71. local _ref = "[".._name_start_char.."][".._name_char.."]*"
  72. local curie_prefix = "[".._name_start_char.."_-][".._name_char.."]*"
  73. --- curie_long - CURIE with prefix and reference as set of chars
  74. local curie_long = curie_prefix..":".._ref
  75. --- curie_no_ref - CURIE with only prefix as set of chars
  76. local curie_no_ref = curie_prefix..":"
  77. --- curie_local - CURIE with only name as set of chars
  78. local curie_local = ":".._ref
  79. --- curie_default - CURIE without prefix or name as char
  80. local curie_default = ":"
  81. -- TODO: curie_re - CURIE as `LPeg.re` regex object
  82. -- TODO: test and replace above curie* patterns
  83. -- @see <https://pandoc.org/lua-filters.html#global-variables>
  84. --local curie_re = re.compile("("..curie_prefix..")?:(".._ref..")?")
  85. -- FIXME: define RDF context same as RDFa
  86. -- TODO: maybe support overriding context with a JSON-LD URI
  87. -- @see <https://www.w3.org/2011/rdfa-context/rdfa-1.1>
  88. --- Namespaces - process RDF namespace IRI declarations
  89. ---
  90. --- Takes as input a list of Para block elements.
  91. --- For each block matching the pattern for a namespace IRI definition,
  92. --- the declared namespace is extracted.
  93. --- Returns an empty paragraph in case of a match,
  94. --- or nothing (to signal preservation of original content).
  95. ---
  96. --- Example:
  97. ---
  98. --- ```Markdown
  99. --- # Annotated paragraph using a custom namespace
  100. ---
  101. --- My favorite animal is the [Liger]{ov:preferredAnimal}.
  102. ---
  103. --- {ov}: http://open.vocab.org/terms/
  104. --- ```
  105. ---
  106. --- @param blocks Markdown with ontological annotations as Blocks
  107. --- @returns Markdown without ontological annotations as Blocks
  108. --- @see <https://pandoc.org/lua-filters.html#type-blocks>
  109. --- @see <https://www.w3.org/TR/rdf12-concepts/#vocabularies>
  110. local function Namespaces(blocks)
  111. -- paragraph with only a braced prefix-only CURIE, colon and one word
  112. local pattern = "^{"..curie_prefix.."}:$"
  113. if #blocks.content == 3
  114. and blocks.content[1].t == "Str"
  115. and blocks.content[2].t == "Space"
  116. and blocks.content[1].text:match(pattern)
  117. then
  118. -- default namespace, misparsed as a citation
  119. if blocks.content[3].t == "Cite"
  120. and #blocks.content[3].content == 1
  121. -- TODO: maybe check case-insensitively
  122. and blocks.content[3].content[1].text == "@default"
  123. then
  124. -- FIXME: add CURIE to metadata
  125. return {}
  126. end
  127. -- namespace
  128. local pattern = "^https?:"
  129. if blocks.content[3].t == "Str"
  130. -- TODO: maybe check case-insensitively
  131. -- TODO: relax to match URI syntax without hardcoded protocols
  132. and blocks.content[3].text:match(pattern)
  133. then
  134. -- FIXME: add CURIE and URI to metadata
  135. return {}
  136. end
  137. end
  138. end
  139. --- Statements - process inline RDF statements
  140. ---
  141. --- Locate and extract ontological annotations
  142. --- within a [Block] element of a Pandoc Abstract Syntax Tree (AST).
  143. ---
  144. --- Markup for ontological annotations is an extension to Markdown
  145. --- using similar syntax as hypermedia annotations,
  146. --- but listing RDFa [CURIEs] in a braced enclosure.
  147. ---
  148. --- ```ASCII-art
  149. --- Simple ontological annotation:
  150. --- "A [map]{foaf:depiction} is not the territory"
  151. --- | ||\~~~~~~~~~~~~/|
  152. --- a bc CURIEa d
  153. ---
  154. --- Nested and mixed-use annotations:
  155. --- ["[Ceci]{foaf:depiction} n'est pas une pipe"]{lang=fr dc:Text}
  156. --- | | ||\~~~~~~~~~~~~/| || \~~~~~/|
  157. --- a a1 |c1 CURIEa d1 bc CURIEb d
  158. --- b1
  159. ---
  160. --- Chained hypermedia and ontological annotations:
  161. --- "A [map](https://osm.org/){foaf:depiction} is not the territory"
  162. --- | || ||\~~~~~~~~~~~~/|
  163. --- a be fc CURIEa d
  164. ---
  165. --- Legend:
  166. --- a-b: braceted enclosure around content
  167. --- c-d: bracketed enclosure around ontological or other annotation
  168. --- e-f: parenthesized enclosure around hypermedia annotation
  169. --- ```
  170. ---
  171. --- Ontological annotations are parsed and reorganised
  172. --- using the following algorithm:
  173. ---
  174. --- 1. locate pairs of bracketed text and braced text
  175. --- either adjacent or separated by parenthesized text,
  176. --- where braced text contains one or more [CURIEs]
  177. --- 2. for each pair,
  178. --- 1. add CURIEs in braced text to metadata
  179. --- 2. add positions of brackets to metadata
  180. --- 3. delete CURIEs
  181. --- 4. delete braced enclosure if now structurally empty
  182. --- 5. delete brackets if now unannotated
  183. ---
  184. --- The implementation is inspired by Pandoc [issue#6038].
  185. ---
  186. --- @param inlines Markdown with semantic annotations as Inlines
  187. --- @returns Markdown stripped of semantic annotations as Inlines
  188. --- @see [Block]: <https://pandoc.org/lua-filters.html#type-block>
  189. --- @see [CURIEs]: <https://www.w3.org/TR/2010/NOTE-curie-20101216/>
  190. --- @see [issue#6038]: <https://github.com/jgm/pandoc/issues/6038>
  191. -- TODO: maybe instead as step #5 add/reuse hypermedia anchor
  192. function Statements (block)
  193. -- flags for enclosing stages
  194. -- TODO: support nested bracket enclosure
  195. local enclosure = Enclosure.NONE
  196. -- amount of detected statements in this block
  197. local statement_count = 0
  198. local stack = {}
  199. for i, el in ipairs(block.content) do
  200. local pos = 1
  201. local stack_next = ""
  202. -- non-string element
  203. if el.t ~= 'Str' then
  204. -- TODO: support mixed-use braced enclosure
  205. if enclosure ~= Enclosure.BRACED then
  206. table.insert(stack, el)
  207. end
  208. goto continue
  209. end
  210. -- unenclosed
  211. -- TODO: support backslash except immediately before bracket
  212. if enclosure == Enclosure.NONE then
  213. _, x, s = el.text:find("^([^%[\\]*)")
  214. if x then
  215. a = x + 1
  216. else
  217. a = 1
  218. end
  219. if el.text:sub(a, a) == "[" then
  220. -- entering bracketed enclosure
  221. pos = a + 1
  222. stack_next = stack_next..s
  223. enclosure = Enclosure.BRACKETED
  224. -- staying unenclosed
  225. else
  226. table.insert(stack, el)
  227. goto continue
  228. end
  229. end
  230. -- in bracketed enclosure
  231. -- TODO: support backslash except immediately before bracket/brace
  232. -- TODO: support nested bracket enclosure
  233. if enclosure == Enclosure.BRACKETED then
  234. _, x, s = el.text:find("^([^%[%]}\\]*)", pos)
  235. if x then
  236. b = x + 1
  237. else
  238. b = pos
  239. end
  240. stack_next = stack_next..s
  241. -- exiting bracketed enclosure
  242. if el.text:sub(b, b) == "]" then
  243. pos = b + 1
  244. enclosure = Enclosure.BRACKETED_DONE
  245. end
  246. end
  247. -- exited bracketed enclosure
  248. if enclosure == Enclosure.BRACKETED_DONE then
  249. -- entering braced enclosure
  250. if el.text:sub(pos, pos) == "{" then
  251. pos = pos + 1
  252. enclosure = Enclosure.BRACED
  253. -- leaving non-annotation enclosure
  254. else
  255. enclosure = Enclosure.NONE
  256. -- TODO: clear only back to entering this bracketed enclosure
  257. stack = {}
  258. -- TODO: parse remains of Str
  259. goto continue
  260. end
  261. end
  262. -- in braced enclosure, leaving it
  263. -- TODO: support mixed-use enclosure
  264. if enclosure == Enclosure.BRACED then
  265. _, d1 = el.text:find("^"..curie_long.."}", pos)
  266. _, d2 = el.text:find("^"..curie_no_ref.."}", pos)
  267. _, d3 = el.text:find("^"..curie_local.."}", pos)
  268. _, d4 = el.text:find("^"..curie_default.."}", pos)
  269. if d1 then d = d1
  270. elseif d2 then d = d2
  271. elseif d3 then d = d3
  272. elseif d4 then d = d4
  273. end
  274. if d then
  275. statement_count = statement_count + 1
  276. pos = d + 1
  277. -- TODO: instead recursively call Statements() on remains of Str
  278. stack_next = stack_next..el.text:sub(pos)
  279. enclosure = Enclosure.NONE
  280. end
  281. end
  282. -- push any string collected from above parsing to stack
  283. if stack_next:len() > 0 then
  284. table.insert(stack, pandoc.Str(stack_next))
  285. end
  286. -- done parsing current Inline element
  287. ::continue::
  288. end
  289. if statement_count > 0 then
  290. return pandoc.Blocks {pandoc.Para(stack)}
  291. end
  292. end
  293. -- First resolve namespace declarations, then statements.
  294. --
  295. -- Although this filter is *not* a full RDF parser,
  296. -- order matters for the parts we do handle --
  297. -- e.g. namespace resolving is similar to other RDF formats
  298. -- with detailed documented process ordering.
  299. --
  300. -- @see <https://www.w3.org/TR/turtle/#sec-parsing>
  301. local meta = {}
  302. return {
  303. -- move aside MetaBlocks to speed up processing content
  304. --
  305. -- @see <https://stackoverflow.com/a/47356252/18619283>
  306. { Meta = function(m) meta = m; return {} end },
  307. {Para = Namespaces},
  308. {Para = Statements},
  309. -- FIXME: add custom declared namespaces in Meta
  310. -- TODO: maybe add only actively used namespaces
  311. -- (do same as for unused link definitions)
  312. { Meta = function(_) return meta; end },
  313. --{ Meta = function(_) return NamespacesToMeta(meta); end },
  314. }