]> git.plutz.net Git - shellwiki/blobdiff - tools.sh
print fallback name of non-existent pages in page_name()
[shellwiki] / tools.sh
index a298394c9cf5881cb4a764587302fe4467030d67..ccd095cb4065d9f2708d3ba2ee36cddb936317b8 100755 (executable)
--- a/tools.sh
+++ b/tools.sh
@@ -185,3 +185,38 @@ has_tag() {
   done
   return 1
 }
+
+page_title() {
+  local mdfile='' PAGE_TITLE=''
+
+  if mdfile="$(mdfile "${1}")"; then
+    PAGE_TITLE="$(
+      # pick title from %title pragma
+      sed -nE '
+        s;^%title[ \t]+([[:graph:]][[:print:]]+)\r?$;\1;p; tQ;
+        b; :Q q;
+      ' "$mdfile"
+    )"
+    [ ! "${PAGE_TITLE}" ] && PAGE_TITLE="$(
+      # pick title from first h1/h2 headline
+      MD_MACROS="" md <"$mdfile" \
+      | sed -nE '
+        s;^.*<h1[^>]*>(.*>)?([^<]+)(<.*)?</h1>.*$;\2;; tQ;
+        s;^.*<h2[^>]*>(.*>)?([^<]+)(<.*)?</h2>.*$;\2;; tQ;
+        b; :Q
+        # reverse escapes of cgilite HTML function,
+        # to prevent later double escaping
+        # later escaping must not be omited
+        s/&lt;/</g; s/&gt;/>/g;  s/&quot;/'\"'/g; s/&#x27;/'\''/g;
+        s/&#x5B;/[/g; s/&#x5D;/]/g;  s/&#x0D;/\r/g; s/&amp;/\&/g;
+        p; q;
+      '
+    )"
+  fi
+  if [ ! "${PAGE_TITLE}" ]; then
+    # use last part of page URL as title
+    PAGE_TITLE="${1%/}"
+    PAGE_TITLE="${PAGE_TITLE##*/}"
+  fi
+  printf %s\\n "$PAGE_TITLE"
+}