1

I often create files with a special extension, e.g. pkl (python pickle), and would like to display these in a read-only buffer after processing them with some external command.

E.g. in the case of pickle files I'd like to automatically run a python command (print(pickle.load(open(filename)))) on the file and display the command's standard output.

In a way it is similar to how opening a docx file triggers docview, and opening a png file, triggers image view.

Has someone written something like this?

1

You asked:

I often create files with a special extension, e.g. pkl (python pickle), and would like to display these in a read only buffer after processing them with some external command.

There remains the open question whether you want to store the processed file buffer. If you want to save the file the operation should be idempotent, i.e., a second application should not change the code anymore. I don't know whether that is the case for python pickle.

E.g. in the case of pickle files I'd like to automatically run a python command print(pickle.load(open(filename))) on the file and display the command's standard output. In a way it is similar to how opening a docx file triggers docview, and opening a png file, triggers image view. Has someone written something like this?

The following lisp code does what you want. Put it into your init file and restart emacs. Afterwards .pkl files are processed by python and displayed in read-only-mode.

(define-derived-mode pkl-mode python-mode "pkl"
  "Major mode for viewing pkl files."
  (delete-region (point-min) (point-max))
  (call-process "python" nil t t "-c" (format "import pickle\nprint(pickle.load(open('%s')))" (buffer-file-name)))
  (set-buffer-modified-p nil)
  (read-only-mode))

(add-to-list 'auto-mode-alist '("\\.pkl\\'" . pkl-mode))

If you want to save the processed buffer to disk you can add (save-buffer)
behind (call-process ...).

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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