white

rjsx with elpa

;;; js2-imenu-extras.el --- Imenu support for additional constructs
;; Copyright (C) 2012-2014 Free Software Foundation, Inc.
;; Author: Dmitry Gutov <dgutov@yandex.ru>
;; Keywords: languages, javascript, imenu
;; This file is part of GNU Emacs.
;; GNU Emacs 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 3 of the License, or
;; (at your option) any later version.
;; GNU Emacs 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. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This package adds Imenu support for additional framework constructs and
;; structural patterns to `js2-mode'.
;; Usage:
;; (add-hook 'js2-mode-hook 'js2-imenu-extras-mode)
;; To customize how it works:
;; M-x customize-group RET js2-imenu RET
(eval-when-compile
(require 'cl))
(require 'js2-mode)
(defvar js2-imenu-extension-styles
`((:framework jquery
:call-re "\\_<\\(?:jQuery\\|\\$\\|_\\)\\.extend\\s-*("
:recorder js2-imenu-record-jquery-extend)
(:framework jquery-ui
:call-re "^\\s-*\\(?:jQuery\\|\\$\\)\\.widget\\s-*("
:recorder js2-imenu-record-string-declare)
(:framework dojo
:call-re "^\\s-*dojo.declare\\s-*("
:recorder js2-imenu-record-string-declare)
(:framework backbone
:call-re ,(concat "\\_<" js2-mode-identifier-re "\\.extend\\s-*(")
:recorder js2-imenu-record-backbone-extend)
(:framework enyo
:call-re "\\_<enyo\\.kind\\s-*("
:recorder js2-imenu-record-enyo-kind)
(:framework react
:call-re "\\_<React\\.createClass\\s-*("
:recorder js2-imenu-record-react-class)
(:framework sencha
:call-re "^\\s-*Ext\\.define\\s-*("
:recorder js2-imenu-record-sencha-class))
"List of JavaScript class definition or extension styles.
:framework is a valid value in `js2-imenu-enabled-frameworks'.
:call-re is a regular expression that has no capturing groups.
:recorder is a function name that will be called when the regular
expression matches some text in the buffer. When it's called, point will be
at the end of the match. The function must keep the point position.")
(defconst js2-imenu-available-frameworks
(mapcar (lambda (style) (plist-get style :framework)) js2-imenu-extension-styles)
"List of available JavaScript framework symbols.")
(defcustom js2-imenu-enabled-frameworks js2-imenu-available-frameworks
"Frameworks to be recognized by `js2-mode'."
:type (cons 'set (mapcar (lambda (x) (list 'const x))
js2-imenu-available-frameworks))
:group 'js2-imenu)
(defcustom js2-imenu-show-other-functions t
"Non-nil to show functions not recognized by other mechanisms,
in a shared namespace."
:type 'boolean
:group 'js2-imenu)
(defcustom js2-imenu-other-functions-ns "?"
"Namespace name to use for other functions."
:type 'string
:group 'js2-imenu)
(defcustom js2-imenu-show-module-pattern t
"Non-nil to recognize the module pattern:
var foobs = (function(a) {
return {fib: function() {}, fub: function() {}};
})(b);
We record the returned hash as belonging to the named module, and
prefix any functions defined inside the IIFE with the module name."
:type 'boolean
:group 'js2-imenu)
(defcustom js2-imenu-split-string-identifiers t
"When non-nil, split string identifiers on dots.
Currently used for jQuery widgets, Dojo and Enyo declarations."
:type 'boolean
:group 'js2-imenu)
;;;###autoload
(defun js2-imenu-extras-setup ()
(when js2-imenu-enabled-frameworks
(add-hook 'js2-build-imenu-callbacks 'js2-imenu-record-declarations t t))
(when (or js2-imenu-show-other-functions js2-imenu-show-module-pattern)
(add-hook 'js2-build-imenu-callbacks 'js2-imenu-walk-ast t t)))
(defun js2-imenu-extras-remove ()
(remove-hook 'js2-build-imenu-callbacks 'js2-imenu-record-declarations t)
(remove-hook 'js2-build-imenu-callbacks 'js2-imenu-walk-ast t))
(defun js2-imenu-record-declarations ()
(let* ((styles (loop for style in js2-imenu-extension-styles
when (memq (plist-get style :framework)
js2-imenu-enabled-frameworks)
collect style))
(re (mapconcat (lambda (style)
(concat "\\(" (plist-get style :call-re) "\\)"))
styles "\\|")))
(goto-char (point-min))
(while (js2-re-search-forward re nil t)
(loop for i from 0 to (1- (length styles))
when (match-beginning (1+ i))
return (funcall (plist-get (nth i styles) :recorder))))))
(defun js2-imenu-record-jquery-extend ()
(let ((pred (lambda (subject)
(and
(js2-prop-get-node-p subject)
(string= (js2-name-node-name (js2-prop-get-node-right subject))
"prototype")))))
(js2-imenu-record-extend-first-arg (1- (point)) pred
'js2-compute-nested-prop-get)))
(defun js2-imenu-record-string-declare ()
(js2-imenu-record-extend-first-arg
(1- (point)) 'js2-string-node-p
(lambda (node)
(if js2-imenu-split-string-identifiers
(split-string (js2-string-node-value node) "\\." t)
(list (js2-string-node-value node))))))
(defun js2-imenu-record-extend-first-arg (point pred qname-fn)
(let* ((node (js2-node-at-point point))
(args (js2-call-node-args node))
(subject (first args)))
(when (funcall pred subject)
(loop for arg in (cdr args)
when (js2-object-node-p arg)
do (js2-record-object-literal
arg (funcall qname-fn subject) (js2-node-abs-pos arg))))))
(defun js2-imenu-record-backbone-or-react ()
(let* ((node (js2-node-at-point (1- (point))))
(args (js2-call-node-args node))
(methods (first args))
(parent (js2-node-parent node)))
(when (js2-object-node-p methods)
(let ((subject (cond ((js2-var-init-node-p parent)
(js2-var-init-node-target parent))
((js2-assign-node-p parent)
(js2-assign-node-left parent)))))
(when subject
(js2-record-object-literal methods
(js2-compute-nested-prop-get subject)
(js2-node-abs-pos methods)))))))
(defalias 'js2-imenu-record-backbone-extend 'js2-imenu-record-backbone-or-react)
(defalias 'js2-imenu-record-react-class 'js2-imenu-record-backbone-or-react)
(defun js2-imenu-record-enyo-kind ()
(let* ((node (js2-node-at-point (1- (point))))
(args (js2-call-node-args node))
(options (first args)))
(when (js2-object-node-p options)
(let ((name-value
(loop for elem in (js2-object-node-elems options)
thereis
(let ((key (js2-object-prop-node-left elem))
(value (js2-object-prop-node-right elem)))
(when (and (equal
(cond ((js2-name-node-p key)
(js2-name-node-name key))
((js2-string-node-p key)
(js2-string-node-value key)))
"name")
(js2-string-node-p value))
(js2-string-node-value value))))))
(when name-value
(js2-record-object-literal options
(if js2-imenu-split-string-identifiers
(split-string name-value "\\.")
(list name-value))
(js2-node-abs-pos options)))))))
(defun js2-imenu-record-sencha-class ()
(let* ((node (js2-node-at-point (1- (point))))
(args (js2-call-node-args node))
(name (first args))
(methods (second args)))
(when (and (js2-string-node-p name) (js2-object-node-p methods))
(let ((name-value (js2-string-node-value name)))
(js2-record-object-literal methods
(if js2-imenu-split-string-identifiers
(split-string name-value "\\." t)
(list name-value))
(js2-node-abs-pos methods))))))
(defun js2-imenu-walk-ast ()
(js2-visit-ast
js2-mode-ast
(lambda (node end-p)
(unless end-p
(cond
((and js2-imenu-show-other-functions
(js2-object-prop-node-p node))
(js2-imenu-record-orphan-prop-node-function node))
((js2-assign-node-p node)
(cond
((and js2-imenu-show-other-functions
(js2-function-node-p
(js2-assign-node-right node)))
(js2-imenu-record-orphan-assign-node-function
(js2-assign-node-left node)
(js2-assign-node-right node)))
((and js2-imenu-show-module-pattern
(js2-call-node-p
(js2-assign-node-right node)))
(js2-imenu-record-module-pattern
(js2-assign-node-left node)
(js2-assign-node-right node)))))
((js2-var-init-node-p node)
(cond
((and js2-imenu-show-other-functions
(js2-function-node-p
(js2-var-init-node-initializer node)))
(js2-imenu-record-orphan-assign-node-function
(js2-var-init-node-target node)
(js2-var-init-node-initializer node)))
((and js2-imenu-show-module-pattern
(js2-call-node-p
(js2-var-init-node-initializer node)))
(js2-imenu-record-module-pattern
(js2-var-init-node-target node)
(js2-var-init-node-initializer node))))))
t))))
(defun js2-imenu-parent-key-names (node)
"Get the list of parent key names of NODE.
For example, for code
{rules: {password: {required: function() {}}}}
when NODE is the inner `js2-object-prop-mode',
it returns `(\"rules\" \"password\")'."
(let (rlt (n node))
(while (setq n (js2-imenu-parent-prop-node n))
(push (js2-prop-node-name (js2-object-prop-node-left n)) rlt))
rlt))
(defun js2-imenu-parent-prop-node (node)
"When the parent of NODE is `js2-object-node',
and the grandparent is `js2-object-prop-node',
return the grandparent."
;; Suppose the code is:
;; {parent-key: {required: function() {}}}
;; NODE is `required: function() {}'.
(let (p2 p3)
;; Parent is `{required: function() {}}'.
(setq p2 (js2-node-parent node))
;; GP is `parent-key: {required: function() {}}'.
(when (and p2 (js2-object-node-p p2))
(setq p3 (js2-node-parent p2))
(if (and p3 (js2-object-prop-node-p p3)) p3))))
(defun js2-imenu-record-orphan-prop-node-function (node)
"Record orphan function when it's the value of NODE.
NODE must be `js2-object-prop-node'."
(when (js2-function-node-p (js2-object-prop-node-right node))
(let ((fn-node (js2-object-prop-node-right node)))
(unless (and js2-imenu-function-map
(gethash fn-node js2-imenu-function-map))
(let ((key-node (js2-object-prop-node-left node))
(parent-prop-node (js2-imenu-parent-prop-node node))
chain)
(setq chain (nconc (js2-imenu-parent-key-names node)
(list (js2-prop-node-name key-node))))
(push js2-imenu-other-functions-ns chain)
(js2-record-imenu-entry fn-node chain
(js2-node-abs-pos key-node)))))))
(defun js2-imenu-record-orphan-assign-node-function (target-node fn-node)
"Record orphan function FN-NODE assigned to node TARGET."
(when (or (not js2-imenu-function-map)
(eq 'skip
(gethash fn-node js2-imenu-function-map 'skip)))
(let ((chain (js2-compute-nested-prop-get target-node)))
(when chain
(push js2-imenu-other-functions-ns chain)
(js2-record-imenu-entry fn-node chain (js2-node-abs-pos fn-node))))))
(defun js2-imenu-record-module-pattern (target init)
"Recognize and record module pattern use instance.
INIT must be `js2-call-node'."
(let ((callt (js2-call-node-target init)))
;; Just basic call form: (function() {...})();
;; TODO: Handle variations without duplicating `js2-wrapper-function-p'?
(when (and (js2-paren-node-p callt)
(js2-function-node-p (js2-paren-node-expr callt)))
(let* ((fn (js2-paren-node-expr callt))
(blk (js2-function-node-body fn))
(ret (car (last (js2-block-node-kids blk)))))
(when (and (js2-return-node-p ret)
(js2-object-node-p (js2-return-node-retval ret)))
;; TODO: Map function names when revealing module pattern is used.
(let ((retval (js2-return-node-retval ret))
(target-qname (js2-compute-nested-prop-get target)))
(js2-record-object-literal retval target-qname
(js2-node-abs-pos retval))
(js2-record-imenu-entry fn target-qname
(js2-node-abs-pos target))))))))
;;;###autoload
(define-minor-mode js2-imenu-extras-mode
"Toggle Imenu support for frameworks and structural patterns."
:lighter ""
(if js2-imenu-extras-mode
(js2-imenu-extras-setup)
(js2-imenu-extras-remove)))
(provide 'js2-imenu-extras)
;;; js2-mode-autoloads.el --- automatically extracted autoloads
;;
;;; Code:
(add-to-list 'load-path (or (file-name-directory #$) (car load-path)))
;;;### (autoloads nil "js2-imenu-extras" "js2-imenu-extras.el" (22981
;;;;;; 60718 536222 176000))
;;; Generated autoloads from js2-imenu-extras.el
(autoload 'js2-imenu-extras-setup "js2-imenu-extras" "\
\(fn)" nil nil)
(autoload 'js2-imenu-extras-mode "js2-imenu-extras" "\
Toggle Imenu support for frameworks and structural patterns.
\(fn &optional ARG)" t nil)
;;;***
;;;### (autoloads nil "js2-mode" "js2-mode.el" (22981 60718 552222
;;;;;; 310000))
;;; Generated autoloads from js2-mode.el
(autoload 'js2-highlight-unused-variables-mode "js2-mode" "\
Toggle highlight of unused variables.
\(fn &optional ARG)" t nil)
(autoload 'js2-minor-mode "js2-mode" "\
Minor mode for running js2 as a background linter.
This allows you to use a different major mode for JavaScript editing,
such as `js-mode', while retaining the asynchronous error/warning
highlighting features of `js2-mode'.
\(fn &optional ARG)" t nil)
(autoload 'js2-mode "js2-mode" "\
Major mode for editing JavaScript code.
\(fn)" t nil)
(autoload 'js2-jsx-mode "js2-mode" "\
Major mode for editing JSX code.
To customize the indentation for this mode, set the SGML offset
variables (`sgml-basic-offset' et al) locally, like so:
(defun set-jsx-indentation ()
(setq-local sgml-basic-offset js2-basic-offset))
(add-hook \\='js2-jsx-mode-hook #\\='set-jsx-indentation)
\(fn)" t nil)
;;;***
;;;### (autoloads nil nil ("js2-mode-pkg.el" "js2-old-indent.el")
;;;;;; (22981 60718 574371 921000))
;;;***
;; Local Variables:
;; version-control: never
;; no-byte-compile: t
;; no-update-autoloads: t
;; End:
;;; js2-mode-autoloads.el ends here
(define-package "js2-mode" "20170815.1415" "Improved JavaScript editing mode"
'((emacs "24.1")
(cl-lib "0.5"))
:url "https://github.com/mooz/js2-mode/" :keywords
'("languages" "javascript"))
;; Local Variables:
;; no-byte-compile: t
;; End:
This diff could not be displayed because it is too large.
No preview for this file type
;;; js2-old-indent.el --- Indentation code kept for compatibility
;; Copyright (C) 2015 Free Software Foundation, Inc.
;; This file is part of GNU Emacs.
;; GNU Emacs 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 3 of the License, or
;; (at your option) any later version.
;; GNU Emacs 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. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; All features of this indentation code have been ported to Emacs's
;; built-in `js-mode' by now, so we derive from it. An older
;; commentary follows.
;; This code is kept for Emacs 24.5 and ealier.
;; This indenter is based on Karl Landström's "javascript.el" indenter.
;; Karl cleverly deduces that the desired indentation level is often a
;; function of paren/bracket/brace nesting depth, which can be determined
;; quickly via the built-in `parse-partial-sexp' function. His indenter
;; then does some equally clever checks to see if we're in the context of a
;; substatement of a possibly braceless statement keyword such as if, while,
;; or finally. This approach yields pretty good results.
;; The indenter is often "wrong", however, and needs to be overridden.
;; The right long-term solution is probably to emulate (or integrate
;; with) cc-engine, but it's a nontrivial amount of coding. Even when a
;; parse tree from `js2-parse' is present, which is not true at the
;; moment the user is typing, computing indentation is still thousands
;; of lines of code to handle every possible syntactic edge case.
;; In the meantime, the compromise solution is that we offer a "bounce
;; indenter", configured with `js2-bounce-indent-p', which cycles the
;; current line indent among various likely guess points. This approach
;; is far from perfect, but should at least make it slightly easier to
;; move the line towards its desired indentation when manually
;; overriding Karl's heuristic nesting guesser.
;; I've made miscellaneous tweaks to Karl's code to handle some Ecma
;; extensions such as `let' and Array comprehensions. Major kudos to
;; Karl for coming up with the initial approach, which packs a lot of
;; punch for so little code. -- Steve
;;; Code:
(require 'sgml-mode)
(defvar js2-language-version)
(declare-function js2-backward-sws "js2-mode")
(declare-function js2-forward-sws "js2-mode")
(declare-function js2-same-line "js2-mode")
(defcustom js2-basic-offset (if (and (boundp 'c-basic-offset)
(numberp c-basic-offset))
c-basic-offset
4)
"Number of spaces to indent nested statements.
Similar to `c-basic-offset'."
:group 'js2-mode
:safe 'integerp
:type 'integer)
(defcustom js2-pretty-multiline-declarations t
"Non-nil to line up multiline declarations vertically:
var a = 10,
b = 20,
c = 30;
If the value is t, and the first assigned value in the
declaration is a function/array/object literal spanning several
lines, it won't be indented additionally:
var o = { var bar = 2,
foo: 3 vs. o = {
}, foo: 3
bar = 2; };
If the value is `all', it will always be indented additionally:
var o = {
foo: 3
};
var o = {
foo: 3
},
bar = 2;
If the value is `dynamic', it will be indented additionally only
if the declaration contains more than one variable:
var o = {
foo: 3
};
var o = {
foo: 3
},
bar = 2;"
:group 'js2-mode
:safe 'symbolp
:type 'symbol)
(defcustom js2-indent-switch-body nil
"When nil, case labels are indented on the same level as the
containing switch statement. Otherwise, all lines inside
switch statement body are indented one additional level."
:type 'boolean
:safe 'booleanp
:group 'js2-mode)
(defconst js2-possibly-braceless-keywords-re
(concat "else[ \t]+if\\|for[ \t]+each\\|"
(regexp-opt '("catch" "do" "else" "finally" "for" "if"
"try" "while" "with" "let")))
"Regular expression matching keywords that are optionally
followed by an opening brace.")
(defconst js2-indent-operator-re
(concat "[-+*/%<>&^|?:.]\\([^-+*/.]\\|$\\)\\|!?=\\|"
(regexp-opt '("in" "instanceof") 'symbols))
"Regular expression matching operators that affect indentation
of continued expressions.")
(defconst js2-declaration-keyword-re
(regexp-opt '("var" "let" "const") 'symbols)
"Regular expression matching variable declaration keywords.")
(defun js2-re-search-forward-inner (regexp &optional bound count)
"Auxiliary function for `js2-re-search-forward'."
(let (parse saved-point)
(while (> count 0)
(re-search-forward regexp bound)
(setq parse (if saved-point
(parse-partial-sexp saved-point (point))
(syntax-ppss (point))))
(cond ((nth 3 parse)
(re-search-forward
(concat "\\(\\=\\|[^\\]\\|^\\)" (string (nth 3 parse)))
(save-excursion (end-of-line) (point)) t))
((nth 7 parse)
(forward-line))
((or (nth 4 parse)
(and (eq (char-before) ?\/) (eq (char-after) ?\*)))
(re-search-forward "\\*/"))
(t
(setq count (1- count))))
(setq saved-point (point))))
(point))
(defun js2-re-search-forward (regexp &optional bound noerror count)
"Search forward but ignore strings and comments.
Invokes `re-search-forward' but treats the buffer as if strings
and comments have been removed."
(let ((saved-point (point)))
(condition-case err
(cond ((null count)
(js2-re-search-forward-inner regexp bound 1))
((< count 0)
(js2-re-search-backward-inner regexp bound (- count)))
((> count 0)
(js2-re-search-forward-inner regexp bound count)))
(search-failed
(goto-char saved-point)
(unless noerror
(error (error-message-string err)))))))
(defun js2-re-search-backward-inner (regexp &optional bound count)
"Auxiliary function for `js2-re-search-backward'."
(let (parse)
(while (> count 0)
(re-search-backward regexp bound)
(setq parse (syntax-ppss (point)))
(cond ((nth 3 parse)
(re-search-backward
(concat "\\([^\\]\\|^\\)" (string (nth 3 parse)))
(line-beginning-position) t))
((nth 7 parse)
(goto-char (nth 8 parse)))
((or (nth 4 parse)
(and (eq (char-before) ?/) (eq (char-after) ?*)))
(re-search-backward "/\\*"))
(t
(setq count (1- count))))))
(point))
(defun js2-re-search-backward (regexp &optional bound noerror count)
"Search backward but ignore strings and comments.
Invokes `re-search-backward' but treats the buffer as if strings
and comments have been removed."
(let ((saved-point (point)))
(condition-case err
(cond ((null count)
(js2-re-search-backward-inner regexp bound 1))
((< count 0)
(js2-re-search-forward-inner regexp bound (- count)))
((> count 0)
(js2-re-search-backward-inner regexp bound count)))
(search-failed
(goto-char saved-point)
(unless noerror
(error (error-message-string err)))))))
(defun js2-looking-at-operator-p ()
"Return non-nil if text after point is a non-comma operator."
(defvar js2-mode-identifier-re)
(and (looking-at js2-indent-operator-re)
(or (not (eq (char-after) ?:))
(save-excursion
(and (js2-re-search-backward "[?:{]\\|\\_<case\\_>" nil t)
(eq (char-after) ??))))
(not (and
(eq (char-after) ?/)
(save-excursion
(eq (nth 3 (syntax-ppss)) ?/))))
(not (and
(eq (char-after) ?*)
;; Generator method (possibly using computed property).
(looking-at (concat "\\* *\\(?:\\[\\|"
js2-mode-identifier-re
" *(\\)"))
(save-excursion
(js2-backward-sws)
;; We might misindent some expressions that would
;; return NaN anyway. Shouldn't be a problem.
(memq (char-before) '(?, ?} ?{)))))))
(defun js2-continued-expression-p ()
"Return non-nil if the current line continues an expression."
(save-excursion
(back-to-indentation)
(if (js2-looking-at-operator-p)
(or (not (memq (char-after) '(?- ?+)))
(progn
(forward-comment (- (point)))
(not (memq (char-before) '(?, ?\[ ?\()))))
(forward-comment (- (point)))
(or (bobp) (backward-char))
(when (js2-looking-at-operator-p)
(backward-char)
(not (looking-at "\\*\\|\\+\\+\\|--\\|/[/*]"))))))
(defun js2-end-of-do-while-loop-p ()
"Return non-nil if word after point is `while' of a do-while
statement, else returns nil. A braceless do-while statement
spanning several lines requires that the start of the loop is
indented to the same column as the current line."
(interactive)
(save-excursion
(when (looking-at "\\s-*\\_<while\\_>")
(if (save-excursion
(skip-chars-backward "[ \t\n]*}")
(looking-at "[ \t\n]*}"))
(save-excursion
(backward-list) (backward-word 1) (looking-at "\\_<do\\_>"))
(js2-re-search-backward "\\_<do\\_>" (point-at-bol) t)
(or (looking-at "\\_<do\\_>")
(let ((saved-indent (current-indentation)))
(while (and (js2-re-search-backward "^[ \t]*\\_<" nil t)
(/= (current-indentation) saved-indent)))
(and (looking-at "[ \t]*\\_<do\\_>")
(not (js2-re-search-forward
"\\_<while\\_>" (point-at-eol) t))
(= (current-indentation) saved-indent))))))))
(defun js2-multiline-decl-indentation ()
"Return the declaration indentation column if the current line belongs
to a multiline declaration statement. See `js2-pretty-multiline-declarations'."
(let (forward-sexp-function ; use Lisp version
at-opening-bracket)
(save-excursion
(back-to-indentation)
(when (not (looking-at js2-declaration-keyword-re))
(when (looking-at js2-indent-operator-re)
(goto-char (match-end 0))) ; continued expressions are ok
(while (and (not at-opening-bracket)
(not (bobp))
(let ((pos (point)))
(save-excursion
(js2-backward-sws)
(or (eq (char-before) ?,)
(and (not (eq (char-before) ?\;))
(prog2 (skip-syntax-backward ".")
(looking-at js2-indent-operator-re)
(js2-backward-sws))
(not (eq (char-before) ?\;)))
(js2-same-line pos)))))
(condition-case _
(backward-sexp)
(scan-error (setq at-opening-bracket t))))
(when (looking-at js2-declaration-keyword-re)
(goto-char (match-end 0))
(1+ (current-column)))))))
(defun js2-ctrl-statement-indentation ()
"Return the proper indentation of current line if it is a control statement.
Returns an indentation if this line starts the body of a control
statement without braces, else returns nil."
(let (forward-sexp-function)
(save-excursion
(back-to-indentation)
(when (and (not (js2-same-line (point-min)))
(not (looking-at "{"))
(js2-re-search-backward "[[:graph:]]" nil t)
(not (looking-at "[{([]"))
(progn
(forward-char)
(when (= (char-before) ?\))
;; scan-sexps sometimes throws an error
(ignore-errors (backward-sexp))
(skip-chars-backward " \t" (point-at-bol)))
(let ((pt (point)))
(back-to-indentation)
(when (looking-at "}[ \t]*")
(goto-char (match-end 0)))
(and (looking-at js2-possibly-braceless-keywords-re)
(= (match-end 0) pt)
(not (js2-end-of-do-while-loop-p))))))
(+ (current-indentation) js2-basic-offset)))))
(defun js2-indent-in-array-comp (parse-status)
"Return non-nil if we think we're in an array comprehension.
In particular, return the buffer position of the first `for' kwd."
(let ((bracket (nth 1 parse-status))
(end (point)))
(when bracket
(save-excursion
(goto-char bracket)
(when (looking-at "\\[")
(forward-char 1)
(js2-forward-sws)
(if (looking-at "[[{]")
(let (forward-sexp-function) ; use Lisp version
(forward-sexp) ; skip destructuring form
(js2-forward-sws)
(if (and (/= (char-after) ?,) ; regular array
(looking-at "for"))
(match-beginning 0)))
;; to skip arbitrary expressions we need the parser,
;; so we'll just guess at it.
(if (and (> end (point)) ; not empty literal
(re-search-forward "[^,]]* \\(for\\) " end t)
;; not inside comment or string literal
(let ((state (parse-partial-sexp bracket (point))))
(not (or (nth 3 state) (nth 4 state)))))
(match-beginning 1))))))))
(defun js2-array-comp-indentation (parse-status for-kwd)
(if (js2-same-line for-kwd)
;; first continuation line
(save-excursion
(goto-char (nth 1 parse-status))
(forward-char 1)
(skip-chars-forward " \t")
(current-column))
(save-excursion
(goto-char for-kwd)
(current-column))))
(defun js2-maybe-goto-declaration-keyword-end (bracket)
"Helper function for `js2-proper-indentation'.
Depending on the value of `js2-pretty-multiline-declarations',
move point to the end of a variable declaration keyword so that
indentation is aligned to that column."
(cond
((eq js2-pretty-multiline-declarations 'all)
(when (looking-at js2-declaration-keyword-re)
(goto-char (1+ (match-end 0)))))
((eq js2-pretty-multiline-declarations 'dynamic)
(let (declaration-keyword-end
at-closing-bracket-p
comma-p)
(when (looking-at js2-declaration-keyword-re)
;; Preserve the match data lest it somehow be overridden.
(setq declaration-keyword-end (match-end 0))
(save-excursion
(goto-char bracket)
(setq at-closing-bracket-p
;; Handle scan errors gracefully.
(condition-case nil
(progn
;; Use the regular `forward-sexp-function' because the
;; normal one for this mode uses the AST.
(let (forward-sexp-function)
(forward-sexp))
t)
(error nil)))
(when at-closing-bracket-p
(js2-forward-sws)
(setq comma-p (looking-at-p ","))))
(when comma-p
(goto-char (1+ declaration-keyword-end))))))))
(cl-defun js2-proper-indentation (parse-status)
"Return the proper indentation for the current line."
(save-excursion
(back-to-indentation)
(when (nth 4 parse-status)
(cl-return-from js2-proper-indentation (js2--comment-indent parse-status)))
(let* ((at-closing-bracket (looking-at "[]})]"))
(same-indent-p (or at-closing-bracket
(looking-at "\\_<case\\_>[^:]")
(and (looking-at "\\_<default:")
(save-excursion
(js2-backward-sws)
(not (memq (char-before) '(?, ?{)))))))
(continued-expr-p (js2-continued-expression-p))
(declaration-indent (and js2-pretty-multiline-declarations
(js2-multiline-decl-indentation)))
(bracket (nth 1 parse-status))
beg indent)
(cond
;; indent array comprehension continuation lines specially
((and bracket
(>= js2-language-version 170)
(not (js2-same-line bracket))
(setq beg (js2-indent-in-array-comp parse-status))
(>= (point) (save-excursion
(goto-char beg)
(point-at-bol)))) ; at or after first loop?
(js2-array-comp-indentation parse-status beg))
((js2-ctrl-statement-indentation))
((and declaration-indent continued-expr-p)
(+ declaration-indent js2-basic-offset))
(declaration-indent)
(bracket
(goto-char bracket)
(cond
((looking-at "[({[][ \t]*\\(/[/*]\\|$\\)")
(when (save-excursion (skip-chars-backward " \t\n)")
(looking-at ")"))
(backward-list))
(back-to-indentation)
(js2-maybe-goto-declaration-keyword-end bracket)
(setq indent
(cond (same-indent-p
(current-column))
(continued-expr-p
(+ (current-column) (* 2 js2-basic-offset)))
(t
(+ (current-column) js2-basic-offset))))
(if (and js2-indent-switch-body
(not at-closing-bracket)
(looking-at "\\_<switch\\_>"))
(+ indent js2-basic-offset)
indent))
(t
(unless same-indent-p
(forward-char)
(skip-chars-forward " \t"))
(current-column))))
(continued-expr-p js2-basic-offset)
(t 0)))))
(defun js2--comment-indent (parse-status)
"Indentation inside a multi-line block comment continuation line."
(save-excursion
(goto-char (nth 8 parse-status))
(if (looking-at "/\\*")
(+ 1 (current-column))
0)))
(defun js2-indent-line (&optional bounce-backwards)
"Indent the current line as JavaScript source text."
(interactive)
(let (parse-status offset
;; Don't whine about errors/warnings when we're indenting.
;; This has to be set before calling parse-partial-sexp below.
(inhibit-point-motion-hooks t))
(setq parse-status (save-excursion
(syntax-ppss (point-at-bol)))
offset (- (point) (save-excursion
(back-to-indentation)
(point))))
;; Don't touch multiline strings.
(unless (nth 3 parse-status)
(indent-line-to (js2-proper-indentation parse-status))
(when (cl-plusp offset)
(forward-char offset)))))
;;; JSX Indentation
;; The following JSX indentation code is copied basically verbatim from js.el at
;; 958da7f, except that the prefixes on the functions/variables are changed.
(defsubst js2--jsx-find-before-tag ()
"Find where JSX starts.
Assume JSX appears in the following instances:
- Inside parentheses, when returned or as the first argument
to a function, and after a newline
- When assigned to variables or object properties, but only
on a single line
- As the N+1th argument to a function
This is an optimized version of (re-search-backward \"[(,]\n\"
nil t), except set point to the end of the match. This logic
executes up to the number of lines in the file, so it should be
really fast to reduce that impact."
(let (pos)
(while (and (> (point) (point-min))
(not (progn
(end-of-line 0)
(when (or (eq (char-before) 40) ; (
(eq (char-before) 44)) ; ,
(setq pos (1- (point))))))))
pos))
(defconst js2--jsx-end-tag-re
(concat "</" sgml-name-re ">\\|/>")
"Find the end of a JSX element.")
(defconst js2--jsx-after-tag-re "[),]"
"Find where JSX ends.
This complements the assumption of where JSX appears from
`js--jsx-before-tag-re', which see.")
(defun js2--jsx-indented-element-p ()
"Determine if/how the current line should be indented as JSX.
Return `first' for the first JSXElement on its own line.
Return `nth' for subsequent lines of the first JSXElement.
Return `expression' for an embedded JS expression.
Return `after' for anything after the last JSXElement.
Return nil for non-JSX lines.
Currently, JSX indentation supports the following styles:
- Single-line elements (indented like normal JS):
var element = <div></div>;
- Multi-line elements (enclosed in parentheses):
function () {
return (
<div>
<div></div>
</div>
);
}
- Function arguments:
React.render(
<div></div>,
document.querySelector('.root')
);"
(let ((current-pos (point))
(current-line (line-number-at-pos))
last-pos
before-tag-pos before-tag-line
tag-start-pos tag-start-line
tag-end-pos tag-end-line
after-tag-line
parens paren type)
(save-excursion
(and
;; Determine if we're inside a jsx element
(progn
(end-of-line)
(while (and (not tag-start-pos)
(setq last-pos (js2--jsx-find-before-tag)))
(while (forward-comment 1))
(when (= (char-after) 60) ; <
(setq before-tag-pos last-pos
tag-start-pos (point)))
(goto-char last-pos))
tag-start-pos)
(progn
(setq before-tag-line (line-number-at-pos before-tag-pos)
tag-start-line (line-number-at-pos tag-start-pos))
(and
;; A "before" line which also starts an element begins with js, so
;; indent it like js
(> current-line before-tag-line)
;; Only indent the jsx lines like jsx
(>= current-line tag-start-line)))
(cond
;; Analyze bounds if there are any
((progn
(while (and (not tag-end-pos)
(setq last-pos (re-search-forward js2--jsx-end-tag-re nil t)))
(while (forward-comment 1))
(when (looking-at js2--jsx-after-tag-re)
(setq tag-end-pos last-pos)))
tag-end-pos)
(setq tag-end-line (line-number-at-pos tag-end-pos)
after-tag-line (line-number-at-pos after-tag-line))
(or (and
;; Ensure we're actually within the bounds of the jsx
(<= current-line tag-end-line)
;; An "after" line which does not end an element begins with
;; js, so indent it like js
(<= current-line after-tag-line))
(and
;; Handle another case where there could be e.g. comments after
;; the element
(> current-line tag-end-line)
(< current-line after-tag-line)
(setq type 'after))))
;; They may not be any bounds (yet)
(t))
;; Check if we're inside an embedded multi-line js expression
(cond
((not type)
(goto-char current-pos)
(end-of-line)
(setq parens (nth 9 (syntax-ppss)))
(while (and parens (not type))
(setq paren (car parens))
(cond
((and (>= paren tag-start-pos)
;; Curly bracket indicates the start of an embedded expression
(= (char-after paren) 123) ; {
;; The first line of the expression is indented like sgml
(> current-line (line-number-at-pos paren))
;; Check if within a closing curly bracket (if any)
;; (exclusive, as the closing bracket is indented like sgml)
(cond
((progn
(goto-char paren)
(ignore-errors (let (forward-sexp-function)
(forward-sexp))))
(< current-line (line-number-at-pos)))
(t)))
;; Indicate this guy will be indented specially
(setq type 'expression))
(t (setq parens (cdr parens)))))
t)
(t))
(cond
(type)
;; Indent the first jsx thing like js so we can indent future jsx things
;; like sgml relative to the first thing
((= current-line tag-start-line) 'first)
('nth))))))
(defmacro js2--as-sgml (&rest body)
"Execute BODY as if in sgml-mode."
`(with-syntax-table sgml-mode-syntax-table
(let (forward-sexp-function
parse-sexp-lookup-properties)
,@body)))
(defun js2--expression-in-sgml-indent-line ()
"Indent the current line as JavaScript or SGML (whichever is farther)."
(let* (indent-col
(savep (point))
;; Don't whine about errors/warnings when we're indenting.
;; This has to be set before calling parse-partial-sexp below.
(inhibit-point-motion-hooks t)
(parse-status (save-excursion
(syntax-ppss (point-at-bol)))))
;; Don't touch multiline strings.
(unless (nth 3 parse-status)
(setq indent-col (save-excursion
(back-to-indentation)
(if (>= (point) savep) (setq savep nil))
(js2--as-sgml (sgml-calculate-indent))))
(if (null indent-col)
'noindent
;; Use whichever indentation column is greater, such that the sgml
;; column is effectively a minimum
(setq indent-col (max (js2-proper-indentation parse-status)
(+ indent-col js2-basic-offset)))
(if savep
(save-excursion (indent-line-to indent-col))
(indent-line-to indent-col))))))
(defun js2-jsx-indent-line ()
"Indent the current line as JSX (with SGML offsets).
i.e., customize JSX element indentation with `sgml-basic-offset'
et al."
(interactive)
(let ((indentation-type (js2--jsx-indented-element-p)))
(cond
((eq indentation-type 'expression)
(js2--expression-in-sgml-indent-line))
((or (eq indentation-type 'first)
(eq indentation-type 'after))
;; Don't treat this first thing as a continued expression (often a "<" or
;; ">" causes this misinterpretation)
(cl-letf (((symbol-function #'js2-continued-expression-p) 'ignore))
(js2-indent-line)))
((eq indentation-type 'nth)
(js2--as-sgml (sgml-indent-line)))
(t (js2-indent-line)))))
(provide 'js2-old-indent)
;;; js2-old-indent.el ends here
No preview for this file type
;;; rjsx-mode-autoloads.el --- automatically extracted autoloads
;;
;;; Code:
(add-to-list 'load-path (or (file-name-directory #$) (car load-path)))
;;;### (autoloads nil "rjsx-mode" "rjsx-mode.el" (22981 60721 372245
;;;;;; 990000))
;;; Generated autoloads from rjsx-mode.el
(autoload 'rjsx-mode "rjsx-mode" "\
Major mode for editing JSX files.
\(fn)" t nil)
(add-to-list 'auto-mode-alist '("\\.jsx\\'" . rjsx-mode))
;;;***
;; Local Variables:
;; version-control: never
;; no-byte-compile: t
;; no-update-autoloads: t
;; End:
;;; rjsx-mode-autoloads.el ends here
(define-package "rjsx-mode" "20170808.634" "Real support for JSX" '((emacs "24.4") (js2-mode "20170504")) :commit "4a24c86a1873289538134fe431e544fa3e12e788" :url "https://github.com/felipeochoa/rjsx-mode/" :keywords '("languages"))
No preview for this file type
;;; rjsx-mode.el --- Real support for JSX -*- lexical-binding: t -*-
;; Copyright (C) 2016 Felipe Ochoa
;; Author: Felipe Ochoa <felipe@fov.space>
;; URL: https://github.com/felipeochoa/rjsx-mode/
;; Package-Version: 20170808.634
;; Package-Requires: ((emacs "24.4") (js2-mode "20170504"))
;; Version: 1.1
;; Keywords: languages
;;; Commentary:
;; Defines a major mode `rjsx-mode' based on `js2-mode' for editing
;; JSX files. `rjsx-mode' extends the parser in `js2-mode' to support
;; the full JSX syntax. This means you get all of the `js2' features
;; plus proper syntax checking and highlighting of JSX code blocks.
;;
;; Some features that this mode adds to js2:
;;
;; - Highlighting JSX tag names and attributes (using the rjsx-tag and
;; rjsx-attr faces)
;; - Highlight undeclared JSX components
;; - Parsing the spread operator {...otherProps}
;; - Parsing && and || in child expressions {cond && <BigComponent/>}
;; - Parsing ternary expressions {toggle ? <ToggleOn /> : <ToggleOff />}
;;
;; Additionally, since rjsx-mode extends the js2 AST, utilities using
;; the parse tree gain access to the JSX structure.
;;; Code:
;;;; Basic mode definitions
(require 'cl-lib)
(require 'js2-mode)
(defgroup rjsx-mode nil
"Support for JSX."
:group 'js2-mode)
;;;###autoload
(define-derived-mode rjsx-mode js2-jsx-mode "RJSX"
"Major mode for editing JSX files."
:lighter ":RJSX"
:group 'rjsx-mode)
;;;###autoload
(add-to-list 'auto-mode-alist '("\\.jsx\\'" . rjsx-mode))
(defun rjsx-parse-xml-initializer (orig-fun)
"Dispatch the xml parser based on variable `rjsx-mode' being active or not.
This function is used to advise `js2-parse-xml-initializer' (ORIG-FUN) using
the `:around' combinator. JS2-PARSER is the original XML parser."
(if (eq major-mode 'rjsx-mode)
(rjsx-parse-top-xml)
(apply orig-fun nil)))
(advice-add 'js2-parse-xml-initializer :around #'rjsx-parse-xml-initializer)
(defun rjsx-unadvice-js2 ()
"Remove the rjsx advice on the js2 parser. This will cause rjsx to stop working globally."
(advice-remove 'js2-parse-xml-initializer #'rjsx-parse-xml-initializer))
(defface rjsx-tag
'((t . (:inherit font-lock-function-name-face)))
"`rjsx-mode' face used to highlight JSX tag names."
:group 'rjsx-mode)
(defface rjsx-attr
'((t . (:inherit font-lock-variable-name-face)))
"`rjsx-mode' face used to highlight JSX attribute names."
:group 'rjsx-mode)
(defface rjsx-text
'((t . (:inherit font-lock-string-face)))
"`rjsx-mode' face used to highlight JSX text."
:group 'rjsx-mode)
;;;; Parser constants struct definitions
;; Token types for XML nodes. We need to re-use some unused values to
;; not mess up the vectors that js2 has set up
(defvar rjsx-JSX js2-ENUM_INIT_KEYS)
(defvar rjsx-JSX-CLOSE js2-ENUM_INIT_VALUES)
(defvar rjsx-JSX-IDENT js2-ENUM_INIT_ARRAY)
(defvar rjsx-JSX-MEMBER js2-ENUM_NEXT)
(defvar rjsx-JSX-ATTR js2-ENUM_ID)
(defvar rjsx-JSX-SPREAD js2-REF_NS_MEMBER)
(defvar rjsx-JSX-TEXT js2-ESCXMLTEXT)
(defvar rjsx-JSX-EXPRESSION js2-ESCXMLATTR)
(dolist (sym '(rjsx-JSX rjsx-JSX-CLOSE rjsx-JSX-IDENT rjsx-JSX-MEMBER rjsx-JSX-ATTR
rjsx-JSX-SPREAD rjsx-JSX-TEXT rjsx-JSX-EXPRESSION))
(aset js2-token-names (symbol-value sym) (downcase (substring (symbol-name sym) 5)))
(puthash sym (symbol-value sym) js2-token-codes))
(js2-msg "msg.bad.jsx.ident" "invalid JSX identifier")
(js2-msg "msg.invalid.jsx.string" "invalid JSX string (cannot contain delimiter in string body)")
(js2-msg "msg.mismatched.close.tag" "mismatched closing JSX tag; expected `%s'")
(js2-msg "msg.no.gt.in.opener" "missing `>' in opening tag")
(js2-msg "msg.no.gt.in.closer" "missing `>' in closing tag")
(js2-msg "msg.no.gt.after.slash" "missing `>' after `/' in self-closing tag")
(js2-msg "msg.no.rc.after.spread" "missing `}' after spread-prop")
(js2-msg "msg.no.value.after.jsx.prop" "missing value after prop `%s'")
(js2-msg "msg.no.dots.in.prop.spread" "missing `...' in spread prop")
(js2-msg "msg.no.rc.after.expr" "missing `}' after expression")
(js2-msg "msg.empty.expr" "empty `{}' expression")
(cl-defstruct (rjsx-node
(:include js2-node (type rjsx-JSX))
(:constructor nil)
(:constructor make-rjsx-node
(&key (pos (js2-current-token-beg))
len
name
rjsx-props
kids)))
name ; AST node containing the parsed xml name
rjsx-props ; linked list of AST nodes (both attributes and spreads)
kids ; linked list of child xml nodes
closing-tag) ; AST node with the tag closer
(js2--struct-put 'rjsx-node 'js2-visitor 'rjsx-node-visit)
(js2--struct-put 'rjsx-node 'js2-printer 'rjsx-node-print)
(defun rjsx-node-visit (ast callback)
"Visit the `rjsx-node' children of AST, invoking CALLBACK on them."
(js2-visit-ast (rjsx-node-name ast) callback)
(dolist (prop (rjsx-node-rjsx-props ast))
(js2-visit-ast prop callback))
(dolist (prop (rjsx-node-kids ast))
(js2-visit-ast prop callback))
(when (rjsx-node-closing-tag ast)
(js2-visit-ast (rjsx-node-closing-tag ast) callback)))
(defun rjsx-node-print (node indent-level)
"Print the `rjsx-node' NODE at indent level INDENT-LEVEL."
(insert (js2-make-pad indent-level) "<")
(js2-print-ast (rjsx-node-name node) 0)
(dolist (attr (rjsx-node-rjsx-props node))
(insert " ")
(js2-print-ast attr 0))
(let ((closer (rjsx-node-closing-tag node)))
(if (null closer)
(insert "/>")
(insert ">")
(dolist (child (rjsx-node-kids node))
(js2-print-ast child 0))
(js2-print-ast closer indent-level))))
(defun rjsx-node-opening-tag-name (node)
"Return a string with NODE's opening tag including any namespace and member operations."
(let ((name-n (rjsx-node-name node)))
(cond
((rjsx-member-p name-n) (rjsx-member-full-name name-n))
((rjsx-identifier-p name-n) (rjsx-identifier-full-name name-n))
;; Otherwise it's either nil or an error. Either way, no name :(
(t ""))))
(defun rjsx-node-push-prop (n rjsx-prop)
"Extend rjsx-node N's rjsx-props with js2-node RJSX-PROP.
Sets JSX-PROPS's parent to N."
(let ((rjsx-props (rjsx-node-rjsx-props n)))
(if rjsx-props
(setcdr rjsx-props (nconc (cdr rjsx-props) (list rjsx-prop)))
(setf (rjsx-node-rjsx-props n) (list rjsx-prop))))
(js2-node-add-children n rjsx-prop))
(defun rjsx-node-push-child (n kid)
"Extend rjsx-node N's children with js2-node KID.
Sets KID's parent to N."
(let ((kids (rjsx-node-kids n)))
(if kids
(setcdr kids (nconc (cdr kids) (list kid)))
(setf (rjsx-node-kids n) (list kid))))
(js2-node-add-children n kid))
(cl-defstruct (rjsx-closing-tag
(:include js2-node (type rjsx-JSX-CLOSE))
(:constructor nil)
(:constructor make-rjsx-closing-tag (&key pos len name)))
name) ; A rjsx-identifier or rjsx-member node
(js2--struct-put 'rjsx-closing-tag 'js2-visitor 'rjsx-closing-tag-visit)
(js2--struct-put 'rjsx-closing-tag 'js2-printer 'rjsx-closing-tag-print)
(defun rjsx-closing-tag-visit (ast callback)
"Visit the `rjsx-closing-tag' children of AST, invoking CALLBACK on them."
(js2-visit-ast (rjsx-closing-tag-name ast) callback))
(defun rjsx-closing-tag-print (node indent-level)
"Print the `rjsx-closing-tag' NODE at INDENT-LEVEL."
(insert (js2-make-pad indent-level) "</" (rjsx-closing-tag-full-name node) ">"))
(defun rjsx-closing-tag-full-name (n)
"Return the string with N's fully-namespaced name, or just name if it's not namespaced."
(let ((child (rjsx-closing-tag-name n)))
(cond
((rjsx-member-p child) (rjsx-member-full-name child))
((rjsx-identifier-p child) (rjsx-identifier-full-name child))
(t ""))))
(cl-defstruct (rjsx-identifier
(:include js2-node (type rjsx-JSX-IDENT))
(:constructor nil)
(:constructor make-rjsx-identifier (&key (pos (js2-current-token-beg))
len namespace name)))
(namespace nil)
name) ; js2-name-node
(js2--struct-put 'rjsx-identifier 'js2-visitor 'js2-visit-none)
(js2--struct-put 'rjsx-identifier 'js2-printer 'rjsx-identifier-print)
(defun rjsx-identifier-print (node indent-level)
"Print the `rjsx-identifier' NODE at INDENT-LEVEL."
(insert (js2-make-pad indent-level) (rjsx-identifier-full-name node)))
(defun rjsx-identifier-full-name (n)
"Return the string with N's fully-namespaced name, or just name if it's not namespaced."
(if (rjsx-identifier-namespace n)
(format "%s:%s" (rjsx-identifier-namespace n) (js2-name-node-name (rjsx-identifier-name n)))
(js2-name-node-name (rjsx-identifier-name n))))
(cl-defstruct (rjsx-member
(:include js2-node (type rjsx-JSX-MEMBER))
(:constructor nil)
(:constructor make-rjsx-member (&key pos len dots-pos idents)))
dots-pos ; List of positions of each dot
idents) ; List of rjsx-identifier nodes
(js2--struct-put 'rjsx-member 'js2-visitor 'js2-visit-none)
(js2--struct-put 'rjsx-member 'js2-printer 'rjsx-member-print)
(defun rjsx-member-print (node indent-level)
"Print the `rjsx-member' NODE at INDENT-LEVEL."
(insert (js2-make-pad indent-level) (rjsx-member-full-name node)))
(defun rjsx-member-full-name (n)
"Return the string with N's combined names together."
(mapconcat 'rjsx-identifier-full-name (rjsx-member-idents n) "."))
(cl-defstruct (rjsx-attr
(:include js2-node (type rjsx-JSX-ATTR))
(:constructor nil)
(:constructor make-rjsx-attr (&key (pos (js2-current-token-beg))
len name value)))
name ; a rjsx-identifier
value) ; a js2-expression
(js2--struct-put 'rjsx-attr 'js2-visitor 'rjsx-attr-visit)
(js2--struct-put 'rjsx-attr 'js2-printer 'rjsx-attr-print)
(defun rjsx-attr-visit (ast callback)
"Visit the `rjsx-attr' children of AST, invoking CALLBACK on them."
(js2-visit-ast (rjsx-attr-name ast) callback)
(js2-visit-ast (rjsx-attr-value ast) callback))
(defun rjsx-attr-print (node indent-level)
"Print the `rjsx-attr' NODE at INDENT-LEVEL."
(js2-print-ast (rjsx-attr-name node) indent-level)
(unless (js2-empty-expr-node-p (rjsx-attr-value node))
(insert "=")
(js2-print-ast (rjsx-attr-value node) 0)))
(cl-defstruct (rjsx-spread
(:include js2-node (type rjsx-JSX-SPREAD))
(:constructor nil)
(:constructor make-rjsx-spread (&key pos len expr)))
expr) ; a js2-expression
(js2--struct-put 'rjsx-spread 'js2-visitor 'rjsx-spread-visit)
(js2--struct-put 'rjsx-spread 'js2-printer 'rjsx-spread-print)
(defun rjsx-spread-visit (ast callback)
"Visit the `rjsx-spread' children of AST, invoking CALLBACK on them."
(js2-visit-ast (rjsx-spread-expr ast) callback))
(defun rjsx-spread-print (node indent-level)
"Print the `rjsx-spread' NODE at INDENT-LEVEL."
(insert (js2-make-pad indent-level) "{...")
(js2-print-ast (rjsx-spread-expr node) 0)
(insert "}"))
(cl-defstruct (rjsx-wrapped-expr
(:include js2-node (type rjsx-JSX-TEXT))
(:constructor nil)
(:constructor make-rjsx-wrapped-expr (&key pos len child)))
child)
(js2--struct-put 'rjsx-wrapped-expr 'js2-visitor 'rjsx-wrapped-expr-visit)
(js2--struct-put 'rjsx-wrapped-expr 'js2-printer 'rjsx-wrapped-expr-print)
(defun rjsx-wrapped-expr-visit (ast callback)
"Visit the `rjsx-wrapped-expr' child of AST, invoking CALLBACK on them."
(js2-visit-ast (rjsx-wrapped-expr-child ast) callback))
(defun rjsx-wrapped-expr-print (node indent-level)
"Print the `rjsx-wrapped-expr' NODE at INDENT-LEVEL."
(insert (js2-make-pad indent-level) "{")
(js2-print-ast (rjsx-wrapped-expr-child node) indent-level)
(insert "}"))
(cl-defstruct (rjsx-text
(:include js2-node (type rjsx-JSX-TEXT))
(:constructor nil)
(:constructor make-rjsx-text (&key (pos (js2-current-token-beg))
(len (js2-current-token-len))
value)))
value) ; a string
(js2--struct-put 'rjsx-text 'js2-visitor 'js2-visit-none)
(js2--struct-put 'rjsx-text 'js2-printer 'rjsx-text-print)
(defun rjsx-text-print (node _indent-level)
"Print the `rjsx-text' NODE at INDENT-LEVEL."
;; Text nodes include whitespace
(insert (rjsx-text-value node)))
;;;; Recursive descent parsing
(defvar rjsx-print-debug-message nil "If t will print out debug messages.")
;(setq rjsx-print-debug-message t)
(defmacro rjsx-maybe-message (&rest args)
"If debug is enabled, call `message' with ARGS."
`(when rjsx-print-debug-message
(message ,@args)))
(js2-deflocal rjsx-in-xml nil "Variable used to track which xml parsing function is the outermost one.")
(defun rjsx-parse-top-xml ()
"Parse a top level XML fragment.
This is the entry point when ‘js2-parse-unary-expr’ finds a '<' character"
(rjsx-maybe-message "Parsing a new xml fragment%s" (if rjsx-in-xml ", recursively" ""))
;; If there are imbalanced tags, we just need to bail out to the
;; topmost JSX parser and let js2 handle the EOF. Our custom scanner
;; will throw `t' if it finds the EOF, which it ordinarily wouldn't
(let (pn)
(when (catch 'rjsx-eof-while-parsing
(let ((rjsx-in-xml t)) ;; We use dynamic scope to handle xml > expr > xml nestings
(setq pn (rjsx-parse-xml)))
nil)
(rjsx-maybe-message "Caught a signal. Rethrowing?: `%s'" rjsx-in-xml)
(if rjsx-in-xml
(throw 'rjsx-eof-while-parsing t)
;; We subtract 1 since js2 sets the cursor the the point after point-max
(setq pn (make-js2-error-node :len (1- (js2-current-token-len))))
(js2-report-error "msg.syntax" nil (js2-node-pos pn) (js2-node-len pn))))
(rjsx-maybe-message "Returning from top xml function: %s" pn)
pn))
(defun rjsx-parse-xml ()
"Parse a complete xml node from start to end tag."
(let ((pn (make-rjsx-node)) self-closing name-n name-str child child-name-str)
(rjsx-maybe-message "Starting rjsx-parse-xml after <")
(if (setq child (rjsx-parse-empty-tag))
child
(setf (rjsx-node-name pn) (setq name-n (rjsx-parse-member-or-ns 'rjsx-tag)))
(if (js2-error-node-p name-n)
(progn (rjsx-maybe-message "could not parse tag name")
(make-js2-error-node :pos (js2-node-pos pn) :len (1+ (js2-node-len name-n))))
(js2-node-add-children pn name-n)
(setq name-str (if (rjsx-member-p name-n) (rjsx-member-full-name name-n)
(rjsx-identifier-full-name name-n)))
(if js2-highlight-external-variables
(let ((name-node (rjsx-identifier-name
(if (rjsx-member-p name-n)
(car (rjsx-member-idents name-n))
name-n)))
(case-fold-search nil))
(when (string-match-p "^[[:upper:]]" (js2-name-node-name name-node))
(js2-record-name-node name-node))))
(rjsx-maybe-message "cleared tag name: '%s'" name-str)
;; Now parse the attributes
(rjsx-parse-attributes pn)
(rjsx-maybe-message "cleared attributes")
;; Now parse either a self closing tag or the end of the opening tag
(rjsx-maybe-message "next type: `%s'" (js2-peek-token))
(if (setq self-closing (js2-match-token js2-DIV))
(progn
(js2-record-text-property (js2-current-token-beg) (js2-current-token-end)
'rjsx-class 'self-closing-slash)
;; TODO: How do we un-mark old slashes?
(js2-must-match js2-GT "msg.no.gt.after.slash"
(js2-node-pos pn) (- (js2-current-token-end) (js2-node-pos pn))))
(js2-must-match js2-GT "msg.no.gt.in.opener" (js2-node-pos pn) (js2-node-len pn)))
(rjsx-maybe-message "cleared opener closer, self-closing: %s" self-closing)
(if self-closing
(setf (js2-node-len pn) (- (js2-current-token-end) (js2-node-pos pn)))
(while (not (rjsx-closing-tag-p (setq child (rjsx-parse-child))))
;; rjsx-parse-child calls our scanner, which always moves
;; forward at least one character. If it hits EOF, it
;; signals to our caller, so we don't have to worry about infinite loops here
(rjsx-maybe-message "parsed child")
(rjsx-node-push-child pn child)
(if (= 0 (js2-node-len child)) ; TODO: Does this ever happen?
(js2-get-token)))
(setq child-name-str (rjsx-closing-tag-full-name child))
(unless (string= name-str child-name-str)
(js2-report-error "msg.mismatched.close.tag" name-str (js2-node-pos child) (js2-node-len child)))
(rjsx-maybe-message "cleared children for `%s'" name-str)
(js2-node-add-children pn child)
(setf (rjsx-node-closing-tag pn) child))
(rjsx-maybe-message "Returning completed XML node")
(setf (js2-node-len pn) (- (js2-current-token-end) (js2-node-pos pn)))
pn))))
(defun rjsx-parse-empty-tag ()
"Check if we are in an empty tag of the form `</>' and consume it if so.
Returns a `js2-error-node' if we are in one or nil if not."
(let ((beg (js2-current-token-beg)))
(when (js2-match-token js2-DIV)
(if (js2-match-token js2-GT)
(progn ; We're in a </> block, likely created by us in `rjsx-electric-lt'
;; We only highlight the < to reduce the visual impact
(js2-report-error "msg.syntax" nil beg 1)
(make-js2-error-node :pos beg :len (- (js2-current-token-end) beg)))
;; TODO: This is probably an unmatched closing tag. We should
;; consume it, mark it an error, and move on
(js2-unget-token)
nil))))
(defun rjsx-parse-attributes (parent)
"Parse all attributes, including key=value and {...spread}, and add them to PARENT."
;; Getting this function to not hang in the loop proved tricky. The
;; key is that `rjsx-parse-spread' and `rjsx-parse-single-attr' both
;; return `js2-error-node's if they fail to consume any tokens,
;; which signals to us that we just need to discard one token and
;; keep going.
(let (attr
(loop-terminators (list js2-DIV js2-GT js2-EOF js2-ERROR)))
(while (not (memql (js2-peek-token) loop-terminators))
(rjsx-maybe-message "Starting loop. Next token type: %s\nToken pos: %s" (js2-peek-token) (js2-current-token-beg))
(setq attr
(if (js2-match-token js2-LC)
(or (rjsx-check-for-empty-curlies t)
(prog1 (rjsx-parse-spread)
(rjsx-maybe-message "Parsed spread")))
(rjsx-maybe-message "Parsing single attr")
(rjsx-parse-single-attr)))
(when (js2-error-node-p attr) (js2-get-token))
; TODO: We should make this conditional on
; `js2-recover-from-parse-errors'
(rjsx-node-push-prop parent attr))))
(cl-defun rjsx-check-for-empty-curlies (&optional dont-consume-rc &key check-for-comments warning)
"If the following token is '}' set empty curly errors.
If DONT-CONSUME-RC is non-nil, the matched right curly token
won't be consumed. Returns a `js2-error-node' if the curlies are
empty or nil otherwise. If CHECK-FOR-COMMENTS (a &KEY argument)
is non-nil, this will check for comments inside the curlies and
returns a `js2-empty-expr-node' if any are found. If WARNING (a
&key argument) is non-nil, reports the empty curlies as a warning
and not an error and also returns a `js2-empty-expr-node'.
Assumes the current token is a '{'."
(let ((beg (js2-current-token-beg)) end len)
(when (js2-match-token js2-RC)
(setq end (js2-current-token-end))
(setq len (- end beg))
(when dont-consume-rc
(js2-unget-token))
(if check-for-comments (rjsx-maybe-message "Checking for comments between %d and %d" beg end))
(unless (and check-for-comments
(dolist (comment js2-scanned-comments)
(rjsx-maybe-message "Comment at %d, length=%d"
(js2-node-pos comment)
(js2-node-len comment))
;; TODO: IF comments are in reverse document order, we should be able to
;; bail out early and know we didn't find one
(when (and (>= (js2-node-pos comment) beg)
(<= (+ (js2-node-pos comment) (js2-node-len comment)) end))
(cl-return-from rjsx-check-for-empty-curlies
(make-js2-empty-expr-node :pos beg :len (- end beg))))))
(if warning
(progn (js2-report-warning "msg.empty.expr" nil beg len)
(make-js2-empty-expr-node :pos beg :len (- end beg)))
(js2-report-error "msg.empty.expr" nil beg len)
(make-js2-error-node :pos beg :len len))))))
(defun rjsx-parse-spread ()
"Parse an {...props} attribute."
(let ((pn (make-rjsx-spread :pos (js2-current-token-beg)))
(beg (js2-current-token-beg))
missing-dots expr)
(setq missing-dots (not (js2-match-token js2-TRIPLEDOT)))
;; parse-assign-expr will go crazy if we're looking at `} /', so we
;; check for an empty spread first
(if (js2-match-token js2-RC)
(setq expr (make-js2-error-node :len 1))
(setq expr (js2-parse-assign-expr))
(when (js2-error-node-p expr)
(pop js2-parsed-errors))) ; We'll add our own error
(unless (or (js2-match-token js2-RC) (js2-error-node-p expr))
(js2-report-error "msg.no.rc.after.spread" nil
beg (- (js2-current-token-end) beg)))
(setf (rjsx-spread-expr pn) expr)
(setf (js2-node-len pn) (- (js2-current-token-end) (js2-node-pos pn)))
(js2-node-add-children pn expr)
(if (js2-error-node-p expr)
(js2-report-error "msg.syntax" nil beg (- (js2-current-token-end) beg))
(when missing-dots
(js2-report-error "msg.no.dots.in.prop.spread" nil beg (js2-node-len pn))))
(if (= 0 (js2-node-len pn)) ; TODO: Is this ever possible?
(make-js2-error-node :pos beg :len 0)
pn)))
(defun rjsx-parse-single-attr ()
"Parse an 'a=b' JSX attribute and return the corresponding XML node."
(let ((pn (make-rjsx-attr)) name value beg)
(setq name (rjsx-parse-identifier 'rjsx-attr)) ; Won't consume token on error
(if (js2-error-node-p name)
name
(setf (rjsx-attr-name pn) name)
(setq beg (js2-node-pos name))
(js2-node-add-children pn name)
(rjsx-maybe-message "Got the name for the attr: `%s'" (rjsx-identifier-full-name name))
(if (js2-match-token js2-ASSIGN) ; Won't consume on error
(progn
(rjsx-maybe-message "Matched the equals sign")
(if (js2-match-token js2-LC)
(setq value (rjsx-parse-wrapped-expr nil t))
(if (js2-match-token js2-STRING)
(setq value (rjsx-parse-string))
(js2-report-error "msg.no.value.after.jsx.prop" (rjsx-identifier-full-name name)
beg (- (js2-current-token-end) beg))
(setq value (make-js2-error-node :pos beg :len (js2-current-token-len))))))
(setq value (make-js2-empty-expr-node :pos (js2-current-token-end) :len 0)))
(rjsx-maybe-message "value type: `%s'" (js2-node-type value))
(setf (rjsx-attr-value pn) value)
(setf (js2-node-len pn) (- (js2-node-end value) (js2-node-pos pn)))
(js2-node-add-children pn value)
(rjsx-maybe-message "Finished single attribute.")
pn)))
(defun rjsx-parse-wrapped-expr (allow-empty skip-to-rc)
"Parse a curly-brace-wrapped JS expression.
If ALLOW-EMPTY is non-nil, will warn for empty braces, otherwise
will signal a syntax error. If it does not find a right curly
and SKIP-TO-RC is non-nil, after the expression, consumes tokens
until the end of the JSX node"
(rjsx-maybe-message "parsing wrapped expression")
(let (pn
(beg (js2-current-token-beg))
(child (rjsx-check-for-empty-curlies nil
:check-for-comments allow-empty
:warning allow-empty)))
(if child
(if allow-empty
(make-rjsx-wrapped-expr :pos beg :len (js2-node-len child) :child child)
child) ;; Will be an error node in this case
(setq child (js2-parse-assign-expr))
(rjsx-maybe-message "parsed expression, type: `%s'" (js2-node-type child))
(setq pn (make-rjsx-wrapped-expr :pos beg :child child))
(js2-node-add-children pn child)
(when (js2-error-node-p child)
(pop js2-parsed-errors)) ; We'll record our own message after checking for RC
(if (js2-match-token js2-RC)
(rjsx-maybe-message "matched } after expression")
(rjsx-maybe-message "did not match } after expression")
(when skip-to-rc
(while (not (memql (js2-get-token) (list js2-RC js2-EOF js2-DIV js2-GT)))
(rjsx-maybe-message "Skipped over `%s'" (js2-current-token-string)))
(when (memq (js2-current-token-type) (list js2-DIV js2-GT))
(js2-unget-token)))
(unless (js2-error-node-p child)
(js2-report-error "msg.no.rc.after.expr" nil beg
(- (js2-current-token-beg) beg))))
(when (js2-error-node-p child)
(js2-report-error "msg.syntax" nil beg (- (js2-current-token-end) beg)))
(setf (js2-node-len pn) (- (js2-current-token-end) beg))
pn)))
(defun rjsx-parse-string ()
"Verify that current token is a valid JSX string.
Returns a `js2-error-node' if TOKEN-STRING is not a valid JSX
string, otherwise returns a `js2-string-node'. (Strings are
invalid if they contain the delimiting quote character inside)"
(rjsx-maybe-message "Parsing string")
(let* ((token (js2-current-token))
(beg (js2-token-beg token))
(len (- (js2-token-end token) beg))
(token-string (js2-token-string token)) ;; JS2 does not include the quote-chars
(quote-char (char-before (js2-token-end token))))
(if (cl-position quote-char token-string)
(progn
(js2-report-error "msg.invalid.jsx.string" nil beg len)
(make-js2-error-node :pos beg :len len))
(make-js2-string-node :pos beg :len len :value token-string))))
(cl-defun rjsx-parse-identifier (&optional face &key (allow-ns t))
"Parse a possibly namespaced identifier and fontify with FACE if given.
Returns a `js2-error-node' if unable to parse. If the &key
argument ALLOW-NS is nil, does not allow namespaced names."
(if (js2-must-match-name "msg.bad.jsx.ident")
(let ((pn (make-rjsx-identifier))
(beg (js2-current-token-beg))
(name-parts (list (js2-current-token-string)))
(allow-colon allow-ns)
(continue t)
(prev-token-end (js2-current-token-end))
(name-start (js2-current-token-beg))
matched-colon)
(while (and continue
(or (and (memq (js2-peek-token) (list js2-SUB js2-ASSIGN_SUB))
(prog2 ; Ensure no whitespace between previous name and this dash
(js2-get-token)
(eq prev-token-end (js2-current-token-beg))
(js2-unget-token)))
(and allow-colon (= (js2-peek-token) js2-COLON))))
(if (setq matched-colon (js2-match-token js2-COLON))
(setf (rjsx-identifier-namespace pn) (apply #'concat (nreverse name-parts))
allow-colon nil
name-parts (list)
name-start nil)
(when (= (js2-get-token) js2-ASSIGN_SUB) ; Otherwise it's a js2-SUB
(setf (js2-token-end (js2-current-token)) (1- (js2-current-token-end))
(js2-token-type (js2-current-token)) js2-SUB
(js2-token-string (js2-current-token)) "-"
js2-ts-cursor (1+ (js2-current-token-beg))
js2-ti-lookahead 0))
(push "-" name-parts))
(setq prev-token-end (js2-current-token-end))
(if (js2-match-token js2-NAME)
(if (eq prev-token-end (js2-current-token-beg))
(progn (push (js2-current-token-string) name-parts)
(setq prev-token-end (js2-current-token-end)
name-start (or name-start (js2-current-token-beg))))
(js2-unget-token)
(setq continue nil))
(when (= js2-COLON (js2-current-token-type))
(js2-report-error "msg.bad.jsx.ident" nil beg (- (js2-current-token-end) beg)))
;; We only keep going if this is an `ident-ending-with-dash-colon:'
(setq continue (and (not matched-colon) (= (js2-peek-token) js2-COLON)))))
(when face
(js2-set-face beg (js2-current-token-end) face 'record))
(setf (js2-node-len pn) (- (js2-current-token-end) beg)
(rjsx-identifier-name pn) (if name-start
(make-js2-name-node :pos name-start
:len (- (js2-current-token-end) name-start)
:name (apply #'concat (nreverse name-parts)))
(make-js2-name-node :pos (js2-current-token-end) :len 0 :name "")))
pn)
(make-js2-error-node :len (js2-current-token-len))))
(defun rjsx-parse-member-or-ns (&optional face)
"Parse a dotted expression or a namespaced identifier and fontify with FACE if given."
(let ((ident (rjsx-parse-identifier face)))
(cond
((js2-error-node-p ident) ident)
((rjsx-identifier-namespace ident) ident)
(t (rjsx-parse-member ident face)))))
(defun rjsx-parse-member (ident &optional face)
"Parse a dotted member expression starting with IDENT and fontify with FACE.
IDENT is the `rjsx-identifier' node for the first item in the
member expression. Returns a `js2-error-node' if unable to
parse."
(let (idents dots-pos pn end)
(setq pn (make-rjsx-member :pos (js2-node-pos ident)))
(setq end (js2-current-token-end))
(push ident idents)
(while (and (js2-match-token js2-DOT) (not (js2-error-node-p ident)))
(push (js2-current-token-beg) dots-pos)
(setq end (js2-current-token-end))
(setq ident (rjsx-parse-identifier nil :allow-ns nil))
(push ident idents)
(unless (js2-error-node-p ident)
(setq end (js2-current-token-end)))
(js2-node-add-children pn ident))
(setf (rjsx-member-idents pn) (nreverse idents)
(rjsx-member-dots-pos pn) (nreverse dots-pos)
(js2-node-len pn) (- end (js2-node-pos pn)))
(when face
(js2-set-face (js2-node-pos pn) end face 'record))
pn))
(defun rjsx-parse-child ()
"Parse an XML child node.
Child nodes include plain (unquoted) text, other XML elements,
and {}-bracketed expressions. Return the parsed child."
(let ((tt (rjsx-get-next-xml-token)))
(rjsx-maybe-message "child type `%s'" tt)
(cond
((= tt js2-LT)
(rjsx-maybe-message "xml-or-close")
(rjsx-parse-xml-or-closing-tag))
((= tt js2-LC)
(rjsx-maybe-message "parsing expression { %s" (js2-peek-token))
(rjsx-parse-wrapped-expr t nil))
((= tt rjsx-JSX-TEXT)
(rjsx-maybe-message "text node: '%s'" (js2-current-token-string))
(js2-set-face (js2-current-token-beg) (js2-current-token-end) 'rjsx-text 'record)
(js2-record-text-property (js2-current-token-beg) (js2-current-token-end)
'syntax-table (standard-syntax-table))
(make-rjsx-text :value (js2-current-token-string)))
((= tt js2-ERROR)
(make-js2-error-node :len (js2-current-token-len)))
(t (error "Unexpected token type: %s" (js2-peek-token))))))
(defun rjsx-parse-xml-or-closing-tag ()
"Parse a JSX tag, which could be a child or a closing tag.
Return the parsed child, which is a `rjsx-closing-tag' if a
closing tag was parsed."
(let ((beg (js2-current-token-beg)) pn)
(if (setq pn (rjsx-parse-empty-tag))
pn
(if (js2-match-token js2-DIV)
(progn (setq pn (make-rjsx-closing-tag :pos beg :name (rjsx-parse-member-or-ns 'rjsx-tag)))
(if (js2-must-match js2-GT "msg.no.gt.in.closer" beg (- (js2-current-token-end) beg))
(rjsx-maybe-message "parsed closing tag")
(rjsx-maybe-message "missing closing `>'"))
(setf (js2-node-len pn) (- (js2-current-token-end) beg))
pn)
(rjsx-maybe-message "parsing a child XML item")
(rjsx-parse-xml)))))
(defun rjsx-get-next-xml-token ()
"Scan through the XML text and push one token onto the stack."
(setq js2-ts-string-buffer nil) ; for recording the text
(when (> js2-ti-lookahead 0)
(setq js2-ts-cursor (js2-current-token-end))
(setq js2-ti-lookahead 0))
(let ((token (js2-new-token 0))
c)
(rjsx-maybe-message "Running the xml scanner")
(catch 'return
(while t
(setq c (js2-get-char))
(rjsx-maybe-message "'%s' (%s)" (if (= c js2-EOF_CHAR) "EOF" (char-to-string c)) c)
(cond
((or (= c ?}) (= c ?>))
(js2-set-string-from-buffer token)
(setf (js2-token-type token) js2-ERROR)
(js2-report-scan-error "msg.syntax" t)
(throw 'return js2-ERROR))
((or (= c ?<) (= c ?{))
(js2-unget-char)
(if js2-ts-string-buffer
(progn
(js2-set-string-from-buffer token)
(setf (js2-token-type token) rjsx-JSX-TEXT)
(rjsx-maybe-message "created rjsx-JSX-TEXT token: `%s'" (js2-token-string token))
(throw 'return rjsx-JSX-TEXT))
(js2-get-char)
(js2-set-string-from-buffer token)
(setf (js2-token-type token) (if (= c ?<) js2-LT js2-LC))
(setf (js2-token-string token) (string c))
(throw 'return (js2-token-type token))))
((= c js2-EOF_CHAR)
(js2-set-string-from-buffer token)
(rjsx-maybe-message "Hit EOF. Current buffer: `%s'" (js2-token-string token))
(setf (js2-token-type token) js2-ERROR)
(rjsx-maybe-message "Scanner hit EOF. Panic!")
(throw 'rjsx-eof-while-parsing t))
(t (js2-add-to-string c)))))))
(defun rjsx--tag-at-point ()
"Return the JSX tag at point, if any, or nil."
(let ((node (js2-node-at-point (point) t)))
(while (and node (not (rjsx-node-p node)))
(setq node (js2-node-parent node)))
node))
;;;; Interactive commands and keybindings
(defun rjsx-electric-lt (n)
"Insert a context-sensitive less-than sign.
Optional prefix argument N indicates how many signs to insert.
If N is greater than one, no special handling takes place.
Otherwise, if the less-than sign would start a JSX block, it
inserts `< />' and places the cursor inside the new tag."
(interactive "p")
(if (/= n 1)
(insert (make-string n "<"))
(let ((inhibit-changing-match-data t))
(if (looking-back (rx (or "=" "(" "?" ":" ">" "}" "&" "|" "{" ","
"return")
(zero-or-more (or "\n" space)))
(point-at-bol -2))
(progn (insert "</>")
(backward-char 2))
(insert "<")))))
(define-key rjsx-mode-map "<" 'rjsx-electric-lt)
(defun rjsx-delete-creates-full-tag (n &optional killflag)
"N and KILLFLAG are as in `delete-char'.
If N is 1 and KILLFLAG nil, checks to see if we're in a
self-closing tag about to delete the slash. If so, deletes the
slash and inserts a matching end-tag."
(interactive "p")
(if (or killflag (/= 1 n) (not (eq (get-char-property (point) 'rjsx-class) 'self-closing-slash)))
(if (called-interactively-p 'any)
(call-interactively 'delete-forward-char)
(delete-char n killflag))
(let ((node (rjsx--tag-at-point)))
(if node
(progn
(delete-char 1)
(search-forward ">" )
(save-excursion
(insert "</" (rjsx-node-opening-tag-name node) ">")))
(delete-char 1)))))
(define-key rjsx-mode-map (kbd "C-d") 'rjsx-delete-creates-full-tag)
(defun rjsx-rename-tag-at-point (new-name)
"Prompt for a new name and modify the tag at point.
NEW-NAME is the name to give the tag."
(interactive "sNew tag name: ")
(let ((tag (rjsx--tag-at-point)) closer)
(if tag
(let* ((head (rjsx-node-name tag))
(tail (when (setq closer (rjsx-node-closing-tag tag)) (rjsx-closing-tag-name closer)))
beg end)
(dolist (part (if tail (list tail head) (list head)))
(setq beg (js2-node-abs-pos part)
end (+ beg (js2-node-len part)))
(delete-region beg end)
(save-excursion (goto-char beg) (insert new-name)))
(js2-reparse))
(message "No JSX tag found at point"))))
(define-key rjsx-mode-map (kbd "C-c C-r") 'rjsx-rename-tag-at-point)
(provide 'rjsx-mode)
;;; rjsx-mode.el ends here
;; Local Variables:
;; outline-regexp: ";;;\\(;* [^
;; ]\\|###autoload\\)\\|(....."
;; End:
No preview for this file type