2
\$\begingroup\$

Sometimes I have the date as part of the file name. And then when Emacs autocompletes the file name, it puts the part of the date. In these situations I have to write the rest of the date manually. Here is a solution, so that I can press Super+d and the suffix of today's date is written in the buffer. For example, if point is after "2019", when I press Super+d it becomes "2019-03-09".

(defun make-suffix (word1 word2)
  (cl-labels ((is-prefix (prefix list)
                         (cond ((null prefix) t)
                               ((null list) nil)
                               ((equal (car prefix) (car list))
                                (is-prefix (cdr prefix) (cdr list)))
                               (t nil)))
              (delete-x-elements (x list)
                                 (cond ((= x 0) list)
                                       ((null list) list)
                                       (t (delete-x-elements (- x 1)
                                                             (cdr list)))))
              (make-suffix-rec (l1 l2)
                               (cond ((null l1) l2)
                                     ((is-prefix l1 l2)
                                      (delete-x-elements (length l1) l2))
                                     (t (make-suffix-rec (cdr l1) l2)))))
    (concat (make-suffix-rec (string-to-list word1) (string-to-list word2)))))
(global-set-key (kbd "s-d")
                (lambda ()
                  (interactive)
                  (let ((cw (current-word))
                        (ds (format-time-string "%Y-%m-%d")))
                          (insert (make-suffix cw ds)))))

So what do you think? Is it a good solution? Is it the right way to use elisp and Emacs?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

I'm concerned that make-suffix is sufficiently general that we'll have name collisions with other packages - or even new Emacs versions. Perhaps prefix with some tag (I tend to begin names with my initials to disambiguate my own functions, for example; that would give you something like an/make-suffix).

Instead of binding a lambda to the keystroke, prefer to give it a name. That makes it easier to bind to other keys (perhaps interactively) and for Control+h k to give the best output.

Talking of which, let's have some docstrings, please!

Finally, since the function will work only on writable buffers, we should have (interactive "*") to avoid wasting effort when used in a read-only context.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.