Interactive 함수에서 변수에 바인딩된 값 중에 하나를 고르기

less than 1 minute read

interactive 함수에서 리스트 요소(element) 중에 하나를 고르게 하고 싶다. ’emacs - Adding Completion to (interactive) - stackoverflow.com’ 글에서 좋은 예제를 발견했다.

(setq my-candidates '("a" "b" "c"))
(defun interactive-choose-test (arg)
  (interactive
   (list
    (completing-read "Choose one: " my-candidates)))
  (message arg))

interactive 함수 인자로 리스트를 넘겨서 구현한다. 함수를 호출할 수 있기 때문이다. completing-read 함수를 사용해 변수에 바인딩된 값 중에 하나를 선택하게 할 수 있다. 위에 예로 든 interactive-choose-test 함수를 실행하면 a, b, c 중 하나를 선택할 수 있다.

여러 개도 받을 수 있을까? a, b, c 중 하나를 선택하고 다음엔 숫자를 입력하게 할 수 있을까?

(setq my-candidates '("a" "b" "c"))
(defun interactive-choose-test (arg1 arg2)
  (interactive
   (list
    (completing-read "Choose one: " my-candidates)
    (read-number "Number: ")))
  (message (format "arg1: %s arg2: %s" arg1 arg2)))
arg1: a arg2: 123213

interactive 함수 인자로 문자열이 아닌 리스트를 넘기기에 read-string 함수를 직접 호출했다. a, b, c 중에 하나를 선택하면 뒤에 숫자를 입력하라는 프롬프트가 뜬다. 입력하면 메시지로 선택한 문자열과 직접 입력한 숫자가 잘 출력된다.

링크

C-x C-s C-x C-c