         sml/show-remote nil
         sml/name-width '(20 . 40)
         sml/shorten-modes t
-        sml/mode-width 30)
+        sml/mode-width 'right)
+  (add-hook 'after-init-hook #'ar/enable-graphical-time)
   (sml/setup))
+
+(defun ar/enable-graphical-time ()
+  "Enable graphical time in modeline."
+  (interactive)
+  (setq display-time-24hr-format t)
+  (setq display-time-day-and-date t)
+  (display-time) ; Align the time to right
+  (setq global-mode-string (remove 'display-time-string global-mode-string))
+  (setq mode-line-end-spaces
+        (list (propertize " " 'display '(space :align-to (- right 17)))
+              'display-time-string)))
 
 ;; Set font face height. Value is 1/10pt.
 (set-face-attribute 'default nil :height 180)

  "Setup up the fringe (graphical display only)."
  (custom-set-faces '(fringe ((t (:background "#1B1D1E"))))))

;; TODO: Revisit this.
(defun ar/setup-graphical-display ()
  "Setup graphical display."
  (when (window-system)
    (ar/setup-graphical-fringe)
    (ar/setup-graphical-fonts)
    (ar/setup-graphical-mode-line)))

(ar/setup-graphical-display)

;; Handy pop-up messages with git info.
(use-package git-messenger :ensure t)

;; Display column numbers.
(setq-default column-number-mode t)

;; Highlights current line.
(use-package hl-line :ensure t)

;; Set color as current line's background face.
;; (set-face-background 'hl-line "black")
;; Keep syntax highlighting in the current line.
;; (set-face-foreground 'highlight nil)

(use-package whitespace :ensure t)
(setq whitespace-style '(face lines-tail))

;;  From http://doc.rix.si/org/fsem.html
(defun ar/gnulinuxp ()
  "Return t if the system is a GNU/Linux machine, otherwise nil."
  (string-equal system-type "gnu/linux"))

(defun ar/osxp ()
  "Return t if the system is a Mac OS X machine, otherwise nil."
  (string-equal system-type "darwin"))

(defun ar/cygwinp ()
  "Return t if Emacs is running inside of Cygwin on Windows, otherwise nil."
  (string-equal system-type "cygwin"))

(defun ar/windowsp ()
  "Return t if the system is a native Emacs for Windows, otherwise nil."
  (string-equal system-type "windows"))

(defun ar/new-browser-tab-shell-command ()
  "Return new browser tab shell command."
  (cond
   ((ar/osxp)
    "open http://google.com")
   ((ar/gnulinuxp)
    "google-chrome http://google.com")
   (nil)))

(defun ar/new-browser-tab ()
  "Open a new browser tab in the default browser."
  (interactive)
  (let ((command (ar/new-browser-tab-shell-command)))
    (message command)
    (if command
        (shell-command command)
      (message "Unrecognized platform."))))
(global-set-key (kbd "C-x t")
                #'ar/new-browser-tab)

(defun ar/init-for-osx ()
  "Perform initializations for Mac OS X."
  (when (ar/osxp)
    ;; Sets the command (Apple) key as Meta.
    (setq mac-command-modifier 'meta)
    ;; Sets the option (Apple) key also as Meta.
    (setq mac-option-modifier 'meta)
    (setq exec-path (append exec-path '("~/homebrew/bin"
                                        "~/homebrew/Cellar/llvm/HEAD/bin")))))
(ar/init-for-osx)

(defun ar/init-for-linux ()
  "Perform initializations for Linux."
  (when (ar/gnulinuxp)
    (setq exec-path (append exec-path '("~/local/bin")))))
(ar/init-for-linux)

;; Disable backup.
;; From: http://anirudhsasikumar.net/blog/2005.01.21.html
(setq backup-inhibited t)

;; Disable auto save.
(setq auto-save-default nil)

;; Disable auto save.
;; From: http://anirudhsasikumar.net/blog/2005.01.21.html
(setq auto-save-default nil)

;; Case-sensitive fold search search (ie. M-/ to autocomplete).
(setq dabbrev-case-fold-search nil)

;; Move buffer file.
;; From: https://sites.google.com/site/steveyegge2/my-dot-emacs-file
(defun ar/move-buffer-file (dir)
  "Move both current buffer and file it's visiting to DIR." (interactive "DNew directory: ")
  (let* ((name (buffer-name))
         (filename (buffer-file-name))
         (dir (if (string-match dir "\\(?:/\\|\\\\)$")
                  (substring dir 0 -1)
                dir))
         (newname (concat dir "/" name)))

    (if (not filename)
        (message "Buffer '%s' is not visiting a file!" name)
      (progn (copy-file filename newname 1)
             (delete-file filename)
             (set-visited-file-name newname)
             (set-buffer-modified-p nil) t))))

;;  http://scottmcpeak.com/elisp/scott.emacs.el
;;  ------------------- yes-or-no-p ---------------------
;;  There are a number of situations where Emacs wants to ask me a question,
;;  but the answer is always the same (or, it's easy to get the effect of
;;  the other answer afterwards).  The main example is the question:
;;
;;    File foo.txt has changed on disk.  Reread from disk?
;;
;;  This question is annoying because it gets asked while I'm moving around
;;  in a debugger stack trace, and often don't care about the file I happen
;;  to be at (because I want to move past that frame anyway).  Moreover,
;;  my F12 binding lets me re-read files with a single keystroke, so if I
;;  actually *do* want to re-read it's easy to do.

;;  First, I need the original definition of yes-or-no-p so I can call it
;;  after I've replaced its definition.  In case .emacs gets re-read
;;  after startup, avoid losing the original definition.
(if (fboundp 'orig-yes-or-no-p)
    nil        ; it's already bound, don't re-bind
  (fset 'orig-yes-or-no-p (symbol-function 'yes-or-no-p)))

;;  Now, define my version in terms of `orig-yes-or-no-p'.
(defun yes-or-no-p (prompt)
  "Ask user a yes-or-no question.  Return t if answer is yes, nil if no.
This is a wrapper around `orig-yes-or-no'.
Argument PROMPT to check for additional prompt."
  (if (string-match
       ;;  This message is created in lisp/files.el, and there are four
       ;;  variations.  I'm intentionally matching two of them.
       "File .* changed on disk.  Reread from disk"
       prompt)

      ;;  it's that question; the answer is no, but I *do* want to know
      ;;  that it has changed
      (progn (message "Note: File has changed on disk.") nil)

    ;;  it's a different question; for now, just ask me; I'll probably
    ;;  add more patterns to the above as I think of other questions that
    ;;  I don't want asked
    (orig-yes-or-no-p prompt)))

(use-package git-link :ensure t)

(use-package magit :ensure t)
;; Use vc-ediff as default.
(eval-after-load "vc-hooks"
  '(define-key vc-prefix-map "=" #'vc-ediff))
(global-set-key (kbd "C-x g")
                #'magit-status)
(setq magit-status-buffer-switch-function #'switch-to-buffer)

(defun ar/sort-lines-ignore-case ()
  "Sort region (case-insensitive)."
  (interactive)
  (let ((sort-fold-case t))
    (call-interactively #'sort-lines)))

(setq css-indent-offset 2)

(defun ar/open-in-external-app-lambda ()
  "Return a function to open FPATH externally."
  (cond
   ((ar/windowsp)
    (lambda (fPath)
      (w32-shell-execute "open" (replace-regexp-in-string "/" "\\" fPath t t))))
   ((ar/osxp)
    (lambda (fPath)
      (shell-command (format "open \"%s\"" fPath))))
   ((ar/gnulinuxp)
    (lambda (fPath)
      (let ((process-connection-type nil))
        (start-process "" nil "xdg-open" fPath))))))

;; Based on http://ergoemacs.org/emacs/emacs_dired_open_file_in_ext_apps.html
(defun ar/open-in-external-app ()
  "Open the current file or dired marked files in external app.
The app is chosen from your OS's preference.

Version 2015-01-26
URL `http://ergoemacs.org/emacs/emacs_dired_open_file_in_ext_apps.html'"
  (interactive)
  (let* ((ξfile-list
          (if (string-equal major-mode "dired-mode")
              (dired-get-marked-files)
            (list (buffer-file-name))))
         (ξdo-it-p (if (<= (length ξfile-list) 5)
                       t
                     (y-or-n-p "Open more than 5 files? "))))
    (when ξdo-it-p
      (mapc (ar/open-in-external-app-lambda) ξfile-list))))
(global-set-key (kbd "C-M-o")
                #'ar/open-in-external-app)

(setq ring-bell-function 'ignore)

(use-package markdown-mode+ :ensure t)
(autoload 'markdown-mode "markdown-mode"
  "Major mode for editing Markdown files" t)
(add-to-list 'auto-mode-alist '("\\.text\\'" . markdown-mode))
(add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode))
(add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode))

(setq display-time-world-list '(("Europe/Paris" "Paris")
                                ("Europe/London" "London")
                                ("America/Los_Angeles" "Los Angeles")))

;; From http://wenshanren.org/?p=298#more-298
(defun ar/edit-current-file-as-root ()
  "Edit the file that is associated with the current buffer as root."
  (interactive)
  (if (buffer-file-name)
      (let ((file (concat "/sudo:root@localhost:" (buffer-file-name))))
        (find-file file))
    (message "Current buffer does not have an associated file.")))

(global-set-key "\M-/" 'hippie-expand)
(setq hippie-expand-try-functions-list '(try-expand-dabbrev
                                         try-expand-dabbrev-visible
                                         try-expand-dabbrev-all-buffers
                                         try-expand-dabbrev-from-kill
                                         try-complete-file-name-partially
                                         try-complete-file-name
                                         try-expand-all-abbrevs
                                         try-expand-list
                                         try-expand-line))
;; Thank you Sacha Chua.
;; From http://pages.sachachua.com/.emacs.d/Sacha.html#sec-1-4-8
(fset 'yes-or-no-p 'y-or-n-p)

;; Ensure files end with newline.
(setq require-final-newline t)

;; From http://www.wisdomandwonder.com/wordpress/wp-content/uploads/2014/03/C3F.html
(setq savehist-file "~/.emacs.d/savehist")
(savehist-mode +1)
(setq savehist-save-minibuffer-history +1)
(setq savehist-additional-variables
      '(kill-ring
        search-ring
        regexp-search-ring))

;; Don't let the cursor go into minibuffer prompt.
;; From http://ergoemacs.org/emacs/emacs_stop_cursor_enter_prompt.html
(setq minibuffer-prompt-properties '(read-only t point-entered minibuffer-avoid-prompt face minibuffer-prompt))

;; From http://pages.sachachua.com/.emacs.d/Sacha.html#sec-1-5-12
(defun ar/smarter-move-beginning-of-line (arg)
  "Move point back to indentation of beginning of line.

Move point to the first non-whitespace character on this line.
If point is already there, move to the beginning of the line.
Effectively toggle between the first non-whitespace character and
the beginning of the line.

If ARG is not nil or 1, move forward ARG - 1 lines first.  If
point reaches the beginning or end of the buffer, stop there."
  (interactive "^p")
  (setq arg (or arg 1))

  ;; Move lines first
  (when (/= arg 1)
    (let ((line-move-visual nil))
      (forward-line (1- arg))))

  (let ((orig-point (point)))
    (back-to-indentation)
    (when (= orig-point (point))
      (move-beginning-of-line 1))))

;; remap C-a to `smarter-move-beginning-of-line'
(global-set-key [remap move-beginning-of-line]
                'ar/smarter-move-beginning-of-line)

;; From http://www.reddit.com/r/emacs/comments/25v0eo/you_emacs_tips_and_tricks/chldury
(defun ar/vsplit-last-buffer ()
  "Vertically splitting the screen and open the previous buffer instead of identical buffers."
  (interactive)
  (split-window-vertically)
  (other-window 1 nil)
  (switch-to-next-buffer))

(defun ar/hsplit-last-buffer ()
  "Horizontally splitting the screen and open the previous buffer instead of identical buffers."
  (interactive)
  (split-window-horizontally)
  (other-window 1 nil)
  (switch-to-next-buffer))

(global-set-key (kbd "C-x 2")
                #'ar/vsplit-last-buffer)
(global-set-key (kbd "C-x 3")
                #'ar/hsplit-last-buffer)

;; Thank you Bozhidar.
;; From https://github.com/bbatsov/prelude/blob/a52cdc83eeec567b13a8a5719a174dfe294ee739/core/prelude-core.el#L340
(defun ar/swap-windows ()
  "If you have 2 windows, it swaps them."
  (interactive)
  (if (/= (count-windows) 2)
      (message "You need exactly 2 windows to do this.")
    (let* ((w1 (car (window-list)))
           (w2 (cadr (window-list)))
           (b1 (window-buffer w1))
           (b2 (window-buffer w2))
           (s1 (window-start w1))
           (s2 (window-start w2)))
      (set-window-buffer w1 b2)
      (set-window-buffer w2 b1)
      (set-window-start w1 s2)
      (set-window-start w2 s1)))
  (other-window 1))
(bind-key "C-\\" #'ar/swap-windows)

;; From https://github.com/bbatsov/prelude/blob/a52cdc83eeec567b13a8a5719a174dfe294ee739/core/prelude-core.el#L111
(defun ar/smart-open-line-above ()
  "Insert an empty line above the current line.
Position the cursor at it's beginning, according to the current mode."
  (interactive)
  (move-beginning-of-line nil)
  (newline-and-indent)
  (forward-line -1)
  (indent-according-to-mode))

;; Do not auto indent current line when pressing <RET>.
(add-hook 'sgml-mode-hook
          (lambda() (local-set-key (kbd "<RET>")
                                   #'electric-indent-just-newline)))

(defun ar/smart-open-line (arg)
  "Insert an empty line after the current line.
Position the cursor at its beginning, according to the current mode.
With a prefix ARG open line above the current line."
  (interactive "P")
  (if arg
      (ar/smart-open-line-above)
    (progn
      (move-end-of-line nil)
      (newline-and-indent))))

(global-set-key (kbd "C-o")
                #'ar/smart-open-line)

(use-package ace-jump-mode :ensure t)

(use-package ace-jump-zap :ensure t
  :bind
  (("M-z" . ace-jump-zap-up-to-char-dwim)
   ("C-M-z" . ace-jump-zap-to-char-dwim)))

(use-package ace-window :ensure t
  :init (setq aw-keys '(?a ?s ?d ?f ?g ?h ?j ?k ?l))
  :bind (("C-x o" . ace-window)))
;; Use larger characters for ace window shortcuts.
;; From http://oremacs.com/2015/02/27/ace-window-leading-char
(custom-set-faces
 '(aw-leading-char-face
   ((t (:inherit ace-jump-face-foreground :height 3.0)))))

;; Interactively resize current window.
(use-package windsize :ensure t)
(windsize-default-keybindings)

(use-package key-chord :ensure t)
(key-chord-define-global "jj" #'ace-jump-char-mode)
(key-chord-define-global "jk" #'ace-jump-char-mode)
(key-chord-define-global "jl" #'ace-jump-line-mode)
(key-chord-define-global "xx" #'execute-extended-command)
(key-chord-define-global "kk" #'kill-whole-line)

;; From http://emacsredux.com/blog/2013/04/28/switch-to-previous-buffer
(defun ar/switch-to-previous-buffer ()
  "Switch to previously open buffer.
Repeated invocations toggle between the two most recently open buffers."
  (interactive)
  (switch-to-buffer (other-buffer (current-buffer) 1)))
(key-chord-define-global "JJ" #'ar/switch-to-previous-buffer)
(key-chord-define-global "BB" #'other-window)
(key-chord-mode +1)

;; Needs clang-format installed.
;; See http://blog.hardcodes.de/articles/63/building-clang-format-and-friends-on-osx-mountain-lion
;; See http://clang.llvm.org/docs/ClangFormat.html
(use-package clang-format :ensure t)

(use-package company :ensure t)
(use-package company-quickhelp :ensure t)
(use-package company-c-headers :ensure t)
(setq company-backends (delete 'company-semantic company-backends))
(setq company-minimum-prefix-length 2)
(setq company-idle-delay 0.5)
(setq company-show-numbers t)
(global-company-mode)
(add-to-list 'company-backends 'company-c-headers)
(global-set-key (kbd "<backtab>")
                #'company-complete)

;; (add-to-list 'load-path
;;              (concat (getenv "HOME") "/.emacs.d/downloads/rtags/src"))
;; (require 'rtags)
;; (require 'company-rtags)
;; (setq rtags-path
;;       (concat (getenv "HOME") "/.emacs.d/downloads/rtags/bin"))
;; (setq company-backends (delete 'company-clang company-backends))
;; (setq company-rtags-begin-after-member-access t)
;; (setq rtags-completions-enabled t)
;; (add-to-list 'company-backends 'company-rtags)
;; (rtags-diagnostics)

(use-package helm-c-yasnippet :ensure t)

(use-package helm-make :ensure t)

(use-package drag-stuff :ensure t)
(global-set-key (kbd "M-<up>")
                #'drag-stuff-up)
(global-set-key (kbd "M-<down>")
                #'drag-stuff-down)

;; Avoid creating lock files (ie. .#some-file.el)
(setq create-lockfiles nil)

;; displays hex strings representing colors
(use-package rainbow-mode :ensure t)

;; If eclim is your cup of tea.
;; (require 'eclim)
;; (global-eclim-mode)
;; (custom-set-variables
;;  '(eclim-eclipse-dirs '("~/tools/eclipse"))
;;  '(eclim-executable "~/tools/eclipse/eclim"))
;; (require 'eclimd)
;; (require 'company-emacs-eclim)
;; (company-emacs-eclim-setup)
;; (global-company-mode t)

;; Relies on manual installation (ie. make emaXcode).
;; Enable auto-complete to use emaXcode while generating snippets.
;;(use-package auto-complete
; :ensure t)
;;(load "~/.emacs.d/downloads/emaXcode/emaXcode.el")
;;(require 'emaXcode)

;; From http://sakito.jp/emacs/emacsobjectivec.html#xcode
(defun ar/xc:build ()
  "Tell Xcode to build."
  (interactive)
  (do-applescript
   (format
    (concat
     "tell application \"Xcode\" to activate \r"
     "tell application \"System Events\" \r"
     "     tell process \"Xcode\" \r"
     "          key code 11 using {command down} \r"
     "    end tell \r"
     "end tell \r"
     ))))

(defun ar/xc:run ()
  "Tell Xcode to run."
  (interactive)
  (do-applescript
   (format
    (concat
     "tell application \"Xcode\" to activate \r"
     "tell application \"System Events\" \r"
     "     tell process \"Xcode\" \r"
     "          key code 15 using {command down} \r"
     "    end tell \r"
     "end tell \r"
     ))))

;;  Note: For ycmd.
;;  * No need for global_ycm_extra_conf.py
;;    (Use .ycm_extra_conf.py)
;;  * Needs .ycm_extra_conf.py (pointing to compile_commands.json location)
;;    (See emacs/ycmd/.ycm_extra_conf.py)
;;  * Needs compile_commands.json
;;    (See http://blog.patspam.com/2014/vim-objc-code-completion)
;;  * Add objc-mode to company-ycmd--extended-features-modes in company-ycmd.el
;; (use-package ycmd
;; :ensure t)
;;
;; (use-package company-ycmd
;; :ensure t)
;;
;; (setq ycmd-server-command (list "python"
;;                                 (expand-file-name "~/.emacs.d/downloads/ycmd/ycmd")))
;; (setq ycmd--log-enabled t)

(use-package objc-font-lock
  :ensure t
  :init (setq objc-font-lock-background-face nil))

(use-package dummy-h-mode :ensure t)
(add-to-list 'auto-mode-alist '("\\.h\\'" . dummy-h-mode))

(defun ar/kill-other-buffers ()
  "Kill all other buffers."
  (interactive)
  (mapc 'kill-buffer
        (delq (current-buffer)
              ;; Disables "required at runtime" warning for cl package.
              (with-no-warnings
                (remove-if-not 'buffer-file-name (buffer-list))))))

;; From: http://emacsredux.com/blog/2013/05/04/rename-file-and-buffer
(defun ar/rename-current-file-and-buffer ()
  "Rename the current buffer and file it is visiting."
  (interactive)
  (let ((filename (buffer-file-name)))
    (if (not (and filename (file-exists-p filename)))
        (message "Buffer is not visiting a file!")
      (let ((new-name (read-file-name "New name: " filename)))
        (cond
         ((vc-backend filename) (vc-rename-file filename new-name))
         (t
          (rename-file filename new-name t)
          (set-visited-file-name new-name t t)))))))

;;  From http://emacsredux.com/blog/2013/04/03/delete-file-and-buffer/
(defun ar/delete-current-file-and-buffer ()
  "Kill the current buffer and deletes the file it is visiting."
  (interactive)
  (let ((filename (buffer-file-name)))
    (when filename
      (if (vc-backend filename)
          (vc-delete-file filename)
        (progn
          (delete-file filename)
          (message "Deleted file %s" filename)
          (kill-buffer))))))

(use-package go-mode :ensure t)
;; Requires gocode daemon. Install with:
;; go get -u github.com/nsf/gocode
;; go get -u code.google.com/p/rog-go/exp/cmd/godef
;; go get -u code.google.com/p/go.tools/cmd/goimports
;; Useful info at:
;; http://tleyden.github.io/blog/2014/05/22/configure-emacs-as-a-go-editor-from-scratch
;; http://tleyden.github.io/blog/2014/05/27/configure-emacs-as-a-go-editor-from-scratch-part-2
;; http://dominik.honnef.co/posts/2013/03/writing_go_in_emacs
(use-package company-go :ensure t)
(add-hook 'go-mode-hook (lambda ()
                          (helm-dash-activate-docset "Go")
                          (set (make-local-variable 'company-backends) '(company-go))
                          (company-mode)
                          (setq tab-width 2 indent-tabs-mode 1)
                          (add-hook 'before-save-hook #'gofmt-before-save)))

(unless (server-running-p)
  (server-start))

;; Customize vertical window divider:
;; Set symbol for the border.
(set-display-table-slot standard-display-table
                        'vertical-border
                        (make-glyph-code ?|))

(defun ar/split-camel-region ()
  "Splits camelCaseWord to camel case word."
  (interactive)
  (let ((case-fold-search nil))
    (while (re-search-forward "[A-Z]" (region-end) t)
      (replace-match (format " %s"
                             (downcase (match-string 0)))
                     t nil))))
(global-set-key (kbd "C-c l")
                #'ar/split-camel-region)

;; Simplify lisp navigation/editing (ie. slurp/barf).
(use-package lispy :ensure t)

;; M-. elisp navigation.
(use-package elisp-slime-nav :ensure t)

(defun ar/add-functions-to-mode-hooks (hook-functions hooks)
  "Add HOOK-FUNCTIONS to mode HOOKS."
  (dolist (hook hooks)
    (dolist (hook-function hook-functions)
      (add-hook hook hook-function))))

(defun ar/emacs-lisp-mode-hook-function ()
  "Called when entering `emacs-lisp-mode'."
  (helm-dash-activate-docset "Emacs Lisp")
  (lispy-mode 1)
  (eldoc-mode)
  (turn-on-elisp-slime-nav-mode))
(ar/add-functions-to-mode-hooks '(ar/emacs-lisp-mode-hook-function)
                                '(emacs-lisp-mode-hook
                                  ielm-mode-hook))

(defun ar/save-point-to-register ()
  "Save point to register."
  (interactive)
  (point-to-register 9999))

(defun ar/jump-to-saved-point-register ()
  "Jumps cursor to register 9999's value."
  (interactive)
  (jump-to-register 9999))
(global-set-key (kbd "C-c `")
                #'ar/jump-to-saved-point-register)

(defun ar/after-prog-mode-text-change (beg end len)
  "Execute for all text modifications in `prog-mode'.
Argument BEG beginning.
Argument END end.
Argument LEN Length."
  ;; Saving point enables jumping back to last change at any time.
  (ar/save-point-to-register))

(defun ar/select-current-block ()
  "Select the current block of text between blank lines.
URL `http://ergoemacs.org/emacs/modernization_mark-word.html'
Version 2015-02-07."
  (interactive)
  (let (p1 p2)
    (if (re-search-backward "\n[ \t]*\n" nil "move")
        (progn (re-search-forward "\n[ \t]*\n")
               (setq p1 (point)))
      (setq p1 (point)))
    (if (re-search-forward "\n[ \t]*\n" nil "move")
        (progn (re-search-backward "\n[ \t]*\n")
               (setq p2 (point)))
      (setq p2 (point)))
    (set-mark p1)))

(defun ar/sort-current-block ()
  "Select and sort current block."
  (interactive)
  (ar/select-current-block)
  (ar/sort-lines-ignore-case))

(defun ar/sort-objc-headers ()
  "Alphabetically sort Objective-C headers."
  (interactive)
  (save-excursion
    (goto-char (point-min))
    (while (re-search-forward "^#\\(include\\|import\\).*\n\n" nil t)
      (goto-char (match-beginning 0))
      (ar/sort-current-block))))

(defun ar/clang-format-buffer ()
  "Clang format current buffer."
  (interactive)
  (clang-format (point-min)
                (point-max)))

(defun ar/objc-mode-hook-function ()
  "Called when entering `objc-mode'."
  (add-hook 'before-save-hook
            #'ar/clang-format-buffer
            nil
            'make-it-local)
  (objc-font-lock-mode)
  (helm-dash-activate-docset "iOS")
  ;; Highlight lines longer than 100 columns.
  (set (make-local-variable 'whitespace-line-column) 100)
  (set (make-local-variable 'company-backends)
       ;; List with multiple back-ends for mutual inclusion.
       '(( ;;company-ycmd
          company-yasnippet
          company-gtags
          company-dabbrev-code
          company-files)))
  ;;(ycmd-mode)

  ;; List targets with xcodebuild -list
  ;; List SDKS with xcodebuild -sdk -version, for example:
  ;; iPhoneSimulator7.1.sdk - Simulator - iOS 7.1 (iphonesimulator7.1)
  ;; SDKVersion: 7.1
  ;; Path: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator7.1.sdk
  ;; PlatformPath: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform
  ;; ProductBuildVersion: 11D167
  ;; ProductCopyright: 1983-2014 Apple Inc.
  ;; ProductName: iPhone OS
  ;; ProductVersion: 7.1
  (set (make-local-variable 'compile-command)
       "xcodebuild -sdk iphonesimulator7.1 -target MyTarget")
  (local-set-key (kbd "<f7>")
                 #'ar/xc:build)
  (local-set-key (kbd "<f8>")
                 #'ar/xc:run)
  (key-chord-define (current-local-map) ";;" "\C-e;"))
(add-hook 'objc-mode-hook #'ar/objc-mode-hook-function)

(defun ar/java-mode-hook-function ()
  "Called when entering `java-mode'."
  ;; 2-char indent for java.
  (defvar c-basic-offset)
  (setq c-basic-offset 2)
  ;; 100-column limit for java.
  (set-fill-column 100))

(add-hook 'java-mode-hook #'ar/java-mode-hook-function)

(defun ar/export-blog-to-html ()
  "Export blog to HTML."
  (interactive)
  (with-current-buffer (find-file-noselect (expand-file-name
                                            "~/stuff/active/blog/index.org"))
    (org-html-export-to-html)
    (browse-url (format "file:%s" (expand-file-name
                                   "~/stuff/active/blog/index.html")))))

(defun ar/org-mode-hook-function ()
  "Called when entering org mode."
  (add-hook 'after-change-functions
            #'ar/after-prog-mode-text-change
            t t)
  (let ((m org-mode-map))
    (define-key m [f6] #'ar/export-blog-to-html))
  (set (make-local-variable 'show-trailing-whitespace) t)
  (set (make-local-variable 'whitespace-line-column) 1000)
  (ar/org-src-color-blocks-dark)
  (flyspell-mode-on)
  (whitespace-mode)
  (rainbow-delimiters-mode)
  (semantic-mode 1)
  (org-bullets-mode 1)
  (yas-minor-mode))

;; https://github.com/howardabrams/dot-files/blob/HEAD/emacs-client.org
(defun ar/org-src-color-blocks-light ()
  "Color the block headers and footers to make them stand out more for lighter themes."
  (interactive)
  (custom-set-faces
   '(org-block-begin-line
     ((t (:underline "#A7A6AA" :foreground "#008ED1" :background "#EAEAFF"))))
   '(org-block-background
     ((t (:background "#FFFFEA"))))
   '(org-block-end-line
     ((t (:overline "#A7A6AA" :foreground "#008ED1" :background "#EAEAFF"))))
   '(mode-line-buffer-id ((t (:foreground "#005000" :bold t))))
   '(which-func ((t (:foreground "#008000"))))))

;; Based on https://github.com/howardabrams/dot-files/blob/HEAD/emacs-client.org
(defun ar/org-src-color-blocks-dark ()
  "Color the block headers and footers to make them stand out more for dark themes."
  (interactive)
  (custom-set-faces
   '(org-block-begin-line
     ((t (:foreground "#008ED1" :background nil))))
   '(org-block ((t (:background "SlateBlue4" :foreground nil :box nil))))
   '(org-block-background
     ((t (:background "#111111"))))
   '(org-block-end-line
     ((t (:foreground "#008ED1" :background nil))))
   '(mode-line-buffer-id ((t (:foreground "black" :bold t))))
   '(which-func ((t (:foreground "green"))))))

;; https://github.com/howardabrams/dot-files/blob/HEAD/emacs-client.org
(deftheme ar/org-theme "Sub-theme to beautify org mode")


                            `(org-level-2 ((t (,@headline ,@sans-font :height 1.5   :box ,padding))))
                            `(org-level-1 ((t (,@headline ,@sans-font :height 1.75  :box ,padding))))
                            `(org-document-title ((t (,@headline ,@sans-font :height 1.5 :underline nil)))))))

;; TODO: Revisit this.
(defun ar/setup-graphical-display ()
  "Setup graphical display."
  (when (window-system)
    (ar/setup-graphical-fringe)
    (ar/setup-graphical-fonts)
    (ar/setup-graphical-mode-line)))

(ar/setup-graphical-display)

;; Handy pop-up messages with git info.
(use-package git-messenger :ensure t)

;; Display column numbers.
(setq-default column-number-mode t)

;; Highlights current line.
(use-package hl-line :ensure t)

;; Set color as current line's background face.
;; (set-face-background 'hl-line "black")
;; Keep syntax highlighting in the current line.
;; (set-face-foreground 'highlight nil)

(use-package whitespace :ensure t)
(setq whitespace-style '(face lines-tail))

;;  From http://doc.rix.si/org/fsem.html
(defun ar/gnulinuxp ()
  "Return t if the system is a GNU/Linux machine, otherwise nil."
  (string-equal system-type "gnu/linux"))

(defun ar/osxp ()
  "Return t if the system is a Mac OS X machine, otherwise nil."
  (string-equal system-type "darwin"))

(defun ar/cygwinp ()
  "Return t if Emacs is running inside of Cygwin on Windows, otherwise nil."
  (string-equal system-type "cygwin"))

(defun ar/windowsp ()
  "Return t if the system is a native Emacs for Windows, otherwise nil."
  (string-equal system-type "windows"))

(defun ar/new-browser-tab-shell-command ()
  "Return new browser tab shell command."
  (cond
   ((ar/osxp)
    "open http://google.com")
   ((ar/gnulinuxp)
    "google-chrome http://google.com")
   (nil)))

(defun ar/new-browser-tab ()
  "Open a new browser tab in the default browser."
  (interactive)
  (let ((command (ar/new-browser-tab-shell-command)))
    (message command)
    (if command
        (shell-command command)
      (message "Unrecognized platform."))))
(global-set-key (kbd "C-x t")
                #'ar/new-browser-tab)

(defun ar/init-for-osx ()
  "Perform initializations for Mac OS X."
  (when (ar/osxp)
    ;; Sets the command (Apple) key as Meta.
    (setq mac-command-modifier 'meta)
    ;; Sets the option (Apple) key also as Meta.
    (setq mac-option-modifier 'meta)
    (setq exec-path (append exec-path '("~/homebrew/bin"
                                        "~/homebrew/Cellar/llvm/HEAD/bin")))))
(ar/init-for-osx)

(defun ar/init-for-linux ()
  "Perform initializations for Linux."
  (when (ar/gnulinuxp)
    (setq exec-path (append exec-path '("~/local/bin")))))
(ar/init-for-linux)

;; Disable backup.
;; From: http://anirudhsasikumar.net/blog/2005.01.21.html
(setq backup-inhibited t)

;; Disable auto save.
(setq auto-save-default nil)

;; Disable auto save.
;; From: http://anirudhsasikumar.net/blog/2005.01.21.html
(setq auto-save-default nil)

;; Case-sensitive fold search search (ie. M-/ to autocomplete).
(setq dabbrev-case-fold-search nil)

;; Move buffer file.
;; From: https://sites.google.com/site/steveyegge2/my-dot-emacs-file
(defun ar/move-buffer-file (dir)
  "Move both current buffer and file it's visiting to DIR." (interactive "DNew directory: ")
  (let* ((name (buffer-name))
         (filename (buffer-file-name))
         (dir (if (string-match dir "\\(?:/\\|\\\\)$")
                  (substring dir 0 -1)
                dir))
         (newname (concat dir "/" name)))

    (if (not filename)
        (message "Buffer '%s' is not visiting a file!" name)
      (progn (copy-file filename newname 1)
             (delete-file filename)
             (set-visited-file-name newname)
             (set-buffer-modified-p nil) t))))

;;  http://scottmcpeak.com/elisp/scott.emacs.el
;;  ------------------- yes-or-no-p ---------------------
;;  There are a number of situations where Emacs wants to ask me a question,
;;  but the answer is always the same (or, it's easy to get the effect of
;;  the other answer afterwards).  The main example is the question:
;;
;;    File foo.txt has changed on disk.  Reread from disk?
;;
;;  This question is annoying because it gets asked while I'm moving around
;;  in a debugger stack trace, and often don't care about the file I happen
;;  to be at (because I want to move past that frame anyway).  Moreover,
;;  my F12 binding lets me re-read files with a single keystroke, so if I
;;  actually *do* want to re-read it's easy to do.

;;  First, I need the original definition of yes-or-no-p so I can call it
;;  after I've replaced its definition.  In case .emacs gets re-read
;;  after startup, avoid losing the original definition.
(if (fboundp 'orig-yes-or-no-p)
    nil        ; it's already bound, don't re-bind
  (fset 'orig-yes-or-no-p (symbol-function 'yes-or-no-p)))

;;  Now, define my version in terms of `orig-yes-or-no-p'.
(defun yes-or-no-p (prompt)
  "Ask user a yes-or-no question.  Return t if answer is yes, nil if no.
This is a wrapper around `orig-yes-or-no'.
Argument PROMPT to check for additional prompt."
  (if (string-match
       ;;  This message is created in lisp/files.el, and there are four
       ;;  variations.  I'm intentionally matching two of them.
       "File .* changed on disk.  Reread from disk"
       prompt)

      ;;  it's that question; the answer is no, but I *do* want to know
      ;;  that it has changed
      (progn (message "Note: File has changed on disk.") nil)

    ;;  it's a different question; for now, just ask me; I'll probably
    ;;  add more patterns to the above as I think of other questions that
    ;;  I don't want asked
    (orig-yes-or-no-p prompt)))

(use-package git-link :ensure t)

(use-package magit :ensure t)
;; Use vc-ediff as default.
(eval-after-load "vc-hooks"
  '(define-key vc-prefix-map "=" #'vc-ediff))
(global-set-key (kbd "C-x g")
                #'magit-status)
(setq magit-status-buffer-switch-function #'switch-to-buffer)

(defun ar/sort-lines-ignore-case ()
  "Sort region (case-insensitive)."
  (interactive)
  (let ((sort-fold-case t))
    (call-interactively #'sort-lines)))

(setq css-indent-offset 2)

(defun ar/open-in-external-app-lambda ()
  "Return a function to open FPATH externally."
  (cond
   ((ar/windowsp)
    (lambda (fPath)
      (w32-shell-execute "open" (replace-regexp-in-string "/" "\\" fPath t t))))
   ((ar/osxp)
    (lambda (fPath)
      (shell-command (format "open \"%s\"" fPath))))
   ((ar/gnulinuxp)
    (lambda (fPath)
      (let ((process-connection-type nil))
        (start-process "" nil "xdg-open" fPath))))))

;; Based on http://ergoemacs.org/emacs/emacs_dired_open_file_in_ext_apps.html
(defun ar/open-in-external-app ()
  "Open the current file or dired marked files in external app.
The app is chosen from your OS's preference.

Version 2015-01-26
URL `http://ergoemacs.org/emacs/emacs_dired_open_file_in_ext_apps.html'"
  (interactive)
  (let* ((ξfile-list
          (if (string-equal major-mode "dired-mode")
              (dired-get-marked-files)
            (list (buffer-file-name))))
         (ξdo-it-p (if (<= (length ξfile-list) 5)
                       t
                     (y-or-n-p "Open more than 5 files? "))))
    (when ξdo-it-p
      (mapc (ar/open-in-external-app-lambda) ξfile-list))))
(global-set-key (kbd "C-M-o")
                #'ar/open-in-external-app)

(setq ring-bell-function 'ignore)

(use-package markdown-mode+ :ensure t)
(autoload 'markdown-mode "markdown-mode"
  "Major mode for editing Markdown files" t)
(add-to-list 'auto-mode-alist '("\\.text\\'" . markdown-mode))
(add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode))
(add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode))

(setq display-time-world-list '(("Europe/Paris" "Paris")
                                ("Europe/London" "London")
                                ("America/Los_Angeles" "Los Angeles")))

;; From http://wenshanren.org/?p=298#more-298
(defun ar/edit-current-file-as-root ()
  "Edit the file that is associated with the current buffer as root."
  (interactive)
  (if (buffer-file-name)
      (let ((file (concat "/sudo:root@localhost:" (buffer-file-name))))
        (find-file file))
    (message "Current buffer does not have an associated file.")))

(global-set-key "\M-/" 'hippie-expand)
(setq hippie-expand-try-functions-list '(try-expand-dabbrev
                                         try-expand-dabbrev-visible
                                         try-expand-dabbrev-all-buffers
                                         try-expand-dabbrev-from-kill
                                         try-complete-file-name-partially
                                         try-complete-file-name
                                         try-expand-all-abbrevs
                                         try-expand-list
                                         try-expand-line))
;; Thank you Sacha Chua.
;; From http://pages.sachachua.com/.emacs.d/Sacha.html#sec-1-4-8
(fset 'yes-or-no-p 'y-or-n-p)

;; Ensure files end with newline.
(setq require-final-newline t)

;; From http://www.wisdomandwonder.com/wordpress/wp-content/uploads/2014/03/C3F.html
(setq savehist-file "~/.emacs.d/savehist")
(savehist-mode +1)
(setq savehist-save-minibuffer-history +1)
(setq savehist-additional-variables
      '(kill-ring
        search-ring
        regexp-search-ring))

;; Don't let the cursor go into minibuffer prompt.
;; From http://ergoemacs.org/emacs/emacs_stop_cursor_enter_prompt.html
(setq minibuffer-prompt-properties '(read-only t point-entered minibuffer-avoid-prompt face minibuffer-prompt))

;; From http://pages.sachachua.com/.emacs.d/Sacha.html#sec-1-5-12
(defun ar/smarter-move-beginning-of-line (arg)
  "Move point back to indentation of beginning of line.

Move point to the first non-whitespace character on this line.
If point is already there, move to the beginning of the line.
Effectively toggle between the first non-whitespace character and
the beginning of the line.

If ARG is not nil or 1, move forward ARG - 1 lines first.  If
point reaches the beginning or end of the buffer, stop there."
  (interactive "^p")
  (setq arg (or arg 1))

  ;; Move lines first
  (when (/= arg 1)
    (let ((line-move-visual nil))
      (forward-line (1- arg))))

  (let ((orig-point (point)))
    (back-to-indentation)
    (when (= orig-point (point))
      (move-beginning-of-line 1))))

;; remap C-a to `smarter-move-beginning-of-line'
(global-set-key [remap move-beginning-of-line]
                'ar/smarter-move-beginning-of-line)

;; From http://www.reddit.com/r/emacs/comments/25v0eo/you_emacs_tips_and_tricks/chldury
(defun ar/vsplit-last-buffer ()
  "Vertically splitting the screen and open the previous buffer instead of identical buffers."
  (interactive)
  (split-window-vertically)
  (other-window 1 nil)
  (switch-to-next-buffer))

(defun ar/hsplit-last-buffer ()
  "Horizontally splitting the screen and open the previous buffer instead of identical buffers."
  (interactive)
  (split-window-horizontally)
  (other-window 1 nil)
  (switch-to-next-buffer))

(global-set-key (kbd "C-x 2")
                #'ar/vsplit-last-buffer)
(global-set-key (kbd "C-x 3")
                #'ar/hsplit-last-buffer)

;; Thank you Bozhidar.
;; From https://github.com/bbatsov/prelude/blob/a52cdc83eeec567b13a8a5719a174dfe294ee739/core/prelude-core.el#L340
(defun ar/swap-windows ()
  "If you have 2 windows, it swaps them."
  (interactive)
  (if (/= (count-windows) 2)
      (message "You need exactly 2 windows to do this.")
    (let* ((w1 (car (window-list)))
           (w2 (cadr (window-list)))
           (b1 (window-buffer w1))
           (b2 (window-buffer w2))
           (s1 (window-start w1))
           (s2 (window-start w2)))
      (set-window-buffer w1 b2)
      (set-window-buffer w2 b1)
      (set-window-start w1 s2)
      (set-window-start w2 s1)))
  (other-window 1))
(bind-key "C-\\" #'ar/swap-windows)

;; From https://github.com/bbatsov/prelude/blob/a52cdc83eeec567b13a8a5719a174dfe294ee739/core/prelude-core.el#L111
(defun ar/smart-open-line-above ()
  "Insert an empty line above the current line.
Position the cursor at it's beginning, according to the current mode."
  (interactive)
  (move-beginning-of-line nil)
  (newline-and-indent)
  (forward-line -1)
  (indent-according-to-mode))

;; Do not auto indent current line when pressing <RET>.
(add-hook 'sgml-mode-hook
          (lambda() (local-set-key (kbd "<RET>")
                                   #'electric-indent-just-newline)))

(defun ar/smart-open-line (arg)
  "Insert an empty line after the current line.
Position the cursor at its beginning, according to the current mode.
With a prefix ARG open line above the current line."
  (interactive "P")
  (if arg
      (ar/smart-open-line-above)
    (progn
      (move-end-of-line nil)
      (newline-and-indent))))

(global-set-key (kbd "C-o")
                #'ar/smart-open-line)

(use-package ace-jump-mode :ensure t)

(use-package ace-jump-zap :ensure t
  :bind
  (("M-z" . ace-jump-zap-up-to-char-dwim)
   ("C-M-z" . ace-jump-zap-to-char-dwim)))

(use-package ace-window :ensure t
  :init (setq aw-keys '(?a ?s ?d ?f ?g ?h ?j ?k ?l))
  :bind (("C-x o" . ace-window)))
;; Use larger characters for ace window shortcuts.
;; From http://oremacs.com/2015/02/27/ace-window-leading-char
(custom-set-faces
 '(aw-leading-char-face
   ((t (:inherit ace-jump-face-foreground :height 3.0)))))

;; Interactively resize current window.
(use-package windsize :ensure t)
(windsize-default-keybindings)

(use-package key-chord :ensure t)
(key-chord-define-global "jj" #'ace-jump-char-mode)
(key-chord-define-global "jk" #'ace-jump-char-mode)
(key-chord-define-global "jl" #'ace-jump-line-mode)
(key-chord-define-global "xx" #'execute-extended-command)
(key-chord-define-global "kk" #'kill-whole-line)

;; From http://emacsredux.com/blog/2013/04/28/switch-to-previous-buffer
(defun ar/switch-to-previous-buffer ()
  "Switch to previously open buffer.
Repeated invocations toggle between the two most recently open buffers."
  (interactive)
  (switch-to-buffer (other-buffer (current-buffer) 1)))
(key-chord-define-global "JJ" #'ar/switch-to-previous-buffer)
(key-chord-define-global "BB" #'other-window)
(key-chord-mode +1)

;; Needs clang-format installed.
;; See http://blog.hardcodes.de/articles/63/building-clang-format-and-friends-on-osx-mountain-lion
;; See http://clang.llvm.org/docs/ClangFormat.html
(use-package clang-format :ensure t)

(use-package company :ensure t)
(use-package company-quickhelp :ensure t)
(use-package company-c-headers :ensure t)
(setq company-backends (delete 'company-semantic company-backends))
(setq company-minimum-prefix-length 2)
(setq company-idle-delay 0.5)
(setq company-show-numbers t)
(global-company-mode)
(add-to-list 'company-backends 'company-c-headers)
(global-set-key (kbd "<backtab>")
                #'company-complete)

;; (add-to-list 'load-path
;;              (concat (getenv "HOME") "/.emacs.d/downloads/rtags/src"))
;; (require 'rtags)
;; (require 'company-rtags)
;; (setq rtags-path
;;       (concat (getenv "HOME") "/.emacs.d/downloads/rtags/bin"))
;; (setq company-backends (delete 'company-clang company-backends))
;; (setq company-rtags-begin-after-member-access t)
;; (setq rtags-completions-enabled t)
;; (add-to-list 'company-backends 'company-rtags)
;; (rtags-diagnostics)

(use-package helm-c-yasnippet :ensure t)

(use-package helm-make :ensure t)

(use-package drag-stuff :ensure t)
(global-set-key (kbd "M-<up>")
                #'drag-stuff-up)
(global-set-key (kbd "M-<down>")
                #'drag-stuff-down)

;; Avoid creating lock files (ie. .#some-file.el)
(setq create-lockfiles nil)

;; displays hex strings representing colors
(use-package rainbow-mode :ensure t)

;; If eclim is your cup of tea.
;; (require 'eclim)
;; (global-eclim-mode)
;; (custom-set-variables
;;  '(eclim-eclipse-dirs '("~/tools/eclipse"))
;;  '(eclim-executable "~/tools/eclipse/eclim"))
;; (require 'eclimd)
;; (require 'company-emacs-eclim)
;; (company-emacs-eclim-setup)
;; (global-company-mode t)

;; Relies on manual installation (ie. make emaXcode).
;; Enable auto-complete to use emaXcode while generating snippets.
;;(use-package auto-complete
; :ensure t)
;;(load "~/.emacs.d/downloads/emaXcode/emaXcode.el")
;;(require 'emaXcode)

;; From http://sakito.jp/emacs/emacsobjectivec.html#xcode
(defun ar/xc:build ()
  "Tell Xcode to build."
  (interactive)
  (do-applescript
   (format
    (concat
     "tell application \"Xcode\" to activate \r"
     "tell application \"System Events\" \r"
     "     tell process \"Xcode\" \r"
     "          key code 11 using {command down} \r"
     "    end tell \r"
     "end tell \r"
     ))))

(defun ar/xc:run ()
  "Tell Xcode to run."
  (interactive)
  (do-applescript
   (format
    (concat
     "tell application \"Xcode\" to activate \r"
     "tell application \"System Events\" \r"
     "     tell process \"Xcode\" \r"
     "          key code 15 using {command down} \r"
     "    end tell \r"
     "end tell \r"
     ))))

;;  Note: For ycmd.
;;  * No need for global_ycm_extra_conf.py
;;    (Use .ycm_extra_conf.py)
;;  * Needs .ycm_extra_conf.py (pointing to compile_commands.json location)
;;    (See emacs/ycmd/.ycm_extra_conf.py)
;;  * Needs compile_commands.json
;;    (See http://blog.patspam.com/2014/vim-objc-code-completion)
;;  * Add objc-mode to company-ycmd--extended-features-modes in company-ycmd.el
;; (use-package ycmd
;; :ensure t)
;;
;; (use-package company-ycmd
;; :ensure t)
;;
;; (setq ycmd-server-command (list "python"
;;                                 (expand-file-name "~/.emacs.d/downloads/ycmd/ycmd")))
;; (setq ycmd--log-enabled t)

(use-package objc-font-lock
  :ensure t
  :init (setq objc-font-lock-background-face nil))

(use-package dummy-h-mode :ensure t)
(add-to-list 'auto-mode-alist '("\\.h\\'" . dummy-h-mode))

(defun ar/kill-other-buffers ()
  "Kill all other buffers."
  (interactive)
  (mapc 'kill-buffer
        (delq (current-buffer)
              ;; Disables "required at runtime" warning for cl package.
              (with-no-warnings
                (remove-if-not 'buffer-file-name (buffer-list))))))

;; From: http://emacsredux.com/blog/2013/05/04/rename-file-and-buffer
(defun ar/rename-current-file-and-buffer ()
  "Rename the current buffer and file it is visiting."
  (interactive)
  (let ((filename (buffer-file-name)))
    (if (not (and filename (file-exists-p filename)))
        (message "Buffer is not visiting a file!")
      (let ((new-name (read-file-name "New name: " filename)))
        (cond
         ((vc-backend filename) (vc-rename-file filename new-name))
         (t
          (rename-file filename new-name t)
          (set-visited-file-name new-name t t)))))))

;;  From http://emacsredux.com/blog/2013/04/03/delete-file-and-buffer/
(defun ar/delete-current-file-and-buffer ()
  "Kill the current buffer and deletes the file it is visiting."
  (interactive)
  (let ((filename (buffer-file-name)))
    (when filename
      (if (vc-backend filename)
          (vc-delete-file filename)
        (progn
          (delete-file filename)
          (message "Deleted file %s" filename)
          (kill-buffer))))))

(use-package go-mode :ensure t)
;; Requires gocode daemon. Install with:
;; go get -u github.com/nsf/gocode
;; go get -u code.google.com/p/rog-go/exp/cmd/godef
;; go get -u code.google.com/p/go.tools/cmd/goimports
;; Useful info at:
;; http://tleyden.github.io/blog/2014/05/22/configure-emacs-as-a-go-editor-from-scratch
;; http://tleyden.github.io/blog/2014/05/27/configure-emacs-as-a-go-editor-from-scratch-part-2
;; http://dominik.honnef.co/posts/2013/03/writing_go_in_emacs
(use-package company-go :ensure t)
(add-hook 'go-mode-hook (lambda ()
                          (helm-dash-activate-docset "Go")
                          (set (make-local-variable 'company-backends) '(company-go))
                          (company-mode)
                          (setq tab-width 2 indent-tabs-mode 1)
                          (add-hook 'before-save-hook #'gofmt-before-save)))

(unless (server-running-p)
  (server-start))

;; Customize vertical window divider:
;; Set symbol for the border.
(set-display-table-slot standard-display-table
                        'vertical-border
                        (make-glyph-code ?|))

(defun ar/split-camel-region ()
  "Splits camelCaseWord to camel case word."
  (interactive)
  (let ((case-fold-search nil))
    (while (re-search-forward "[A-Z]" (region-end) t)
      (replace-match (format " %s"
                             (downcase (match-string 0)))
                     t nil))))
(global-set-key (kbd "C-c l")
                #'ar/split-camel-region)

;; Simplify lisp navigation/editing (ie. slurp/barf).
(use-package lispy :ensure t)

;; M-. elisp navigation.
(use-package elisp-slime-nav :ensure t)

(defun ar/add-functions-to-mode-hooks (hook-functions hooks)
  "Add HOOK-FUNCTIONS to mode HOOKS."
  (dolist (hook hooks)
    (dolist (hook-function hook-functions)
      (add-hook hook hook-function))))

(defun ar/emacs-lisp-mode-hook-function ()
  "Called when entering `emacs-lisp-mode'."
  (helm-dash-activate-docset "Emacs Lisp")
  (lispy-mode 1)
  (eldoc-mode)
  (turn-on-elisp-slime-nav-mode))
(ar/add-functions-to-mode-hooks '(ar/emacs-lisp-mode-hook-function)
                                '(emacs-lisp-mode-hook
                                  ielm-mode-hook))

(defun ar/save-point-to-register ()
  "Save point to register."
  (interactive)
  (point-to-register 9999))

(defun ar/jump-to-saved-point-register ()
  "Jumps cursor to register 9999's value."
  (interactive)
  (jump-to-register 9999))
(global-set-key (kbd "C-c `")
                #'ar/jump-to-saved-point-register)

(defun ar/after-prog-mode-text-change (beg end len)
  "Execute for all text modifications in `prog-mode'.
Argument BEG beginning.
Argument END end.
Argument LEN Length."
  ;; Saving point enables jumping back to last change at any time.
  (ar/save-point-to-register))

(defun ar/select-current-block ()
  "Select the current block of text between blank lines.
URL `http://ergoemacs.org/emacs/modernization_mark-word.html'
Version 2015-02-07."
  (interactive)
  (let (p1 p2)
    (if (re-search-backward "\n[ \t]*\n" nil "move")
        (progn (re-search-forward "\n[ \t]*\n")
               (setq p1 (point)))
      (setq p1 (point)))
    (if (re-search-forward "\n[ \t]*\n" nil "move")
        (progn (re-search-backward "\n[ \t]*\n")
               (setq p2 (point)))
      (setq p2 (point)))
    (set-mark p1)))

(defun ar/sort-current-block ()
  "Select and sort current block."
  (interactive)
  (ar/select-current-block)
  (ar/sort-lines-ignore-case))

(defun ar/sort-objc-headers ()
  "Alphabetically sort Objective-C headers."
  (interactive)
  (save-excursion
    (goto-char (point-min))
    (while (re-search-forward "^#\\(include\\|import\\).*\n\n" nil t)
      (goto-char (match-beginning 0))
      (ar/sort-current-block))))

(defun ar/clang-format-buffer ()
  "Clang format current buffer."
  (interactive)
  (clang-format (point-min)
                (point-max)))

(defun ar/objc-mode-hook-function ()
  "Called when entering `objc-mode'."
  (add-hook 'before-save-hook
            #'ar/clang-format-buffer
            nil
            'make-it-local)
  (objc-font-lock-mode)
  (helm-dash-activate-docset "iOS")
  ;; Highlight lines longer than 100 columns.
  (set (make-local-variable 'whitespace-line-column) 100)
  (set (make-local-variable 'company-backends)
       ;; List with multiple back-ends for mutual inclusion.
       '(( ;;company-ycmd
          company-yasnippet
          company-gtags
          company-dabbrev-code
          company-files)))
  ;;(ycmd-mode)

  ;; List targets with xcodebuild -list
  ;; List SDKS with xcodebuild -sdk -version, for example:
  ;; iPhoneSimulator7.1.sdk - Simulator - iOS 7.1 (iphonesimulator7.1)
  ;; SDKVersion: 7.1
  ;; Path: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator7.1.sdk
  ;; PlatformPath: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform
  ;; ProductBuildVersion: 11D167
  ;; ProductCopyright: 1983-2014 Apple Inc.
  ;; ProductName: iPhone OS
  ;; ProductVersion: 7.1
  (set (make-local-variable 'compile-command)
       "xcodebuild -sdk iphonesimulator7.1 -target MyTarget")
  (local-set-key (kbd "<f7>")
                 #'ar/xc:build)
  (local-set-key (kbd "<f8>")
                 #'ar/xc:run)
  (key-chord-define (current-local-map) ";;" "\C-e;"))
(add-hook 'objc-mode-hook #'ar/objc-mode-hook-function)

(defun ar/java-mode-hook-function ()
  "Called when entering `java-mode'."
  ;; 2-char indent for java.
  (defvar c-basic-offset)
  (setq c-basic-offset 2)
  ;; 100-column limit for java.
  (set-fill-column 100))

(add-hook 'java-mode-hook #'ar/java-mode-hook-function)

(defun ar/export-blog-to-html ()
  "Export blog to HTML."
  (interactive)
  (with-current-buffer (find-file-noselect (expand-file-name
                                            "~/stuff/active/blog/index.org"))
    (org-html-export-to-html)
    (browse-url (format "file:%s" (expand-file-name
                                   "~/stuff/active/blog/index.html")))))

(defun ar/org-mode-hook-function ()
  "Called when entering org mode."
  (add-hook 'after-change-functions
            #'ar/after-prog-mode-text-change
            t t)
  (let ((m org-mode-map))
    (define-key m [f6] #'ar/export-blog-to-html))
  (set (make-local-variable 'show-trailing-whitespace) t)
  (set (make-local-variable 'whitespace-line-column) 1000)
  (ar/org-src-color-blocks-dark)
  (flyspell-mode-on)
  (whitespace-mode)
  (rainbow-delimiters-mode)
  (semantic-mode 1)
  (org-bullets-mode 1)
  (yas-minor-mode))

;; https://github.com/howardabrams/dot-files/blob/HEAD/emacs-client.org
(defun ar/org-src-color-blocks-light ()
  "Color the block headers and footers to make them stand out more for lighter themes."
  (interactive)
  (custom-set-faces
   '(org-block-begin-line
     ((t (:underline "#A7A6AA" :foreground "#008ED1" :background "#EAEAFF"))))
   '(org-block-background
     ((t (:background "#FFFFEA"))))
   '(org-block-end-line
     ((t (:overline "#A7A6AA" :foreground "#008ED1" :background "#EAEAFF"))))
   '(mode-line-buffer-id ((t (:foreground "#005000" :bold t))))
   '(which-func ((t (:foreground "#008000"))))))

;; Based on https://github.com/howardabrams/dot-files/blob/HEAD/emacs-client.org
(defun ar/org-src-color-blocks-dark ()
  "Color the block headers and footers to make them stand out more for dark themes."
  (interactive)
  (custom-set-faces
   '(org-block-begin-line
     ((t (:foreground "#008ED1" :background nil))))
   '(org-block ((t (:background "SlateBlue4" :foreground nil :box nil))))
   '(org-block-background
     ((t (:background "#111111"))))
   '(org-block-end-line
     ((t (:foreground "#008ED1" :background nil))))
   '(mode-line-buffer-id ((t (:foreground "black" :bold t))))
   '(which-func ((t (:foreground "green"))))))

;; https://github.com/howardabrams/dot-files/blob/HEAD/emacs-client.org
(defun ar/change-theme (theme org-block-style)
