unwind-protect로 timer를 설정하고 안전하게 해지하는 방법

less than 1 minute read

vertico에서 한글 증분 완성(incremental completion)을 지원하려고 timer를 적용했다. 0.01초마다 입력을 검사해서 완성 후보를 골라서 출력한다. vertico 모드가 종료될 때 이 timer를 잘 해제해야 한다. 제대로 해제가 안 되면 편집 중에도 이 timer가 계속 돌아갈 것이다. timer를 잘 해제하는 게 설정하는 것만큼이나 중요하다.

timer를 해제할 때는 주요 흐름(happy path)만 고려해서는 안 된다. 중간에 에러가 날 수도 있기 때문에 에러가 나도 timer를 잘 해제할 수 있게 코드를 짜야 한다.

(defun my/vertico-exhibit-with-timer (&rest args)
  (let (timer)
    (unwind-protect ;; <-- 1
        (progn
          (setq timer (run-with-idle-timer
                       0.01
                       'repeat
                       (lambda ()
                         (with-selected-window (or (active-minibuffer-window)
                                                   (minibuffer-window))
                           (vertico--exhibit))
                         )))
          (apply args))
      (when timer (cancel-timer timer))))) ;; <-- 2

unwind-protect를 이럴 때, 사용할 수 있다. unwind-protect는 body 실행을 종료할 때, cleanup을 실행하는 걸 보장한다. helm-core.el 소스 코드를 참고했다.

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