;;; esc-html.el --- Escape HTML Meta-characters -*- lexical-binding: t; -*-
;; Copyright (C) 2023 Philip Kaludercic
;; Author: Philip Kaludercic
;; URL: https://wwwcip.cs.fau.de/~oj14ozun/src+etc/esc-html.el
;; Version: $Id: esc-html.el,v 1.6 2023/10/12 22:11:08 oj14ozun Exp $
;; Package-Version: 1
;; Keywords: wp
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see .
;;; Commentary:
;; Enable the `esc-html-mode' minor mode to replace HTML
;; meta-characters while typing. You can enable it automatically in
;; HTML buffers by adding (add-hook 'html-mode-hook #'esc-html-mode)
;; to your init.el.
;;; Code:
(defvar esc-html-alist
'((?& . "amp")
(?' . "apos")
(?\" . "quot")
(?< . "lt")
(?> . "gt"))
"Alist of HTML meta-characters and their replacements.")
(defvar esc-html-skip-regexp
"[\"'&=<>]"
"A regular expression to indicate not to replace the input.")
(defun esc-html-self-insert-command ()
"Insert the typed character or the escaped character entity.
The character entities are inserted for HTML meta-characters, as
specified in `esc-html-alist'. If the text prior to the point is
the corresponding character entity, replace it with the typed
character."
(interactive)
(let ((ent (alist-get last-command-event esc-html-alist)))
(if (and (not (looking-back esc-html-skip-regexp (line-beginning-position))) ent)
(let ((rep (concat "&" ent ";")))
(if (looking-back (regexp-quote rep) (line-beginning-position))
(replace-match (string last-command-event))
(insert rep)))
(funcall-interactively #'self-insert-command (prefix-numeric-value current-prefix-arg)))))
(defvar esc-html-mode-map
(let ((map (make-sparse-keymap)))
(dolist (ent esc-html-alist)
(define-key map (string (car ent)) #'esc-html-self-insert-command))
map))
(define-minor-mode esc-html-mode
"Escape certain HTML meta-characters."
:lighter " <&>")
(provide 'esc-html)
;;; esc-html.el ends here