Skip to content
This repository
tag: v1591
Fetching contributors…

Cannot retrieve contributors at this time

file 849 lines (701 sloc) 31.811 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
;;; opa-mode.el --- Major mode for editing Opa-Classic programs

;; To automatically use this mode on .opa files, add the following to your
;; .emacs:
;; (autoload 'opa-classic-mode "/usr/share/opa/emacs/opa-mode.el" "Opa-Classic editing mode." t)
;; (add-to-list 'auto-mode-alist '("\\.opa$" . opa-classic-mode))


;; user definable variables
;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv

(defcustom opa-indent-offset 2
  "*Amount of offset per level of indentation"
  :type 'integer
  :group 'opa)

(defface opa-font-stop-face
  '((t
     (:foreground "White")
     (:background "Red")))
  "Opa font stop face"
  :group 'opa-faces)

(defface opa-font-ppdebug-face
  '((t :weight bold))
  "Opa face for ppdebug directives"
  :group 'opa-faces)

(defface opa-font-xhtml-face
  '((t :inherit font-lock-string-face))
  "Opa face to use for XHTML code"
  :group 'opa-faces)

(defface opa-font-raw-ident-face
  '((t :underline t))
  "Opa face for raw idents (between backquotes)"
  :group 'opa-faces)

(defface opa-font-doc-directive-face
  '((t :foreground "turquoise3"))
  "Opa face to use for opadoc directives"
  :group 'opa-faces)

(defface opa-font-doc-title-face
  '((default (:inherit font-lock-doc-face))
    (t (:weight bold)))
  "Opa face to use for titles in opadoc"
  :group 'opa-faces)

(defface opa-font-directive-face
  '((t :foreground "orangered3"))
  "Opa face for directives"
  :group 'opa-faces)


;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT

(defvar bident-regexp "[a-zA-Z0-9_]*")
(defvar ident-regexp (concat "[a-zA-Z_']" bident-regexp))
(defvar type-ident-regexp (concat "[a-zA-Z_']" bident-regexp))
(defvar dotted-type-ident-regexp (concat "\\(" ident-regexp "\\.\\)*" type-ident-regexp))

(defconst opa-intdent-keywords-cont
  '("then" "else" "with" "end" "true" "false" "open"))
(defconst opa-intdent-keywords (append opa-intdent-keywords-cont
  '("type" "if" "match" "do" "parser" "xml_parser" "database" "server" "rec" "and" "as" "css" "db" "with" "val"
    "import" "import-plugin" "package")))
(defconst opa-directives
  '("xml" "typeval" "static_content_directory" "static_resource_directory" "static_source_content" "static_binary_content" "static_include_directory" "catch" "client" "fail" "typeof" "lazy" "lazy_record" "thread_context" "with_thread_context" "throw" "track" "wrap" "unwrap" "callcc" "uncps" "atomic" "js_ident" "expand" "spawn" "wait" "server" "unsafe_cast" "toplevel" "assert" "opensums" "publish" "publish_async" "both" "prefer_client" "prefer_server" "prefer_both" "both_implem" "abstract" "private" "public" "package" "nonexpansive" "async" "compiletime" "sliced_expr" "may_cps" "llarray" "specialize" "specialize_strict" "server_private" "opacapi" "stringifier" "xmlizer" "serializer" "comparator" "deprecated" "todo"))

(defun match-opa-tuple-type (limit)
  (when (and (looking-at "( *")
             (goto-char (match-end 0))
             (match-opa-type limit))
    (while (and (looking-at " *, *")
                (goto-char (match-end 0))
                (match-opa-type limit)))
    (when (looking-at " *)")
      (goto-char (match-end 0)))))

(defun match-opa-simple-type (limit)
  (when (looking-at dotted-type-ident-regexp)
    (goto-char (match-end 0))
    (let ((data (match-data)))
      (if (match-opa-tuple-type limit)
          t
        (set-match-data data)
        t))))

(defun match-opa-nonfun-type (limit)
  (cond
   ((match-opa-tuple-type limit)
    t)
   ((match-opa-simple-type limit)
    t)))

;; parsing the lhs of an arrow types ie a comma separated list (perhaps empty) of types
;; @return -1 if nothing was parsed
;; otherwise, the position of the end of the first type parsed
;; (ie before the first comma, if any)
(defun match-opa-arrow-lhs (limit)
  (let ((before-first-comma -1))
    (when (match-opa-nonfun-type limit)
      (setq before-first-comma (match-end 0))
      (while (and (looking-at " *, *")
                  (goto-char (match-end 0))
                  (match-opa-nonfun-type limit))))
    before-first-comma))

;; not parsing a -> b -> c on purpose because is it not valid syntax (anymore)
;; if you modify it, beware that you must parse [a -> c], [a,b -> c], [-> c]
;; but NOT [a,b] or []
(defun match-opa-type (limit)
  (let ((before-first-comma (match-opa-arrow-lhs limit)))
    (if (and (looking-at " *-> *") ;; if you see an arrow, parse it an a type
             (goto-char (match-end 0))
             (match-opa-nonfun-type limit))
      (progn (goto-char (match-end 0)) t)
      ;; if you don't see any arrow, two choices
      (if (= before-first-comma -1)
          ;; you didn't parse anything, so you fail in parsing the type
          nil
          ;; you parsed one type (and possibly others with separated commas)
        (progn
          ;; use the first one of these types: in [ident:a,b], only [a]
          ;; is a valid type since no arrow follows
          (set-match-data (list before-first-comma before-first-comma))
            ;; setting match-data with a wierd value but the following
            ;; function will read just the second value anyway
          t)))))

(defun match-opa-type-annotation (limit)
  (when (re-search-forward ": *\\|@typeval( *" limit t)
    (goto-char (match-end 0))
    (let ((start (if (eq (char-after (match-beginning 0)) ?:)
                     (match-beginning 0); fontifying the ':'
                   (match-end 0))))
      (when (match-opa-type limit)
        (let ((end (match-end 0)))
          (set-match-data (list start end))
          (<= end limit))))))

(defun match-opa-doc-directive-aux (limit)
  (if (re-search-forward "@[a-zA-Z]+" limit t)
      (if (is-in-doc-zone) 'succeed 'continue)
    'stop))

(defun match-opa-doc-title-aux (limit)
  (if (re-search-forward "{[0-9]+\\([^}]*\\)}" limit t)
      (if (is-in-doc-zone) 'succeed 'continue)
    'stop))

(defun skip-coercion-and-comments (limit)
  (let ((continue t))
    (while (and continue (< (point) limit))
      (looking-at "\s*")
      (goto-char (match-end 0))
      (if (looking-at ":\s*")
          (goto-char (match-end 0))
        (if (or (is-in-comment-zone) (is-in-type-zone))
            (forward-char)
          (setq continue nil))))))

(defun match-opa-binding-aux (limit)
  ;; matching a.b.c so that in {r with a.b.c = 1} a.b.c highlighted in pink
  (if (re-search-forward (concat "\\<" ident-regexp "\\>" "\\(\\.\\<" ident-regexp "\\>\\)*") limit t)
      (let ((begin (match-beginning 0)))
        (skip-coercion-and-comments limit)
        (if (and (looking-at "\s*\\(=\\)\\([a-zA-Z_0-9 ]\\|$\\)") (< (point) limit))
            (let ((end (match-end 1)))
              (set-match-data (list begin end))
              'succeed)
          'continue
          ))
    'stop))

(defun match-wrapper (f limit)
  (let ((result)
        (continue t))
    (while continue
      (let ((res (funcall f limit)))
        (if (eq res 'continue)
            t
          (if (eq res 'succeed)
              (progn
                (setq result t)
                (setq continue nil))
            (progn ; res = 'stop
              (setq result nil)
              (setq continue nil))))))
    result))

(defun match-opa-doc-directive (limit)
  (match-wrapper 'match-opa-doc-directive-aux limit))

(defun match-opa-binding (limit)
  (match-wrapper 'match-opa-binding-aux limit))

(defun match-opa-doc-title (limit)
  (match-wrapper 'match-opa-doc-title-aux limit))

(defun match-invalid-space-aux (limit)
  (if (re-search-forward "[a-zA-Z0-9_)]\\( *\\)([^*]" limit t)
      (if (is-in-keyword-zone-with-point (match-beginning 0))
          ; if (1 == 2) shouldn't complain because of the space after "if"
          'continue
        'succeed)
    'stop))

(defun match-invalid-space (limit)
  (match-wrapper 'match-invalid-space-aux limit))

(defvar opa-font-lock-keywords
    (list
     ;; bypasses (must be done before other rules in case the bypass contains weird chars, eg: %%+%%)
     (cons "%%[^%]*%%" '(0 font-lock-string-face))

     (cons "`[^`]*`" '(0 'opa-font-raw-ident-face))

     ;; directives
     (cons (concat "@" (regexp-opt opa-directives 'words)) '(0 'opa-font-directive-face))

     ;; keywords
     (cons (concat "\\(" (regexp-opt opa-intdent-keywords 'words) "\\)" "\\([ \n\t]\\|[^(]\\|$\\)") 1)

     ;; ppdebug
     (cons "#<[^>]*>" '(0 'opa-font-ppdebug-face))

     ;; type annotation
     (cons #'match-opa-type-annotation '(0 font-lock-type-face))

     ;; let-in
     '(match-opa-binding . (0 font-lock-builtin-face keep))

     ;; operators, separators
     (cons (concat "[+*{};\\]") 0)

     ;; database value declaration
     (cons "^\\(db\\) */" 1)

     ;; subrule name (parser)
     ;;(cons "\\([a-zA-Z]+\\)\\(=\\)" '((1 font-lock-comment-face) (2 font-lock-builtin-face)))
     (cons "[a-zA-Z_]+=" '(0 font-lock-builtin-face))

     ;; function call
     (cons (concat "\\(" ident-regexp "\\(\\." ident-regexp "\\)*\\)(") '(1 font-lock-function-name-face))

     ;; dot call
     (cons (concat "\\." ident-regexp) '(0 font-lock-constant-face))

     ;; some more operators
     (cons "\\(->\\|<-\\|-\\)" 0)

     ;; invalid spaces between function name and open parenthesis
     ;(cons "[a-zA-Z0-9_)]\\( *\\)([^*]" '(1 'opa-font-stop-face))
     '(match-invalid-space . (1 'opa-font-stop-face))

     ;; opa-doc directives
     (cons 'match-opa-doc-directive '(0 'opa-font-doc-directive-face t))
     (cons 'match-opa-doc-title '(1 'opa-font-doc-title-face t))

     ;; xhtml
     'opa-highlights-xhtml

; (cons (concat (mapconcat 'identity '("[,.:=]") "\\|")) '(0 font-lock-builtin-face))
     )
  "Additional expressions to highlight in Opa-Classic mode.")
(put 'opa-classic-mode 'font-lock-defaults '(opa-font-lock-keywords))

(make-variable-buffer-local 'opa-indent-offset)

;; same as tuareg mode, /** for documentation
(defun opa-font-lock-syntactic-face-function (state)
  (if (nth 3 state) font-lock-string-face
    (let ((start (nth 8 state)))
      (if (and (> (point-max) (+ start 2))
               (eq (char-after (+ start 2)) ?*)
               (not (eq (char-after (+ start 3)) ?*)))
          ;; This is a documentation comment
          font-lock-doc-face
        font-lock-comment-face))))


;; Major mode boilerplate
(defmacro inc(a) (list 'setq a (list '1+ a)))
(defmacro dec(a) (list 'setq a (list '1- a)))

;; define a mode-specific abbrev table for those who use such things
(defvar opa-classic-mode-abbrev-table nil
  "Abbrev table in use in `opa-classic-mode' buffers.")
(define-abbrev-table 'opa-classic-mode-abbrev-table nil)

(defvar opa-classic-mode-hook nil
  "*Hook called by `opa-classic-mode'.")

(defvar opa-classic-mode-syntax-table nil
  "Syntax table used in `opa-classic-mode' buffers.")
(if opa-classic-mode-syntax-table
    nil
  (setq opa-classic-mode-syntax-table (make-syntax-table))
  (modify-syntax-entry ?\( "()" opa-classic-mode-syntax-table)
  (modify-syntax-entry ?\) ")(" opa-classic-mode-syntax-table)
  (modify-syntax-entry ?\[ "(]" opa-classic-mode-syntax-table)
  (modify-syntax-entry ?\] ")[" opa-classic-mode-syntax-table)
  (modify-syntax-entry ?\{ "(}" opa-classic-mode-syntax-table)
  (modify-syntax-entry ?\} "){" opa-classic-mode-syntax-table)
  ;; double quote are string delimiters
  (modify-syntax-entry ?\" "\"" opa-classic-mode-syntax-table)

  ;; Add operator symbols misassigned in the std table
  (modify-syntax-entry ?\* "." opa-classic-mode-syntax-table)
  (modify-syntax-entry ?\+ "." opa-classic-mode-syntax-table)
  (modify-syntax-entry ?\- "." opa-classic-mode-syntax-table)
  (modify-syntax-entry ?\/ "." opa-classic-mode-syntax-table)
  (modify-syntax-entry ?\< "." opa-classic-mode-syntax-table)
  (modify-syntax-entry ?\= "." opa-classic-mode-syntax-table)
  (modify-syntax-entry ?\> "." opa-classic-mode-syntax-table)
  (modify-syntax-entry ?\| "." opa-classic-mode-syntax-table)

  (modify-syntax-entry ?\; "." opa-classic-mode-syntax-table)
  (modify-syntax-entry ?\= "." opa-classic-mode-syntax-table)

  ; / is first character of comment start
  ; and last character of comment end
  (modify-syntax-entry ?\/ ". 124b" opa-classic-mode-syntax-table)
  ; * is second character of comment start,
  ; and first character of comment end
  (modify-syntax-entry ?* ". 23n" opa-classic-mode-syntax-table)
  ; end-of-line finishes // comment
  (modify-syntax-entry 10 "> b" opa-classic-mode-syntax-table)


  )

(defvar opa-classic-mode-syntax-table-xhtml nil
  "Syntax table used in `opa-classic-mode' buffers for xhtml constructs.")
(if opa-classic-mode-syntax-table-xhtml
    nil
  (setq opa-classic-mode-syntax-table-xhtml (make-syntax-table))
  (setq i 0) (while (< i 256)
               (modify-syntax-entry i "." opa-classic-mode-syntax-table-xhtml)
               (inc i))
  )


;;;###autoload
(defun opa-classic-mode ()
  "Major mode for editing Opa-Classic files"
  (interactive)
  ;; set up local variables
  (kill-all-local-variables)
  (make-local-variable 'font-lock-defaults)
  (make-local-variable 'paragraph-separate)
  (make-local-variable 'paragraph-start)
  (make-local-variable 'require-final-newline)
  (make-local-variable 'comment-start)
  (make-local-variable 'comment-end)
  (make-local-variable 'comment-start-skip)
  (make-local-variable 'comment-column)
; (make-local-variable 'indent-region-function)
; (make-local-variable 'indent-line-function)
  ;;
  (set-syntax-table opa-classic-mode-syntax-table)

  ; don't know what this does exactly, but the javascript-mode does
  ; that and it seems to make ?_ a word constituent for the purpose of
  ; fontification but not for moving the point (awesome!)
  (set (make-local-variable 'font-lock-defaults)
       (list opa-font-lock-keywords
             nil nil '((?_ . "w")) nil))

  (setq major-mode 'opa-classic-mode
        mode-name "Opa-Classic"
        local-abbrev-table opa-classic-mode-abbrev-table
        font-lock-syntactic-face-function 'opa-font-lock-syntactic-face-function
        paragraph-separate "^[ \t]*$"
        paragraph-start "^[ \t]*$"
        require-final-newline t
        comment-start "// "
        comment-end ""
        comment-start-skip "// *"
        comment-column 40
        indent-tabs-mode nil
; indent-region-function 'opa-indent-region
; indent-line-function 'opa-indent-line
        )
  (use-local-map opa-classic-mode-map)
  ;; Run the mode hook.
  (if opa-classic-mode-hook (run-hooks 'opa-classic-mode-hook))
)



;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; various useful functions

(defun buffer-substring1 (pos)
  (buffer-substring pos (1+ pos)))

(defun is-in-xhtml-zone ()
  (eq (get-text-property (point) 'syntax-table) opa-classic-mode-syntax-table-xhtml))

(defun is-in-ppdebug-zone ()
  (eq (get-text-property (point) 'face) 'opa-font-ppdebug-face))

(defun is-in-comment-zone ()
  (let ((prop (get-text-property (point) 'face)))
    (or (eq prop font-lock-comment-face)
        (eq prop font-lock-doc-face))))

(defun is-in-strict-comment-zone ()
  (eq (get-text-property (point) 'face) font-lock-comment-face))

(defun is-in-doc-zone ()
  (eq (get-text-property (point) 'face) font-lock-doc-face))

(defun is-in-keyword-zone-with-point (p)
  (eq (get-text-property p 'face) font-lock-keyword-face))

(defun is-in-keyword-zone ()
  (is-in-keyword-zone-with-point (point)))

(defun is-in-string-zone ()
  (eq (get-text-property (point) 'face) font-lock-string-face))

(defun is-in-type-zone ()
  (eq (get-text-property (point) 'face) font-lock-type-face))

(defun re-search-forward--skipping-comments (re end)
  (let ((found nil))
    (while (and (not found) (re-search-forward re end t))
      (setq found (not (is-in-comment-zone))))
    found))

(defun re-search-forward--skipping-strings-comments-ppdebug (re end)
  (let ((found nil))
    (while (and (not found) (re-search-forward re end t))
      (setq found (not (or (is-in-comment-zone) (is-in-string-zone) (is-in-ppdebug-zone)))))
    found))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; xhtml parsing and setting face property

; returns the beginning position and sets (point) to the end position
(defun find-nested--skipping-strings-comments (re_open re_close end)
  (if (re-search-forward--skipping-strings-comments-ppdebug re_open end)
      (let ((b (point))
            (re (concat re_open "\\|" re_close))
            (deep 1))
        (while (and (< (point) end) (re-search-forward--skipping-strings-comments-ppdebug re end))
          ;(message (concat "find-nested--skipping-strings-comments found at " (int-to-string (point)) " deep is " (int-to-string deep)))
          (goto-char (match-beginning 0))
          (if (looking-at re_close)
              (if (= (dec deep) 0) (setq end (point)))
            (inc deep))
          (forward-char) ; move to the next char otherwise we will search at the same place
          )
        b)))

(defun skip-attributes ()
  (while (looking-at " +[a-zA-Z][a-zA-Z0-9_:-]* *= *")
      (goto-char (match-end 0))
      (cond ((looking-at "\"[^\"]*\"")
             (goto-char (match-end 0)))
            ((looking-at "'[^\']*'")
             (goto-char (match-end 0)))
            ((looking-at "{[^}]*}")
             (goto-char (match-end 0)))
            (t (re-search-forward "[ \t/<>]")
               (backward-char)))))

;; starting from point being just after opening tag "tag", search the closing tag
(defun search-xhtml-end (tag)
  (skip-attributes)
  (if (and (not (equal tag "")) (looking-at "[ \n\t]*/>"))
      ; <tag/> format
      (match-end 0)
    (let ((re (concat "</?\\(" tag "\\)?>"))
        (end (1- (point-max)))
        (deep 1))
    (while (and (< (point) end) (re-search-forward--skipping-comments re (point-max)))
      ;(message (concat "search-xhtml-end looking for " tag " found at " (int-to-string (point)) " deep is " (int-to-string deep)))
      (if (equal (buffer-substring1 (1+ (match-beginning 0))) "/")
        (if (= (dec deep) 0) (setq end (match-end 0)))
        (inc deep)))
    ;(message (concat "search-xhtml-end looking for " tag " found at " (int-to-string (point)) " deep is " (int-to-string deep)))
    (goto-char end)
    (point))))

;; search an opening tag before "end"
(defun search-xhtml-beg-raw (end)
  (let ((found nil))
    (while (and (not found) )
      (setq found (not (is-in-comment-zone))))
    found))

(defun search-xhtml-beg (end)
  (let ((found (re-search-forward--skipping-strings-comments-ppdebug "<\\([a-zA-Z][a-zA-Z0-9:-]*\\|>\\)" end)))
    (if (and found (equal (buffer-substring1 (1- (point))) ">"))
        (backward-char))
    found))

(defun set-xhtml-property (beg end)
  (put-text-property beg end 'syntax-table opa-classic-mode-syntax-table-xhtml)
  (put-text-property beg end 'face 'opa-font-xhtml-face)
  (put-text-property beg end 'font-lock-multiline t)

  (save-excursion
    (goto-char beg)
    (while (re-search-forward--skipping-strings-comments-ppdebug "<\\(/?[a-zA-Z][a-zA-Z0-9-]* */?\\)\\|/>" end)
      (if (equal (buffer-substring1 (match-beginning 0)) "<")
          (put-text-property (match-beginning 1) (match-end 1) 'face 'font-lock-keyword-face)
        ; colorize the "/" in "<zzzz .... />"
        (put-text-property (match-beginning 0) (1+ (match-beginning 0)) 'face 'font-lock-keyword-face))))
)

(defun set-xhtml-except-braces (beg end)
  (goto-char beg)
  (let ((beg_brace nil))
    (while (setq beg_brace (find-nested--skipping-strings-comments "[^\\]{" "[^\\]}" end))
      (set-xhtml-property beg beg_brace)
      (setq beg (point))))
  (set-xhtml-property beg end))


(defun opa-highlights-xhtml (end)
  ;(message (concat "opa-highlights-xhtml on " (int-to-string start) ".." (int-to-string end)))
  (if (search-xhtml-beg end)
      (let* ((b (match-beginning 0))
             (tag (buffer-substring (1+ b) (point)))
             (e (search-xhtml-end tag)))
        ;(message (concat "setting xhtml on " (int-to-string b) ".." (int-to-string e)))
        (set-xhtml-except-braces b e)
        e
        )))




;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; compilation

(require 'compile)
(require 'ansi-color)

(setq compilation-error-regexp-alist
      '(
        ;the format of syntax errors (to be unified)
        ("In \\(.+\\) \\[\\([0-9]+\\):\\([0-9]+\\)-\\([0-9]+\\):\\([0-9]+\\) | global chars=[0-9]+-[0-9]+\\]" 1 (2 . 4) (3 . 5) 1)

        ;this fallback one presents the advantage that it does also match Ocaml errors and back-traces
        ("[Ff]ile \\\"?\\([^ \\\"]*?\\)\\\"?, line \\([0-9]+\\), characters \\([0-9]+\\)-\\([0-9]+\\)" 1 2 (3 . 4) 1)
        ;corresponds to FilePos.to_string
        ("[Ff]ile \\\"?\\([^ \\\"]*?\\)\\\"?, line [0-9]+, characters [0-9]+-[0-9]+, (\\([0-9]+\\):\\([0-9]+\\)-\\([0-9]+\\):\\([0-9]+\\) | [0-9]+-[0-9]+)" 1 (2 . 4) (3 . 5) 1)
        )
      )
(set (make-local-variable 'compilation-first-column) 1)

(add-hook 'compilation-filter-hook
          (lambda () (ansi-color-apply-on-region (point-min-marker) (point)))
)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Launch/Stop


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; keymap

(defvar opa-classic-mode-map nil "Keymap for opa-classic-mode")

(setq opa-classic-mode-map (make-sparse-keymap))
(define-key opa-classic-mode-map "\C-c\C-c" 'compile)


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; menu

(define-key opa-classic-mode-map [menu-bar]
    (make-sparse-keymap))
  (let ((opa-menu-map (make-sparse-keymap "Opa-Classic")))
    (define-key opa-classic-mode-map [menu-bar opa]
      (cons "Opa-Classic" opa-menu-map))
    (define-key opa-menu-map [opa-kill]
      '("Stop application" . opa-stop))
    (define-key opa-menu-map [opa-start]
      '("Launch application" . opa-start))
    (define-key opa-menu-map [compile]
      '("Compile this file" . compile))
    (define-key opa-menu-map [separator]
      '("--" ))
    (define-key opa-menu-map [goto-home-page]
      '("Open documentation" .
        (lambda ()
          (interactive)
          (browse-url "http://www.mlstate.com/wiki/admin/opa_documentation"))))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; below is currently unused, work-in-progress only


(defvar opa-syntax-error nil)

(defun opa-set-syntax-error-face-once ()
  (if (null opa-syntax-error) ()
    (put-text-property (car opa-syntax-error) (cdr opa-syntax-error) 'face 'opa-font-stop-face)
    (setq opa-syntax-error nil)
    ))

(defun opa-indent-line (&optional arg)
  "Fix the indentation of the current line according to Opa-Classic rules.

This function is normally bound to `indent-line-function' so
\\[indent-for-tab-command] will call it."
  (interactive "P")
  (let* ((ci (current-indentation))
         (syntax-error nil)
         (need (opa-compute-indentation)))
    (if (or (/= ci need) syntax-error)
        (save-excursion
          (beginning-of-line)
          (delete-horizontal-space)
          (indent-to need)

          (setq opa-syntax-error (if syntax-error (cons (- (point) need) (point)) nil))
          ))
    ))

(defun opa-backward-pattern ()
  ; TODO: handle comma for "x, y -> ..."
  (backward-sexp))

(defun backward-if-non-meaningful ()
    (while (looking-at "[ \t\n]") (backward-char))
    (while (is-in-comment-zone) (backward-char))
    (while (looking-at "[ \t\n]") (backward-char)))

(defun backward-until-outdent ()
  (let ((indent (current-indentation)))
    (while (progn (forward-line -1) (>= (current-indentation) indent)))
    (move-to-column indent)))

(defun previous-meaningful-end-of-line ()
  (beginning-of-line) (backward-char) (backward-if-non-meaningful))

(defun is-value ()
  (or (looking-at "[a-zA-Z0-9_)}]\\|\\]")
      (is-in-xhtml-zone)))

(defun count-values (beg end)
  (let ((cnt 0))
    (save-excursion
      (goto-char end) (end-of-line) (backward-if-non-meaningful)
      (if (< end (point)) (previous-meaningful-end-of-line))

      (while (<= beg (point))
        ;(message (concat "count-values looking at " (int-to-string (point))))
        (if (is-value) (inc cnt))
        (previous-meaningful-end-of-line)
        ;(message (concat "count-values is now at " (int-to-string (point))))
      ))
    ;(message (concat "count-values gives " (int-to-string cnt) " between " (int-to-string (point)) " and " (int-to-string last)))
    cnt))

(defconst opa-statement-re
  "\\([;=(){}]\\|\\[\\|\\]\\|->\\|\\bmatch\\b\\)")

(defun opa-classify-statement ()
  (cond
   ((looking-at ";") 'semi-colon)
   ((looking-at "=") 'def)
   ((looking-at "->") 'ano-func)
   ((looking-at "[)}]\\|\\]") 'close-paren)
   ((looking-at "[({]\\|\\[") 'open-paren)
   ((looking-at "match\\b") 'match)
   ((looking-at "end\\b") 'end)
   ((looking-at "[a-zA-Z0-9_]") 'value)
   ))

(defadvice opa-classify-statement (around opa-classify-statement-around)
  (let ((kind (ad-do-it)))
    ;(message (concat "opa-classify-statement at pos " (int-to-string (point)) " gives " (pp-to-string kind)))
    kind))

(defun opa-find-first-statement-forward (beg end)
  ;(message (concat "opa-find-first-statement-forward between " (int-to-string beg) " and " (int-to-string end)))
  (save-excursion
    (goto-char beg)
    (let ((stop nil))
      (while (and (null stop)
                  (re-search-forward opa-statement-re end t))
        (goto-char (match-beginning 0))
        (cond
         ((looking-at "[({]\\|\\[")
          ; using forward-sexp to handle (...), [...], {...} (we must not look into them)
          (forward-sexp))

         (t
          (setq stop (opa-classify-statement)
          ))))
      ;(message (concat "opa-find-first-statement-forward found " (pp-to-string stop)))
      stop)))

(defun opa-find-statement-backward ()
  ;(message (concat "we found an implicit ';' (was looking at " (int-to-string (point)) ")"))
  (let ((last (point))
        (deep 0)
        (stop nil))
    (while (and (null stop)
                (re-search-backward opa-statement-re nil t))
      (setq deep (+ deep (count-values (point) last)))
      (setq last (point))
      (cond
       ((looking-at "[)}]\\|\\]")
        ; using backward-sexp to handle (...), [...], {...} (we must not look into them)
        (forward-char 1) (backward-sexp))

       ((looking-at "[({]\\|\\[")
        ; we found unclosed, we can't go further. If deep is not 0, it mean syntax error in the code
        (setq stop 'open-paren) (forward-char 1))

       ((looking-at ";")
        (inc deep))

       (t
        (dec deep)
        (if (> deep 0) ()
          (setq stop (opa-classify-statement))
          ))))

    ;(message (concat "opa-find-statement-backward stopped at " (int-to-string (point)) " (deep is " (int-to-string deep) ")"))

    stop
    ))

;(toggle-debug-on-error)


(defun opa-compute-indentation-from-here (current-indentation-pos current-eol current-kind previous-kind)
  (cond ((or (eq previous-kind 'operator) (eq previous-kind 'match))
         (opa-backward-pattern) (+ (current-indentation) opa-indent-offset))
        ((eq previous-kind 'def)
         (opa-backward-pattern) (current-column))

        ((eq previous-kind 'ano-func)
         (opa-backward-pattern)
         (let ((current-statement-kind (opa-find-first-statement-forward current-indentation-pos current-eol)))
           (if (eq current-statement-kind 'def)
               (progn
                 ;(message (concat "point is " (int-to-string (point))))
                 (backward-until-outdent)
                 ;(message (concat "point is " (int-to-string (point))))
                 (end-of-line)
                 (opa-compute-indentation-from-here current-indentation-pos current-eol current-kind (opa-find-statement-backward))
                 )
             (current-column))))

        ((eq previous-kind 'open-paren)
         (if (or (eq current-kind 'value) (eq current-kind 'match) (eq current-kind 'open-paren))
             (setq syntax-error t))
         (current-column))
        ))

(defun opa-compute-indentation ()
  ;; implements all the rules for indentation computation.
  (save-excursion

    (let* ((current-indentation-pos (progn (back-to-indentation) (point)))
           (current-kind (opa-classify-statement))
           (current-eol (progn (end-of-line) (point)))
           (previous-kind (progn
               (previous-meaningful-end-of-line)
               (if (is-value)
                  ; we found an implicit ";"
                  (progn (forward-char) (opa-find-statement-backward))

                 ;(message (concat "we found an operator, simply indent (was looking at " (int-to-string (point)) ")"))
                 'operator))))

      (opa-compute-indentation-from-here current-indentation-pos current-eol current-kind previous-kind)
      )))


(defun opa-indent-region (start end &optional indent-offset)
  "Reindent a region of Opa-Classic code.

The lines from the line containing the start of the current region up
to (but not including) the line containing the end of the region are
reindented. If the first line of the region has a non-whitespace
character in the first column, the first line is left alone and the
rest of the region is reindented with respect to it. Else the entire
region is reindented with respect to the (closest code or indenting
comment) statement immediately preceding the region.

This is useful when code blocks are moved or yanked, when enclosing
control structures are introduced or removed, or to reformat code
using a new value for the indentation offset.

If a numeric prefix argument is given, it will be used as the value of
the indentation offset. Else the value of `opa-indent-offset' will be
used.
"
  (interactive "*r\nP") ; region; raw prefix arg
  (save-excursion
    (goto-char end) (beginning-of-line) (setq end (point-marker))
    (goto-char start) (beginning-of-line)
    (let ((opa-indent-offset (prefix-numeric-value
                             (or indent-offset opa-indent-offset)))
          (indents '(-1)) ; stack of active indent levels
          (target-column 0) ; column to which to indent
          (base-shifted-by 0) ; amount last base line was shifted
          (indent-base (if (looking-at "[ \t\n]")
                           (opa-compute-indentation)
                         0))
          ci)
      (while (< (point) end)
        (setq ci (current-indentation))
        ;; figure out appropriate target column
        (cond
         ((or (eq (following-char) ?#) ; comment in column 1
              (looking-at "[ \t]*$")) ; entirely blank
          (setq target-column 0))
         (t ; new base line
          (if (> ci (car indents)) ; going deeper; push it
              (setq indents (cons ci indents))
            ;; else we should have seen this indent before
            (setq indents (memq ci indents)) ; pop deeper indents
            (if (null indents)
                (error "Bad indentation in region, at line %d"
                       (save-restriction
                         (widen)
                         (1+ (count-lines 1 (point)))))))
          (setq target-column (+ indent-base
                                 (* opa-indent-offset
                                    (- (length indents) 2))))
          (setq base-shifted-by (- target-column ci))))
        ;; shift as needed
        (if (/= ci target-column)
            (progn
              (delete-horizontal-space)
              (indent-to target-column)))
        (forward-line 1))))
  (set-marker end nil))


(provide 'opa-classic-mode)
;;; opa-mode.el ends here
Something went wrong with that request. Please try again.