Skip to content

Auto‐restore gptel‐mode in chat buffers

MetaChip edited this page Jan 13, 2025 · 1 revision

When a chat buffer is saved to a file, gptel prepends a properties drawer to capture the metadata for the chat. When the chat buffer is re-opened, the mode will be org mode or markdown, based on the file suffix (presuming you saved it that way). However, when re-opening the saved chat buffer it does not re-enable gptel-mode. It’s a chat buffer, so it makes sense to re-enable gptel-mode automatically when the chat buffer is (re)opened. For this, you can use a property line at the top of the file.

# -*- eval: (gptel-mode 1) -*-

I frequently use the property line for other purposes and I find it inconvenient to remember to add this if I enable gptel-mode. I want it added automatically.

(defun my/gptel-mode-auto ()
  "Ensure that this file opens with `gptel-mode' enabled."
  (save-excursion
    (let ((enable-local-variables t))  ; Ensure we can modify local variables
      (if (and (save-excursion
                 (goto-char (point-min))
                 (looking-at ".*-\\*-")))  ; If there's a -*- line
        ;; First remove any existing eval, then add the new one
        (modify-file-local-variable-prop-line
          'eval nil 'delete))
      ;; Always add our eval
      (add-file-local-variable-prop-line
        'eval '(and (fboundp 'gptel-mode) (gptel-mode 1))))))

(add-hook 'gptel-save-state-hook #'my/gptel-mode-auto)

This function is run when a chat buffer is saved. It first enables local variable modification in case it’s disabled. It then checks if there’s a property line and adds or rewrites the eval property to ensure gptel-mode is enabled when next this file is open. It won’t do anything if there is no property line. It will blow away any eval property that may previously be there. I rarely use eval for other purposes, so it’s generally not a problem for me.

See #491 for back story.