Creating a script
To learn more about the Script Editor, we'll write a script that displays a file dialog and reads the file that the user selects. Begin by creating a new visual part with a name such as OpenFile. Don't worry about adding parts yet; we will do that later. From the Composition Editor, switch to the Script Editor by clicking the Script Editor symbolsymbol in the bottom-right corner.
To create a new script, select New method template from the Methods menu. This template appears in the text area:
messagePattern
"comment"
| temporaries |
statements
Replace the template text with the following script:
openFile
"Opens a file and reads its contents. Note that a File
Prompter visual part can be used instead of this script.
The How Do I... help contains an example."
| dialog file fileStream text |
dialog := CwFileSelectionPrompter new initialize;
searchMask: '*.*'.
file := dialog prompt.
file == nil
ifFalse: [fileStream := CfsReadFileStream open: file.
text := (fileStream upToEnd) trimSeparators.
fileStream close.]
The first two statements of this script display a file dialog and save the name of the file that the user selects in the variable file. If the user cancels the file dialog instead of selecting a file name, the variable file is nil. The last statement checks to see whether a file exists and, if so, creates an input file stream, reads the contents of the file into the text object while removing leading and tailing whitespace characters and, finally, closes the input file stream.
To compile the script, select Save from the pop-up menu of the text area. The name of the script appears in the method list, which is a list of all the scripts in the currently selected category for this visual part. The category Not categorized appears in the category list. This category is the default category used to list all scripts that have not been moved to other categories.
Categories
Let's explore categories a bit further. Select Rename from the pop-up menu of the category list. Type fileSelection in the prompter. Select OK to change the category name. The category list now contains fileSelection, and openFile appears in the method list for the fileSelection category.
Last modified date: 03/13/2020