Class Buffer
- All Implemented Interfaces:
Proxy
TextBuffer.
A GtkSourceBuffer object is the model for View widgets.
It extends the TextBuffer class by adding features useful to display
and edit source code such as syntax highlighting and bracket matching.
To create a GtkSourceBuffer use Buffer() or
withLanguage(org.gnome.gtksourceview.Language). The second form is just a convenience
function which allows you to initially set a Language. You can also
directly create a View and get its Buffer with
TextView.getBuffer().
The highlighting is enabled by default, but you can disable it with
setHighlightSyntax(boolean).
Context Classes:
It is possible to retrieve some information from the syntax highlighting
engine. The default context classes that are applied to regions of a
GtkSourceBuffer:
- **comment**: the region delimits a comment;
- **no-spell-check**: the region should not be spell checked;
- **path**: the region delimits a path to a file;
- **string**: the region delimits a string.
Custom language definition files can create their own context classes,
since the functions like iterHasContextClass(org.gnome.gtk.TextIter, java.lang.String) take
a string parameter as the context class.
GtkSourceBuffer provides an API to access the context classes:
iterHasContextClass(org.gnome.gtk.TextIter, java.lang.String),
getContextClassesAtIter(org.gnome.gtk.TextIter),
iterForwardToContextClassToggle(org.gnome.gtk.TextIter, java.lang.String) and
iterBackwardToContextClassToggle(org.gnome.gtk.TextIter, java.lang.String).
And the GtkSource.Buffer::highlight-updated signal permits to be notified
when a context class region changes.
Each context class has also an associated TextTag with the name
gtksourceview:context-classes:<name>. For example to
retrieve the TextTag for the string context class, one can write:
GtkTextTagTable *tag_table;
GtkTextTag *tag;
tag_table = gtk_text_buffer_get_tag_table (buffer);
tag = gtk_text_tag_table_lookup (tag_table, "gtksourceview:context-classes:string");
buffer = GtkSource.Buffer()
tag_table = buffer.get_tag_table()
tag = tag_table.lookup(name="gtksourceview:context-classes:string")
The tag must be used for read-only purposes.
Accessing a context class via the associated TextTag is less
convenient than the GtkSourceBuffer API, because:
- The tag doesn't always exist, you need to listen to the
Gtk.TextTagTable::tag-addedandGtk.TextTagTable::tag-removedsignals. - Instead of the
GtkSource.Buffer::highlight-updatedsignal, you can listen to theGtk.TextBuffer::apply-tagandGtk.TextBuffer::remove-tagsignals.
A possible use-case for accessing a context class via the associated
TextTag is to read the region but without adding a hard dependency on the
GtkSourceView library (for example for a spell-checking library that wants to
read the no-spell-check region).
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfaceFunctional interface declaration of theBracketMatchedCallbackcallback.static classstatic classBuffer.Builder<B extends Buffer.Builder<B>>Inner class implementing a builder pattern to construct a GObject with properties.static interfaceFunctional interface declaration of theCursorMovedCallbackcallback.static interfaceFunctional interface declaration of theHighlightUpdatedCallbackcallback.static interfaceFunctional interface declaration of theSourceMarkUpdatedCallbackcallback.Nested classes/interfaces inherited from class org.gnome.gtk.TextBuffer
TextBuffer.ApplyTagCallback, TextBuffer.BeginUserActionCallback, TextBuffer.ChangedCallback, TextBuffer.DeleteRangeCallback, TextBuffer.EndUserActionCallback, TextBuffer.InsertChildAnchorCallback, TextBuffer.InsertPaintableCallback, TextBuffer.InsertTextCallback, TextBuffer.MarkDeletedCallback, TextBuffer.MarkSetCallback, TextBuffer.ModifiedChangedCallback, TextBuffer.PasteDoneCallback, TextBuffer.RedoCallback, TextBuffer.RemoveTagCallback, TextBuffer.TextBufferClass, TextBuffer.UndoCallbackNested classes/interfaces inherited from class org.gnome.gobject.GObject
GObject.NotifyCallback, GObject.ObjectClass -
Constructor Summary
ConstructorsConstructorDescriptionBuffer()Creates a new Buffer.Buffer(MemorySegment address) Create a Buffer proxy instance for the provided memory address.Buffer(@Nullable TextTagTable table) Creates a new source buffer. -
Method Summary
Modifier and TypeMethodDescriptionprotected BufferasParent()Returns this instance as if it were its parent type.booleanbackwardIterToSourceMark(TextIter iter, @Nullable String category) Movesiterto the position of the previousMarkof the given category.protected voidbracketMatched(TextIter iter, BracketMatchType state) static Buffer.Builder<? extends Buffer.Builder> builder()ABuffer.Builderobject constructs aBufferwith the specified properties.voidchangeCase(ChangeCaseType caseType, TextIter start, TextIter end) Changes the case of the text between the specified iterators.createSourceMark(@Nullable String name, String category, TextIter where) Creates a source mark in thebufferof categorycategory.createSourceTag(@Nullable String tagName, @Nullable String firstPropertyName, Object... varargs) In short, this is the same function asTextBuffer.createTag(java.lang.String, java.lang.String, java.lang.Object...)but instead of creating aTextTag, this function creates aTag.voidemitBracketMatched(@Nullable TextIter iter, BracketMatchType state) Emits the "bracket-matched" signal.voidEmits the "cursor-moved" signal.voidemitHighlightUpdated(@Nullable TextIter start, @Nullable TextIter end) Emits the "highlight-updated" signal.voidemitSourceMarkUpdated(@Nullable TextMark mark) Emits the "source-mark-updated" signal.voidensureHighlight(TextIter start, TextIter end) Forces buffer to analyze and highlight the given area synchronously.booleanforwardIterToSourceMark(TextIter iter, @Nullable String category) String[]Get all defined context classes atiter.booleanDetermines whether bracket match highlighting is activated for the source buffer.booleanDetermines whether syntax highlighting is activated in the source buffer.boolean@Nullable LanguageReturns theLanguageassociated with the buffer, seesetLanguage(org.gnome.gtksourceview.Language).booleanReturns the text in the specified range converting any text formatting to equivalent Pango markup tags.static MemoryLayoutThe memory layout of the native struct.getSourceMarksAtIter(TextIter iter, @Nullable String category) Returns the list of marks of the given category atiter.getSourceMarksAtLine(int line, @Nullable String category) Returns the list of marks of the given category atline.@Nullable StyleSchemeReturns theStyleSchemeassociated with the buffer, seesetStyleScheme(org.gnome.gtksourceview.StyleScheme).static @Nullable TypegetType()Get the GType of the Buffer classbooleaniterBackwardToContextClassToggle(TextIter iter, String contextClass) Moves backward to the next toggle (on or off) of the context class.booleaniterForwardToContextClassToggle(TextIter iter, String contextClass) Moves forward to the next toggle (on or off) of the context class.booleaniterHasContextClass(TextIter iter, String contextClass) Check if the classcontextClassis set oniter.voidJoins the lines of text between the specified iterators.iteris set to a valid iterator pointing to the matching bracket ifstateisBracketMatchType.FOUND.onCursorMoved(Buffer.CursorMovedCallback handler) The "cursor-moved" signal is emitted when then insertion mark has moved.The ::highlight-updated signal is emitted when the syntax highlighting and context classes are updated in a certain region of thebuffer.The ::source-mark-updated signal is emitted each time a mark is added to, moved or removed from thebuffer.voidremoveSourceMarks(TextIter start, TextIter end, @Nullable String category) Remove all marks ofcategorybetweenstartandendfrom the buffer.voidsetHighlightMatchingBrackets(boolean highlight) Controls the bracket match highlighting function in the buffer.voidsetHighlightSyntax(boolean highlight) Controls whether syntax is highlighted in the buffer.voidsetImplicitTrailingNewline(boolean implicitTrailingNewline) Sets whether the this Buffer has an implicit trailing newline.voidsetLanguage(@Nullable Language language) Associates aLanguagewith the buffer.voidsetStyleScheme(@Nullable StyleScheme scheme) Sets aStyleSchemeto be used by the buffer and the view.voidSort the lines of text between the specified iterators.voidSort the lines of text between the specified iterators.static BufferwithLanguage(Language language) Creates a new source buffer using the highlighting patterns inlanguage.Methods inherited from class org.gnome.gtk.TextBuffer
addCommitNotify, addCommitNotify, addMark, addSelectionClipboard, applyTag, applyTagByName, backspace, beginIrreversibleAction, beginUserAction, changed, copyClipboard, createChildAnchor, createMark, createTag, cutClipboard, delete, deleteInteractive, deleteMark, deleteMarkByName, deleteRange, deleteSelection, emitApplyTag, emitBeginUserAction, emitChanged, emitDeleteRange, emitEndUserAction, emitInsertChildAnchor, emitInsertPaintable, emitInsertText, emitMarkDeleted, emitMarkSet, emitModifiedChanged, emitPasteDone, emitRedo, emitRemoveTag, emitUndo, endIrreversibleAction, endUserAction, getBounds, getCanRedo, getCanUndo, getCharCount, getEnableUndo, getEndIter, getHasSelection, getInsert, getIterAtChildAnchor, getIterAtLine, getIterAtLineIndex, getIterAtLineOffset, getIterAtMark, getIterAtOffset, getLineCount, getMark, getMaxUndoLevels, getModified, getSelectionBound, getSelectionBounds, getSelectionContent, getSlice, getStartIter, getTagTable, getText, insert, insertAtCursor, insertChildAnchor, insertInteractive, insertInteractiveAtCursor, insertMarkup, insertPaintable, insertRange, insertRangeInteractive, insertText, insertWithTags, insertWithTagsByName, markDeleted, markSet, modifiedChanged, moveMark, moveMarkByName, onApplyTag, onBeginUserAction, onChanged, onDeleteRange, onEndUserAction, onInsertChildAnchor, onInsertPaintable, onInsertText, onMarkDeleted, onMarkSet, onModifiedChanged, onPasteDone, onRedo, onRemoveTag, onUndo, pasteClipboard, pasteDone, placeCursor, redo, removeAllTags, removeCommitNotify, removeSelectionClipboard, removeTag, removeTagByName, selectRange, setEnableUndo, setMaxUndoLevels, setModified, setText, undoMethods inherited from class org.gnome.gobject.GObject
addToggleRef, addWeakPointer, bindProperty, bindProperty, bindProperty, bindPropertyFull, bindPropertyFull, bindPropertyWithClosures, bindPropertyWithClosures, compatControl, connect, connect, connect, constructed, disconnect, dispatchPropertiesChanged, dispose, dupData, dupQdata, emit, emitNotify, finalize_, forceFloating, freezeNotify, get, getData, getProperty, getProperty, getProperty, getQdata, getv, interfaceFindProperty, interfaceInstallProperty, interfaceListProperties, isFloating, newInstance, newInstance, newv, notify, notify, notifyByPspec, onNotify, ref, refSink, removeToggleRef, removeWeakPointer, replaceData, replaceQdata, runDispose, set, setData, setDataFull, setProperty, setProperty, setProperty, setQdata, setQdataFull, setv, stealData, stealQdata, takeRef, thawNotify, unref, watchClosure, weakRef, weakUnref, withPropertiesMethods inherited from class org.gnome.gobject.TypeInstance
callParent, callParent, cast, getPrivate, readGClass, writeGClassMethods inherited from class org.javagi.base.ProxyInstance
equals, handle, hashCode
-
Constructor Details
-
Buffer
Create a Buffer proxy instance for the provided memory address.- Parameters:
address- the memory address of the native object
-
Buffer
Creates a new source buffer.- Parameters:
table- aGtkTextTagTable, ornullto create a new one.
-
Buffer
public Buffer()Creates a new Buffer.
-
-
Method Details
-
getType
-
getMemoryLayout
The memory layout of the native struct.- Returns:
- the memory layout
-
asParent
Returns this instance as if it were its parent type. This is mostly synonymous to the Javasuperkeyword, but will set the native typeclass function pointers to the parent type. When overriding a native virtual method in Java, "chaining up" withsuper.methodName()doesn't work, because it invokes the overridden function pointer again. To chain up, callasParent().methodName(). This will call the native function pointer of this virtual method in the typeclass of the parent type.- Overrides:
asParentin classTextBuffer
-
withLanguage
Creates a new source buffer using the highlighting patterns inlanguage.This is equivalent to creating a new source buffer with a new tag table and then calling
setLanguage(org.gnome.gtksourceview.Language).- Parameters:
language- aGtkSourceLanguage.- Returns:
- a new source buffer which will highlight text
according to the highlighting patterns in
language.
-
backwardIterToSourceMark
Movesiterto the position of the previousMarkof the given category.Returns
trueifiterwas moved. Ifcategoryis NULL, the previous source mark can be of any category.- Parameters:
iter- an iterator.category- category to search for, ornull- Returns:
- whether
iterwas moved.
-
changeCase
Changes the case of the text between the specified iterators.Since 5.4, this function will update the position of
startandendto surround the modified text.- Parameters:
caseType- how to change the case.start- aGtkTextIter.end- aGtkTextIter.
-
createSourceMark
Creates a source mark in thebufferof categorycategory.A source mark is a
TextMarkbut organized into categories. Depending on the category a pixbuf can be specified that will be displayed along the line of the mark.Like a
TextMark, aMarkcan be anonymous if the passednameisnull. Also, the buffer owns the marks so you shouldn't unreference it.Marks always have left gravity and are moved to the beginning of the line when the user deletes the line they were in.
Typical uses for a source mark are bookmarks, breakpoints, current executing instruction indication in a source file, etc..
- Parameters:
name- the name of the mark, ornull.category- a string defining the mark category.where- location to place the mark.- Returns:
- a new
Mark, owned by the buffer.
-
createSourceTag
public TextTag createSourceTag(@Nullable String tagName, @Nullable String firstPropertyName, Object... varargs) In short, this is the same function asTextBuffer.createTag(java.lang.String, java.lang.String, java.lang.Object...)but instead of creating aTextTag, this function creates aTag.This function creates a
Tagand adds it to the tag table forbuffer. Equivalent to callingTextTag()and then adding the tag to the buffer’s tag table. The returned tag is owned by the buffer’s tag table, so the ref count will be equal to one.If
tag_nameisnull, the tag is anonymous.If
tag_nameis non-null, a tag calledtag_namemust not already exist in the tag table for this buffer.The
first_property_nameargument and subsequent arguments are a list of properties to set on the tag, as withGObject.set(java.lang.String, java.lang.Object...).- Parameters:
tagName- name of the new tag, ornullfirstPropertyName- name of first property to set, ornullvarargs-null-terminated list of property names and values- Returns:
- a new
Tag.
-
ensureHighlight
Forces buffer to analyze and highlight the given area synchronously.**Note**:
This is a potentially slow operation and should be used only when you need to make sure that some text not currently visible is highlighted, for instance before printing.
- Parameters:
start- start of the area to highlight.end- end of the area to highlight.
-
forwardIterToSourceMark
Movesiterto the position of the nextMarkof the givencategory.Returns
trueifiterwas moved. Ifcategoryis NULL, the next source mark can be of any category.- Parameters:
iter- an iterator.category- category to search for, ornull- Returns:
- whether
iterwas moved.
-
getContextClassesAtIter
Get all defined context classes atiter.See the
Bufferdescription for the list of default context classes.- Parameters:
iter- aGtkTextIter.- Returns:
- a new
nullterminated array of context class names. Use g_strfreev() to free the array if it is no longer needed.
-
getHighlightMatchingBrackets
public boolean getHighlightMatchingBrackets()Determines whether bracket match highlighting is activated for the source buffer.- Returns:
trueif the source buffer will highlight matching brackets.
-
getHighlightSyntax
public boolean getHighlightSyntax()Determines whether syntax highlighting is activated in the source buffer.- Returns:
trueif syntax highlighting is enabled,falseotherwise.
-
getImplicitTrailingNewline
public boolean getImplicitTrailingNewline() -
getLanguage
Returns theLanguageassociated with the buffer, seesetLanguage(org.gnome.gtksourceview.Language).The returned object should not be unreferenced by the user.
- Returns:
- the
Languageassociated with the buffer, ornull.
-
getLoading
public boolean getLoading() -
getMarkup
Returns the text in the specified range converting any text formatting to equivalent Pango markup tags. This allows the styled text to be displayed in other widgets that support Pango markup, such asGtkLabel.For very long ranges this function can take long enough that you could potentially miss frame renderings.
- Parameters:
start- start of range as aGtkTextIterend- end of range as aGtkTextIter- Returns:
- a newly-allocated string containing the text
with Pango markup, or
nullifstartandendare invalid. - Since:
- 5.18
-
getSourceMarksAtIter
-
getSourceMarksAtLine
-
getStyleScheme
Returns theStyleSchemeassociated with the buffer, seesetStyleScheme(org.gnome.gtksourceview.StyleScheme).The returned object should not be unreferenced by the user.
- Returns:
- the
StyleSchemeassociated with the buffer, ornull.
-
iterBackwardToContextClassToggle
Moves backward to the next toggle (on or off) of the context class.If no matching context class toggles are found, returns
false, otherwisetrue. Does not return toggles located atiter,only toggles afteriter.Setsiterto the location of the toggle, or to the end of the buffer if no toggle is found.See the
Bufferdescription for the list of default context classes.- Parameters:
iter- aGtkTextIter.contextClass- the context class.- Returns:
- whether we found a context class toggle before
iter
-
iterForwardToContextClassToggle
Moves forward to the next toggle (on or off) of the context class.If no matching context class toggles are found, returns
false, otherwisetrue. Does not return toggles located atiter,only toggles afteriter.Setsiterto the location of the toggle, or to the end of the buffer if no toggle is found.See the
Bufferdescription for the list of default context classes.- Parameters:
iter- aGtkTextIter.contextClass- the context class.- Returns:
- whether we found a context class toggle after
iter
-
iterHasContextClass
Check if the classcontextClassis set oniter.See the
Bufferdescription for the list of default context classes.- Parameters:
iter- aGtkTextIter.contextClass- class to search for.- Returns:
- whether
iterhas the context class.
-
joinLines
-
removeSourceMarks
Remove all marks ofcategorybetweenstartandendfrom the buffer.If
categoryis NULL, all marks in the range will be removed.- Parameters:
start- aGtkTextIter.end- aGtkTextIter.category- category to search for, ornull.
-
setHighlightMatchingBrackets
public void setHighlightMatchingBrackets(boolean highlight) Controls the bracket match highlighting function in the buffer.If activated, when you position your cursor over a bracket character (a parenthesis, a square bracket, etc.) the matching opening or closing bracket character will be highlighted.
- Parameters:
highlight-trueif you want matching brackets highlighted.
-
setHighlightSyntax
public void setHighlightSyntax(boolean highlight) Controls whether syntax is highlighted in the buffer.If
highlightistrue, the text will be highlighted according to the syntax patterns specified in theLanguageset withsetLanguage(org.gnome.gtksourceview.Language).If
highlightisfalse, syntax highlighting is disabled and all theTextTagobjects that have been added by the syntax highlighting engine are removed from the buffer.- Parameters:
highlight-trueto enable syntax highlighting,falseto disable it.
-
setImplicitTrailingNewline
public void setImplicitTrailingNewline(boolean implicitTrailingNewline) Sets whether the this Buffer has an implicit trailing newline.If an explicit trailing newline is present in a
TextBuffer,TextViewshows it as an empty line. This is generally not what the user expects.If
implicitTrailingNewlineistrue(the default value):- when a
FileLoaderloads the content of a file into thebuffer,the trailing newline (if present in the file) is not inserted into thebuffer. - when a
FileSaversaves the content of the this Buffer into a file, a trailing newline is added to the file.
On the other hand, if
implicitTrailingNewlineisfalse, the file's content is not modified when loaded into thebuffer,and thebuffer'scontent is not modified when saved into a file.- Parameters:
implicitTrailingNewline- the new value.
- when a
-
setLanguage
Associates aLanguagewith the buffer.Note that a
Languageaffects not only the syntax highlighting, but also the context classes. If you want to disable just the syntax highlighting, seesetHighlightSyntax(boolean).The buffer holds a reference to
language.- Parameters:
language- aGtkSourceLanguageto set, ornull.
-
setStyleScheme
Sets aStyleSchemeto be used by the buffer and the view.Note that a
StyleSchemeaffects not only the syntax highlighting, but also otherViewfeatures such as highlighting the current line, matching brackets, the line numbers, etc.Instead of setting a
nullscheme,it is better to disable syntax highlighting withsetHighlightSyntax(boolean), and setting theStyleSchemewith the "classic" or "tango" ID, because those two style schemes follow more closely the GTK theme (for example for the background color).The buffer holds a reference to
scheme.- Parameters:
scheme- aGtkSourceStyleSchemeornull.
-
sortLines
Sort the lines of text between the specified iterators.- Parameters:
start- aGtkTextIter.end- aGtkTextIter.flags-GtkSourceSortFlagsspecifying how the sort should behavecolumn- sort considering the text starting at the given column
-
sortLines
Sort the lines of text between the specified iterators.- Parameters:
start- aGtkTextIter.end- aGtkTextIter.flags-GtkSourceSortFlagsspecifying how the sort should behavecolumn- sort considering the text starting at the given column
-
bracketMatched
-
onBracketMatched
public SignalConnection<Buffer.BracketMatchedCallback> onBracketMatched(Buffer.BracketMatchedCallback handler) iteris set to a valid iterator pointing to the matching bracket ifstateisBracketMatchType.FOUND. Otherwiseiteris meaningless.The signal is emitted only when the
statechanges, typically when the cursor moves.A use-case for this signal is to show messages in a
Statusbar.- Parameters:
handler- the signal handler- Returns:
- a signal handler ID to keep track of the signal connection
- See Also:
-
emitBracketMatched
Emits the "bracket-matched" signal. SeeonBracketMatched(org.gnome.gtksourceview.Buffer.BracketMatchedCallback). -
onCursorMoved
public SignalConnection<Buffer.CursorMovedCallback> onCursorMoved(Buffer.CursorMovedCallback handler) The "cursor-moved" signal is emitted when then insertion mark has moved.- Parameters:
handler- the signal handler- Returns:
- a signal handler ID to keep track of the signal connection
- See Also:
-
emitCursorMoved
public void emitCursorMoved()Emits the "cursor-moved" signal. SeeonCursorMoved(org.gnome.gtksourceview.Buffer.CursorMovedCallback). -
onHighlightUpdated
public SignalConnection<Buffer.HighlightUpdatedCallback> onHighlightUpdated(Buffer.HighlightUpdatedCallback handler) The ::highlight-updated signal is emitted when the syntax highlighting and context classes are updated in a certain region of thebuffer.- Parameters:
handler- the signal handler- Returns:
- a signal handler ID to keep track of the signal connection
- See Also:
-
emitHighlightUpdated
Emits the "highlight-updated" signal. SeeonHighlightUpdated(org.gnome.gtksourceview.Buffer.HighlightUpdatedCallback). -
onSourceMarkUpdated
public SignalConnection<Buffer.SourceMarkUpdatedCallback> onSourceMarkUpdated(Buffer.SourceMarkUpdatedCallback handler) The ::source-mark-updated signal is emitted each time a mark is added to, moved or removed from thebuffer.- Parameters:
handler- the signal handler- Returns:
- a signal handler ID to keep track of the signal connection
- See Also:
-
emitSourceMarkUpdated
Emits the "source-mark-updated" signal. SeeonSourceMarkUpdated(org.gnome.gtksourceview.Buffer.SourceMarkUpdatedCallback). -
builder
ABuffer.Builderobject constructs aBufferwith the specified properties. Use the variousset...()methods to set properties, and finish construction withBuffer.Builder.build().- Returns:
- the builder object
-