index rss mastodon twitter github linkedin email
Álvaro Ramírez
sponsor

Álvaro Ramírez

09 July 2022 Emacs: Password-protect current pdf (revisited)

UPDATE: dwim-shell-command is now available on melpa.

passprotect.gif

With a recent look at writing DWIM shell commands, I've been revisiting my custom Emacs functions invoking command line utilities.

Take this post, for example, where I invoke qpdf via a elisp. Using the new dwim-shell-command--on-marked-files in dwim-shell-command.el, the code is stripped down to a bare minimum:

(defun dwim-shell-commands-pdf-password-protect ()
  "Password protect pdf."
  (interactive)
  (dwim-shell-command-on-marked-files
   "Password protect pdf"
   (format "qpdf --verbose --encrypt '%s' '%s' 256 -- '<<f>>' '<<fne>>_enc.<<e>>'"
           (read-passwd "user-password: ")
           (read-passwd "owner-password: "))
   :utils "qpdf"
   :extensions "pdf"))

Compare the above dwim-shell-command--on-marked-files usage to my previous implementation:

(defun pdf-password-protect ()
  "Password protect current pdf in buffer or `dired' file."
  (interactive)
  (unless (executable-find "qpdf")
    (user-error "qpdf not installed"))
  (unless (equal "pdf"
                 (or (when (buffer-file-name)
                       (downcase (file-name-extension (buffer-file-name))))
                     (when (dired-get-filename nil t)
                       (downcase (file-name-extension (dired-get-filename nil t))))))
    (user-error "no pdf to act on"))
  (let* ((user-password (read-passwd "user-password: "))
         (owner-password (read-passwd "owner-password: "))
         (input (or (buffer-file-name)
                    (dired-get-filename nil t)))
         (output (concat (file-name-sans-extension input)
                         "_enc.pdf")))
    (message
     (string-trim
      (shell-command-to-string
       (format "qpdf --verbose --encrypt '%s' '%s' 256 -- '%s' '%s'"
               user-password owner-password input output))))))

This really changes things for me. I'll be more inclined to add more of these tiny integrations to lots of great command line utilities. Take this recent Hacker News post on ocrmypdf as an example. Their cookbook has lots of examples that can be easily used via dwim-shell-command--on-marked-files.

What command line utils would you use?