;;
;; Support code for the Pan-STARRS C coding standards
;;
;; The basic tool is a "panstarrs-c" mode derived from c-mode. If you want to
;; always use this mode, add the commands
;;   (load-file "/path/to/panstarrs.el")
;;   (add-to-list 'auto-mode-alist (cons "\\.[ch]$" 'panstarrs-c-mode))
;; to your .emacs file
;;
;; You might want to copy some of these add-hook lines to your .emacs file too:
;;  (add-hook 'panstarrs-c-mode-hook 'panstarrs-c99-comments)
;;  (add-hook 'panstarrs-c-mode-hook 'panstarrs-set-width)
;;  (add-hook 'panstarrs-c-mode-hook
;;	    '(lambda ()
;;	       (set (make-variable-buffer-local 'comment-indent-function)
;;		    'panstarrs-comment-indent)))
;; These respectively:
;;   use C99-style comments (i.e. // to end of line)
;;   have your emacs window set to 110 characters wide
;;   somewhat improve (or spoil?) the handling of re-indenting comments

(define-derived-mode panstarrs-c-mode
  c-mode "Pan-STARRS C"
  "Major mode for editing Pan-STARRS C source.
          \\{panstarrs-c-mode-map}
"
  
  (let ( (our-mode-name mode-name) )
    (c-mode)			        ; get correct font-lock behaviour
    (setq mode-name our-mode-name))	; keep our desired name

  (setq c-default-style '((other . "k&r")))
  (setq c-basic-offset 4)

  (setq comment-column 40)
  (setq fill-column 110)
  
  (add-to-list 'c-offsets-alist (cons 'statement-case-intro 2))
  (add-to-list 'c-offsets-alist (cons 'statement-case-open 2))
  (add-to-list 'c-offsets-alist (cons 'case-label 2)))
;;
;; Various useful commands for writing panstarrs code
;;
(defun panstarrs-c99-comments ()
  "Use C99-style // comments"
  (setq comment-start "// ")
  (setq comment-end ""))
;;
(defun panstarrs-set-width ()
  "Set frame width to fill-column + 1 ( + 1 to allow for wrap column)"
  (set-frame-width default-minibuffer-frame (1+ fill-column)))
;;
;;
(defun panstarrs-comment-indent (&optional delete)
  "Make ESC; indent new comments to comment-column even if previous line
has a comment indented further to the right"

  (interactive "p")
  (let ( (indent (c-comment-indent)) )
    (if (> indent comment-column)
	(save-excursion
	  (beginning-of-line)
	  (if (not (looking-at (concat "^[ \t]*" comment-start)))
	      (setq indent comment-column))))
    indent))

(defun panstarrs-c-default (&optional delete)
  "Use Pan-STARRS C-mode as default"

  (interactive "p")
  (add-to-list 'auto-mode-alist (cons "\\.[ch]$" 'panstarrs-c-mode))
  (add-hook 'panstarrs-c-mode-hook 'panstarrs-set-comments)
  (add-hook 'panstarrs-c-mode-hook
	    '(lambda ()
	       (set (make-variable-buffer-local 'comment-indent-function)
		    'panstarrs-comment-indent))))

