js-emacs / js2-refactor.el

A JavaScript refactoring library for emacs
GNU General Public License v3.0
373 stars 47 forks source link

Add js2r-string-to-single-quote and js2r-string-to-double-quote #118

Open Zirak opened 5 years ago

Zirak commented 5 years ago

Allows converting a string to single-quote and double-quote delimiters, not just template strings.

Zirak commented 5 years ago

As an added bonus, this does something cute (I hope?) of unescaping the original delimiter. e.g.

var foo = "I will not buy this tobacconist's, it is scratched.";
// js2r-string-to-single-quote
var foo = 'I will not buy this tobacconist\'s, it is scratched.';
// notice the added escape, as js2r previously did with `, but now!
// js2r-string-to-double-quote
var foo = "I will not buy this tobacconist's, it is scratched.";
// we got rid of the escape, howdy ho!
NicolasPetton commented 5 years ago

Thanks a lot for the PR!

I like what it does, but it would be even nicer IMO if it was js2r-string-toggle-single-quote. js2r could detect if the string at point has single or double quotes and do the right thing. What do you think?

ArneBab commented 3 years ago

I think from the keymap it makes sense to keep this as it is: C RET st for template, C RET s' for single-quote, and C RET s" for double-quote.

sandinmyjoints commented 1 year ago

I've seen similar sorts of cases handled by cycle functions, something like js2r-cycle-string-literal-type that would go from single -> double -> template -> single etc. when invoked. Seems like a nice way to handle it to me.

sandinmyjoints commented 1 year ago

Here's my quick stab at it, making use of this PR's js2r--convert-string-delimiter:

(defun js2r-cycle-string-literal-type ()
  "Cycle: single -> double -> template -> single, etc."
  (interactive)
  (let ((node (js2-node-at-point)))
    (when (js2-string-node-p node)
      (let* ((start (js2-node-abs-pos node))
             (prev-delim (char-after start)))
        (pcase prev-delim
          (?' (js2r--convert-string-delimiter "\""))
          (?\" (js2r--convert-string-delimiter "`"))
          (?` (js2r--convert-string-delimiter "'")))))))