; better compilation window
;   make the compilation window always appear at the bottom
(defun organize-compilation-window ()
  (when (not (get-buffer-window "*compilation*"))
    (save-selected-window
      (save-excursion
        (let* ((w (split-window-vertically))
               (h (window-height w)))
          (select-window w)
          (switch-to-buffer "*compilation*"))))))
;   automatically close the compilation frame if no errors occurred
(setq compilation-finish-function
      (lambda (buf str)
        (if (not (or (string-match "grep" (buffer-name buf))
                     (string-match "ag text:" (buffer-name buf))
                     ))
            (if (string-match "exited abnormally" str)

                ;;there were errors
                (message "compilation errors, press C-x ` to visit")
              ;;no errors, make the compilation window go away in 0.5 seconds
              (run-at-time 3 nil 'delete-windows-on buf)
              (message "NO COMPILATION ERRORS!")))))
(add-hook 'compilation-mode-hook 'organize-compilation-window)

(defun my/compilation-last-error () (interactive)
  (while (not (next-error)))
)

(global-set-key (kbd "C-x ~") 'my/compilation-last-error)

(defvar my/compilation-history-file "~/.emacs-compilation-history"
  "Where to save compilation history between sessions")

(defvar my/compilation-history-save-size 1000
  "How many previous compilation history items to save")

(defun my/save-compilation-history ()
  "Saves compilation history to my/compilation-history-file"
  (interactive)
  (with-temp-file my/compilation-history-file
    (emacs-lisp-mode)
    (insert ";; Autogenerated")
    (newline)
    (newline)
    (mapc #'(lambda (p)
	      (insert (format "(add-to-list 'compile-history \"%s\")" p))
	      (newline))
	  (-take my/compilation-history-save-size compile-history))
    (newline)
  ))

(require 'compile)

(add-to-list 'kill-emacs-hook 'my/save-compilation-history)

(if (file-exists-p my/compilation-history-file)
    (load-file my/compilation-history-file))

