;;; pugs -- simple major mode for pgs files
;;; Commentary:
;;; simple major mode for pugs
;;; Code:

(define-derived-mode pugs-output-mode compilation-mode "pugs-output"
  "Define a special mode for pugs process output."
)

(defun pugs-run-file ()
  "Execute the current pugs script.
Ask to save the buffer if needed"
  (interactive)
  (when (buffer-modified-p)
    (save-buffer))
  (let ((output-buffer "*pugs-output*")
	(pugs-binary "~/src/pugs/build/pugs")
	(pugs-file (buffer-file-name (current-buffer)))
	(pugs-buffer (current-buffer)))
    (when (get-buffer output-buffer)
      (kill-buffer output-buffer))
    (get-buffer-create output-buffer)
    (follow-mode)
    (display-buffer output-buffer)
    (set-buffer output-buffer)
    (pugs-output-mode)
    (setq-local inhibit-read-only t)
    (insert (format "started: %s\n" (current-time-string)))
    (insert (format "binary : %s\n" pugs-binary))
    (insert (format "script : %s\n\n" pugs-file))
    ;;; run the process
    (process-file pugs-binary nil output-buffer nil pugs-file "--no-color")
;    (start-process pugs-binary nil output-buffer t pugs-file "--no-color")
    ;;;
    (insert (format "\nfinished: %s\n" (current-time-string)))
    (insert (format "binary : %s\n" pugs-binary))
    (insert (format "script : %s\n" pugs-file))
    ))

(define-derived-mode pugs-mode prog-mode "pugs"
  "pugs mode is a major mode for editing pugs files"
  ;; define pugs keywords
  (defvar pugs-keywords
    '("import" "let" "Z" "N" "B" "R" "string" "and" "or" "xor" "not" "true" "false" "let" "do" "while" "for" "if" "else" "break" "continue" "cout" "cerr" "clog" "+"))

  (defvar pugs-special-symbols
    '(":" "," ";" "{" "}" "->" "<=" ">=" "=" "+" "-" "*" "/"  "<" ">" "^"))

  (defvar pugs-font-lock-defaults
    `((
       ;; strings
       ("\"\\.\\*\\?" . font-lock-string-face)
       ;; keywords
       ( ,(regexp-opt pugs-keywords 'words) . font-lock-keyword-face)
       ;; special symbols
       ( ,(regexp-opt pugs-special-symbols) . font-lock-constant-face)
       )))

  (setq font-lock-defaults pugs-font-lock-defaults)

  ;; for comments
  (setq comment-start "//")
  (setq comment-end "")

  (modify-syntax-entry ?\\ "\\" pugs-mode-syntax-table)
  (modify-syntax-entry ?/ ". 124b" pugs-mode-syntax-table)
  (modify-syntax-entry ?* ". 23" pugs-mode-syntax-table)
  (modify-syntax-entry ?\n "> b" pugs-mode-syntax-table)

  (local-set-key (kbd "C-c C-c") 'pugs-run-file)
  )
(provide 'pugs-mode)

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