Here is a potential solution:
(defun org-mode-<>-syntax-fix (start end)
(when (eq major-mode 'org-mode)
(save-excursion
(goto-char start)
(while (re-search-forward "<\\|>" end t)
(when (get-text-property (point) 'src-block)
;; This is a < or > in an org-src block
(put-text-property (point) (1- (point))
'syntax-table (string-to-syntax "_")))))))
(add-hook 'org-mode-hook
(lambda ()
(setq syntax-propertize-function 'org-mode-<>-syntax-fix)
(syntax-propertize (point-max))))
This basically just changes the syntax table for <> inside src blocks I think. It seems to solve the problem.
The code above depends on source blocks already propertized with src-block
.
The src-block
property is put on source blocks by org-fontify-meta-lines-and-blocks
during keyword fontification through font-lock
. But, syntax fontification comes before keyword fontification. So maybe the following function is better.
For easier copy-paste the full code is given. The main change is the search for source blocks by re-search-backward
.
We set syntax-propertize-function
as a buffer-local variable to avoid unforeseen consequences outside of our org-mode buffers, such as in cc-mode
's check for syntax-table
functionality, which otherwise fails and prevents HTML exports of org-mode buffers.
(defun org-mode-<>-syntax-fix (start end)
"Change syntax of characters ?< and ?> to symbol within source code blocks."
(let ((case-fold-search t))
(when (eq major-mode 'org-mode)
(save-excursion
(goto-char start)
(while (re-search-forward "<\\|>" end t)
(when (save-excursion
(and
(re-search-backward "[[:space:]]*#\\+\\(begin\\|end\\)_src\\_>" nil t)
(string-equal (downcase (match-string 1)) "begin")))
;; This is a < or > in an org-src block
(put-text-property (point) (1- (point))
'syntax-table (string-to-syntax "_"))))))))
(defun org-setup-<>-syntax-fix ()
"Setup for characters ?< and ?> in source code blocks.
Add this function to `org-mode-hook'."
(make-local-variable 'syntax-propertize-function)
(setq syntax-propertize-function 'org-mode-<>-syntax-fix)
(syntax-propertize (point-max)))
(add-hook 'org-mode-hook #'org-setup-<>-syntax-fix)