Personal emacs config
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
2.0 KiB

  1. ;;; js2r-conditionals.el --- Conditional refactoring functions for js2-refactor -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2012-2014 Magnar Sveen
  3. ;; Copyright (C) 2015-2016 Magnar Sveen and Nicolas Petton
  4. ;; Author: Magnar Sveen <magnars@gmail.com>,
  5. ;; Nicolas Petton <nicolas@petton.fr>
  6. ;; Keywords: conveniences
  7. ;; This program is free software; you can redistribute it and/or modify
  8. ;; it under the terms of the GNU General Public License as published by
  9. ;; the Free Software Foundation, either version 3 of the License, or
  10. ;; (at your option) any later version.
  11. ;; This program is distributed in the hope that it will be useful,
  12. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. ;; GNU General Public License for more details.
  15. ;; You should have received a copy of the GNU General Public License
  16. ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. ;;; Code:
  18. (require 's)
  19. (defun js2r-ternary-to-if ()
  20. "Convert a ternary operator to an if-statement."
  21. (interactive)
  22. (js2r--guard)
  23. (save-excursion
  24. (let* ((ternary (js2r--closest 'js2-cond-node-p))
  25. (test-expr (js2-node-string (js2-cond-node-test-expr ternary)))
  26. (true-expr (js2-node-string (js2-cond-node-true-expr ternary)))
  27. (false-expr (js2-node-string (js2-cond-node-false-expr ternary)))
  28. (stmt (js2-node-parent-stmt ternary))
  29. (stmt-pre (buffer-substring (js2-node-abs-pos stmt) (js2-node-abs-pos ternary)))
  30. (stmt-post (s-trim (buffer-substring (js2-node-abs-end ternary) (js2-node-abs-end stmt))))
  31. (beg (js2-node-abs-pos stmt)))
  32. (goto-char beg)
  33. (delete-char (js2-node-len stmt))
  34. (insert "if (" test-expr ") {")
  35. (newline)
  36. (insert stmt-pre true-expr stmt-post)
  37. (newline)
  38. (insert "} else {")
  39. (newline)
  40. (insert stmt-pre false-expr stmt-post)
  41. (newline)
  42. (insert "}")
  43. (indent-region beg (point)))))
  44. (provide 'js2r-conditionals)
  45. ;;; js2r-conditionals ends here