Why people say "Emacs is the best operating system"

people say "Emacs is the best operating system" :en:emacs:font:linux:terminal:terminator: It's becasue Emacs has great documentation and enough APIs.

Emacs manual even helps me even on non-Emacs stuff.

When configuring the font for Terminator (a terminal emulator) I find its manual is NOT clear. The manual doesn't explain what is "Pango font name". But Emacs manual provides all I need.

fc-list is to list installed fonts. Since terminal use Mono font, I can type below command:

fc-list | grep Mono

The output is like:

/usr/share/fonts/urw-fonts/n022003l.pfb: Nimbus Mono L:style=Regular
/usr/share/fonts/urw-fonts/n022024l.pfb: Nimbus Mono L:style=Bold Oblique
/usr/share/fonts/liberation-fonts/LiberationMono-Regular.ttf: Liberation Mono:style=Regular
/usr/share/fonts/urw-fonts/n022004l.pfb: Nimbus Mono L:style=Bold
/usr/share/fonts/liberation-fonts/LiberationMono-BoldItalic.ttf: Liberation Mono:style=Bold Italic
/usr/share/fonts/liberation-fonts/LiberationMono-Bold.ttf: Liberation Mono:style=Bold
/usr/share/fonts/wqy-zenhei/wqy-zenhei.ttc: 文泉驿等宽正黑,文泉驛等寬正黑,WenQuanYi Zen Hei Mono:style=Medium,中等
/usr/share/fonts/liberation-fonts/LiberationMono-Italic.ttf: Liberation Mhttp://blog.binchen.org/posts/why-people-say-emacs-is-the-best-operating-system.htmlono:style=Italic
/usr/share/fonts/urw-fonts/n022023l.pfb: Nimbus Mono L:style=Regular Oblique

Since Emacs manual explains the meaning of output, I know the font name "WenQuanYi Zen Hei Mono" is the key component of "Pango font name"

Because the manual also gives the details of other components of "Pango font name", the final "~/.config/terminator/config" is like:

  use_system_font = False
  # @see emacs manual for tools and explanation of font formats
  # https://www.gnu.org/software/emacs/manual/html_node/emacs/GTK-Resource-Basics.html
  # https://www.gnu.org/software/emacs/manual/html_node/emacs/Fonts.html#Fonts
  font =  WenQuanYi Zen Hei Mono 16


I create a new Emacs plugin which lists file names containing Chinese characters. At beginning I use Emacs API "find-name-dired". It uses the GNU find as the backend. But there is some integration issue on Linux. Chinese file names are displayed as garbled text in Emacs. I guess there is some decode/encode error between the interaction of Emacs process and GNU find process because Chinese files are fine on OS X.

Emacs has enough APIs. Later I found another pure Lisp API "find-lisp-find-dired". Problem solved.

Demo blog post created by nikola&org2nikola

python code:

import getopt, sys
if __name__ == '__main__':
    opts, args = getopt.getopt(sys.argv[1:], "hf:", ["help", "file="])
    for o, a in opts:
        if o in ("-h", "--help"):
            assert False, "unhandled option"
    print "hello world";

This is table:

Name Description Alternatives
Evil convert Emacs into vim none
org-mode Get Things Done (GTD) none
company-mode code completion auto-complete
expand-region selection region efficiently none

This is list:

  • list item 1
  • list item 2
  • list item 3
  • list item 4

Demo blog post created by nikola&org2nikola

python code:

import getopt, sys
if __name__ == '__main__':
    opts, args = getopt.getopt(sys.argv[1:], "hf:", ["help", "file="])
    for o, a in opts:
        if o in ("-h", "--help"):
            assert False, "unhandled option"
    print "hello world";

This is table:

Name Description Alternatives
Evil convert Emacs into vim none
org-mode Get Things Done (GTD) none
company-mode code completion auto-complete
expand-region selection region efficiently none

This is list:

  • list item 1
  • list item 2
  • list item 3
  • list item 4

How to validate HTML5 code with Flymake effectively

UPDATED: <2014-12-11 Thu>

CREATED: <2014-12-05 Fri>

Here is the solution from EmacsWiki.

I found it not effective because tidy is too strict to HTML5 and produces too much noise.

I only need validation of missing open/closed html tag(s). Nothing more!

So here is my complete solution:

(defun flymake-html-init ()
       (let* ((temp-file (flymake-init-create-temp-buffer-copy
              (local-file (file-relative-name
                           (file-name-directory buffer-file-name))))
         (list "tidy" (list local-file))))

(defun flymake-html-load ()
  (when (and (not (null buffer-file-name)) (file-writable-p buffer-file-name))
    (set (make-local-variable 'flymake-allowed-file-name-masks)
         '(("\\.html\\|\\.ctp\\|\\.ftl\\|\\.jsp\\|\\.php\\|\\.erb\\|\\.rhtml" flymake-html-init))
    (set (make-local-variable 'flymake-err-line-patterns)
         ;; only validate missing html tags
         '(("line \\([0-9]+\\) column \\([0-9]+\\) - \\(Warning\\|Error\\): \\(missing <\/[a-z0-9A-Z]+>.*\\|discarding unexpected.*\\)" nil 1 2 4))
    (flymake-mode t)))

(add-hook 'web-mode-hook 'flymake-html-load)
(add-hook 'html-mode-hook 'flymake-html-load)
(add-hook 'nxml-mode-hook 'flymake-html-load)
(add-hook 'php-mode-hook 'flymake-html-load)

The only difference from EmacsWiki is only one line:

'(("line \\([0-9]+\\) column \\([0-9]+\\) - \\(Warning\\|Error\\): \\(missing <\/[a-z0-9A-Z]+>.*\\|discarding unexpected.*\\)" nil 1 2 4))

Advanced tip on using mozrepl to automatically refresh browser

Here is the setup on Emacswiki.

I find it annoying instead of helpful in real world usage.

The mozrepl trick basically will refresh the current active page in Firefox. It's not smart enough. When developing a web application, I will open many stackoverflow pages to look for technical solution. I don't like my stackoverflow page being refreshed when I'm saving the HTML code for some web application.

So here is my improved solution:

(defun my-moz-refresh-browser-condition (current-file)
  "Should return a boolean javascript expression or nil"
  (let (rlt)
     ((string-match "\\(beeta\\|cb_tutorial\\)" current-file)
      (setq rlt "content.document.location.href.indexOf(':8001')!==-1"))
      (setq rlt nil)))

;; {{ mozrepl auto-refresh browser
(defun moz-reload-browser ()
  (let (js-cond cmd)
    (if (fboundp 'my-moz-refresh-browser-condition)
        (setq js-cond (funcall 'my-moz-refresh-browser-condition (buffer-file-name))))
      (setq cmd (concat "if(" js-cond "){setTimeout(function(){content.document.location.reload(true);}, '500');}")))
      (setq cmd "setTimeout(function(){content.document.location.reload(true);}, '500');")))
    (comint-send-string (inferior-moz-process) cmd)

(defun moz-after-save ()
  (when (memq major-mode '(web-mode html-mode nxml-mode nxhml-mode php-mode))

(add-hook 'after-save-hook
              'append 'local)
;; }}

Tips on using Ctags with Emacs

Ctags is critical to my web projects. I use it for code navigation by `M-x find-tag` and code auto-completion by using company-etags from company-mode.

The first tip is to use global variable `tags-table-list` instead of `tags-file-name`. The Emacs documentation says you should NOT set both. `tags-table-list` is better because it's a list, where you can store multiple tag files.

Here is the value of `tags-table-list` for one project:

("/Users/cb/projs/their-project/test/cdn/test/assets/test/js/TAGS" "/Users/cb/projs/their-project/test/app/TAGS")

The purpose to use multiple tag files in sub-folders instead of one tag file in root folder is to scan less code files.

The second tip is we can avoid feeding big js files to ctags. Currently one of my client's project is not managed well. They place the concatenated js files, third party js libraries, and normal code file into one folder. The naming of files is a mess. So I can not tell which is which from file name or file path. The tag file created from those big concatenated js files will crash my Emacs.

Change the ctags command line underhood will solve the problem. Here is the actual liner to create a tag file:

find proj-dir -type f -not -iwholename '*TAGS' -not -size +16k | ctags -f ~/proj/output/TAGS -e -L -

The point is the option `-not -size +16k`. It means only handle files less thank 16k.

Here is the Emacs lisp function to wrap above shell command:

(defun my-create-tags-if-needed (SRC-DIR CTAGS-OPTS &optional FORCE)
  "return the full path of tags file"
  ;; TODO save the CTAGS-OPTS into hash
  (let ((dir (file-name-as-directory (file-truename SRC-DIR)) )
    (setq file (concat dir "TAGS"))
    (when (or FORCE (not (file-exists-p file)))
      (setq cmd (format "find %s -type f -not -iwholename '*TAGS' -not -size +24k | ctags -f %s -e  %s -L -" dir file CTAGS-OPTS))
      (shell-command cmd))

BTW, here is my ~/.ctags.

In summary, there are ONLY two points:

  • What's the `tags-table-list`
  • How the tags file are created by ctags


  1. My tags file management strategy is described at How to use ctags in Emacs effectively. It's effective to me. But it may be not generic enough to apply to others' use cases.
  2. I do use Gnu Global for C/C++/Java code. I use it exactly in the same way as ctags. Please `man global` for the details. Hint, all you need care is the environment variable GTAGSLIBPATH.

Debug efficiently in Emacs

Please note:

  • I use javascript as a use case. The solution is generic enough to be applied to any language. At the end of the article, Emacs Lisp is used as another example.
  • I'm good at most debuggers. The point of this article is to deal with more difficult issues the debugger can not handle.
  • My code quality is fine. It handles all the corner cases I've met. For example, single quote and double quotes will be escaped properly.


As a freelancer I am often required to debug legacy javascript code from some huge "enterprise"" applications.

The only way to debug such application is to insert as many as possible logging code, watch the output, and think.

So my problem is how to insert logging code as quickly as possible.


My solution is Yasnippet. Yasnippet allow me to insert executable Emacs Lisp code in its snippet. I will Sotake full advantage of that feature.

Logging simple JS variable

Given a variable name like "var1", I need insert javascript code as below:

console.log("var1=", var1)

Snippet: https://github.com/redguardtoo/emacs.d/blob/master/snippets/js-mode/logobject.yasnippet

This snippet need you input variable name once.

Logging complex JS variable

In real world, the JS variable is often a string like "MyController.servicea.find('.class').attr1" which I hate to type.

So the solution is that I copy the JS variable into kill ring where my snippet will read the variable name.

Snippet: https://github.com/redguardtoo/emacs.d/blob/master/snippets/js-mode/log-recent-kill-ring.yasnippet

Logging JS function name when it's called

In below example, I need insert "console.log('hello is called');" in function "hello":

function hello() {
  console.log('hello is called');

Snippet: https://github.com/redguardtoo/emacs.d/blob/master/snippets/js-mode/log-which-function.yasnippet

This snippet use the Emacs command `which-function`. If you read the code of `which-function`, you will find that it's Imenu-mode who actually extracts the function name. But Imenu-mode requires you pre-define enough regular expressions.

Please check https://github.com/redguardtoo/emacs.d/blob/master/lisp/init-javascript.el. I have defined many regular expressions for AngularJS and JQuery.

The regular expressions could be used in both js-mode and js2-mode.

Logging JS function name with its parameters

JS example:

function hello(v1, v2,
               v3, v4) {
  console.log("v1=", v1, "v2=", v2, "v3=", v3, "v4=", v4);

I copy the parameter of JS function named "hello". It's just the content between "hello(" and ")", then Emacs Lisp code embedded in the snippet will parse and output the right content from kill ring.

Snippet: https://github.com/redguardtoo/emacs.d/blob/master/snippets/js-mode/log-which-function-with-para.yasnippet

BTW, since I use Evil, copy the parameter into kill-ring is as simple as pressing "yi(".

Insert JS debugger statement

@cjk provided this tip. The debugger like Firebug will pause at the debugger statement. It saves me the time to locate JS file, to go to the specific line and set breakpoint after re-deploying the application.

Snippets: https://github.com/redguardtoo/emacs.d/blob/master/snippets/js-mode/debugger.yasnippet



Similar snippets for Emacs Lisp are defined HERE.

Use bootstrap+font-awesome+jquery for IE7 web application

Live demo: http://binchen.org/schools/

Screenshot: e86f11a6-733c-11e4-8312-a6c8ad2b17be.png


  • Bootstrap 2.3.2
  • font-awesome 3.2.1
  • JQuery 1.8.2

I only use the grid layout from bootstrap and minimum API from jQuery.


  • IE7 does not support media query. So I abandon "mobile first" strategy, new strategy is "IE7 first".
  • IE7 does not support inline-block properly, I need below css code hack:
.myclass {
  display: inline-block;
  /* ie7*/
  *display: inline;
  zoom: 1;
  • bootstrap's row-fluid has issues in IE7. I use row-fluid in this case, but have to hard code the row width sometimes.
  • add below code into javascript so that I can hack IE7-only css code:
if($.browser.msie && parseFloat($.browser.version) < 8){
  that.ie7 = true;

Make web-mode support HTML with AngularJS data-binding

I find it very useful to use `M-x imenu` to jump to the AngularJS binding point of one HTML file.

Insert below code into ~/.emacs:

(eval-after-load 'web-mode
     ;; angular imenu
     (add-to-list 'web-mode-imenu-regexp-list
                  '(" \\(ng-[a-z]*\\)=\"\\([a-zA-Z0-9]*\\)" 1 2 "="))))

Export org file embedded with code snippets

CREATED: <2014-11-20 Thu>

UPDATED: <2015-06-06 Sat>


I use Org-mode to record all my notes.

As a developer, I place code snippets from many programming languages into one org file.

The issue is when exporting the org file, major mode for each language will be loaded to render the code snippet.

It means the hooks of the major modes will be executed. Since I put lots of heavy weight setup things in those hooks, my exporting is extremely slow.

My hooks are also dependent on third party tools. So if anyone else uses my setup without those tools, his/her exporting will fail.



In order to solve the issue, I write a small function which will be called at the beginning of each major mode hook.

The function basically check whether the `(buffer-file-name)` is the temporary file created by Org-mode or the output HTML converted from org file. If answer is "YES", then code in major mode hook will not be executed.

(defvar load-user-customized-major-mode-hook t)
(defvar cached-normal-file-full-path nil)
(defun is-buffer-file-temp ()
  "If (buffer-file-name) is nil or a temp file or HTML file converted from org file"
  (let ((f (buffer-file-name))
        (rlt t))
     ((not load-user-customized-major-mode-hook) t)
     ((not f)
      ;; file does not exist at all
      (setq rlt t))
     ((string= f cached-normal-file-full-path)
      (setq rlt nil))
     ((string-match (concat "^" temporary-file-directory) f)
      ;; file is create from temp directory
      (setq rlt t))
     ((and (string-match "\.html$" f)
           (file-exists-p (setq org (replace-regexp-in-string "\.html$" ".org" f))))
      ;; file is a html file exported from org-mode
      (setq rlt t))
      ;; avoid calling to file-exists-p too often for performance reason
      (setq cached-normal-file-full-path f)
      (setq rlt nil)))


I use python-mode-hook setup as an example:

(add-hook 'python-mode-hook
          '(lambda ()
             (unless (is-buffer-file-temp)
               (if (executable-find "pyflakes")
               (setq electric-indent-chars (delq ?: electric-indent-chars))


Export shell code

Exporting shell code will fail if `sh-mode` is loaded. So I use "bash" instead. Since there is no "bash-mode", exporting will be fine.

Yasnippet setup

To avoid loading yasnippets when exporting, I have to "use yas-minor-mode on a per-buffer basis".

Manually turn off the major-mode hook

It's controlled by global flag `load-user-customized-major-mode-hook`, as you can see from the "Setup" section.

Say I want to turn off the major mode hooks when `M-x org-publish`, here is the setup:

(defadvice org-publish (around org-publish-advice activate)
  "Stop running major-mode hook when org-publish"
  (let ((old load-user-customized-major-mode-hook))
    (setq load-user-customized-major-mode-hook nil)
    (setq load-user-customized-major-mode-hook old)))


`after-save-hook` is the "Normal hook that is run after a buffer is saved to its file". You may also need tweak it up because it will be called when exporting org files