aboutsummaryrefslogtreecommitdiff
path: root/_extensions/ruc-play/semantic-markdown/semantic-markdown.lua
blob: 5795f5c5bf43768dea62273eae9278ed0c639fd6 (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. -- element types representing content enclosure in Markdown
  66. local ElementTypeIsEnclosure = {
  67. Emph = true,
  68. Image = true,
  69. Link = true,
  70. Strong = true,
  71. }
  72. -- TODO: cover non-ASCII Unicode characters
  73. -- @see <https://www.lua.org/manual/5.4/manual.html#6.5>
  74. --- curie_prefix - CURIE prefix component as set of chars
  75. --- @see <https://www.w3.org/TR/2010/NOTE-curie-20101216/>
  76. local _name_start_char = "A-Z_a-z"
  77. local _name_char = _name_start_char.."-0-9"
  78. local _ref = "[".._name_start_char.."][".._name_char.."]*"
  79. local curie_prefix = "[".._name_start_char.."_-][".._name_char.."]*"
  80. --- curie_long - CURIE with prefix and reference as set of chars
  81. local curie_long = curie_prefix..":".._ref
  82. --- curie_no_ref - CURIE with only prefix as set of chars
  83. local curie_no_ref = curie_prefix..":"
  84. --- curie_local - CURIE with only name as set of chars
  85. local curie_local = ":".._ref
  86. --- curie_default - CURIE without prefix or name as char
  87. local curie_default = ":"
  88. -- TODO: curie_re - CURIE as `LPeg.re` regex object
  89. -- TODO: test and replace above curie* patterns
  90. -- @see <https://pandoc.org/lua-filters.html#global-variables>
  91. --local curie_re = re.compile("("..curie_prefix..")?:(".._ref..")?")
  92. -- FIXME: define RDF context same as RDFa
  93. -- TODO: maybe support overriding context with a JSON-LD URI
  94. -- @see <https://www.w3.org/2011/rdfa-context/rdfa-1.1>
  95. --- Namespaces - process RDF namespace IRI declarations
  96. ---
  97. --- Takes as input a list of Para block elements.
  98. --- For each block matching the pattern for a namespace IRI definition,
  99. --- the declared namespace is extracted.
  100. --- Returns an empty paragraph in case of a match,
  101. --- or nothing (to signal preservation of original content).
  102. ---
  103. --- Example:
  104. ---
  105. --- ```Markdown
  106. --- # Annotated paragraph using a custom namespace
  107. ---
  108. --- My favorite animal is the [Liger]{ov:preferredAnimal}.
  109. ---
  110. --- {ov}: http://open.vocab.org/terms/
  111. --- ```
  112. ---
  113. --- @param blocks Markdown with ontological annotations as Blocks
  114. --- @returns Markdown without ontological annotations as Blocks
  115. --- @see <https://pandoc.org/lua-filters.html#type-blocks>
  116. --- @see <https://www.w3.org/TR/rdf12-concepts/#vocabularies>
  117. local function Namespaces(blocks)
  118. -- paragraph with only a braced prefix-only CURIE, colon and one word
  119. local curie_pattern = "^{"..curie_prefix.."}:$"
  120. if #blocks.content == 3
  121. and blocks.content[1].t == "Str"
  122. and blocks.content[2].t == "Space"
  123. and blocks.content[1].text:match(curie_pattern)
  124. then
  125. local el = blocks.content[3]
  126. -- default namespace, parsed as commonmark
  127. if el.t == "Str"
  128. and el.text == "@default"
  129. then
  130. -- FIXME: add CURIE to metadata
  131. return {}
  132. end
  133. -- default namespace, parsed as markdown
  134. if el.t == "Cite"
  135. and #el.content == 1
  136. and el.content[1].text == "@default"
  137. then
  138. -- FIXME: add CURIE to metadata
  139. return {}
  140. end
  141. -- namespace
  142. -- TODO: relax to match URI syntax without hardcoded protocols
  143. local proto_pattern = "^[Hh][Tt][Tt][Pp][Ss]?:"
  144. if el.t == "Str"
  145. and el.text:match(proto_pattern)
  146. then
  147. -- FIXME: add CURIE and URI to metadata
  148. return {}
  149. end
  150. end
  151. end
  152. --- Statements - process inline RDF statements
  153. ---
  154. --- Locate and extract ontological annotations
  155. --- within a [Block] element of a Pandoc Abstract Syntax Tree (AST).
  156. ---
  157. --- Markup for ontological annotations is an extension to Markdown
  158. --- using similar syntax as hypermedia annotations,
  159. --- but listing RDFa [CURIEs] in a braced enclosure.
  160. ---
  161. --- ```ASCII-art
  162. --- Simple ontological annotation:
  163. --- "A [map]{foaf:depiction} is not the territory"
  164. --- | ||\~~~~~~~~~~~~/|
  165. --- a bc CURIEa d
  166. ---
  167. --- Nested and mixed-use annotations:
  168. --- ["[Ceci]{foaf:depiction} n'est pas une pipe"]{lang=fr dc:Text}
  169. --- | | ||\~~~~~~~~~~~~/| || \~~~~~/|
  170. --- a a1 |c1 CURIEa d1 bc CURIEb d
  171. --- b1
  172. ---
  173. --- Chained hypermedia and ontological annotations:
  174. --- "A [map](https://osm.org/){foaf:depiction} is not the territory"
  175. --- | || ||\~~~~~~~~~~~~/|
  176. --- a be fc CURIEa d
  177. ---
  178. --- Legend:
  179. --- a-b: braceted enclosure around content
  180. --- c-d: bracketed enclosure around ontological or other annotation
  181. --- e-f: parenthesized enclosure around hypermedia annotation
  182. --- ```
  183. ---
  184. --- Ontological annotations are parsed and reorganised
  185. --- using the following algorithm:
  186. ---
  187. --- 1. locate pairs of bracketed text and braced text
  188. --- either adjacent or separated by parenthesized text,
  189. --- where braced text contains one or more [CURIEs]
  190. --- 2. for each pair,
  191. --- 1. add CURIEs in braced text to metadata
  192. --- 2. add positions of brackets to metadata
  193. --- 3. delete CURIEs
  194. --- 4. delete braced enclosure if now structurally empty
  195. --- 5. delete brackets if now unannotated
  196. ---
  197. --- The implementation is inspired by Pandoc [issue#6038].
  198. ---
  199. --- @param inlines Markdown with semantic annotations as Inlines
  200. --- @returns Markdown stripped of semantic annotations as Inlines
  201. --- @see [Block]: <https://pandoc.org/lua-filters.html#type-block>
  202. --- @see [CURIEs]: <https://www.w3.org/TR/2010/NOTE-curie-20101216/>
  203. --- @see [issue#6038]: <https://github.com/jgm/pandoc/issues/6038>
  204. -- TODO: maybe instead as step #5 add/reuse hypermedia anchor
  205. local function Statements (block)
  206. -- flags for enclosing stages
  207. -- TODO: support nested bracket enclosure
  208. local encl = Enclosure.NONE
  209. -- amount of detected statements in this block
  210. local statement_count = 0
  211. local elems = {}
  212. for _, el in ipairs(block.content) do
  213. local pos = 1
  214. local chars = ""
  215. -- non-string element
  216. if el.t ~= 'Str' then
  217. -- specific elements represent content enclosure
  218. if encl == Enclosure.NONE then
  219. if ElementTypeIsEnclosure[el.t] then
  220. encl = Enclosure.BRACKETED_DONE
  221. end
  222. -- disqualify bracketing not directly followed by brace
  223. elseif encl == Enclosure.BRACKETED_DONE then
  224. encl = Enclosure.NONE
  225. end
  226. -- collect element, except in braced enclosure
  227. -- TODO: support mixed-use braced enclosure
  228. if encl ~= Enclosure.BRACED then
  229. table.insert(elems, el)
  230. end
  231. goto continue
  232. end
  233. -- unenclosed
  234. -- TODO: accept backslash except immediately before bracket
  235. if encl == Enclosure.NONE then
  236. local _, x, s = el.text:find("^([^%[\\]*)")
  237. pos = x and x + 1 or pos + 1
  238. chars = chars..s
  239. -- entering bracketed enclosure
  240. if el.text:sub(pos, pos) == "[" then
  241. pos = pos + 1
  242. encl = Enclosure.BRACKETED
  243. end
  244. end
  245. -- in bracketed enclosure
  246. -- TODO: accept backslash except immediately before bracket/brace
  247. -- TODO: support nested bracket enclosure
  248. if encl == Enclosure.BRACKETED then
  249. local _, x, s = el.text:find("^([^%[%]}\\]*)", pos)
  250. pos = x and x + 1 or pos + 1
  251. chars = chars..s
  252. -- exiting bracketed enclosure
  253. if el.text:sub(pos, pos) == "]" then
  254. pos = pos + 1
  255. encl = Enclosure.BRACKETED_DONE
  256. end
  257. end
  258. -- exited bracketed enclosure
  259. if encl == Enclosure.BRACKETED_DONE then
  260. -- entering braced enclosure
  261. if el.text:sub(pos, pos) == "{" then
  262. pos = pos + 1
  263. encl = Enclosure.BRACED
  264. -- leaving non-annotation enclosure
  265. else
  266. encl = Enclosure.NONE
  267. -- TODO: parse remains of Str
  268. end
  269. end
  270. -- in braced enclosure, leaving it
  271. -- TODO: support mixed-use enclosure
  272. if encl == Enclosure.BRACED then
  273. local _, d1 = el.text:find("^"..curie_long.."}", pos)
  274. local _, d2 = el.text:find("^"..curie_no_ref.."}", pos)
  275. local _, d3 = el.text:find("^"..curie_local.."}", pos)
  276. local _, d4 = el.text:find("^"..curie_default.."}", pos)
  277. local d = d1 or d2 or d3 or d4
  278. if d then
  279. statement_count = statement_count + 1
  280. pos = d + 1
  281. -- TODO: instead recursively call Statements() on remains of Str
  282. chars = chars..el.text:sub(pos)
  283. encl = Enclosure.NONE
  284. end
  285. end
  286. -- push any string collected from above parsing to stack
  287. if chars:len() > 0 then
  288. table.insert(elems, pandoc.Str(chars))
  289. end
  290. -- done parsing current Inline element
  291. ::continue::
  292. end
  293. if statement_count > 0 then
  294. return pandoc.Blocks {pandoc.Para(elems)}
  295. end
  296. end
  297. -- First resolve namespace declarations, then statements.
  298. --
  299. -- Although this filter is *not* a full RDF parser,
  300. -- order matters for the parts we do handle --
  301. -- e.g. namespace resolving is similar to other RDF formats
  302. -- with detailed documented process ordering.
  303. --
  304. -- @see <https://www.w3.org/TR/turtle/#sec-parsing>
  305. local meta = {}
  306. return {
  307. -- move aside MetaBlocks to speed up processing content
  308. --
  309. -- @see <https://stackoverflow.com/a/47356252/18619283>
  310. { Meta = function(m) meta = m; return {} end },
  311. {Para = Namespaces},
  312. {Block = Statements},
  313. -- FIXME: add custom declared namespaces in Meta
  314. -- TODO: maybe add only actively used namespaces
  315. -- (do same as for unused link definitions)
  316. { Meta = function(_) return meta; end },
  317. --{ Meta = function(_) return NamespacesToMeta(meta); end },
  318. }