Skip to content

Instantly share code, notes, and snippets.

@ifree
Created June 23, 2014 18:04
Show Gist options
  • Save ifree/dd6a94b3a369a4b07ba6 to your computer and use it in GitHub Desktop.
Save ifree/dd6a94b3a369a4b07ba6 to your computer and use it in GitHub Desktop.
eplace array expression with real value
(defun js2-remap-array ()
"replace array expression with real value, eg. arr[1] into 123"
(interactive)
(let*
(
(node (js2-node-at-point))
(current-start (js2-node-abs-pos node))
(current-pos current-start)
(offset 0)
(elems (js2-array-to-list node))
(pattern (concat (js2-name-node-name node) "\\[\\(\[0-9\]+\\)\\]"))
)
(save-excursion
(mapc (lambda (x)
(when (not (= x current-start))
(if (> x current-pos)
(goto-char (+ offset x))
(goto-char x))
(setq current-pos (point))
(when (search-forward-regexp pattern nil t)
(let* ((content (match-string-no-properties 0))
(index (string-to-number (match-string-no-properties 1)))
(replacement (nth index elems))
)
(goto-char current-pos)
(setq offset (- (length content) (length replacement)))
(delete-region current-pos
(+ current-pos (length content)))
; (print `(,index ,replacement ,content))
(insert replacement)))))
(js2r--local-var-positions node)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment