[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to read an integer from the minibuffer

From: Gregory Heytings
Subject: Re: How to read an integer from the minibuffer
Date: Thu, 11 Nov 2021 10:25:02 +0000

I'd like to read an integer (or something else e.g. matching a regex) from a minibuffer. Basically, I'm after a version of `read-string', but either allowing only some characters, or accepting only input matching some regex (possibly both).

How do I do that? One way would be to use `read-from-minibuffer' with a suitable keymap, but that seems slightly low-level. If that is the way to go, is there a good way to set up a keymap so that nothing except some specified characters are self-inserting? IOW, is `suppress-keymap' the way to go or is there some other way?

(defun restricted-read-from-minibuffer (prompt allowed-chars)
  "Read a string from the minibuffer, prompting with PROMPT.
The only allowed characters are those in the string ALLOWED-CHARS."
  (let ((m (make-keymap)))
    (define-key m [t] #'ignore)
    (define-key m (kbd "RET") #'exit-minibuffer)
    (define-key m (kbd "<return>") #'exit-minibuffer)
    (define-key m (kbd "C-j") #'exit-minibuffer)
    (define-key m (kbd "C-g") #'abort-minibuffers)
    (dolist (c (split-string allowed-chars "" t))
      (define-key m c #'self-insert-command))
    (read-from-minibuffer prompt nil m)))

reply via email to

[Prev in Thread] Current Thread [Next in Thread]