PageRenderTime 64ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

/jEdit/tags/jedit-4-5-pre1/doc/users-guide/macro-tips.xml

#
XML | 921 lines | 729 code | 167 blank | 25 comment | 0 complexity | 2b539682b7accfb9b8bed917b8ae5271 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. <?xml version="1.0" encoding="UTF-8"?>
  2. <chapter id="macro-tips">
  3. <title>Macro Tips and Techniques</title>
  4. <!-- jEdit 4.0 Macro Guide, (C) 2001, 2002 John Gellene -->
  5. <!-- Wed Jun 20 16:56:26 EDT 2001 @914 /Internet Time/ -->
  6. <!-- -->
  7. <!-- jEdit buffer-local properties: -->
  8. <!-- :indentSize=1:noTabs=yes:maxLineLen=0:wrap=soft:tabSize=2: -->
  9. <!-- :xml.root=users-guide.xml: -->
  10. <!-- -->
  11. <!-- This file covers the chapter "Macro tips and techniques" -->
  12. <!-- $Id: macro-tips.xml 16181 2009-09-08 19:26:57Z ezust $
  13. -->
  14. <section id="macro-tips-input">
  15. <title>Getting Input for a Macro</title>
  16. <para>The dialog-based macro discussed in <xref
  17. linkend="dialog-macro" /> reflects a conventional approach to obtaining
  18. input in a Java program. Nevertheless, it can be too lengthy or tedious
  19. for someone trying to write a macro quickly. Not every macro needs a
  20. user interface specified in such detail; some macros require only a
  21. single keystroke or no input at all. In this section we outline some
  22. other techniques for obtaining input that will help you write macros
  23. quickly.</para>
  24. <section id="macro-tips-input-single-line">
  25. <title>Getting a Single Line of Text</title>
  26. <para>As mentioned earlier in <xref linkend="helpful-methods" />,
  27. the method <function>Macros.input()</function> offers a convenient
  28. way to obtain a single line of text input. Here is an example that
  29. inserts a pair of HTML markup tags specified by the user.</para>
  30. <informalexample>
  31. <programlisting>// Insert_Tag.bsh
  32. void insertTag()
  33. {
  34. caret = textArea.getCaretPosition();
  35. tag = Macros.input(view, <quote>Enter name of tag:</quote>);
  36. if( tag == null || tag.length() == 0) return;
  37. text = textArea.getSelectedText();
  38. if(text == null) text = <quote></quote>;
  39. sb = new StringBuffer();
  40. sb.append(<quote>&lt;</quote>).append(tag).append(<quote>&gt;</quote>);
  41. sb.append(text);
  42. sb.append(<quote>&lt;/</quote>).append(tag).append(<quote>&gt;</quote>);
  43. textArea.setSelectedText(sb.toString());
  44. if(text.length() == 0)
  45. textArea.setCaretPosition(caret + tag.length() + 2);
  46. }
  47. insertTag();
  48. // end Insert_Tag.bsh</programlisting>
  49. </informalexample>
  50. <para>Here the call to <function>Macros.input()</function> seeks the
  51. name of the markup tag. This method sets the message box title to a
  52. fixed string, <quote>Macro input</quote>, but the specific message
  53. <guilabel>Enter name of tag</guilabel> provides all the information
  54. necessary. The return value <varname>tag</varname> must be tested to
  55. see if it is null. This would occur if the user presses the
  56. <guilabel>Cancel</guilabel> button or closes the dialog window
  57. displayed by <function>Macros.input()</function>.</para>
  58. </section>
  59. <section id="macro-tips-input-multiple-data">
  60. <title>Getting Multiple Data Items</title>
  61. <para>If more than one item of input is needed, a succession of
  62. calls to <function>Macros.input()</function> is a possible, but
  63. awkward approach, because it would not be possible to correct early
  64. input after the corresponding message box is dismissed. Where more
  65. is required, but a full dialog layout is either unnecessary or too
  66. much work, the Java method
  67. <function>JOptionPane.showConfirmDialog()</function> is available.
  68. The version to use has the following prototype:</para>
  69. <itemizedlist>
  70. <listitem>
  71. <funcsynopsis>
  72. <funcprototype>
  73. <funcdef>public static int
  74. <function>showConfirmDialog</function></funcdef>
  75. <paramdef>Component
  76. <parameter>parentComponent</parameter></paramdef>
  77. <paramdef>Object
  78. <parameter>message</parameter></paramdef>
  79. <paramdef>String
  80. <parameter>title</parameter></paramdef>
  81. <paramdef>int
  82. <parameter>optionType</parameter></paramdef>
  83. <paramdef>int
  84. <parameter>messageType</parameter></paramdef>
  85. </funcprototype>
  86. </funcsynopsis>
  87. </listitem>
  88. </itemizedlist>
  89. <para>The usefulness of this method arises from the fact that the
  90. <varname>message</varname> parameter can be an object of any Java
  91. class (since all classes are derived from
  92. <classname>Object</classname>), or any array of objects. The
  93. following example shows how this feature can be used.</para>
  94. <informalexample>
  95. <programlisting>// excerpt from Write_File_Header.bsh
  96. title = <quote>Write file header</quote>;
  97. currentName = buffer.getName();
  98. nameField = new JTextField(currentName);
  99. authorField = new JTextField(<quote>Your name here</quote>);
  100. descField = new JTextField(<quote></quote>, 25);
  101. namePanel = new JPanel(new GridLayout(1, 2));
  102. nameLabel = new JLabel(<quote>Name of file:</quote>, SwingConstants.LEFT);
  103. saveField = new JCheckBox(<quote>Save file when done</quote>,
  104. !buffer.isNewFile());
  105. namePanel.add(nameLabel);
  106. namePanel.add(saveField);
  107. message = new Object[9];
  108. message[0] = namePanel;
  109. message[1] = nameField;
  110. message[2] = Box.createVerticalStrut(10);
  111. message[3] = <quote>Author's name:</quote>;
  112. message[4] = authorField;
  113. message[5] = Box.createVerticalStrut(10);
  114. message[6] = <quote>Enter description:</quote>;
  115. message[7] = descField;
  116. message[8] = Box.createVerticalStrut(5);
  117. if( JOptionPane.OK_OPTION !=
  118. JOptionPane.showConfirmDialog(view, message, title,
  119. JOptionPane.OK_CANCEL_OPTION,
  120. JOptionPane.QUESTION_MESSAGE))
  121. return null;
  122. // *****remainder of macro script omitted*****
  123. // end excerpt from Write_File_Header.bsh</programlisting>
  124. </informalexample>
  125. <para>This macro takes several items of user input and produces a
  126. formatted file header at the beginning of the buffer. The full macro
  127. is included in the set of macros installed by jEdit. There are a
  128. number of input features of this excerpt worth noting.</para>
  129. <itemizedlist>
  130. <listitem>
  131. <para>The macro uses a total of seven visible components.
  132. Two of them are created behind the scenes by
  133. <function>showConfirmDialog()</function>, the rest are made
  134. by the macro. To arrange them, the script creates an array
  135. of <classname>Object</classname> objects and assigns
  136. components to each location in the array. This translates to
  137. a fixed, top-to-bottom arrangement in the message box
  138. created by <function>showConfirmDialog()</function>.</para>
  139. </listitem>
  140. <listitem>
  141. <para>The macro uses <classname>JTextField</classname>
  142. objects to obtain most of the input data. The fields
  143. <varname>nameField</varname> and
  144. <varname>authorField</varname> are created with constructors
  145. that take the initial, default text to be displayed in the
  146. field as a parameter. When the message box is displayed, the
  147. default text will appear and can be altered or deleted by
  148. the user.</para>
  149. </listitem>
  150. <listitem>
  151. <para>The text field <varname>descField</varname> uses an
  152. empty string for its initial value. The second parameter in
  153. its constructor sets the width of the text field component,
  154. expressed as the number of characters of
  155. <quote>average</quote> width. When
  156. <function>showConfirmDialog()</function> prepares the layout
  157. of the message box, it sets the width wide enough to
  158. accommodate the designated with of
  159. <varname>descField</varname>. This technique produces a
  160. message box and input text fields that are wide enough for
  161. your data with one line of code.</para>
  162. </listitem>
  163. <listitem>
  164. <para>The displayed message box includes a
  165. <classname>JCheckBox</classname> component that determines
  166. whether the buffer will be saved to disk immediately after
  167. the file header is written. To conserve space in the message
  168. box, we want to display the check box to the right of the
  169. label <guilabel>Name of file:</guilabel>. To do that, we
  170. create a <classname>JPanel</classname> object and populate
  171. it with the label and the checkbox in a left-to-right
  172. <classname>GridLayout</classname>. The
  173. <classname>JPanel</classname> containing the two components
  174. is then added to the beginning of <varname>message</varname>
  175. array.</para>
  176. </listitem>
  177. <listitem>
  178. <para>The two visible components created by
  179. <function>showConfirmDialog()</function> appear at positions
  180. 3 and 6 of the <varname>message</varname> array. Only the
  181. text is required; they are rendered as text labels.</para>
  182. </listitem>
  183. <listitem>
  184. <para>There are three invisible components created by
  185. <function>showConfirmDialog()</function>. Each of them
  186. involves a call to
  187. <function>Box.createVerticalStrut()</function>. The
  188. <classname>Box</classname> class is a sophisticated layout
  189. class that gives the user great flexibility in sizing and
  190. positioning components. Here we use a
  191. <function>static</function> method of the
  192. <classname>Box</classname> class that produces a vertical
  193. <glossterm>strut</glossterm>. This is a transparent
  194. component whose width expands to fill its parent component
  195. (in this case, the message box). The single parameter
  196. indicates the height of the strut in pixels. The last call
  197. to <function>createVerticalStrut()</function> separates the
  198. description text field from the <guilabel>OK</guilabel> and
  199. <guilabel>Cancel</guilabel> buttons that are automatically
  200. added by <function>showConfirmDialog()</function>.</para>
  201. </listitem>
  202. <listitem>
  203. <para>Finally, the call to
  204. <function>showConfirmDialog()</function> uses defined
  205. constants for the option type and the message type. The
  206. constants are the same as those used with the
  207. <function>Macros.confirm()</function> method; see <xref
  208. linkend="helpful-methods" />. The option type signifies the
  209. use of <guilabel>OK</guilabel> and
  210. <guilabel>Cancel</guilabel> buttons. The
  211. <constant>QUERY_MESSAGE</constant> message type causes the
  212. message box to display a question mark icon.</para>
  213. <para>The return value of the method is tested against the
  214. value <constant>OK_OPTION</constant>. If the return value is
  215. something else (because the <guilabel>Cancel</guilabel>
  216. button was pressed or because the message box window was
  217. closed without a button press), a <constant>null</constant>
  218. value is returned to a calling function, signaling that the
  219. user canceled macro execution. If the return value is
  220. <constant>OK_OPTION</constant>, each of the input components
  221. can yield their contents for further processing by calls to
  222. <function>JTextField.getText()</function> (or, in the case
  223. of the check box,
  224. <function>JCheckBox.isSelected()</function>).</para>
  225. </listitem>
  226. </itemizedlist>
  227. </section>
  228. <section id="tips-macro-input-combo">
  229. <title>Selecting Input From a List</title>
  230. <para>Another useful way to get user input for a macro is to use a
  231. combo box containing a number of pre-set options. If this is the
  232. only input required, one of the versions of
  233. <function>showInputDialog()</function> in the
  234. <classname>JOptionPane</classname> class provides a shortcut. Here
  235. is its prototype:</para>
  236. <itemizedlist>
  237. <listitem>
  238. <funcsynopsis>
  239. <funcprototype>
  240. <funcdef>public static Object
  241. <function>showInputDialog</function></funcdef>
  242. <paramdef>Component
  243. <parameter>parentComponent</parameter></paramdef>
  244. <paramdef>Object
  245. <parameter>message</parameter></paramdef>
  246. <paramdef>String
  247. <parameter>title</parameter></paramdef>
  248. <paramdef>int
  249. <parameter>messageType</parameter></paramdef>
  250. <paramdef>Icon <parameter>icon</parameter></paramdef>
  251. <paramdef>Object[]
  252. <parameter>selectionValues</parameter></paramdef>
  253. <paramdef>Object
  254. <parameter>initialSelectionValue</parameter></paramdef>
  255. </funcprototype>
  256. </funcsynopsis>
  257. </listitem>
  258. </itemizedlist>
  259. <para>This method creates a message box containing a drop-down list
  260. of the options specified in the method's parameters, along with
  261. <guilabel>OK</guilabel> and <guilabel>Cancel</guilabel> buttons.
  262. Compared to <function>showConfirmDialog()</function>, this method
  263. lacks an <varname>optionType</varname> parameter and has three
  264. additional parameters: an <varname>icon</varname> to display in the
  265. dialog (which can be set to <constant>null</constant>), an array of
  266. <varname>selectionValues</varname> objects, and a reference to one
  267. of the options as the <varname>initialSelectionValue</varname> to be
  268. displayed. In addition, instead of returning an
  269. <classname>int</classname> representing the user's action,
  270. <function>showInputDialog()</function> returns the
  271. <classname>Object</classname> corresponding to the user's selection,
  272. or <constant>null</constant> if the selection is canceled.</para>
  273. <para>The following macro fragment illustrates the use of this
  274. method.</para>
  275. <informalexample>
  276. <programlisting>// fragment illustrating use of showInputDialog()
  277. options = new Object[5];
  278. options[0] = "JLabel";
  279. options[1] = "JTextField";
  280. options[2] = "JCheckBox";
  281. options[3] = "HistoryTextField";
  282. options[4} = "-- other --";
  283. result = JOptionPane.showInputDialog(view,
  284. "Choose component class",
  285. "Select class for input component",
  286. JOptionPane.QUESTION_MESSAGE,
  287. null, options, options[0]);</programlisting>
  288. </informalexample>
  289. <para>The return value <varname>result</varname> will contain either
  290. the <classname>String</classname> object representing the selected
  291. text item or <constant>null</constant> representing no selection.
  292. Any further use of this fragment would have to test the value of
  293. <varname>result</varname> and likely exit from the macro if the
  294. value equaled <constant>null</constant>.</para>
  295. <para>A set of options can be similarly placed in a
  296. <classname>JComboBox</classname> component created as part of a
  297. larger dialog or <function>showMessageDialog()</function> layout.
  298. Here are some code fragments showing this approach:</para>
  299. <informalexample>
  300. <programlisting>// fragments from Display_Abbreviations.bsh
  301. // import statements and other code omitted
  302. // from main routine, this method call returns an array
  303. // of Strings representing the names of abbreviation sets
  304. abbrevSets = getActiveSets();
  305. ...
  306. // from showAbbrevs() method
  307. combo = new JComboBox(abbrevSets);
  308. // set width to uniform size regardless of combobox contents
  309. Dimension dim = combo.getPreferredSize();
  310. dim.width = Math.max(dim.width, 120);
  311. combo.setPreferredSize(dim);
  312. combo.setSelectedItem(STARTING_SET); // defined as "global"
  313. // end fragments</programlisting>
  314. </informalexample>
  315. </section>
  316. <section id="macro-tips-single-char">
  317. <title>Using a Single Keypress as Input</title>
  318. <para>Some macros may choose to emulate the style of character-based
  319. text editors such as <application>emacs</application> or
  320. <application>vi</application>. They will require only a single
  321. keypress as input that would be handled by the macro but not
  322. displayed on the screen. If the keypress corresponds to a character
  323. value, jEdit can pass that value as a parameter to a BeanShell
  324. script.</para>
  325. <para>The jEdit class <ulink
  326. url="../api/org/gjt/sp/jedit/gui/InputHandler.html">InputHandler</ulink>
  327. is an abstract class that that manages associations between keyboard
  328. input and editing actions, along with the recording of macros.
  329. Keyboard input in jEdit is normally managed by the derived class
  330. <ulink
  331. url="../api/org/gjt/sp/jedit/gui/DefaultInputHandler.html">DefaultInputHandler</ulink>.
  332. One of the methods in the <ulink
  333. url="../api/org/gjt/sp/jedit/gui/InputHandler.html">InputHandler</ulink>
  334. class handles input from a single keypress:</para>
  335. <itemizedlist>
  336. <listitem>
  337. <funcsynopsis>
  338. <funcprototype>
  339. <funcdef>public void
  340. <function>readNextChar</function></funcdef>
  341. <paramdef>String
  342. <parameter>prompt</parameter></paramdef>
  343. <paramdef>String
  344. <parameter>code</parameter></paramdef>
  345. </funcprototype>
  346. </funcsynopsis>
  347. </listitem>
  348. </itemizedlist>
  349. <para>When this method is called, the contents of the
  350. <varname>prompt</varname> parameter is shown in the view's status
  351. bar. The method then waits for a key press, after which the contents
  352. of the <varname>code</varname> parameter will be run as a BeanShell
  353. script, with one important modification. Each time the string
  354. <varname>__char__</varname> appears in the parameter script, it will
  355. be substituted by the character pressed. The key press is
  356. <quote>consumed</quote> by <function>readNextChar()</function>. It
  357. will not be displayed on the screen or otherwise processed by
  358. jEdit.</para>
  359. <para>Using <function>readNextChar()</function> requires a macro
  360. within the macro, formatted as a single, potentially lengthy string
  361. literal. The following macro illustrates this technique. It selects
  362. a line of text from the current caret position to the first
  363. occurrence of the character next typed by the user. If the character
  364. does not appear on the line, no new selection occurs and the display
  365. remains unchanged.</para>
  366. <informalexample>
  367. <programlisting>// Next_Char.bsh
  368. script = new StringBuffer(512);
  369. script.append( "start = textArea.getCaretPosition();" );
  370. script.append( "line = textArea.getCaretLine();" );
  371. script.append( "end = textArea.getLineEndOffset(line) + 1;" );
  372. script.append( "text = buffer.getText(start, end - start);" );
  373. script.append( "match = text.indexOf(__char__, 1);" );
  374. script.append( "if(match != -1) {" );
  375. script.append( "if(__char__ != '\\n') ++match;" );
  376. script.append( "textArea.select(start, start + match - 1);" );
  377. script.append( "}" );
  378. view.getInputHandler().readNextChar("Enter a character",
  379. script.toString());
  380. // end Next_Char.bsh</programlisting>
  381. </informalexample>
  382. <para>Once again, here are a few comments on the macro's
  383. design.</para>
  384. <itemizedlist>
  385. <listitem>
  386. <para>A <classname>StringBuffer</classname> object is used
  387. for efficiency; it obviates multiple creation of
  388. fixed-length <classname>String</classname> objects. The
  389. parameter to the constructor of <varname>script</varname>
  390. specifies the initial size of the buffer that will receive
  391. the contents of the child script.</para>
  392. </listitem>
  393. <listitem>
  394. <para>Besides the quoting of the script code, the formatting
  395. of the macro is entirely optional but (hopefully) makes it
  396. easier to read.</para>
  397. </listitem>
  398. <listitem>
  399. <para>It is important that the child script be
  400. self-contained. It does not run in the same namespace as the
  401. <quote>parent</quote> macro
  402. <filename>Next_Char.bsh</filename> and therefore does not
  403. share variables, methods, or scripted objects defined in the
  404. parent macro.</para>
  405. </listitem>
  406. <listitem>
  407. <para>Finally, access to the <ulink
  408. url="../api/org/gjt/sp/jedit/gui/InputHandler.html">InputHandler</ulink>
  409. object used by jEdit is available by calling
  410. <function>getInputHandler()</function> on the current
  411. view.</para>
  412. </listitem>
  413. </itemizedlist>
  414. </section>
  415. </section>
  416. <section id="startup-scripts">
  417. <title>Startup Scripts</title>
  418. <para>On startup, jEdit runs any BeanShell scripts located in the
  419. <filename>startup</filename> subdirectory of the jEdit installation and
  420. user settings directories (see <xref linkend="settings-directory" />).
  421. As with macros, the scripts must have a <filename>.bsh</filename> file
  422. name extension. Startup scripts are run near the end of the startup
  423. sequence, after plugins, properties and such have been initialized, but
  424. before the first view is opened.</para>
  425. <para>Startup scripts can perform initialization tasks that cannot be
  426. handled by command line options or ordinary configuration options, such
  427. as customizing jEdit's user interface by changing entries in the Java
  428. platform's <classname>UIManager</classname> class.</para>
  429. <para>Startup scripts have an additional feature lacking in ordinary
  430. macros that can help you further customize jEdit. Variables and methods
  431. defined in a startup script are available in all instances of the
  432. BeanShell interpreter created in jEdit. This allows you to create a
  433. personal library of methods and objects that can be accessed at any time
  434. during the editing session in another macro, the BeanShell shell of the
  435. Console plugin, or menu items such as
  436. <guimenu>Utilities</guimenu>&gt;<guisubmenu>BeanShell</guisubmenu>&gt;<guimenuitem>Evaluate
  437. BeanShell Expression</guimenuitem>.</para>
  438. <para>The startup script routine will run script files in the
  439. installation directory first, followed by scripts in the user settings
  440. directory. In each case, scripts will be executed in alphabetical order,
  441. applied without regard to whether the file name contains upper or lower
  442. case characters.</para>
  443. <para>If a startup script throws an exception (because, for example, it
  444. attempts to call a method on a <constant>null</constant> object). jEdit
  445. will show an error dialog box and move on to the next startup script. If
  446. script bugs are causing jEdit to crash or hang on startup, you can use
  447. the <userinput>-nostartupscripts</userinput> command line option to
  448. disable them for that editing session.</para>
  449. <para>Another important difference between startup scripts and ordinary
  450. macros is that startup scripts cannot use the pre-defined variables
  451. <varname>view</varname>, <varname>textArea</varname>,
  452. <varname>editPane</varname> and <varname>buffer</varname>. This is
  453. because they are executed before the initial view is created.</para>
  454. <para>If you are writing a method in a startup script and wish to use
  455. one of the above variables, pass parameters of the appropriate type to
  456. the method, so that a macro calling them after startup can supply the
  457. appropriate values. For example, a startup script could include a
  458. method</para>
  459. <informalexample>
  460. <programlisting>void doSomethingWithView(View v, String s) {
  461. ...
  462. }</programlisting>
  463. </informalexample>
  464. <para>so that during the editing session another macro can call the
  465. method using</para>
  466. <informalexample>
  467. <programlisting>doSomethingWithView(view, "something");</programlisting>
  468. </informalexample>
  469. <sidebar>
  470. <title>Reloading startup scripts without restarting</title>
  471. <para>It is actually possible to reload startup scripts or load
  472. other scripts without restarting jEdit, using a BeanShell statement
  473. like the following:</para>
  474. <programlisting>BeanShell.runScript(view,<replaceable>path</replaceable>,null,false);</programlisting>
  475. <para>For <replaceable>path</replaceable>, you can substitute any
  476. string, or a method call such as
  477. <function>buffer.getPath()</function>.</para>
  478. </sidebar>
  479. </section>
  480. <section id="scripts-command-line">
  481. <title>Running Scripts from the Command Line</title>
  482. <para>The <userinput>-run</userinput> command line switch specifies a
  483. BeanShell script to run on startup:</para>
  484. <screen><prompt>$ </prompt><userinput>jedit -run=test.bsh</userinput></screen>
  485. <para>Note that just like with startup scripts, the
  486. <varname>view</varname>, <varname>textArea</varname>,
  487. <varname>editPane</varname> and <varname>buffer</varname> variables are
  488. not defined.</para>
  489. <para>If another instance is already running, the script will be run in
  490. that instance, and you will be able to use the
  491. <function>jEdit.getLastView()</function> method to obtain a view.
  492. However, if a new instance of jEdit is being started, the script will be
  493. run at the same time as all other startup scripts; that is, before the
  494. first view is opened.</para>
  495. <para>If your script needs a view instance to operate on, you can use
  496. the following code pattern to obtain one, no matter how or when the
  497. script is being run:</para>
  498. <programlisting>void doSomethingUseful()
  499. {
  500. void run()
  501. {
  502. view = jEdit.getLastView();
  503. // put actual script body here
  504. }
  505. if(jEdit.getLastView() == null)
  506. VFSManager.runInAWTThread(this);
  507. else
  508. run();
  509. }
  510. doSomethingUseful();</programlisting>
  511. <para>If the script is being run in a loaded instance, it can be invoked
  512. to perform its work immediately. However, if the script is running at
  513. startup, before an initial view exists, its operation must be delayed to
  514. allow the view object first to be created and displayed. In order to
  515. queue the macro's operation, the scripted <quote>closure</quote> named
  516. <function>doSomethingUseful()</function> implements the
  517. <classname>Runnable</classname> interface of the Java platform. That
  518. interface contains only a single <function>run()</function> method that
  519. takes no parameters and has no return value. The macro's implementation
  520. of the <function>run()</function> method contains the
  521. <quote>working</quote> portion of the macro. Then the scripted object,
  522. represented by a reference to <varname>this</varname>, is passed to the
  523. <function>runInAWTThread()</function> method. This schedules the macro's
  524. operations for execution after the startup routine is complete.</para>
  525. <para>As this example illustrates, the
  526. <function>runInAWTThread()</function> method can be used to ensure that
  527. a macro will perform operations after other operations have completed.
  528. If it is invoked during startup, it schedules the specified
  529. <classname>Runnable</classname> object to run after startup is complete.
  530. If invoked when jEdit is fully loaded, the
  531. <classname>Runnable</classname> object will execute after all pending
  532. input/output is complete, or immediately if there are no pending I/O
  533. operations. This will delay operations on a new buffer, for example,
  534. until after the buffer is loaded and displayed.</para>
  535. </section>
  536. <section id="macro-tips-BeanShell">
  537. <title>Advanced BeanShell Techniques</title>
  538. <para>BeanShell has a few advanced features that we haven't mentioned
  539. yet. They will be discussed in this section.</para>
  540. <section id="macro-tips-BeanShell-convenience">
  541. <title>BeanShell's Convenience Syntax</title>
  542. <para>We noted earlier that BeanShell syntax does not require that
  543. variables be declared or defined with their type, and that variables
  544. that are not typed when first used can have values of differing
  545. types assigned to them. In addition to this <quote>loose</quote>
  546. syntax, BeanShell allows a <quote>convenience</quote> syntax for
  547. dealing with the properties of JavaBeans. They may be accessed or
  548. set as if they were data members. They may also be accessed using
  549. the name of the property enclosed in quotation marks and curly
  550. brackets. For example, the following statement are all equivalent,
  551. assuming <varname>btn</varname> is a <classname>JButton</classname>
  552. instance:</para>
  553. <informalexample>
  554. <programlisting>b.setText("Choose");
  555. b.text = "Choose";
  556. b{"text"} = "Choose";
  557. </programlisting>
  558. </informalexample>
  559. <para>The last form can also be used to access a key-value pair of a
  560. <classname>Hashtable</classname> object.</para>
  561. <!-- actually, the following requires the bsh.classpath package, which
  562. is not included with jEdit at this point in time.
  563. a future release of jEdit will use bsh.classpath, and hence support
  564. 'import *'
  565. <para>
  566. Finally, when importing classes, BeanShell permits the following form
  567. to import all classes lying within the interpreter's classpath:
  568. </para>
  569. <informalexample><programlisting>import *;
  570. </programlisting></informalexample>
  571. -->
  572. </section>
  573. <section id="macro-tips-BeanShell-keywords">
  574. <title>Special BeanShell Keywords</title>
  575. <para>BeanShell uses special keywords to refer to variables or
  576. methods defined in the current or an enclosing block's scope:</para>
  577. <itemizedlist>
  578. <listitem>
  579. <para>The keyword <function>this</function> refers to the
  580. current scope.</para>
  581. </listitem>
  582. <listitem>
  583. <para>The keyword <function>super</function> refers to the
  584. immediately enclosing scope.</para>
  585. </listitem>
  586. <listitem>
  587. <para>The keyword <function>global</function> refers to the
  588. top-level scope of the macro script.</para>
  589. </listitem>
  590. </itemizedlist>
  591. <para>The following script illustrates the use of these
  592. keywords:</para>
  593. <informalexample>
  594. <programlisting>a = "top\n";
  595. foo() {
  596. a = "middle\n";
  597. bar() {
  598. a = "bottom\n";
  599. textArea.setSelectedText(global.a);
  600. textArea.setSelectedText(super.a);
  601. // equivalent to textArea.setSelectedText(this.a):
  602. textArea.setSelectedText(a);
  603. }
  604. bar();
  605. }
  606. foo();</programlisting>
  607. </informalexample>
  608. <para>When the script is run, the following text is inserted in the
  609. current buffer:</para>
  610. <screen>top
  611. middle
  612. bottom</screen>
  613. </section>
  614. <section id="macro-tips-BeanShell-class">
  615. <title>Implementing Classes and Interfaces</title>
  616. <para>As discussed in the macro example in <xref
  617. linkend="dialog-macro" />, scripted objects can implicitly implement
  618. Java interfaces such as <classname>ActionListener</classname>. For
  619. example:</para>
  620. <programlisting>myRunnable() {
  621. run() {
  622. System.out.println("Hello world!");
  623. }
  624. return this;
  625. }
  626. Runnable r = myRunnable();
  627. new Thread(r).start();</programlisting>
  628. <para>Frequently it will not be necessary to implement all of the
  629. methods of a particular interface in order to specify the behavior
  630. of a scripted object. To prevent BeanShell from throwing exceptions
  631. for missing interface methods, implement the
  632. <function>invoke()</function> method, which is called when an
  633. undefined method is invoked on a scripted object. Typically, the
  634. implementation of this method will do nothing, as in the following
  635. example:</para>
  636. <informalexample>
  637. <programlisting>invoke(method, args) {}</programlisting>
  638. </informalexample>
  639. <para>In addition to the implicit interface definitions described
  640. above, BeanShell permits full-blown classes to be defined. Indeed,
  641. almost any Java class definition should work in BeanShell:</para>
  642. <programlisting>class Cons {
  643. // Long-live LISP!
  644. Object car;
  645. Object cdr;
  646. rplaca(Object car) {
  647. this.car = car;
  648. }
  649. rplacd(Object cdr) {
  650. this.cdr = cdr;
  651. }
  652. }</programlisting>
  653. </section>
  654. </section>
  655. <section id="macro-tips-debugging">
  656. <title>Debugging Macros</title>
  657. <para>Here are a few techniques that can prove helpful in debugging
  658. macros.</para>
  659. <section id="macro-tips-debugging-exceptions">
  660. <title>Identifying Exceptions</title>
  661. <para>An <glossterm>exception</glossterm> is a condition reflecting
  662. an error or other unusual result of program execution that requires
  663. interruption of normal program flow and some kind of special
  664. handling. Java has a rich (and extensible) collection of exception
  665. classes which represent such conditions.</para>
  666. <para>jEdit catches exceptions thrown by BeanShell scripts and
  667. displays them in a dialog box. In addition, the full traceback is
  668. written to the activity log (see <xref linkend="activity-log" /> for
  669. more information about the activity log).</para>
  670. <para>There are two broad categories of errors that will result in
  671. exceptions:</para>
  672. <itemizedlist>
  673. <listitem>
  674. <para><emphasis>Interpreter errors</emphasis>, which may
  675. arise from typing mistakes like mismatched brackets or
  676. missing semicolons, or from BeanShell's failure to find a
  677. class corresponding to a particular variable.</para>
  678. <para>Interpreter errors are usually accompanied by the line
  679. number in the script, along with the cause of the
  680. error.</para>
  681. </listitem>
  682. <listitem>
  683. <para><emphasis>Execution errors</emphasis>, which result
  684. from runtime exceptions thrown by the Java platform when
  685. macro code is executed.</para>
  686. <para>Some exceptions thrown by the Java platform can often
  687. seem cryptic. Nevertheless, examining the contents of the
  688. activity log may reveals clues as to the cause of the
  689. error.</para>
  690. </listitem>
  691. </itemizedlist>
  692. </section>
  693. <section id="macro-tips-debugging-log">
  694. <title>Using the Activity Log as a Tracing Tool</title>
  695. <para>Sometimes exception tracebacks will say what kind of error
  696. occurred but not where it arose in the script. In those cases, you
  697. can insert calls that log messages to the activity log in your
  698. macro. If the logged messages appear when the macro is run, it means
  699. that up to that point the macro is fine; but if an exception is
  700. logged first, it means the logging call is located after the cause
  701. of the error.</para>
  702. <para>To write a message to the activity log, use the following
  703. method of the <ulink
  704. url="../api/org/gjt/sp/util/Log.html">Log</ulink> class:</para>
  705. <itemizedlist>
  706. <listitem>
  707. <funcsynopsis>
  708. <funcprototype>
  709. <funcdef>public static void
  710. <function>log</function></funcdef>
  711. <paramdef>int
  712. <parameter>urgency</parameter></paramdef>
  713. <paramdef>Object
  714. <parameter>source</parameter></paramdef>
  715. <paramdef>Object
  716. <parameter>message</parameter></paramdef>
  717. </funcprototype>
  718. </funcsynopsis>
  719. </listitem>
  720. </itemizedlist>
  721. <para>See the documentation for the <ulink
  722. url="../api/org/gjt/sp/util/Log.html">Log</ulink> class for
  723. information about the method's parameters.</para>
  724. <para>The following code sends a typical debugging message to the
  725. activity log:</para>
  726. <informalexample>
  727. <programlisting>Log.log(Log.DEBUG, BeanShell.class,
  728. "counter = " + counter);</programlisting>
  729. </informalexample>
  730. <para>The corresponding activity log entry might read as
  731. follows:</para>
  732. <informalexample>
  733. <programlisting>[debug] BeanShell: counter = 15</programlisting>
  734. </informalexample>
  735. <sidebar>
  736. <title>Using message dialog boxes as a tracing tool</title>
  737. <para>If you would prefer not having to deal with the activity
  738. log, you can use the <function>Macros.message()</function>
  739. method as a tracing tool. Just insert calls like the following
  740. in the macro code:</para>
  741. <programlisting>Macros.message(view,"tracing");</programlisting>
  742. <para>Execution of the macro is halted until the message dialog
  743. box is closed. When you have finished debugging the macro, you
  744. should delete or comment out the debugging calls to
  745. <function>Macros.message()</function> in your final source
  746. code.</para>
  747. </sidebar>
  748. </section>
  749. </section>
  750. </chapter>