emacs显示http结果到buffer时异常

今天用elisp写了一个http的ajax调用:

(defun ab/ajax-build-status (arg)
  "ajax pelpa building status"
  (interactive "P")
  (let* ((pelpa-build-status-url "http://pelpa.popkit.org/elpa/build/ajaxBuildStatus.json")
         (pelpa-buffer-name "*pelpa*")
         (pelpa-buffer (get-buffer-create pelpa-buffer-name))
         (buffer (url-retrieve-synchronously pelpa-build-status-url))
         (headers nil)
         (handle nil))
    (if (not buffer)
        (error "请求%s失败,请重试!" pelpa-build-status-url))
    (with-current-buffer buffer
      (unless (= 200 url-http-response-status)
        (error "Http error %s fetching %s" url-http-response-status pelpa-build-status-url))
      (message "buffer name%s" (buffer-name))
      (setq headers (buffer-string))
      
      (with-current-buffer pelpa-buffer
        (setq-default major-mode 'text-mode)
        (set-buffer-major-mode pelpa-buffer)
        (erase-buffer)     ;; 先清空原有的内容
        (insert headers))
      )))

发现返回结果的buffer,中文显示不正常:

emacs显示http结果到buffer时异常_第1张图片
Paste_Image.png

出现了\345\274\200\345\247\213\344\272\216..
原因是没有将字符串进行decode(调用decode-coding-string函数)
将上面的(insert headers)替换为如下语句就ok了:

(insert (decode-coding-string headers 'utf-8))

显示正常如下:

emacs显示http结果到buffer时异常_第2张图片
Paste_Image.png

后来发现有人遇到过,其实url.el应该按照http的content-type类型来decode才对:
http://emacs.stackexchange.com/questions/4100/why-must-i-set-and-reset-buffer-multibyte-to-correctly-view-multibyte-buffers

你可能感兴趣的:(emacs显示http结果到buffer时异常)