PageRenderTime 49ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/www/tags/NOV_07_2009/htdocs/users-guide/macro-tips-input.html

#
HTML | 294 lines | 272 code | 22 blank | 0 comment | 0 complexity | 8ebf5063dcc3e53663d7e2c25d86fd81 MD5 | raw file
Possible License(s): BSD-3-Clause, AGPL-1.0, Apache-2.0, LGPL-2.0, LGPL-3.0, GPL-2.0, CC-BY-SA-3.0, LGPL-2.1, GPL-3.0, MPL-2.0-no-copyleft-exception, IPL-1.0
  1. <html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Getting Input for a Macro</title><meta name="generator" content="DocBook XSL Stylesheets V1.73.2"><link rel="start" href="index.html" title="jEdit 4.3 User's Guide"><link rel="up" href="macro-tips.html" title="Chapter 15. Macro Tips and Techniques"><link rel="prev" href="macro-tips.html" title="Chapter 15. Macro Tips and Techniques"><link rel="next" href="startup-scripts.html" title="Startup Scripts"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">Getting Input for a Macro</th></tr><tr><td width="20%" align="left"><a accesskey="p" href="macro-tips.html">Prev</a> </td><th width="60%" align="center">Chapter 15. Macro Tips and Techniques</th><td width="20%" align="right"> <a accesskey="n" href="startup-scripts.html">Next</a></td></tr></table><hr></div><div class="sect1" lang="en"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="macro-tips-input"></a>Getting Input for a Macro</h2></div></div></div><p>The dialog-based macro discussed in <a class="xref" href="dialog-macro.html" title="Chapter 14. A Dialog-Based Macro">Chapter 14, <i>A Dialog-Based Macro</i></a> reflects a conventional approach to obtaining
  2. input in a Java program. Nevertheless, it can be too lengthy or tedious
  3. for someone trying to write a macro quickly. Not every macro needs a
  4. user interface specified in such detail; some macros require only a
  5. single keystroke or no input at all. In this section we outline some
  6. other techniques for obtaining input that will help you write macros
  7. quickly.</p><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="macro-tips-input-single-line"></a>Getting a Single Line of Text</h3></div></div></div><p>As mentioned earlier in <a class="xref" href="helpful-methods.html" title="Helpful Methods in the Macros Class">the section called &#8220;Helpful Methods in the Macros Class&#8221;</a>,
  8. the method <code class="function">Macros.input()</code> offers a convenient
  9. way to obtain a single line of text input. Here is an example that
  10. inserts a pair of HTML markup tags specified by the user.</p><div class="informalexample"><pre class="programlisting">// Insert_Tag.bsh
  11. void insertTag()
  12. {
  13. caret = textArea.getCaretPosition();
  14. tag = Macros.input(view, &#8220;<span class="quote">Enter name of tag:</span>&#8221;);
  15. if( tag == null || tag.length() == 0) return;
  16. text = textArea.getSelectedText();
  17. if(text == null) text = &#8220;<span class="quote"></span>&#8221;;
  18. sb = new StringBuffer();
  19. sb.append(&#8220;<span class="quote">&lt;</span>&#8221;).append(tag).append(&#8220;<span class="quote">&gt;</span>&#8221;);
  20. sb.append(text);
  21. sb.append(&#8220;<span class="quote">&lt;/</span>&#8221;).append(tag).append(&#8220;<span class="quote">&gt;</span>&#8221;);
  22. textArea.setSelectedText(sb.toString());
  23. if(text.length() == 0)
  24. textArea.setCaretPosition(caret + tag.length() + 2);
  25. }
  26. insertTag();
  27. // end Insert_Tag.bsh</pre></div><p>Here the call to <code class="function">Macros.input()</code> seeks the
  28. name of the markup tag. This method sets the message box title to a
  29. fixed string, &#8220;<span class="quote">Macro input</span>&#8221;, but the specific message
  30. <span class="guilabel"><strong>Enter name of tag</strong></span> provides all the information
  31. necessary. The return value <code class="varname">tag</code> must be tested to
  32. see if it is null. This would occur if the user presses the
  33. <span class="guilabel"><strong>Cancel</strong></span> button or closes the dialog window
  34. displayed by <code class="function">Macros.input()</code>.</p></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="macro-tips-input-multiple-data"></a>Getting Multiple Data Items</h3></div></div></div><p>If more than one item of input is needed, a succession of
  35. calls to <code class="function">Macros.input()</code> is a possible, but
  36. awkward approach, because it would not be possible to correct early
  37. input after the corresponding message box is dismissed. Where more
  38. is required, but a full dialog layout is either unnecessary or too
  39. much work, the Java method
  40. <code class="function">JOptionPane.showConfirmDialog()</code> is available.
  41. The version to use has the following prototype:</p><div class="itemizedlist"><ul type="disc"><li><div class="funcsynopsis"><table border="0" summary="Function synopsis" cellspacing="0" cellpadding="0"><tr><td><code class="funcdef">public static int
  42. <b class="fsfunc">showConfirmDialog</b>(</code></td><td>Component
  43.  </td><td><var class="pdparam">parentComponent</var>, </td></tr><tr><td> </td><td>Object
  44.  </td><td><var class="pdparam">message</var>, </td></tr><tr><td> </td><td>String
  45.  </td><td><var class="pdparam">title</var>, </td></tr><tr><td> </td><td>int
  46.  </td><td><var class="pdparam">optionType</var>, </td></tr><tr><td> </td><td>int
  47.  </td><td><var class="pdparam">messageType</var><code>)</code>;</td></tr></table></div></li></ul></div><p>The usefulness of this method arises from the fact that the
  48. <code class="varname">message</code> parameter can be an object of any Java
  49. class (since all classes are derived from
  50. <code class="classname">Object</code>), or any array of objects. The
  51. following example shows how this feature can be used.</p><div class="informalexample"><pre class="programlisting">// excerpt from Write_File_Header.bsh
  52. title = &#8220;<span class="quote">Write file header</span>&#8221;;
  53. currentName = buffer.getName();
  54. nameField = new JTextField(currentName);
  55. authorField = new JTextField(&#8220;<span class="quote">Your name here</span>&#8221;);
  56. descField = new JTextField(&#8220;<span class="quote"></span>&#8221;, 25);
  57. namePanel = new JPanel(new GridLayout(1, 2));
  58. nameLabel = new JLabel(&#8220;<span class="quote">Name of file:</span>&#8221;, SwingConstants.LEFT);
  59. saveField = new JCheckBox(&#8220;<span class="quote">Save file when done</span>&#8221;,
  60. !buffer.isNewFile());
  61. namePanel.add(nameLabel);
  62. namePanel.add(saveField);
  63. message = new Object[9];
  64. message[0] = namePanel;
  65. message[1] = nameField;
  66. message[2] = Box.createVerticalStrut(10);
  67. message[3] = &#8220;<span class="quote">Author's name:</span>&#8221;;
  68. message[4] = authorField;
  69. message[5] = Box.createVerticalStrut(10);
  70. message[6] = &#8220;<span class="quote">Enter description:</span>&#8221;;
  71. message[7] = descField;
  72. message[8] = Box.createVerticalStrut(5);
  73. if( JOptionPane.OK_OPTION !=
  74. JOptionPane.showConfirmDialog(view, message, title,
  75. JOptionPane.OK_CANCEL_OPTION,
  76. JOptionPane.QUESTION_MESSAGE))
  77. return null;
  78. // *****remainder of macro script omitted*****
  79. // end excerpt from Write_File_Header.bsh</pre></div><p>This macro takes several items of user input and produces a
  80. formatted file header at the beginning of the buffer. The full macro
  81. is included in the set of macros installed by jEdit. There are a
  82. number of input features of this excerpt worth noting.</p><div class="itemizedlist"><ul type="disc"><li><p>The macro uses a total of seven visible components.
  83. Two of them are created behind the scenes by
  84. <code class="function">showConfirmDialog()</code>, the rest are made
  85. by the macro. To arrange them, the script creates an array
  86. of <code class="classname">Object</code> objects and assigns
  87. components to each location in the array. This translates to
  88. a fixed, top-to-bottom arrangement in the message box
  89. created by <code class="function">showConfirmDialog()</code>.</p></li><li><p>The macro uses <code class="classname">JTextField</code>
  90. objects to obtain most of the input data. The fields
  91. <code class="varname">nameField</code> and
  92. <code class="varname">authorField</code> are created with constructors
  93. that take the initial, default text to be displayed in the
  94. field as a parameter. When the message box is displayed, the
  95. default text will appear and can be altered or deleted by
  96. the user.</p></li><li><p>The text field <code class="varname">descField</code> uses an
  97. empty string for its initial value. The second parameter in
  98. its constructor sets the width of the text field component,
  99. expressed as the number of characters of
  100. &#8220;<span class="quote">average</span>&#8221; width. When
  101. <code class="function">showConfirmDialog()</code> prepares the layout
  102. of the message box, it sets the width wide enough to
  103. accommodate the designated with of
  104. <code class="varname">descField</code>. This technique produces a
  105. message box and input text fields that are wide enough for
  106. your data with one line of code.</p></li><li><p>The displayed message box includes a
  107. <code class="classname">JCheckBox</code> component that determines
  108. whether the buffer will be saved to disk immediately after
  109. the file header is written. To conserve space in the message
  110. box, we want to display the check box to the right of the
  111. label <span class="guilabel"><strong>Name of file:</strong></span>. To do that, we
  112. create a <code class="classname">JPanel</code> object and populate
  113. it with the label and the checkbox in a left-to-right
  114. <code class="classname">GridLayout</code>. The
  115. <code class="classname">JPanel</code> containing the two components
  116. is then added to the beginning of <code class="varname">message</code>
  117. array.</p></li><li><p>The two visible components created by
  118. <code class="function">showConfirmDialog()</code> appear at positions
  119. 3 and 6 of the <code class="varname">message</code> array. Only the
  120. text is required; they are rendered as text labels.</p></li><li><p>There are three invisible components created by
  121. <code class="function">showConfirmDialog()</code>. Each of them
  122. involves a call to
  123. <code class="function">Box.createVerticalStrut()</code>. The
  124. <code class="classname">Box</code> class is a sophisticated layout
  125. class that gives the user great flexibility in sizing and
  126. positioning components. Here we use a
  127. <code class="function">static</code> method of the
  128. <code class="classname">Box</code> class that produces a vertical
  129. <em class="glossterm">strut</em>. This is a transparent
  130. component whose width expands to fill its parent component
  131. (in this case, the message box). The single parameter
  132. indicates the height of the strut in pixels. The last call
  133. to <code class="function">createVerticalStrut()</code> separates the
  134. description text field from the <span class="guilabel"><strong>OK</strong></span> and
  135. <span class="guilabel"><strong>Cancel</strong></span> buttons that are automatically
  136. added by <code class="function">showConfirmDialog()</code>.</p></li><li><p>Finally, the call to
  137. <code class="function">showConfirmDialog()</code> uses defined
  138. constants for the option type and the message type. The
  139. constants are the same as those used with the
  140. <code class="function">Macros.confirm()</code> method; see <a class="xref" href="helpful-methods.html" title="Helpful Methods in the Macros Class">the section called &#8220;Helpful Methods in the Macros Class&#8221;</a>. The option type signifies the
  141. use of <span class="guilabel"><strong>OK</strong></span> and
  142. <span class="guilabel"><strong>Cancel</strong></span> buttons. The
  143. <code class="constant">QUERY_MESSAGE</code> message type causes the
  144. message box to display a question mark icon.</p><p>The return value of the method is tested against the
  145. value <code class="constant">OK_OPTION</code>. If the return value is
  146. something else (because the <span class="guilabel"><strong>Cancel</strong></span>
  147. button was pressed or because the message box window was
  148. closed without a button press), a <code class="constant">null</code>
  149. value is returned to a calling function, signaling that the
  150. user canceled macro execution. If the return value is
  151. <code class="constant">OK_OPTION</code>, each of the input components
  152. can yield their contents for further processing by calls to
  153. <code class="function">JTextField.getText()</code> (or, in the case
  154. of the check box,
  155. <code class="function">JCheckBox.isSelected()</code>).</p></li></ul></div></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="tips-macro-input-combo"></a>Selecting Input From a List</h3></div></div></div><p>Another useful way to get user input for a macro is to use a
  156. combo box containing a number of pre-set options. If this is the
  157. only input required, one of the versions of
  158. <code class="function">showInputDialog()</code> in the
  159. <code class="classname">JOptionPane</code> class provides a shortcut. Here
  160. is its prototype:</p><div class="itemizedlist"><ul type="disc"><li><div class="funcsynopsis"><table border="0" summary="Function synopsis" cellspacing="0" cellpadding="0"><tr><td><code class="funcdef">public static Object
  161. <b class="fsfunc">showInputDialog</b>(</code></td><td>Component
  162.  </td><td><var class="pdparam">parentComponent</var>, </td></tr><tr><td> </td><td>Object
  163.  </td><td><var class="pdparam">message</var>, </td></tr><tr><td> </td><td>String
  164.  </td><td><var class="pdparam">title</var>, </td></tr><tr><td> </td><td>int
  165.  </td><td><var class="pdparam">messageType</var>, </td></tr><tr><td> </td><td>Icon  </td><td><var class="pdparam">icon</var>, </td></tr><tr><td> </td><td>Object[]
  166.  </td><td><var class="pdparam">selectionValues</var>, </td></tr><tr><td> </td><td>Object
  167.  </td><td><var class="pdparam">initialSelectionValue</var><code>)</code>;</td></tr></table></div></li></ul></div><p>This method creates a message box containing a drop-down list
  168. of the options specified in the method's parameters, along with
  169. <span class="guilabel"><strong>OK</strong></span> and <span class="guilabel"><strong>Cancel</strong></span> buttons.
  170. Compared to <code class="function">showConfirmDialog()</code>, this method
  171. lacks an <code class="varname">optionType</code> parameter and has three
  172. additional parameters: an <code class="varname">icon</code> to display in the
  173. dialog (which can be set to <code class="constant">null</code>), an array of
  174. <code class="varname">selectionValues</code> objects, and a reference to one
  175. of the options as the <code class="varname">initialSelectionValue</code> to be
  176. displayed. In addition, instead of returning an
  177. <code class="classname">int</code> representing the user's action,
  178. <code class="function">showInputDialog()</code> returns the
  179. <code class="classname">Object</code> corresponding to the user's selection,
  180. or <code class="constant">null</code> if the selection is canceled.</p><p>The following macro fragment illustrates the use of this
  181. method.</p><div class="informalexample"><pre class="programlisting">// fragment illustrating use of showInputDialog()
  182. options = new Object[5];
  183. options[0] = "JLabel";
  184. options[1] = "JTextField";
  185. options[2] = "JCheckBox";
  186. options[3] = "HistoryTextField";
  187. options[4} = "-- other --";
  188. result = JOptionPane.showInputDialog(view,
  189. "Choose component class",
  190. "Select class for input component",
  191. JOptionPane.QUESTION_MESSAGE,
  192. null, options, options[0]);</pre></div><p>The return value <code class="varname">result</code> will contain either
  193. the <code class="classname">String</code> object representing the selected
  194. text item or <code class="constant">null</code> representing no selection.
  195. Any further use of this fragment would have to test the value of
  196. <code class="varname">result</code> and likely exit from the macro if the
  197. value equaled <code class="constant">null</code>.</p><p>A set of options can be similarly placed in a
  198. <code class="classname">JComboBox</code> component created as part of a
  199. larger dialog or <code class="function">showMessageDialog()</code> layout.
  200. Here are some code fragments showing this approach:</p><div class="informalexample"><pre class="programlisting">// fragments from Display_Abbreviations.bsh
  201. // import statements and other code omitted
  202. // from main routine, this method call returns an array
  203. // of Strings representing the names of abbreviation sets
  204. abbrevSets = getActiveSets();
  205. ...
  206. // from showAbbrevs() method
  207. combo = new JComboBox(abbrevSets);
  208. // set width to uniform size regardless of combobox contents
  209. Dimension dim = combo.getPreferredSize();
  210. dim.width = Math.max(dim.width, 120);
  211. combo.setPreferredSize(dim);
  212. combo.setSelectedItem(STARTING_SET); // defined as "global"
  213. // end fragments</pre></div></div><div class="sect2" lang="en"><div class="titlepage"><div><div><h3 class="title"><a name="macro-tips-single-char"></a>Using a Single Keypress as Input</h3></div></div></div><p>Some macros may choose to emulate the style of character-based
  214. text editors such as <span class="application">emacs</span> or
  215. <span class="application">vi</span>. They will require only a single
  216. keypress as input that would be handled by the macro but not
  217. displayed on the screen. If the keypress corresponds to a character
  218. value, jEdit can pass that value as a parameter to a BeanShell
  219. script.</p><p>The jEdit class <a class="ulink" href="../api/org/gjt/sp/jedit/gui/InputHandler.html" target="_top">InputHandler</a>
  220. is an abstract class that that manages associations between keyboard
  221. input and editing actions, along with the recording of macros.
  222. Keyboard input in jEdit is normally managed by the derived class
  223. <a class="ulink" href="../api/org/gjt/sp/jedit/gui/DefaultInputHandler.html" target="_top">DefaultInputHandler</a>.
  224. One of the methods in the <a class="ulink" href="../api/org/gjt/sp/jedit/gui/InputHandler.html" target="_top">InputHandler</a>
  225. class handles input from a single keypress:</p><div class="itemizedlist"><ul type="disc"><li><div class="funcsynopsis"><table border="0" summary="Function synopsis" cellspacing="0" cellpadding="0"><tr><td><code class="funcdef">public void
  226. <b class="fsfunc">readNextChar</b>(</code></td><td>String
  227.  </td><td><var class="pdparam">prompt</var>, </td></tr><tr><td> </td><td>String
  228.  </td><td><var class="pdparam">code</var><code>)</code>;</td></tr></table></div></li></ul></div><p>When this method is called, the contents of the
  229. <code class="varname">prompt</code> parameter is shown in the view's status
  230. bar. The method then waits for a key press, after which the contents
  231. of the <code class="varname">code</code> parameter will be run as a BeanShell
  232. script, with one important modification. Each time the string
  233. <code class="varname">__char__</code> appears in the parameter script, it will
  234. be substituted by the character pressed. The key press is
  235. &#8220;<span class="quote">consumed</span>&#8221; by <code class="function">readNextChar()</code>. It
  236. will not be displayed on the screen or otherwise processed by
  237. jEdit.</p><p>Using <code class="function">readNextChar()</code> requires a macro
  238. within the macro, formatted as a single, potentially lengthy string
  239. literal. The following macro illustrates this technique. It selects
  240. a line of text from the current caret position to the first
  241. occurrence of the character next typed by the user. If the character
  242. does not appear on the line, no new selection occurs and the display
  243. remains unchanged.</p><div class="informalexample"><pre class="programlisting">// Next_Char.bsh
  244. script = new StringBuffer(512);
  245. script.append( "start = textArea.getCaretPosition();" );
  246. script.append( "line = textArea.getCaretLine();" );
  247. script.append( "end = textArea.getLineEndOffset(line) + 1;" );
  248. script.append( "text = buffer.getText(start, end - start);" );
  249. script.append( "match = text.indexOf(__char__, 1);" );
  250. script.append( "if(match != -1) {" );
  251. script.append( "if(__char__ != '\\n') ++match;" );
  252. script.append( "textArea.select(start, start + match - 1);" );
  253. script.append( "}" );
  254. view.getInputHandler().readNextChar("Enter a character",
  255. script.toString());
  256. // end Next_Char.bsh</pre></div><p>Once again, here are a few comments on the macro's
  257. design.</p><div class="itemizedlist"><ul type="disc"><li><p>A <code class="classname">StringBuffer</code> object is used
  258. for efficiency; it obviates multiple creation of
  259. fixed-length <code class="classname">String</code> objects. The
  260. parameter to the constructor of <code class="varname">script</code>
  261. specifies the initial size of the buffer that will receive
  262. the contents of the child script.</p></li><li><p>Besides the quoting of the script code, the formatting
  263. of the macro is entirely optional but (hopefully) makes it
  264. easier to read.</p></li><li><p>It is important that the child script be
  265. self-contained. It does not run in the same namespace as the
  266. &#8220;<span class="quote">parent</span>&#8221; macro
  267. <code class="filename">Next_Char.bsh</code> and therefore does not
  268. share variables, methods, or scripted objects defined in the
  269. parent macro.</p></li><li><p>Finally, access to the <a class="ulink" href="../api/org/gjt/sp/jedit/gui/InputHandler.html" target="_top">InputHandler</a>
  270. object used by jEdit is available by calling
  271. <code class="function">getInputHandler()</code> on the current
  272. view.</p></li></ul></div></div></div><div class="navfooter"><hr><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="macro-tips.html">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="macro-tips.html">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="startup-scripts.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">Chapter 15. Macro Tips and Techniques </td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top"> Startup Scripts</td></tr></table></div></body></html>