0
  • Context: using Emacs 26.2

I would like to write Emacs Lisp code that inserts or over-types text depending of the state of the overwrite-mode. I would call this function to insert text instead of the standard insert function. When code uses the standard insert function while overwrite-mode is t, text is inserted and not overwritten.

I could write and use the following function, but I would have thought that such functionality would already be built-in Emacs. I can't find it. Does Emacs already provide a similar function?

(defun insert-or-overwrite (text)
  "Insert or overwrite text depending of overwrite-mode status."
  (when overwrite-mode
    (delete-char (length text)))
  (insert text))
PRouleau
  • 744
  • 3
  • 10

1 Answers1

1

The answer is almost yes. self-insert-command is the command that is run for those keys that simply insert a character into the current buffer, and it handles overwrite correctly (and it handles the edge cases that you have forgotten in the code you wrote; I recommend taking a look at it yourself). Of course it's not really very convenient to use, since it doesn't take a string of text as an argument.

db48x
  • 15,741
  • 1
  • 19
  • 23
  • Thanks. I know my code does not handle a single character. It should check for it as in: (defun insert-or-overwrite (text) "Insert or overwrite text depending of overwrite-mode status." (when overwrite-mode (if (stringp text) (delete-char (length text)) (delete-char 1))) (insert text)) --- However I can't see how to invoke ``self-insert-command`` from code and pass it a string. How would you call it to insert a single character? And it's written in C, so that's not really an option unless I contribute one directly in Emacs. – PRouleau Jul 27 '20 at 20:57
  • I suppose that could be an edge case, if your function were called with a char instead of a string, but note carefully how `self-insert-command` handles double-wide characters, in both the input and the buffer. – db48x Jul 27 '20 at 21:01
  • I didn't think of multi-byte characters. But even for non-ASCII, it only works for strings not characters. I just tried it with ``?ß`` as an input and I got it failing sequencep (223). However attempting to overwrite "-ß-" worked fine. – PRouleau Jul 27 '20 at 21:07