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