;;; turtle-mode.el --- major mode for editing turtle files

;; Author: Mark Triggs <mst@dishevelled.net>

;; This file is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.

;; This file is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING.  If not, write to
;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.

;;; Commentary:

;; I have an assignment that involves writing a compiler for a turtle-like
;; language. Damned if I'm indenting code manually.

;;; Code:

(define-generic-mode 'turtle
  '("//")
  '("for" "while" "var" "fun" "return" "up" "down" "moveto" "read" "else" "if"
    "turtle")
  '() '() '())

(defun turtle-base ()
  (interactive)
  (generic-mode "turtle"))

(defun turtle-indent ()
  (interactive)
  (let ((p (point-marker)))
    (beginning-of-line)
    (delete-horizontal-space)
    (let ((indent (save-excursion
                    (let ((count 0))
                      (while (ignore-errors (progn (backward-up-list) (point)))
                        (incf count))
                      count))))
      (if (looking-at "}")
          (indent-to-column (* 4 (1- indent)))
        (indent-to-column (* 4 indent))))
    (goto-char (marker-position p))
    (when (= (current-column) 0)
      (back-to-indentation))))

(defun turtle-indent-block ()
  (interactive)
  (indent-region (point)
                 (save-excursion (forward-sexp) (point))))

(defvar turtle-mode-map (make-sparse-keymap))

(define-derived-mode turtle-mode turtle-base
  "Turtle"
  (setq indent-tabs-mode nil)
  (set (make-local-variable 'indent-line-function) 'turtle-indent)

  (define-key turtle-mode-map (kbd "C-M-q")
    'turtle-indent-block)

  (use-local-map turtle-mode-map))

(provide 'turtle-mode)
;;; turtle-mode.el ends here
