Variables in "if" statements?


#1

I’m trying to put the awesome actions created by @agiletortoise for wrapping text in various symbols into a single action with a prompt menu. But I can’t figure out how to assign the variables based on the buttons selected. The following script sort of works, it just always wraps the text in parentheses no matter what button is pressed. I understand this is because the “var” isn’t getting reset with each if statement, but I don’t know enough about scripting to know why, or how to repair it.

var range = editor.getSelectedRange();
var priorText = editor.getTextInRange(0, range[0]);

var p = Prompt.create();

p. title = "Wrap Text";
p.message = "Choose symbol to wrap text";

p.addButton("Parentheses");
p.addButton("Braces");
p.addButton("Double Quotes");
p.addButton("Single Quotes");
p.addButton("Square Brackets");
p.addButton("Angle Brackets");

if (p.show("Parentheses")) {
  var open="(";
  var close=")";
  }
else if (p.show("Braces")) {
  var open = "{";
  var close = "}";
  }
else if (p.show("Double Quotes")) {
  var open = "\x22";
  var close = "\x22";
  }
else if (p.show("Single Quotes")) {
  var open = "\x27";
  var close = "\x27";
  }
else if (p.show("Square Brackets")) {
  var open = "[";
  var close = "]";
  }
else if (p.show("Angle Brackets")) {
  var open = "<";
  var close = ">";
}

if (range[1] > 0) {
 //text selected, wrap it!
 editor.setSelectedText(open + editor.getSelectedText() + close);
 editor.setSelectedRange(range[0] + range[1] + open.length + close.length, 0);
}
else {
 // no selection, find last
 var lastOpen = priorText.lastIndexOf(open);
 var lastClose = priorText.lastIndexOf(close);

 if	(lastOpen == -1 || lastClose > lastOpen) { // no close, use open
   editor.setSelectedText(open);
   editor.setSelectedRange(range[0]+open.length, 0);
 }
 else { // close last open
   editor.setSelectedText(close);
   editor.setSelectedRange(range[0]+close.length, 0);
 }
}

#2

Try:

p.show();
if (p.buttonPressed == "Braces") {
...
}

#3

That did it. Thanks!

Here’s the action: https://actions.getdrafts.com/a/1Q8