oneShot: free the responder before running user func (avoid error)
[supercollider.git] / HelpSource / Classes / String.schelp
blobf6badf4f84e13e5c5c4b145daba8ef9d857aebe3
1 CLASS::String
2 summary::array of characters
3 categories:: Collections>Ordered
5 DESCRIPTION::
6 String represents an array of characters.
8 Strings can be written literally using double quotes:
9 code::
10 "my string".class.postln;
13 CLASSMETHODS::
15 private::initClass
17 method::readNew
18 Read the entire contents of a link::Classes/File:: and return them as a new String.
20 INSTANCEMETHODS::
22 private::prUnixCmd, prFormat, prCat
24 method::at
25 Strings respond to .at in a manner similar to other indexed collections. Each element is a link::Classes/Char::.
26 code::
27 "ABCDEFG".at(2).postln;
30 method::compare
31 Returns a -1, 0, or 1 depending on whether the receiver should be sorted before the argument, is equal to the argument or should be sorted after the argument. This is a case sensitive compare.
33 method::<
34 Returns a link::Classes/Boolean:: whether the receiver should be sorted before the argument.
36 method::==
37 Returns a link::Classes/Boolean:: whether the two Strings are equal.
39 method::post
40 Prints the string to the current post window.
42 method::postln
43 Prints the string and a carriage return to the current post window.
45 method::postc, postcln
46 As link::#-post:: and link::#-postln::, but formatted as a comment.
47 code::
48 "This is a comment.".postcln;
51 method::postf
52 Prints a formatted string with arguments to the current post window. The % character in the format string is replaced by a string representation of an argument. To print a % character use \\% .
53 code::
54 postf("this % a %. pi = %, list = %\n", "is", "test", pi.round(1e-4), (1..4))
56 this is a test. pi = 3.1416, list = [ 1, 2, 3, 4 ]
59 method::format
60 Returns a formatted string with arguments. The % character in the format string is replaced by a string representation of an argument. To print a % character use \\% .
61 code::
62 format("this % a %. pi = %, list = %\n", "is", "test", pi.round(1e-4), (1..4))
64 this is a test. pi = 3.1416, list = [ 1, 2, 3, 4 ]
67 method::matchRegexp
68 POSIX regular expression matching. Returns true if the receiver (a regular expression pattern) matches the string passed to it. The strong::start:: is an offset where to start searching in the string (default: 0), strong::end:: where to stop.
69 code::
70 "c".matchRegexp("abcdefg", 2, 5); // true
71 "c".matchRegexp("abcdefg", 4, 5); // false
73 "behaviou?r".matchRegexp("behavior"); // true
74 "behaviou?r".matchRegexp("behaviour"); // true
75 "behaviou?r".matchRegexp("behavir"); // false
76 "b.h.v.r".matchRegexp("behavor"); // true
77 "b.h.vi*r".matchRegexp("behaviiiiir"); // true
78 "(a|u)nd".matchRegexp("und"); // true
79 "(a|u)nd".matchRegexp("and"); // true
80 "[a-c]nd".matchRegexp("ind"); // false
81 "[a-c]nd".matchRegexp("bnd"); // true
84 method::findRegexp
85 POSIX regular expression search.
86 code::
87 "foobar".findRegexp("o*bar");
88 "32424 334 /**aaaaaa*/".findRegexp("/\\*\\*a*\\*/");
89 "foobar".findRegexp("(o*)(bar)");
90 "aaaabaaa".findAllRegexp("a+");
93 method::error
94 Prepends an error banner and posts the string.
97 method::warn
98 Prepends a warning banner and posts the string.
100 method::inform
101 Posts the string.
103 method::++
104 Return a concatenation of the two strings.
107 method::+
108 Return a concatenation of the two strings with a space between them.
110 method::compile
111 Compiles a String containing legal SuperCollider code and returns a Function.
112 code::
114 var f;
115 f = "2 + 1".compile.postln;
116 f.value.postln;
120 method::asCompileString
121 Returns a String formatted for compiling.
122 code::
124 var f;
125 f = "myString";
126 f.postln;
127 f.asCompileString.postln;
131 method::postcs
132 As link::#-postln::, but posts the compileString of the reciever.
133 code::
134 List[1, 2, ["comment", [3, 2]], { 1.0.rand }].postcs;
137 method::interpret
138 Compile and execute a String containing legal SuperCollider code, returning the result.
139 code::
140 "2 + 1".interpret.postln;
143 method::interpretPrint
144 Compile, execute and print the result of a String containing legal SuperCollider code.
145 code::
146 "2 + 1".interpretPrint;
149 method::asSymbol
150 Return a link::Classes/Symbol:: derived from the String.
151 code::
153 var z;
154 z = "myString".asSymbol.postln;
155 z.class.postln;
159 method::asInteger
160 Return an link::Classes/Integer:: derived from the String. Strings beginning with non-numeric characters return 0.
161 code::
162 "4".asInteger.postln;
165 method::asFloat
166 Return a link::Classes/Float:: derived from the String. Strings beginning with non-numeric characters return 0.
167 code::
168 "4.3".asFloat.postln;
171 method::asSecs
172 Return a link::Classes/Float:: based on converting a time string in format (dd):hh:mm:ss.s. This is the inverse method to link::Classes/SimpleNumber#-asTimeString::.
173 code::
174 (45296.asTimeString).asSecs;
175 "32.1".asSecs;
176 "62.1".asSecs;          // warns
177 "0:0:59.9".asSecs;
178 "1:1:1.1".asSecs;
179 "-1".asSecs;            // neg sign supported
180 "-12:34:56".asSecs;
181 "12:-34:56".asSecs;     // warns
182 "-23:12.3456".asSecs;   //
183 "-1:00:00:00".asSecs;   // days too.
186 method::catArgs
187 Concatenate this string with the following args.
188 code::
189 "These are some args: ".catArgs(\fish, SinOsc.ar, {4 + 3}).postln;
192 method::scatArgs
193 Same as link::#-catArgs::, but with spaces in between.
194 code::
195 "These are some args: ".scatArgs(\fish, SinOsc.ar, {4 + 3}).postln;
198 method::ccatArgs
199 Same as link::#-catArgs::, but with commas in between.
200 code::
201 "a String".ccatArgs(\fish, SinOsc.ar, {4 + 3}).postln;
204 method::catList, scatList, ccatList
205 As link::#-catArgs::, link::#-scatArgs:: and link::#-ccatArgs:: above, but takes a Collection (usually a link::Classes/List:: or an link::Classes/Array::) as an argument.
206 code::
207 "a String".ccatList([\fish, SinOsc.ar, {4 + 3}]).postln;
210 method::split
211 Returns an Array of Strings split at the separator. The separator is a link::Classes/Char::, and is not included in the output array. The default separator is $/, handy for Unix paths.
212 code::
213 "This/could/be/a/Unix/path".split.postln;
214 "These are several words".split($ ).postln;
217 method::ascii
218 Returns an Array of asci numbers of the Strings's characters.
219 code::
220 "wertvoll".ascii;
223 method::find
224 Returns the index of the string in the receiver, or nil if not found. If strong::ignoreCase:: is true, find makes no difference between uppercase and lowercase letters. The strong::offset:: is the point in the string where the search begins.
225 code::
226 "These are several words".find("are").postln;
227 "These are several words".find("fish").postln;
230 method::findBackwards
231 Same like link::#-find::, but starts at the end of the string.
232 code::
233 // compare:
234 "These words are several words".find("words"); // 6
235 "These words are several words".findBackwards("words"); // 24
238 method::findAll
239 Returns the indices of the string in the receiver, or nil if not found.
240 code::
241 "These are several words which are fish".findAll("are").postln;
242 "These are several words which are fish".findAll("fish").postln;
245 method::contains
246 Returns a link::Classes/Boolean:: indicating if the String contains string.
247 code::
248 "These are several words".contains("are").postln;
249 "These are several words".contains("fish").postln;
252 method::containsi
253 Same as link::#-contains::, but case insensitive.
254 code::
255 "These are several words".containsi("ArE").postln;
258 method::containsStringAt
259 Returns a link::Classes/Boolean:: indicating if the String contains string beginning at the specified index.
260 code::
261 "These are several words".containsStringAt(6, "are").postln;
264 method::icontainsStringAt
265 Same as link::#-containsStringAt::, but case insensitive.
267 method::escapeChar
268 Add the escape character (\) at the location of your choice.
269 code::
270 "This will become a Unix friendly string".escapeChar($ ).postln;
273 method::tr
274 Transliteration. Replace all instances of strong::from:: with strong::to::.
275 code::
276 ":-(:-(:-(".tr($(, $)); //turn the frowns upside down
279 method::replace
280 Like link::#-tr::, but with strings as arguments.
281 code::
282 "Here are several words which are fish".replace("are", "were");
285 method::printOn
286 Print the String on stream.
287 code::
288 "Print this on Post".printOn(Post);
290 // equivalent to:
291 Post << "Print this on Post";
294 method::storeOn
295 Same as link::#-printOn::, but formatted link::#-asCompileString::.
296 code::
297 "Store this on Post".storeOn(Post);
299 // equivalent to:
300 Post <<< "Store this on Post";
303 method::inspectorClass
304 Returns class link::Classes/StringInspector::.
306 method::stripRTF
307 Returns a new String with all RTF formatting removed.
308 code::
310 // same as File-readAllStringRTF
311 g = File("/code/SuperCollider3/build/Help/UGens/Chaos/HenonC.help.rtf","r");
312 g.readAllString.stripRTF.postln;
313 g.close;
317 subsection::Unix Support
319 Where relevant, the current working directory is the same as the location of the SuperCollider app and the shell is the Bourne shell (sh). Note that the cwd, and indeed the shell itself, does not persist:
320 code::
321 "echo $0".unixCmd; // print the shell (sh)
322 "pwd".unixCmd;
323 "cd Help/".unixCmd;
324 "pwd".unixCmd;
326 "export FISH=mackerel".unixCmd;
327 "echo $FISH".unixCmd;
329 It is however possible to execute complex commands:
330 code::
331 "pwd; cd Help/; pwd".unixCmd;
332 "export FISH=mackerel; echo $FISH".unixCmd;
334 Also on os x applescript can be called via osascript:
335 code::
336 "osascript -e 'tell application \"Safari\" to activate'".unixCmd;
338 Should you need an environment variable to persist you can use link::#-setenv::.
340 note::
341 Despite the fact that the method is called 'unixCmd', strong::it does work in Windows::. The string must be a DOS command, however: "dir" rather than "ls" for instance.
344 method::unixCmd
345 Execute the String on the command line using the Bourne shell (sh). Returns the pid of the newly created process (use Integer.pidRunning to test if a pid is alive). action is a Function that is called when the process has exited. It is passed two arguments: the exit code and pid of the exited process. postOutput is a Boolean that controls whether or not the output of the process is displayed in the post window.
346 code::
347 "ls Help".unixCmd;
348 "echo one; sleep 1; echo two; sleep 1".unixCmd { |res, pid| [\done, res, pid].postln };
351 method::unixCmdGetStdOut
352 Similar to link::#-unixCmd:: except that the stdout of the process is returned (synchronously) rather than sent to the post window.
353 code::
354 ~listing = "ls Help".unixCmdGetStdOut; // Grab
355 ~listing.reverse.as(Array).stutter.join.postln; // Mangle
358 method::systemCmd
359 Executes a unix command synchronously.
361 returns:: Error code of the unix command
363 method::runInTerminal
364 Execute the String in a new terminal window. (The string is incorporated into a temporary script file and executed using a shell. "/usr/bash" is the default shell used but you can optionally specify which shell to use as an argument.)
365 code::
366 "echo ---------Hello delightful SuperCollider user----------".runInTerminal;
369 method::setenv
370 Set the environment variable indicated in the string to equal the String strong::value::. This value will persist until it is changed or SC is quit. Note that if strong::value:: is a path you may need to call link::#-standardizePath:: on it.
371 code::
372 // all defs in this directory will be loaded when a local server boots
373 "SC_SYNTHDEF_PATH".setenv("~/scwork/".standardizePath);
374 "echo $SC_SYNTHDEF_PATH".unixCmd;
377 method::getenv
378 Returns the value contained in the environment variable indicated by the String.
379 code::
380 "USER".getenv;
383 method::pathMatch
384 Returns an link::Classes/Array:: containing all paths matching this String. Wildcards apply, non-recursive.
385 code::
386 Post << "Help/*".pathMatch;
389 method::loadPaths
390 Perform link::#-pathMatch:: on this String, then load and execute all paths in the resultant link::Classes/Array::.
391 code::
392 //first prepare a file with some code...
394 var f = File("/tmp/loadPaths_example.scd", "w");
395 if(f.isOpen, {
396         f.putString("\"This text is the result of a postln command which was loaded and executed by loadPaths\".postln");
397 }, {
398         "test file could not be created - please edit the file's path above".warn;
400 f.close;
403 //then load the file...
404 "/tmp/loadPaths_example.scd".loadPaths; //This file posts some text
407 method::load
408 Load and execute the file at the path represented by the receiver.
411 method::loadRelative
412 Load and execute the file at the path represented by the receiver, interpreting the path as relative to the current document or text file. Requires that the file has been saved.
414 method::resolveRelative
415 Convert the receiver from a relative path to an absolute path, relative to the current document or text file. Requires that the current text file has been saved. Absolute paths are left untransformed.
417 method::standardizePath
418 Expand ~ to your home directory, and resolve symbolic links. See link::Classes/PathName:: for more complex needs.
419 code::
420 "~/".standardizePath; //This will print your home directory
423 method::basename
424 Return the filename from a Unix path.
425 code::
426 "Imaginary/Directory/fish.rtf".basename;
429 method::dirname
430 Return the directory name from a Unix path.
431 code::
432 "Imaginary/Directory/fish.rtf".dirname;
435 method::splitext
436 Split off the extension from a filename or path and return both in an link::Classes/Array:: as [path or filename, extension].
437 code::
438 "fish.rtf".splitext;
439 "Imaginary/Directory/fish.rtf".splitext;
442 method::openOS
443 Open file, directory or URL via the operating system. On OSX this is implemented via teletype::open::, on Linux via
444 teletype::xdg-open:: and on Windows via teletype::start::.
445 code::
446 Platform.userConfigDir.openOS;
447 "http://supercollider.sf.net".openOS;
450 subsection::Document Support
452 method::newTextWindow
453 Create a new link::Classes/Document:: with this.
454 code::
455 "Here is a new Document".newTextWindow;
458 method::openDocument
459 Create a new link::Classes/Document:: from the path corresponding to this. Returns the Document.
460 code::
462 d = "Help/Help.html".openDocument;
463 d.class;
467 method::openTextFile
468 Create a new link::Classes/Document:: from the path corresponding to this. The selection arguments will preselect the indicated range in the new window. Returns this.
469 code::
471 d = "Help/Help.html".openTextFile(20, 210);
472 d.class;
476 method::findHelpFile
477 Returns the path for the helpfile named this, if it exists, else returns nil.
478 code::
479 "Document".findHelpFile;
480 "foobar".findHelpFile;
483 method::openHelpFile
484 Performs link::#-findHelpFile:: on this, and opens the file it if it exists, otherwise opens the main helpfile.
485 code::
486 "Document".openHelpFile;
487 "foobar".openHelpFile;
490 method::speak
491 Sends string to the speech synthesisier of the OS. (OS X only.) see: link::Classes/Speech::
492 code::
493 "hi i'm talking with the default voice now, i guess".speak;
496 subsection::Drawing Support
498 The following methods must be called within an Window-drawHook or a SCUserView-drawFunc function, and will only be visible once the window or the view is refreshed. Each call to Window-refresh SCUserView-refresh will 'overwrite' all previous drawing by executing the currently defined function.
500 See also: link::Classes/Window::, link::Classes/UserView::, link::Classes/Color::, and link::Classes/Pen::.
502 note::
503 for cross-platform GUIs, use code::Pen.stringAtPoint, Pen.stringInRect, Pen.stringCenteredIn, Pen.stringLeftJustIn, Pen.stringRightJustIn:: instead.
506 method::draw
507 Draws the String at the current 0@0 link::Classes/Point::. If not transformations of the graphics state have taken place this will be the upper left corner of the window. See also link::Classes/Pen::.
508 code::
510 w = Window.new.front;
511 w.view.background_(Color.white);
512 w.drawHook = {
513         "abababababa\n\n\n".scramble.draw
515 w.refresh
519 method::drawAtPoint
520 Draws the String at the given link::Classes/Point:: using the link::Classes/Font:: and link::Classes/Color:: specified.
521 code::
523 w = Window.new.front;
524 w.view.background_(Color.white);
525 w.drawHook = {
526         "abababababa\n\n\n".scramble.drawAtPoint(
527                 100@100,
528                 Font("Courier", 30),
529                 Color.blue(0.3, 0.5))
531 w.refresh;
535 method::drawInRect
536 Draws the String into the given link::Classes/Rect:: using the link::Classes/Font:: and link::Classes/Color:: specified.
537 code::
539 w = Window.new.front;
540 r = Rect(100, 100, 100, 100);
541 w.view.background_(Color.white);
542 w.drawHook = {
543         "abababababa\n\n\n".scramble.drawInRect(r, Font("Courier", 12), Color.blue(0.3, 0.5));
544         Pen.strokeRect(r);
546 w.refresh;
550 method::drawCenteredIn
551 Draws the String into the given Rect using the Font and Color specified.
552 code::
554 w = Window.new.front;
555 w.view.background_(Color.white);
556 r = Rect(100, 100, 100, 100);
557 w.drawHook = {
558         "abababababa\n\n\n".scramble.drawCenteredIn(
559                 r,
560                 Font("Courier", 12),
561                 Color.blue(0.3, 0.5)
562         );
563         Pen.strokeRect(r);
565 w.refresh;
569 method::drawLeftJustIn
570 Draws the String into the given Rect using the Font and Color specified.
571 code::
573 w = Window.new.front;
574 w.view.background_(Color.white);
575 r = Rect(100, 100, 100, 100);
576 w.drawHook = {
577         "abababababa\n\n\n".scramble.drawLeftJustIn(
578                 r,
579                 Font("Courier", 12),
580                 Color.blue(0.3, 0.5)
581         );
582         Pen.strokeRect(r);
584 w.refresh;
588 method::drawRightJustIn
589 Draws the String into the given link::Classes/Rect:: using the link::Classes/Font:: and link::Classes/Color:: specified.
590 code::
592 w = Window.new.front;
593 w.view.background_(Color.white);
594 r = Rect(100, 100, 100, 100);
595 w.drawHook = {
596         "abababababa\n\n\n".scramble.drawRightJustIn(
597                 r,
598                 Font("Courier", 12),
599                 Color.blue(0.3, 0.5)
600         );
601         Pen.strokeRect(r);
603 w.refresh;