Emacs Lispのループ内で関数を作る

(let (($num 0))
  (while (< $num 10)
    (defalias (intern (format "my-func-%d" $num))
      `(lambda ()
         (interactive)
         (insert (format "\nNumber: %s" ,$num))))
    (setq $num (1+ $num))))

実行するとmy-func-0 から my-func-9 が作られます。M-x my-func-5 などで使えるようになります。

応用

[C-c C-c 数字キー]で選択範囲をコピー、[C-c コピーに使った数字キー]で貼付けができます。

(setq my-cp-list (make-list 10 nil))
(let (($num 0) $fn-copy $fn-paste)
  (while (< $num 10)
    (setq $fn-copy (format "my-cp-copy-%d" $num))
    (setq $fn-paste (format "my-cp-paste-%d" $num))
    (defalias (intern $fn-copy)
      `(lambda ()
         (interactive)
         (if mark-active
             (let (($str (buffer-substring-no-properties
                          (region-beginning) (region-end))))
               (setf (nth ,$num my-cp-list) $str)
               (message "copy to clipboard %d" ,$num))
           nil)
         (deactivate-mark)))
    (defalias (intern $fn-paste)
      `(lambda ()
         (interactive)
         (interactive)
         (let (($str (nth ,$num my-cp-list)))
           (if $str
               (insert (format "%s" (nth ,$num my-cp-list)))
             (message "clipboard %d is not copied yet" ,$num)))))
    (global-set-key (kbd (format "C-c C-c %d" $num)) (intern $fn-copy))
    (global-set-key (kbd (format "C-c %d" $num)) (intern $fn-paste))
    (setq $num (1+ $num))))