;;; ol-hclnotes.el - Support for links to HCL Notes documents in Org mode  -*- lexical-binding: t -*-

(require 'org)

(org-link-set-parameters "hclnotes" :follow #'org-hclnotes-open)

(defun org-hclnotes-open (path _)
  ;; Do not display "Wrote ..." messages in the minibuffer.
  (let ((inhibit-message t))
    ;; Create a temporary file with the link data.
    (let ((ndl-file (make-temp-file "org-link-" nil ".ndl" path)))
      (make-process
       :name "hcl-notes"
       :command (list "rundll32" "url.dll,FileProtocolHandler" ndl-file)))))

(defun org-hclnotes-insert-link (arg)
  (interactive "P" arg)
  (let (link description)
    (with-temp-buffer
      (yank)
      (beginning-of-buffer)
      (search-forward " - " nil t)
      (setq description (buffer-substring-no-properties (point) (point-at-eol)))
      (forward-line 1)
      (if (not (looking-at "<NDL>\\(.\\|\n\\)+</NDL>"))
	  (message "Not an HCL Notes document link")
	(let ((start (point)))
	  ;; Strip newlines.
	  (while (re-search-forward "[\n\r]" nil t)
	    (replace-match ""))
	  (goto-char start)
	  ;; Remove unnecessary HINT tag.
	  (when (re-search-forward "<HINT>.+</HINT>")
	    (replace-match ""))
	  ;; Remove unnecessary REM tag.
	  (when (re-search-forward "<REM>.+</REM>")
	    (replace-match ""))
	  (setq link (buffer-substring-no-properties start (point-max)))
	  (message link))))
    (when link
      (let ((description (if arg description (read-string "Description: " description))))
	(insert (format "[[hclnotes:%s][%s]]" link description))))))

(provide 'ol-hclnotes)

;;; ol-hclnotes.el end