Document:
Filter:
Classes | Frontends

Document

Editor-specific text document editing
Location: NOT INSTALLED!

Description

The Document class represents a text document within the context of your text editing environment. You can use the class to programmatically create, modify, and query these documents.

Document used to be an abstract class, meaning it didn't provide all the functionality itself, but instead relied on subclasses to complete the functionality. One such subclass was CocoaDocument. Although CocoaDocument was available only to macOS and had an ad hoc interface, it possessed many additional features like code animation and rich text.

In SuperCollider 3.6, Document changed a bit and now the "abstract class" descriptor is only partially true. The SuperCollider IDE provides its own version of the Document class. The Emacs editor still supplies ScelDocument (which links to EmacsDocument) as a subclass of Document. As an unfortunate byproduct of the history of Document, there are inconsistencies in the APIs of SCIDE's Document and Emacs' ScelDocument. This help file describes that of SCIDE.

Future versions of SuperCollider will aim to fix these API inconsistencies and restore the functionality of CocoaDocument.

Setting the Environment

By default envir it is set to the current Environment. However, you can make it use its own Environment also. Thus, e.g., if you were to set the Environment variable ~myVar = 12 in the current Environment, you can create a new Document window in which that Environment variable is not set.

Class Methods

.new

Arguments:

title

An instance of String or Symbol.

string

An instance of String. The contents of the document.

envir

An instance of Environment. The Environment to be used by the interpreter of the document window. By default, it is set to the current Environment.

Discussion:

Document.new("this is the title", "this is the text");

.open

Open a document from a path.

Arguments:

path

The file system path to the document. An instance of String.

selectionStart

The beginning of the cursor selection of the file content.

selectionLength

The length of the cursor selection of the file content.

envir

An instance of Environment. The Environment to be used by the interpreter of the document window. By default, it is set to the current Environment.

Discussion:

Document.open("README", 292,253); // notice the selected text in the open document

.openDocuments

Returns an Array of all open documents.

d = Document.openDocuments.do{ |doc| doc.name.postln };

.hasEditedDocuments

Returns true if there are edited Documents.

.closeAll

WARNING: Closes all open Documents, whether edited or not.

Arguments:

leavePostWindowOpen

An instance of Boolean.

.closeAllUnedited

Closes all unedited Documents.

Arguments:

leavePostWindowOpen

An instance of Boolean.

.current

Gets/sets the current Document.

Arguments:

value

A Document.

Discussion:

Document.current.name.postln; // Prints "Document.html"

.allDocuments

Returns all documents.

.globalKeyDownAction

Get/set A global action to be performed when a key is pressed.

Arguments:

action

An instance of Function or FunctionList.

.globalKeyUpAction

Get/set A global action to be performed when a key is released.

Arguments:

action

An instance of Function or FunctionList.

.initAction

Get/set A an action to be performed up opening or creating a Document.

Arguments:

action

An instance of Function or FunctionList.

.autoRun

If a document begins with the String, "/*RUN*/", then the code following it int he file will be executed on opening the file, if autorun is set to true.

Arguments:

value

An instance of Boolean. Default value is true.

.implementationClass

The editor implementation specific class which will handle Documents.

Arguments:

value

A class for implementing Document.

Path Utilities

Utilities and settings for dealing with documents such as SuperCollider code files. By default the document directory is SuperCollider's application directory.

.dir

Get/set the default document directory. The default is dependent on Document: implementationClass.

Arguments:

path

The file system path to the directory. An instance of String.

Discussion:

In Main-startUp you can set this to a more practical directory:

Document.dir = "~/Documents/SuperCollider";

.standardizePath

Arguments:

p

The file system path to the directory. An instance of String.

Discussion:

If it is a relative path, expand it to an absolute path relative to your document directory. Expand tildes in path (your home directory), resolve symbolic links (but not aliases). Also converts from Mac OS 9 path format. See PathName for more complex needs.

Document.standardizePath("~/"); // This will print your home directory

Document.standardizePath(":Patches:newfoots:fastRuckAndTuck");
// Returns: /Volumes/Macintosh HD/Users/cruxxial/Documents/SC3docs/Patches/newfoots/fastRuckAndTuck

Document.standardizePath("~/Documents/SC3docs/Patches/newfoots/fastRuckAndTuck");
// Returns: Patches/newfoots/fastRuckAndTuck

Document.standardizePath("Patches/newfoots/fastRuckAndTuck")
// Returns: Patches/newfoots/fastRuckAndTuck

.abrevPath

Returns a path relative to Document.dir, if the path is inside Document.dir.

Arguments:

path

The file system path to the directory. An instance of String.

Inherited class methods

Instance Methods

General Document Properties

.path

Get / set the the Document's path.

Arguments:

apath

An instance of String. A files system path.

Discussion:

Document.current.path.postln;

.dir

Returns the directory of a Document.

Discussion:

Document.current.dir.postln;

==

A binary operator.

Arguments:

that

An instance of Document.

Discussion:

Document.current == Document.listener; // presumably returns false

.editable

Get / set the the document is editable.

Arguments:

bool

An instance of Boolean.

.name

Get / set the title (same as Document: title).

Arguments:

aname

An instance of String.

Discussion:

Document.current.name.postln;

.title

Get / set the title (same as Document: name).

Arguments:

newTitle

An instance of String.

.promptToSave

Get/set whether a document is prompts to save if it has been changed. Use this with caution.

Arguments:

bool

An instance of Boolean.

.closed

Returns true if the document has been closed.

.isEdited

Returns true if the document has been edited.

Document.current.isEdited.postln;

.isFront

Returns true if the document is in front.

.didBecomeKey

Saves the current Environment, makes the document current, and performs its Document: toFrontAction.

.didResignKey

Performs the Document's Document: endFrontAction and restores the current Environment.

Controlling Document

.close

Close a document.

(
Task({
    var doc;
    doc = Document("background", "closing in 2 seconds");
    doc.stringColor_(Color.blue);
    1.wait;
    doc.background_(Color.blue(alpha:0.8));
    1.wait;
    doc.close;
}).play(AppClock);
)

.front

Bring a document to the front.

Document.listener.front;

.onClose

Get/set the action to be performed on closing the document.

Arguments:

value

An instance of Function or FunctionList.

.endFrontAction

Get/set the action to be performed when the document becomes no longer the front document.

Arguments:

value

An instance of Function or FunctionList.

.toFrontAction

Get / set the action to be performed when the document become the front document.

Arguments:

value

An instance of Function or FunctionList.

.mouseDownAction

Get/set the action to be performed on Document: mouseDown.

Arguments:

action

An instance of Function or FunctionList. The arguments passed to the function are: document, x, y, modifiers, buttonNumber, clickCount, clickPos.

.mouseUpAction

Get/set the action to be performed on Document: mouseUp.

Arguments:

action

An instance of Function or FunctionList. The arguments passed to the function are: document, x, y, modifiers, buttonNumber, clickCount, clickPos.

Discussion:

(

//add a mouse action to this document:
//example: easy button:
//when you click in front of a 17 a SinOsc will start up;
s.waitForBoot({
    Document.current.mouseUpAction_({arg doc;
        var char;
        char = doc.rangeText(doc.selectionStart, 2);
        if(char == "17",{
            {EnvGen.kr(Env.perc, doneAction: Done.freeSelf) * SinOsc.ar([600,720,300].choose, 0, 0.5)}.play;
        });
        if(char == "23",{
            {EnvGen.kr(Env.perc, doneAction: Done.freeSelf) * PinkNoise.ar(0.2)}.play;
        });
    })
});
)

Test here and click in front of the numbers: 17 and 23.

Document.current.mouseUpAction = nil; // clear mouseUpActiont

.keyDownAction

Get/set the action to be performed on Document: keyDown.

Arguments:

action

An instance of Function or FunctionList. The arguments passed to the function are: document, char, modifiers, unicode, keycode. See View: Key actions for details on these arguments.

Discussion:

Document.current.keyDownAction = { arg ...args; args.postln };
// now type some text
Document.current.keyDownAction = nil;

.keyUpAction

Get/set the action to be performed on Document: keyUp.

Arguments:

action

An instance of Function or FunctionList. The arguments passed to the function are: document, char, modifiers, unicode, keycode. See View: Key actions for details on these arguments.

Discussion:

Document.current.keyUpAction = { arg ...args; args.postln };
// now type some text
Document.current.keyUpAction = nil;

Editing Content

.selectLine

Select a line of the document by number.

Arguments:

line

An Integer.

Discussion:

Document.current.selectLine(390);

.selectRange

Select a text range in the string of the document.

Arguments:

start

The start index.

length

The length of the selection.

Discussion:

(
Document.current.selectRange(Document.current.selectedRangeLocation + 3, 150);
)

.selectionStart

Returns the start of a current selection.

Document.current.selectionStart.postln;

.selectionSize

Returns the size of a current selection.

(
var doc;
doc = Document.current;
doc.selectRange(doc.selectionStart - 40, 10);
doc.selectionSize.postln;
)

.selectedString

Gets/sets the selected string.

Arguments:

txt

An instance of String.

Discussion:

(
var doc;
doc = Document.current;
doc.selectRange(doc.selectionStart - 40, 10);
doc.selectedString.postln;
)

.currentLine

Returns the current line as a String.

(
var doc;
doc = Document.current;
doc.selectRange(doc.selectionStart - 40, 10);
doc.currentLine.postln;
)

.getSelectedLines

Returns all full lines from before rangestart to after rangestart + rangesize as a String.

Discussion:

(
var doc;
doc = Document.current;
doc.selectRange(doc.selectionStart - 40, 10);
doc.getSelectedLines(doc.selectionStart - 40, 130).postln;
)

.string

Gets or sets the string within a certain range.

Arguments:

string

A String.

rangestart

An Integer.

rangesize

An Integer.

Discussion:

// Select the following code in parentheses and execute it
(
Document.current.string_(": test test test test test ",
    Document.current.selectedRangeLocation + 12,
    18);
)
// Watch me change content

Subclassing and Internal Methods

The following methods are usually not used directly or are called by a primitive. Programmers can still call or override these as needed.

    *startup
    *numberOfOpen
    mouseUp (x, y, modifiers, buttonNumber, clickCount, clickPos)
    keyDown (character, modifiers, unicode, keycode)
    keyUp (character, modifiers, unicode, keycode)
    getIdentifierCoordFromEnd (endPos)
    dataptr

    Private. Used only internally:
    *newFromIndex (idx)
    *prnumberOfOpen
    *prGetLast
    *prGetIndexOfListener
    *prBasicNew
    prAdd
    prGetLastIndex
    setFont (font, rangeStart, rangeSize)
    setTextColor (color, rangeStart, rangeSize)
    propen (path, selectionStart, selectionLength)
    rangeText (rangestart, rangesize)
    insertTextRange (string, rangestart, rangesize)
    prinitByString (title, str, makeListener)
    prSetBackgroundColor (color)
    prGetBackgroundColor (color)
    prSelectLine (line)
    prIsEditable_ (editable)
    prSetTitle (argName)
    prGetTitle
    prGetFileName
    prSetFileName (apath)
    prGetBounds (argBounds)
    prSetBounds (argBounds)
    prclose
    prinsertText (dataPtr, txt)
    prinitByIndex (idx)
    envir
    envir_ (ev)
    text
    removeUndo
    selectedText
    selectUnderlinedText (clickPos)
    linkAtClickPos (clickPos)
    selectedRangeLocation
    selectedRangeSize
    restoreCurrentEnvironment
    saveCurrentEnvironment
    initByIndex (idx)
    initLast
    initFromPath (path, selectionStart, selectionLength)
    initByString (argTitle, str, makeListener)

Inherited instance methods

Examples

//unfocusedFront_
(
Document.allDocuments.at(0).unfocusedFront
)


(
var doc;
doc = Document("", "||");
doc.background_(Color.blue(alpha: 1.0.rand));

Task({
    1000.do({
        doc.setFont(rangeSize: [7, 8, 9, 24].choose);
        0.08.wait;
    })
}).play(AppClock);

Task({
    100.do({
        1.01.wait;
        doc.stringColor_([Color.red(alpha: 1.0.rand), Color.green(alpha: 1.0.rand)].choose);
    })
}).play(AppClock);

Task({
    100.do({
        1.01.wait;
        doc.selectedString_(["\"\n#", "||", "-", "--"].choose);
    })
}).play(AppClock);

Task({
    var co, mul;
    co = 0.1;
    mul = 1.02;
    100.do({
        0.16.wait;
        co = co * mul;
        if(co > 0.99, { co = 0.1 });
        doc.background_(Color.blue(alpha: co));
    });
    doc.close;
}).play(AppClock)
)

A simple implementation of TBT (time based text) http://tbt.dyne.org/?info=download

// record: type some text
(
var time = Main.elapsedTime;
a = List.new;
r = Routine { |char|
loop {
    a = a.add([char, Main.elapsedTime - time]);
    char = 0.yield;
}
};

Document.new("type some text")
    .bounds_(Rect(100,SCWindow.screenBounds.height - 250, 400, 200))
    .keyDownAction = { |doc, key| r.value(key) ; time = Main.elapsedTime};
)

// play back text in time
(
d = Document.new("type some text")
    .bounds_(Rect(550,SCWindow.screenBounds.height-250,400,200));
fork({
    a.do { |pair|
        d.string = d.string ++ pair[0];
        pair[1].wait;
    }
}, AppClock)
)

Changing the default look of documents can be done with the help of the *initAction method. Run the following example once. Afterwards all newly created documents will have a dark grey background. To make this change happen every time you start SuperCollider, put the code inside your startup.scd file (and optionally wrap it in a {}.defer(0.1) ).

(
Document.listener.background = Color.red;    //a special color for post document
Document.listener.bounds = Rect(1, 461, 620, 567);    //move and resize post document
Document.initAction = {|doc|            //function to run for every new document
    doc.background = Color.grey(0.1, 0.9);
    doc.bounds = Rect(0, 119, 1280, 659);
    doc.selectedBackground = Color(0.4, 0.05, 0.18);
    doc.stringColor = Color.grey(0.9);
};
)