Documentation

YASHE extends the CodeMirror Library. For a complete overview of the functionality they offer (such as event hooks), check out the CodeMirror Documentation. Below we elaborate on the functionality YASHE offers (in addition to the CodeMiror API).
Note: Where CodeMirror provides CodeMirror in the global namespace, we provide YASHE.

Getting Started

Initialize YASHE via its constructor, or via the command fromTextArea. Both return in instance of YASHE, from now on referred to as yashe (lowercase). Both function take as argument a config object. See the section on defaults for more information on this config object.

YASHE(parent: DOM-Element, settings: Object) → YASHE instance: yashe

Main YASHE constructor. Pass a DOM element as argument to append the editor to, and (optionally) pass along config settings (see the YASHE.defaults object below, as well as the regular CodeMirror documentation, for more information on configurability)

YASHE.fromTextArea(textArea: DOM element, config: Object) → YASHE instance: yashe

Initialize YASHE from an existing text area (see CodeMirror for more info)

Examples

Configuration

This configuration object is accessible/changeable via YASHE.defaults and yashe.options, and you can pass these along when initializing YASHE as well. Other than the configuration we describe here, check the CodeMirror documentation for even more options you can set, such as disabling line numbers, or changing keyboard shortcut keys.

Defaults

var yashe = YASHE(document.getElementById('domId'), {
value:'Starting value of the editor',
mode:'shex',
theme:'wiki', //dark
lineNumbers: true,
lineWrapping: true,
fontSize: 14,
cursorHeight:15,
firstLineNumber:1,
readOnly:false,
showCursorWhenSelecting:fasle,
tabMode: 'indent',
collapsePrefixesOnLoad: false,
matchBrackets: true,
fixedGutter: true,
syntaxErrorCheck: true,
showTooltip: true,
showUploadButton: true,
showDownloadButton: true,
showCopyButton: true,
showDeleteButton: true,
showThemeButton: true,
showFullScreenButton: true,
persistent: null,
extraKeys: {
"Ctrl-Space": YASHE.autoComplete,
"Cmd-Space": YASHE.autoComplete,
"Ctrl-D": YASHE.deleteLine,
"Cmd-K": YASHE.deleteLine,
"Ctrl-/": YASHE.commentLines,
"Cmd-/": YASHE.commentLines,
"Ctrl-Down": YASHE.copyLineDown,
"Ctrl-Up": YASHE.copyLineUp,
"Cmd-Down": YASHE.copyLineDown,
"Cmd-Up": YASHE.copyLineUp,
"Shift-Ctrl-F": YASHE.doAutoFormat,
"Shift-Cmd-F": YASHE.doAutoFormat,
"Ctrl-S": YASHE.storeContent,
"Cmd-S": YASHE.storeConten,
"Ctrl-Enter": YASHE.executeQuery,
"Cmd-Enter": YASHE.executeQuery,
} });

Events

"change" (instance: CodeMirror, changeObj: object)

Fires every time the content of the editor is changed

"cursorActivity" (instance: CodeMirror)

Will be fired when the cursor or selection moves, or any change is made to the editor content

"keyHandled" (instance: CodeMirror, name: string, event: Event)

Fired after a key is handled through a key map. name is the name of the handled key (for example "Ctrl-X" or "'q'"), and event is the DOM keydown or keypress event

"focus" (instance: CodeMirror, event: Event)

Fires whenever the editor is focused

"blur" (instance: CodeMirror, event: Event)

Fires whenever the editor is unfocused

"scroll" (instance: CodeMirror)

Fires when the editor is scrolled

refresh

Fires when the editor is refreshed or resized. Mostly useful to invalidate cached values that depend on the editor or character size

"optionChange" (instance: CodeMirror, option: string)

Dispatched every time an option is changed with setOption

"upload"(instance: CodeMirror)

Fires after uploading a file by the upload button

"download"(instance: CodeMirror)

Fires after downloading a file by the upload button

"copy"(instance: CodeMirror)

Fires after downloading a file by the download button

"changeTheme"(instance: CodeMirror)

Fires after changing the editor theme using the change theme button

"delete"(instance: CodeMirror)

Fires after deleting the editor content by the delete buttton

"expandScreen"(instance: CodeMirror)

Fires after expanding screen

"collapseScreen"(instance: CodeMirror)

Fires after collapsing screen

Event Handlers

cm.on(type: string, func: (...args))

Register an event handler for the given event type (a string) on the editor instance. There is also a CodeMirror.on(object, type, func) version that allows registering of events on any object

yashe.on('blur', function(yashe) {
console.log('The editor has been unfocused!');
});

cm.off(type: string, func: (...args))

Remove an event handler on the editor instance. An equivalent CodeMirror.off(object, type, func) also exists.

yashe.off('blur');

Fire your own events

CodeMirror.signal(target, name, args...)

Codemirror.signal(yashe,'myOwnEvent'args...);

API

API methods accessible via the yashe instance
yashe.setValue(query: String)

Set query value in editor (see also)

yashe.getValue() → query: String

Get query value from editor (see also)

yashe.getLine(n: integer) → string

Get the content of line n

yashe.lineCount() → integer

Get the number of lines in the editor

yashe.firstLine() → integer

Get the number of first line in the editor

yashe.lastLine() → integer

Get the number of last line in the editor

yashe.getSelection(?lineSep: string) → string

Get the currently selected code. Optionally pass a line separator to put between the lines in the output. When multiple selections are present, they are concatenated with instances of lineSep in between.

yashe.replaceSelection(replacement: string, ?select: string)

Replace the selection(s) with the given string. By default, the new selection ends up after the inserted text. The optional select argument can be used to change this—passing "around" will cause the new text to be selected, passing "start" will collapse the selection to the start of the inserted text.

yashe.getCursor(?start: string) → {line, ch}

Retrieve one end of the primary selection. start is an optional string indicating which end of the selection to return. It may be "from", "to", "head" (the side of the selection that moves when you press shift+arrow), or "anchor" (the fixed side of the selection). Omitting the argument is the same as passing "head". A {line, ch} object will be returned.

yashe.somethingSelected() → boolean

Return true if any text is selected

yashe.setCursor(pos: {line, ch}|number, ?ch: number, ?options: object)

Set the cursor position. You can either pass a single {line, ch} object, or the line and the character as two separate parameters. Will replace all selections with a single, empty selection at the given position

yashe.hasFocus() → boolean

Tells you whether the editor currently has focus

yashe.findWordAt(pos: {line, ch}) → {anchor: {line, ch}, head: {line, ch}}

Returns the start and end of the 'word' (the stretch of letters, whitespace, or punctuation) at the given position

yashe.getOption(option: string) → any

Retrieves the current value of the given option for this editor instance

yashe.setOption(option: string, value: any)

Change the configuration of the editor. option should the name of an option, and value should be a valid value for that option

yashe.getDoc() → Doc

Retrieve the currently active document from an editor

yashe.getEditor() → CodeMirror

Retrieve the editor associated with a document. May return null

yashe.undo()

Undo one edit (if any undo events are stored)

yashe.redo()

Redo one undone edit

yashe.setSize(width: number|string, height: number|string)

Programmatically set the size of the editor (overriding the applicable CSS rules). width and height can be either numbers (interpreted as pixels) or CSS units ("100%", for example). You can pass null for either of them to indicate that that dimension should not be changed

yashe.scrollTo(x: number, y: number)

Scroll the editor to a given (pixel) position. Both arguments may be left as null or undefined to have no effect

yashe.refresh()

If your code does something to change the size of the editor element (window resizes are already listened for), or unhides it, you should probably follow up by calling this method to ensure CodeMirror is still looking as intended

yashe.getTokenAt(pos: {line, ch}, ?precise: boolean) → object

Retrieves information about the token the current mode found before the given position (a {line, ch} object). The returned object has the following properties:

start -> The character (on the given line) at which the token starts

end -> The character at which the token ends

string->The token's string

type -> The token type the mode assigned to the token, such as "keyword" or "comment" (may also be null)

state -> The mode's state at the end of this token

yashe.getDefinedPrefixes() → object:

Fetch defined prefixes

yashe.addPrefixes(prefixes: object)

Add prefixes to the query. The prefixes are defined as {"rdf: "http://www.w3.org/1999/02/22-rdf-syntax-ns#"}

yashe.removePrefixes(prefixes: object)

Remove prefixes from query. The prefixes are defined as {"rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#"}

yashe.setSize(width: Number|string, height: Number|string)

Set size. Use null value to leave width or height unchanged. To resize the editor to fit its content, see http://codemirror.net/demo/resize.html

yashe.enableCompleter(completerName: String)

Enable an autocompleter with this name. Only makes sense if you've programatically disabled this completer before, as a plugin is automatically enabled when registering it (see this function)

yashe.disableCompleter(completerName: String)

Disable an autocompleter with this name.

yashe.storeBulkCompletions(type: String)

Store bulk completions in memory as trie, and in localstorage as well (if enabled). The argument should be a key from the autocompletion settings

yashe.collapsePrefixes(collapse: boolean)

Collapsing prefixes if there are any. Use false to expand them.

Statics

Static functions YASHE
YASHE.registerAutocompleter(name: String, autocompleter: function)

Register an autocompleter in YASHE. This automatically enables the completer as well

YASHE.getCompleteToken(doc: yashe, token: Object, cursor: Object) → token: Object

When typing a shape, this shape is sometimes syntactically invalid, causing the current tokens to be incorrect This causes problem for autocompletion. http://bla might result in two tokens: http:// and bla. We'll want to combine these

Writing an Autocompletion Plugin

To register an autocompletion, one needs to execute the YASHE.registerAutocompleter function. Below, we describe the autocompletion function in more detail, and the object it should return.
constructor(doc: yashe) → configurationObject: Object

Autocompleter constructor, which should return the object described below

get: function|array Required

Get the autocompletions. Either a function which returns an array, or an actual array. The array should be in the form ["<completionsString1>", "<completionsString2>"].

If used as a function, the parameters it receives are

  1. token: object If 'bulk' loading is disabled, use this token to return the appropriate list of suggestions for
  2. callback: function If 'async' is enabled, return the suggestions by passing it on to this callback
isValidCompletionPosition: function() → boolean Required

Check whether the cursor is in a proper position for this autocompletion.

preProcessToken: function(token: object|string) → token: object Optional

Preprocesses the codemirror token before matching it with the autocompletions list. Use this for e.g. autocompleting prefixed resources when your autocompletion list contains only full-length URIs E.g., foaf:name -> http://xmlns.com/foaf/0.1/name

postProcessToken: function(token: object|string, suggestion: string) → string Optional

Postprocesses the autocompletion suggestion. Use this for e.g. returning a prefixed URI based on a full-length URI suggestion E.g., http://xmlns.com/foaf/0.1/name -> foaf:name

async: boolean Required

Specifies that the get function is asynchronous

bulk: boolean Required

Use bulk loading of completions: all completions are retrieved onLoad using the get() function. Alternatively, disable bulk loading, to call the get() function whenever a token needs autocompletion (in which case the completion token is passed on to the get() function). whenever you have an autocompletion list that is static, and that easily fits in memory, we advice you to enable bulk for performance reasons (especially because the autocompletions are stored in a trie)

autoShow: boolean Optional

Auto-show the autocompletion dialog. Disabling this requires the user to press [ctrl|cmd]-space to summon the dialog. Note: this only works when completions are not fetched asynchronously

persistent: string|function Optional

Automatically store autocompletions in localstorage. This is particularly useful when the get() function is an expensive ajax call. Autocompletions are stored for a period of a month. Set this property to null to disable persistency. Otherwise, set a string value (or a function returning a string val), returning the key in which to store the data. Note: this feature only works when completions are loaded in memory (i.e. bulk: true)

callbacks: object Optional

A set of callbacks. Most, taken from the CodeMirror showhint plugin

validPosition: function Optional

Fires when a codemirror change occurs in a position where we can show this particular type of autocompletion

invalidPosition: function Optional

Fires when a codemirror change occurs in a position where we can not show this particular type of autocompletion

showHint: function Optional

See CodeMirror manual

select: function Optional

See CodeMirror manual

pick: function Optional

See CodeMirror manual

close: function Optional

See CodeMirror manual

Configuring Autocompletion Plugins

To modify how autocompletion plugins work, you can simply overwrite the settings and/or function that are explained in the section above. To e.g. modify the autoShow setting for the prefix autocompleter, set `YASHE.Autocompleters.prefixes.autoShow = false` before you initialize YASHE. Some plugins may come with extra configuration options such as the prefix autocompleter, that allows you to change the url from where the prefix json is fetched:
YASHE.Autocompleters.prefixes.fetchFrom: string (default: //prefix.cc/popular/all.file.json)

Where to fetch the prefix json from. Change this when you'd like to host the json yourself. This might be useful when you run YASHE on an `https` site, considering that prefix.cc currently does not support `https`