I am trying to modify a buffer written by desktop-save to a file. The file is named .emacs.desktop and I am trying to modify it from a Perl script. It turns out that it is saved in emacs-mule encoding.

From M-x list-coding-systems :

U -- utf-8 (alias: mule-utf-8)
  UTF-8 (no signature (BOM))
M -- emacs-mule
  Emacs 21 internal format used in buffer and string.

I would like to read the file in Perl as UTF-8, how can this be done? (I would prefer a solution that does not depend on a running Emacs server)

(An example: emacs-mule saves the letter æ as two bytes 0x81 0xe6, ISO Latin 1 saves it as a single byte 0xe6, whereas UTF-8 saves it as two bytes 0xc3 0xa6.. )

  • Can M-x revert-buffer-with-coding-system help? – Name Jul 24 '15 at 11:43
  • @Name Yes it seems like I have to consider options for doing the conversion from within Emacs.. I could not find any Perl modules that can convert between MULE and UTF-8.. so currently, it seems only Emacs knows how to do the conversion. The drawback with this approach is that the Perl script needs to rely on running a new Emacs instance in batch mode.. – Håkon Hægland Jul 24 '15 at 11:55
  • I am not sure if the problem discussed in this link stackoverflow.com/q/627661 is related to your question but it is worth looking at. – Name Jul 24 '15 at 13:46
  • 1
    You might be able to dig the details of the emacs-mule coding out of the file src/coding.c in the emacs source code. There are extensive comments in that file. – Harald Hanche-Olsen Jul 24 '15 at 15:32

Here is the solution I ended up with:

  • Assume an Emacs server with name my_server is up and running.

  • Convert emacs-mule to utf-8 by calling emacsclient from the Perl script:

    emacsclient -s my_server -e '(my-convert-mule-utf8 \".emacs.desktop\")' >/dev/null 2>&1`

where my-convert-mule-utf8 is

(defun my-convert-mule-utf8 (fn)
  (let*  ((temp-fn (concat fn ".utf8"))
         (coding-system-for-write 'utf-8))
    (with-temp-file temp-fn
      (insert-file-contents fn)
      (when (re-search-forward "coding: \\(emacs-mule\\);" (line-end-position) t)
        (replace-match "utf-8" nil t nil 1)))))
  • To convert utf-8 to emacs-mule:

    emacsclient -s my_server -e '(my-convert-utf8-mule \".emacs.desktop\")' >/dev/null 2>&1

where my-convert-utf8-mule is:

(defun my-convert-utf8-mule (fn)
  (let* ((temp-fn (concat fn ".utf8"))
         (coding-system-for-write 'emacs-mule))
    (with-temp-file fn
      (insert-file-contents temp-fn)
      (when (re-search-forward "coding: \\(utf-8\\);" (line-end-position) t)
        (replace-match "emacs-mule" nil t nil 1)))))

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.