enchanter
enchanter

Reputation: 924

Replace character at point in Emacs

Is it there any function to replace character at point in Emacs Lisp?

Currently what I can do is:

(goto-char pt)
(delete-char 1)
(insert c)

Upvotes: 3

Views: 1496

Answers (2)

Andreas Röhler
Andreas Röhler

Reputation: 4804

There are some common replacements, for example toggle the case, switch "(" to ")", raise/lower a number. Might be done with the following:

(defun reverse-chars (&optional arg)
  "Reverse reciproke chars as \"[\" to \"]\", upcase or downcase,
Switch `\"' with `''

If over a number, add ARG to it.
With negative arg, substract from number.
Et EOB, look backward for next number. "
  (interactive "*p")
  (let (i done)
    (if (looking-at "[0-9]")
        (ar-add-to-number arg)
      (let* ((cf (char-after))
             (cn (when (char-or-string-p cf)(downcase cf))))
        (cond ((or (eobp)(eq cf 32)(eq cf ?\ ))
               (when (< 0 (abs (skip-chars-backward "^0-9" (line-beginning-position))))
                 (forward-char -1)
                 (ar-add-to-number arg)
                 (setq done t)))
              ((eq cf 34) ;; ?\"
               (setq cn "'"))
              ((eq cf 39) ;; ?\'
               (setq cn "\""))
              ((eq cf 43) ;; ?\+
               (setq cn "-"))
              ((eq cf 62) ;; ?\>
               (setq cn "<"))
              ((eq cf 60) ;; ?\<
               (setq cn ">"))
              ((eq cf 187) ;; ?\»
               (setq cn "«"))
              ((eq cf 171) ;; ?\«
               (setq cn "»"))
              ((eq cf 41) ;; ?\)
               (setq cn "("))
              ((eq cf 40) ;; ?\(
               (setq cn ")"))
              ((eq cf 123)
               (setq cn "}")) 
              ((eq cf 125) 
               (setq cn "{"))
              ((eq cf 93) ;; ?\]
               (setq cn "["))
              ((eq cf 91) ;; ?\[
               (setq cn "]"))
              ((eq cf 45) ;; ?\-
               (setq cn "_"))
              ((eq cf 95) ;; ?\_
               (setq cn "-"))
              ((eq cf 92) ;; ?\\
               (setq cn "/"))
              ((eq cf 47) ;; ?\/
               (setq cn "\\"))
              (t (when (eq cf cn)
                   (setq cn (upcase cf)))))
        (unless done
          (delete-char 1)
          (insert cn))))))

Upvotes: 0

Tom Tromey
Tom Tromey

Reputation: 22529

I don't think there's a function to do that, but of course you can wrap the above in a defun.

Upvotes: 1

Related Questions