2015年10月21日水曜日

Go lang Syntax highlighting with Emacs Mac OS X

This example provides Syntax highlighting support for Google Go Language (golang) in Emacs.
I use El-Get with Emacs.

Syntax highlighting
Add El-Get code to Emacs int.el file.
$ emacs ~/.emacs.d/init.el
(when load-file-name
  (setq user-emacs-directory (file-name-directory load-file-name)))

(add-to-list 'load-path (locate-user-emacs-file "el-get/el-get"))
(unless (require 'el-get nil 'noerror)
  (with-current-buffer
      (url-retrieve-synchronously
       "https://raw.githubusercontent.com/dimitri/el-get/master/el-get-install.el")
    (goto-char (point-max))
    (eval-print-last-sexp)))
    ;; golang
    (el-get-bundle go-mode)
Open .go file.
$ emacs sample.go
Thats it.

goimports
https://godoc.org/golang.org/x/tools/cmd/goimports
Command goimports updates your Go import lines, adding missing ones and removing unreferenced ones.

Lets set goimports..
Add GOPATH and PATH to .bashrc. GOPATH is ~/gocode.
$ emacs ~/.bashrc
export GOPATH=$HOME/gocode
 if [ -d $GOPATH/bin ]; then
     PATH=$PATH:$GOPATH/bin
 fi
$ source $HOME/.bashrc
Get goimports.
$ go get golang.org/x/tools/cmd/goimports
Set ~/.emacs.d/init.el.
$ emacs ~/.emacs.d/init.el
(when load-file-name
  (setq user-emacs-directory (file-name-directory load-file-name)))

(add-to-list 'load-path (locate-user-emacs-file "el-get/el-get"))
(unless (require 'el-get nil 'noerror)
  (with-current-buffer
      (url-retrieve-synchronously
       "https://raw.githubusercontent.com/dimitri/el-get/master/el-get-install.el")
    (goto-char (point-max))
    (eval-print-last-sexp)))
    (el-get-bundle go-mode)

(add-hook 'before-save-hook 'gofmt-before-save)
(let ((goimports (executable-find "goimports")))
  (if goimports (setq gofmt-command goimports)))
Lets make new sample code. this code has no import and no Indentation for exsample.
$ mkdir $GOPATH/src/sample
$ emacs $GOPATH/src/sample/sample_code.go
package main

func main() {
fmt.Printf(stringutil.Reverse("!oG ,olleH"))
}
Run Emacs save command.
C-x C-s
package main

import "fmt"

func main() {
        fmt.Printf(stringutil.Reverse("!oG ,olleH"))
}
The new line of import was added automaticaly. Nice!