| 1 | --[[ |
| 2 | anchor-sections - add anchor sections link to headers |
| 3 | |
| 4 | MIT License |
| 5 | |
| 6 | Copyright © 2020 RStudio |
| 7 | |
| 8 | Permission is hereby granted, free of charge, to any person obtaining |
| 9 | a copy of this software and associated documentation files (the |
| 10 | "Software"), to deal in the Software without restriction, including |
| 11 | without limitation the rights to use, copy, modify, merge, publish, |
| 12 | distribute, sublicense, and/or sell copies of the Software, and to |
| 13 | permit persons to whom the Software is furnished to do so, subject to |
| 14 | the following conditions: |
| 15 | |
| 16 | The above copyright notice and this permission notice shall be |
| 17 | included in all copies or substantial portions of the Software. |
| 18 | |
| 19 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
| 20 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
| 21 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND |
| 22 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE |
| 23 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION |
| 24 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION |
| 25 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 26 | ]] |
| 27 | |
| 28 | local anchor_depth |
| 29 | |
| 30 | -- retrieve metadata |
| 31 | function get_anchor_depth(el) |
| 32 | anchor_depth = tonumber(el.rmd_anchor_depth) |
| 33 | if not anchor_depth then |
| 34 | anchor_depth = 6 |
| 35 | end |
| 36 | end |
| 37 | |
| 38 | -- insert anchor link |
| 39 | function insert_anchor(el) |
| 40 | -- do not add anchor on empty headings |
| 41 | if #el.content == 0 then return(nil) end |
| 42 | |
| 43 | if el.identifier ~= "" then |
| 44 | if el.level <= anchor_depth then |
| 45 | --[[ |
| 46 | with --section-divs this will be added on the section div not the Header. |
| 47 | The class will be moved to the header node by anchor-sections.js |
| 48 | ]] |
| 49 | table.insert(el.classes, "hasAnchor") |
| 50 | end |
| 51 | -- .hasAnchor could be added by the piece above or manually by the user |
| 52 | if el.classes:find("hasAnchor") then |
| 53 | table.insert(el.content, |
| 54 | pandoc.Link("", "#"..el.identifier, "", |
| 55 | pandoc.Attr( |
| 56 | "", {"anchor-section"}, {["aria-label"]="Anchor link to header"} |
| 57 | ) |
| 58 | ) |
| 59 | ) |
| 60 | end |
| 61 | end |
| 62 | return(el) |
| 63 | end |
| 64 | |
| 65 | |
| 66 | return { |
| 67 | { Meta = get_anchor_depth }, |
| 68 | { Header = insert_anchor } |
| 69 | } |