document

package
v1.7.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package document holds documents: a buffer with metadata, undo and decorations (SPEC §7.1).

Index

Constants

View Source
const (
	DefaultTabSize      = 4
	DefaultInsertSpaces = true
)

Default indentation, as VS Code's.

View Source
const (
	// SchemeFile is a file on disk; the path is absolute.
	SchemeFile = "file"
	// SchemeUntitled is a document that has no file yet; the path is its number.
	SchemeUntitled = "untitled"
	// SchemeVirtual is read-only generated content, such as the default settings
	// JSON or the saved version of a file for "Compare with Saved".
	SchemeVirtual = "emetos-virtual"
)

The URI schemes of SPEC §7.1.

View Source
const DefaultAutoSaveDelay = time.Second

DefaultAutoSaveDelay is the files.autoSaveDelay VS Code uses when the setting is not a number of 0 or more.

View Source
const DefaultLanguage = "plaintext"

DefaultLanguage is the language of a document nothing else is known about.

Variables

This section is empty.

Functions

func AutoSaveDelay

func AutoSaveDelay(milliseconds float64) time.Duration

AutoSaveDelay is the delay files.autoSaveDelay (milliseconds) stands for: as VS Code, a number of 0 or more is used as it is and anything else (negative, not a number) is the default of one second.

func SameStat

func SameStat(a, b fileio.FileStat) bool

SameStat reports whether two stats describe the same file content as far as the editor can tell: the same size and the same modification time. This is the test of SPEC §10.5, for the editor's own writes and for the changes of other programs.

func TrackOffset

func TrackOffset(p int, sticksToPrevious bool, editStart, editEnd, textLen int) int

TrackOffset is where the offset p ends up when the bytes [editStart, editEnd) are replaced by textLen bytes: the rule decorations follow, for a single point. A point at the edit's start or end stays before the inserted text when sticksToPrevious, and moves after it otherwise; a point inside the replaced bytes keeps its offset while that is inside the new text, and else goes to the end of the new text.

Types

type AutoSave

type AutoSave struct {
	// contains filtered or unexported fields
}

AutoSave is the controller of the auto save of the documents of one window.

func NewAutoSave

func NewAutoSave(clock AutoSaveClock, host AutoSaveHost) *AutoSave

NewAutoSave makes a controller that follows documents once Track is called for them.

func (*AutoSave) Check

func (a *AutoSave) Check(doc *Document, reason SaveReason) AutoSaveBlock

Check tells why the document is not saved by itself for a reason (AutoSaveNotBlocked when it is).

func (*AutoSave) ConfigChanged

func (a *AutoSave) ConfigChanged()

ConfigChanged tells that the settings may have changed. A document whose configuration changed loses its timer and, when auto save is on for it, is saved at once, as VS Code saves every dirty document when the configuration of auto save changes ("Toggle Auto Save" on a window with unsaved changes saves them); switching auto save off cancels what was pending.

func (*AutoSave) Dispose

func (a *AutoSave) Dispose()

Dispose untracks every document.

func (*AutoSave) FocusLost

func (a *AutoSave) FocusLost(doc *Document)

FocusLost tells that the editor of a document lost the focus, or that another editor became the active one: with onFocusChange the document is saved.

func (*AutoSave) MarkersChanged

func (a *AutoSave) MarkersChanged()

MarkersChanged tells that the markers changed: a document that waited for its errors to go is saved when it has none now.

func (*AutoSave) OnClose

func (a *AutoSave) OnClose(doc *Document) (SaveReason, bool)

OnClose tells how a document is saved before its editor closes, and whether it is at all: with onFocusChange the editor saves instead of asking (the reason is SaveFocusChange), and with onWindowChange too (SaveWindowChange; VS Code does so on Linux and Windows, where a dialog takes the focus from the window). afterDelay asks like any other mode. A document that may not be auto saved (see Check) is asked about.

Ported from VS Code: src/vs/workbench/browser/parts/editor/editorGroupView.ts (doHandleCloseConfirmation)

func (*AutoSave) OnShutdown

func (a *AutoSave) OnShutdown(doc *Document) bool

OnShutdown tells whether a dirty document is saved by itself when the window closes, whatever the mode, as VS Code's backup tracker does before it asks or backs up (the reason is SaveAuto and the save participants are skipped, for speed).

Ported from VS Code: src/vs/workbench/services/workingCopy/electron-browser/workingCopyBackupTracker.ts (onBeforeShutdownWithModified)

func (*AutoSave) Paused

func (a *AutoSave) Paused(doc *Document) bool

Paused tells whether a failed save keeps the document from being saved by itself.

func (*AutoSave) Reschedule

func (a *AutoSave) Reschedule(doc *Document)

Reschedule starts the timer of a dirty document again, for a caller that dropped a save of it (a Save As dialog was open) and wants it tried later.

func (*AutoSave) SaveFailed

func (a *AutoSave) SaveFailed(doc *Document)

SaveFailed tells that a save of the document failed, whoever asked for it: its auto save pauses until a save succeeds or the file is read again, so that one broken file is not tried on every key.

func (*AutoSave) Track

func (a *AutoSave) Track(doc *Document)

Track makes the controller follow a document: its edits start and restart the timer of afterDelay, its saves stop it. A dirty document is scheduled at once. Tracking a document twice does nothing.

func (*AutoSave) Tracked

func (a *AutoSave) Tracked(doc *Document) bool

Tracked tells whether the controller follows a document.

func (*AutoSave) Untrack

func (a *AutoSave) Untrack(doc *Document)

Untrack stops following a document (it was closed) and cancels what is pending for it.

func (*AutoSave) WindowFocusLost

func (a *AutoSave) WindowFocusLost()

WindowFocusLost tells that the window lost the focus: with onFocusChange or onWindowChange every dirty document that may be is saved.

type AutoSaveBlock

type AutoSaveBlock int

AutoSaveBlock is why a document is not saved by itself now (VS Code's AutoSaveDisabledReason, with the cases that its resource checks cover).

const (
	// AutoSaveNotBlocked means the document may be saved.
	AutoSaveNotBlocked AutoSaveBlock = iota
	// AutoSaveBlockedBySettings means the mode is off, or is not one that the event asks for.
	AutoSaveBlockedBySettings
	// AutoSaveBlockedNoFile means the document has no file: it is untitled or virtual.
	AutoSaveBlockedNoFile
	// AutoSaveBlockedReadOnly means the document is read-only.
	AutoSaveBlockedReadOnly
	// AutoSaveBlockedOutOfWorkspace means files.autoSaveWorkspaceFilesOnly is on and the file is outside the folder.
	AutoSaveBlockedOutOfWorkspace
	// AutoSaveBlockedByErrors means files.autoSaveWhenNoErrors is on and the document has errors.
	AutoSaveBlockedByErrors
	// AutoSaveBlockedPaused means a save of the document failed and has not been mended: no auto save until a save
	// succeeds or the file is read again.
	AutoSaveBlockedPaused
	// AutoSaveBlockedExternal means the file of the document was changed or deleted by another program (the
	// document is conflicted or orphaned, external.go): the user decides, with the buttons of the notification
	// or with a save, until the file is as the document has it again or the document is read again.
	AutoSaveBlockedExternal
)

type AutoSaveClock

type AutoSaveClock interface {
	// AfterFunc calls f once after d, on the goroutine that uses the AutoSave, and returns the function that
	// cancels it.
	AfterFunc(d time.Duration, f func()) (stop func())
}

AutoSaveClock starts timers.

type AutoSaveClockFunc

type AutoSaveClockFunc func(d time.Duration, f func()) (stop func())

AutoSaveClockFunc makes a function an AutoSaveClock.

func (AutoSaveClockFunc) AfterFunc

func (c AutoSaveClockFunc) AfterFunc(d time.Duration, f func()) (stop func())

AfterFunc implements AutoSaveClock.

type AutoSaveConfig

type AutoSaveConfig struct {
	// Mode is files.autoSave.
	Mode AutoSaveMode
	// Delay is files.autoSaveDelay, for AutoSaveAfterDelay (see AutoSaveDelay).
	Delay time.Duration
	// WorkspaceFilesOnly is files.autoSaveWorkspaceFilesOnly: only documents inside the folder are saved.
	WorkspaceFilesOnly bool
	// WhenNoErrors is files.autoSaveWhenNoErrors: a document with errors in its markers waits until it has none.
	WhenNoErrors bool
}

AutoSaveConfig is what files.autoSave and its three companions say for one document.

type AutoSaveHost

type AutoSaveHost interface {
	// Config is the auto save configuration for a document (the settings of its language).
	Config(doc *Document) AutoSaveConfig
	// InWorkspace tells whether the file of a document is inside the folder of the window.
	InWorkspace(doc *Document) bool
	// HasErrors tells whether the markers have an error for the document.
	HasErrors(doc *Document) bool
	// Save saves the document in its file, silently (no dialog), for the reason. It returns at once; the write
	// goes on in the background, and the host tells SaveFailed when it fails. A save that is going on already
	// for the document is the host's to join.
	Save(doc *Document, reason SaveReason)
}

AutoSaveHost is what an AutoSave asks of its window.

type AutoSaveMode

type AutoSaveMode int

AutoSaveMode is the value of files.autoSave.

const (
	// AutoSaveOff never saves by itself (files.autoSave "off").
	AutoSaveOff AutoSaveMode = iota
	// AutoSaveAfterDelay saves a document after files.autoSaveDelay without edits.
	AutoSaveAfterDelay
	// AutoSaveOnFocusChange saves when the editor loses the focus or the window does.
	AutoSaveOnFocusChange
	// AutoSaveOnWindowChange saves when the window loses the focus.
	AutoSaveOnWindowChange
)

func ParseAutoSaveMode

func ParseAutoSaveMode(s string) (AutoSaveMode, bool)

ParseAutoSaveMode reads a value of files.autoSave. A value that is none of the four reports false and gives AutoSaveOff, as VS Code treats an unknown value as no auto save.

func (AutoSaveMode) String

func (m AutoSaveMode) String() string

String is the value of the setting.

type Cause

type Cause int

Cause says why a document changed.

const (
	// CauseEdit is an edit.
	CauseEdit Cause = iota
	// CauseUndo is an undo.
	CauseUndo
	// CauseRedo is a redo.
	CauseRedo
	// CauseLineEnding is a change of the line ending, which changes no text.
	CauseLineEnding
	// CauseSetText is a replacement of the whole text that clears the history.
	CauseSetText
)

type Change

type Change struct {
	// OldRange, OldOffset and OldText are the replaced text in the text before the batch.
	OldRange  buffer.Range
	OldOffset int
	OldText   string
	// NewRange, NewOffset and NewText are the inserted text in the text after the batch.
	NewRange  buffer.Range
	NewOffset int
	NewText   string
}

Change is an edit as it was applied: where it was, where its text went, and both texts.

type ChangeEvent

type ChangeEvent struct {
	Cause Cause
	// Version and AlternativeVersion are the document's ids after the change.
	Version            int
	AlternativeVersion int
	// Changes are the replacements of the batch, in order of position.
	Changes []Change
	// Before and After are the text before and after the change.
	Before, After buffer.Snapshot
	// Selections are the selections an undo or a redo restores; nil otherwise.
	Selections []buffer.Selection
}

ChangeEvent tells that a document changed.

type Decoration

type Decoration struct {
	// ID identifies the decoration in its document; it is never reused.
	ID int
	// Owner is the id of the feature that made it; owners are 1 or more.
	Owner int
	// Range is where the decoration is now.
	Range   buffer.Range
	Options DecorationOptions
}

Decoration is a range of the document that moves with its edits (SPEC §7.1): find matches, bracket highlights, snippet tab stops, auto-closed characters, diff changes, folded regions, diagnostics.

type DecorationOptions

type DecorationOptions struct {
	Stickiness Stickiness
	// CollapseOnReplaceEdit makes the decoration collapse when an edit replaces
	// all of it, instead of moving to the end of the new text.
	CollapseOnReplaceEdit bool
	ClassName             string
	Data                  any
}

DecorationOptions are what a decoration means and how it moves. ClassName and Data are opaque to the document: the feature that adds a decoration and the view that draws it agree on them.

type Disk

type Disk interface {
	// Stat gives the stat of the file, and whether it exists. A path that is gone, or that is a folder or has a
	// file in the place of a folder above it, does not exist; other failures are errors.
	Stat(ctx context.Context, path string) (stat fileio.FileStat, exists bool, err error)
	// Read reads the file as fileio.Read does.
	Read(ctx context.Context, path string, opts fileio.ReadOptions) (fileio.ReadResult, error)
}

Disk is what looking at a file asks of the file system. The default is the operating system's; tests put their own in to make a read fail or to change a file between the look and the read.

type Document

type Document struct {
	// contains filtered or unexported fields
}

Document is a text buffer with what an editor needs to know about it: its URI, version ids that tell whether it is dirty, an undo history, and the file properties kept for saving (SPEC §7.1). A Document belongs to one goroutine; its Snapshots can go to others.

func FromRead

func FromRead(uri URI, res fileio.ReadResult, opts Options) *Document

FromRead makes the document of a file that fileio.Read returned: its text, encoding, line ending, byte order mark, large-file mode and stat.

func New

func New(uri URI, text string, opts Options) *Document

New makes a document that holds text, which must use "\n" only. Its encoding is "utf8" and it counts as saved.

func NewVirtual

func NewVirtual(uri URI, c VirtualContent) *Document

NewVirtual makes the read-only document of generated content: never dirty, never saved.

func (*Document) AddDecoration

func (d *Document) AddDecoration(owner int, r buffer.Range, opts DecorationOptions) int

AddDecoration adds a decoration for an owner (1 or more) and returns its id. The range is moved into the text like an edit's.

func (*Document) AllDecorations

func (d *Document) AllDecorations() []Decoration

AllDecorations returns every decoration, in order of position.

func (*Document) AllocOwners

func (d *Document) AllocOwners(n int) int

AllocOwners reserves n consecutive owners for one user of the document's decorations and returns the first of them (the owners are base to base+n-1). Features that put decorations on a document take the owners from here, so that two editors that show one document (two groups, SPEC §10.3) never share an owner. The first reservation of a document starts at 1.

func (*Document) AlternativeVersion

func (d *Document) AlternativeVersion() int

AlternativeVersion is the alternative version id: it goes up with every edit, and an undo or a redo sets it to the value it had at that point of the history, so it is the same again when the text is.

func (*Document) ApplyExternal

func (d *Document) ApplyExternal(j *ExternalJob, p ExternalProbe) ExternalResult

ApplyExternal applies what Probe found to the document, on the goroutine that owns it. Nothing is changed when the document is not as it was when the job began (a different file, saved, or edited in a way that matters): the outcome is ExternalStale, and a look must be made again. While a save of the document is in flight the outcome is ExternalDeferred: the file is being written, and what is on the disk now means nothing.

func (*Document) BeginExternal

func (d *Document) BeginExternal(read fileio.ReadOptions) (*ExternalJob, error)

BeginExternal starts a look at the file of the document after another program may have changed it. read says how a file is read when the document is reloaded (the size limits, binary files); the encoding is the one the document has. It fails with the tag ExternalNoFile for a document that has no file (untitled, virtual).

func (*Document) BeginRevert

func (d *Document) BeginRevert(read fileio.ReadOptions) (*RevertJob, error)

BeginRevert starts reading the document again from its file, in the encoding it has now ("Reopen with Encoding" is kept). An untitled document has nothing to read: its revert makes it empty. It fails with the tag RevertNoFile (a virtual document).

func (*Document) BeginSave

func (d *Document) BeginSave(opts SaveOptions) (*SaveJob, error)

BeginSave starts saving the document in its file. It fails with the tags SaveReadOnlyDocument, SaveNoFile (the document has no file: untitled or virtual; it needs SaveAs) and SaveParticipantFailed.

func (*Document) BeginSaveAs

func (d *Document) BeginSaveAs(path string, opts SaveOptions) (*SaveJob, error)

BeginSaveAs starts saving the document in another file, which must not exist unless opts.Overwrite is set. It fails with the tags SaveReadOnlyDocument, SavePathInvalid (the path is empty or relative) and SaveParticipantFailed. A path that is the document's own file saves it in place, as BeginSave does.

func (*Document) CanRedo

func (d *Document) CanRedo() bool

CanRedo reports whether there is something to redo.

func (*Document) CanUndo

func (d *Document) CanUndo() bool

CanUndo reports whether there is something to undo.

func (*Document) ChangeDecorationOptions

func (d *Document) ChangeDecorationOptions(id int, opts DecorationOptions) bool

ChangeDecorationOptions replaces the options of a decoration, the stickiness too (VS Code's changeDecorationOptions): the decoration keeps its place, and the new stickiness decides how it moves with the next edits. It reports whether there is a decoration with the id.

func (*Document) CheckExternal

func (d *Document) CheckExternal(ctx context.Context, disk Disk, read fileio.ReadOptions) (ExternalResult, error)

CheckExternal looks at the file of the document and applies what it finds: BeginExternal, Probe and ApplyExternal in a row, for callers that need no goroutine.

func (*Document) ClearHistory

func (d *Document) ClearHistory()

ClearHistory forgets every undo and redo.

func (*Document) Conflicted

func (d *Document) Conflicted() bool

Conflicted reports that the file changed on the disk while the document has unsaved changes.

func (*Document) Decoration

func (d *Document) Decoration(id int) (Decoration, bool)

Decoration returns the decoration with an id.

func (*Document) DecorationsIn

func (d *Document) DecorationsIn(r buffer.Range, owner int) []Decoration

DecorationsIn returns the decorations that overlap a range, in order of position (a decoration that only touches an end of the range is included, and so is an empty one at it). With an owner of 1 or more only that owner's are returned; 0 means every owner.

func (*Document) DecorationsOf

func (d *Document) DecorationsOf(owner int) []Decoration

DecorationsOf returns every decoration of an owner, in order of position.

func (*Document) DeltaDecorations

func (d *Document) DeltaDecorations(owner int, remove []int, add []NewDecoration) []int

DeltaDecorations removes decorations by id and adds new ones for an owner in one step, as VS Code's deltaDecorations does; it returns the new ids in order. An id that is not a decoration of this owner is ignored.

func (*Document) Dirty

func (d *Document) Dirty() bool

Dirty reports whether the text differs from the one last saved or read; undoing back to the saved text clears it. An untitled document has no saved text: it is dirty while it has any text, as VS Code's.

func (*Document) DiskStat

func (d *Document) DiskStat() fileio.FileStat

DiskStat is the FileStat the file has on the disk, as the last look at it found it; it is only set while Conflicted.

func (*Document) Edit

func (d *Document) Edit(batch []Edit, opts EditOptions) (EditResult, error)

Edit applies a batch of non-overlapping edits and records it in the undo history. It fails with the tags DocumentReadOnly and EditsOverlap.

func (*Document) Encoding

func (d *Document) Encoding() string

Encoding is the id of the file's encoding (see fileio.Encodings).

func (*Document) ExternalState

func (d *Document) ExternalState() ExternalState

ExternalState tells whether the file is gone or was changed under the unsaved changes of the document.

func (*Document) FinishRevert

func (d *Document) FinishRevert(j *RevertJob, res fileio.ReadResult)

FinishRevert replaces the text and the properties of the document with what the job read (Reload): the unsaved changes and the undo history are dropped and the document counts as saved. An untitled document becomes empty.

func (*Document) FinishSave

func (d *Document) FinishSave(j *SaveJob, stat fileio.FileStat) SaveResult

FinishSave records that the job was written with the given stat. The text of the job is now the saved text, so the document is clean unless it was edited since BeginSave; it keeps the stat of the file either way, so that the next save does not take the document's own write for a change by another program. A Save As gives the document the URI of the file (SetURI tells its listeners) and looks for the language of the new name. Undo history is kept.

func (*Document) HasBOM

func (d *Document) HasBOM() bool

HasBOM reports whether the file has a byte order mark.

func (*Document) Indentation

func (d *Document) Indentation() (tabSize int, insertSpaces bool)

Indentation is editor.tabSize and editor.insertSpaces for this document.

func (*Document) Label

func (d *Document) Label() string

Label is the name of the document when its URI does not give a good one (Options.Label), or "".

func (*Document) LanguageID

func (d *Document) LanguageID() string

LanguageID is the language id.

func (*Document) LargeFile

func (d *Document) LargeFile() bool

LargeFile reports whether the document is in large file mode (SPEC §6.4); it is decided when the document is made and features check it.

func (*Document) LineEnding

func (d *Document) LineEnding() fileio.LineEnding

LineEnding is the line ending the file is saved with.

func (*Document) MarkSaved

func (d *Document) MarkSaved(stat fileio.FileStat)

MarkSaved records that the text now is the one on disk, with the FileStat the write returned.

func (*Document) OnExternalStateChange

func (d *Document) OnExternalStateChange(fn func(ExternalState)) (unsubscribe func())

OnExternalStateChange calls fn after the orphaned or the conflicted state of the document changed, with the state it has now. The returned function removes it.

func (*Document) OnSaved

func (d *Document) OnSaved(fn func(SavedEvent)) (unsubscribe func())

OnSaved calls fn after the document was written to disk (and the version, the stat and, for a Save As, the URI were updated). The returned function removes it.

func (*Document) OnURIChange

func (d *Document) OnURIChange(fn func(oldURI, newURI URI)) (unsubscribe func())

OnURIChange calls fn after SetURI changed the URI, with the old one and the new one. The returned function removes it.

func (*Document) Orphaned

func (d *Document) Orphaned() bool

Orphaned reports that the file of the document was deleted (or moved away) by another program.

func (*Document) PopStackElement

func (d *Document) PopStackElement()

PopStackElement reopens the current undo group so that the next edit may join it (VS Code's popStackElement).

func (*Document) PushStackElement

func (d *Document) PushStackElement()

PushStackElement closes the current undo group: the next edit starts a new one (VS Code's pushStackElement, called when the cursor moves by other means).

func (*Document) ReadOnly

func (d *Document) ReadOnly() bool

ReadOnly reports whether the document refuses edits.

func (*Document) Redo

func (d *Document) Redo() (HistoryResult, error)

Redo redoes the last undone group; see Undo. It fails with the tag DocumentReadOnly.

func (*Document) Reload

func (d *Document) Reload(res fileio.ReadResult)

Reload replaces the text and the file properties of the document with those of a file that was read again, as "Reopen with Encoding" does: the text, the encoding, the byte order mark, the line ending and the stat; the large file mode stays as it was decided when the document was made. The undo history is cleared and the document counts as saved, as with SetText. The result of fileio.Read is already in "\n" lines.

func (*Document) RemoveDecorations

func (d *Document) RemoveDecorations(ids ...int)

RemoveDecorations removes decorations by id, whoever owns them.

func (*Document) RemoveDecorationsOf

func (d *Document) RemoveDecorationsOf(owner int)

RemoveDecorationsOf removes every decoration of an owner.

func (*Document) RestoreUnsaved

func (d *Document) RestoreUnsaved(u Unsaved) (dirty bool, err error)

RestoreUnsaved puts the unsaved state of a backup into a document that was just made (from the file as it is on the disk now, or empty for an untitled document or one whose file is gone): the text is set as one edit, so the document is dirty and an undo returns to the text it had, and the properties, the stat and the state of the file are set as the backup says. It reports whether the document has unsaved changes afterwards: false when the backup holds the text the document has already (and the file is not gone). It fails with the tag DocumentReadOnly.

func (*Document) Revert

func (d *Document) Revert(ctx context.Context, read fileio.ReadOptions) error

Revert reads the document again from its file and drops the unsaved changes and the undo history: BeginRevert, Read and FinishRevert. It fails with the tags RevertNoFile and those of fileio.Read.

func (*Document) Save

func (d *Document) Save(ctx context.Context, opts SaveOptions) (SaveResult, error)

Save writes the document to its file: BeginSave, Write and FinishSave.

func (*Document) SaveAs

func (d *Document) SaveAs(ctx context.Context, path string, opts SaveOptions) (SaveResult, error)

SaveAs writes the document to another file and makes that file the document's own: BeginSaveAs, Write and FinishSave. The file the document had stays as it was.

func (*Document) SaveInFlight

func (d *Document) SaveInFlight() bool

SaveInFlight reports that a save of the document was begun and is not finished: its file is being written.

func (*Document) SavedAlternativeVersion

func (d *Document) SavedAlternativeVersion() int

SavedAlternativeVersion is the alternative version id of the text last saved or read.

func (*Document) SetBOM

func (d *Document) SetBOM(has bool)

SetBOM changes whether the file is saved with a byte order mark.

func (*Document) SetDecorationOptions

func (d *Document) SetDecorationOptions(id int, opts DecorationOptions) bool

SetDecorationOptions changes the options of a decoration, which keeps its place. The stickiness does not change (it is read when the decoration is added). It reports whether there is a decoration with the id.

func (*Document) SetEncoding

func (d *Document) SetEncoding(id string)

SetEncoding changes the encoding the file is saved in.

func (*Document) SetIndentation

func (d *Document) SetIndentation(tabSize int, insertSpaces bool)

SetIndentation changes the indentation options, as detecting them from the text or the "Indent Using" commands do.

func (*Document) SetLanguageID

func (d *Document) SetLanguageID(id string)

SetLanguageID changes the language.

func (*Document) SetLineEnding

func (d *Document) SetLineEnding(le fileio.LineEnding) error

SetLineEnding changes the line ending the file is saved with. The change is undoable, as in VS Code, though it changes no text.

func (*Document) SetReadOnly

func (d *Document) SetReadOnly(readOnly bool)

SetReadOnly changes whether the document refuses edits.

func (*Document) SetSaveEncoding

func (d *Document) SetSaveEncoding(id string) error

SetSaveEncoding makes the document save in another encoding ("Save with Encoding"): the encoding changes, and so does the byte order mark, which UTF-16 and "UTF-8 with BOM" have and the others do not (as VS Code's encoding.ts addBOM). The text stays as it is. It fails with the tag SaveEncodingUnknown.

func (*Document) SetText

func (d *Document) SetText(text string)

SetText replaces the whole text, as when a file is reloaded after it changed on disk. The undo history is cleared, the document counts as saved, and the text is "\n" only.

func (*Document) SetURI

func (d *Document) SetURI(uri URI)

SetURI gives the document another identity, when the file it shows was renamed or moved (SPEC §10.5). The text, the history, the version ids and the dirty mark stay. The listeners of OnURIChange are told.

func (*Document) Snapshot

func (d *Document) Snapshot() buffer.Snapshot

Snapshot is the text now, as an immutable value.

func (*Document) Stat

func (d *Document) Stat() fileio.FileStat

Stat is the FileStat of the last read or write.

func (*Document) Subscribe

func (d *Document) Subscribe(fn func(ChangeEvent)) (unsubscribe func())

Subscribe registers fn to be called, in the goroutine that changed the document, after every change. The returned function removes it.

func (*Document) Text

func (d *Document) Text() string

Text is the whole text, with "\n" line endings.

func (*Document) URI

func (d *Document) URI() URI

URI is the document's identity.

func (*Document) Undo

func (d *Document) Undo() (HistoryResult, error)

Undo undoes the last group. The text, the line ending and the alternative version id go back to what they were before it. One change event is sent for each step of the group, in order, each with its own Before and After snapshots (use them, not the document's snapshot, which is the final one); the last carries the Selections. It fails with the tag DocumentReadOnly.

func (*Document) Version

func (d *Document) Version() int

Version is the version id: it goes up with every change, undo and redo included.

type Edit

type Edit struct {
	Range buffer.Range
	Text  string
}

Edit replaces a range with text. In a batch every range is in the text as it was before the batch.

type EditKind

type EditKind int

EditKind classifies an edit for undo grouping (SPEC §7.1).

const (
	// KindOther edits always start a new undo group.
	KindOther EditKind = iota
	// KindTyping is typing text.
	KindTyping
	// KindDeleteLeft is backspace.
	KindDeleteLeft
	// KindDeleteRight is the Delete key.
	KindDeleteRight
)

type EditOptions

type EditOptions struct {
	// Kind decides whether the edit joins the previous undo group: edits of the
	// same kind other than KindOther join it while it is open and the cursors are
	// where it left them.
	Kind EditKind
	// Before are the selections before the edit; an undo of the group restores
	// the ones of its first edit.
	Before []buffer.Selection
	// After computes the selections after the edit from the inverse edits (whose
	// ranges are in the new text); a redo of the group restores the ones of its
	// last edit. It may be nil.
	After func(inverse []Edit) []buffer.Selection
	// Join makes the edit part of the open undo group, whatever its kind, when there is one (the group was not closed by
	// PushStackElement); without an open group it starts a new one that stays open. It is for the edits that one action makes
	// in several steps, such as the additional edits and the insertion of an accepted suggestion (VS Code's executeEdits,
	// which joins the open stack element).
	Join bool
}

EditOptions describe an edit for the undo history.

type EditResult

type EditResult struct {
	// Changed reports whether the text changed; a batch of no-op edits changes nothing.
	Changed bool
	// Inverse is the batch that undoes the edit when applied to the new text.
	Inverse []Edit
	// Selections are the selections After computed.
	Selections []buffer.Selection
}

EditResult is what an edit did.

type ExternalJob

type ExternalJob struct {
	// contains filtered or unexported fields
}

ExternalJob is a look at the file of a document that was begun. Probe may be called from any goroutine; nothing else of a job may.

func (*ExternalJob) Path

func (j *ExternalJob) Path() string

Path is the file the job looks at.

func (*ExternalJob) Probe

func (j *ExternalJob) Probe(ctx context.Context, disk Disk) ExternalProbe

Probe looks at the file: whether it is there, its stat, and, when it differs from the stat the document has and the document can be reloaded, its content. The stat is taken before and after the read; a file that changed in between is being written, and the probe says so (Unstable) instead of returning half a write. disk nil is the operating system's. Failures are in the result (tags ExternalStatFailed and those of fileio.Read).

type ExternalOutcome

type ExternalOutcome int

ExternalOutcome says what ApplyExternal did.

const (
	// ExternalUnchanged means the file is as the document has it: nothing was reloaded. An orphaned or
	// conflicted state was cleared when the file is back as it was.
	ExternalUnchanged ExternalOutcome = iota
	// ExternalReloaded means the file differed and the document had no unsaved changes: its text and
	// properties were replaced (Reload), so the editors must keep their view state.
	ExternalReloaded
	// ExternalConflicted means the file differs and the document has unsaved changes: the text was left alone
	// and the document is conflicted.
	ExternalConflicted
	// ExternalOrphaned means the file is gone: the document is orphaned.
	ExternalOrphaned
	// ExternalRetry means the file could not be read or was being written: nothing was changed, and the next
	// event of the watcher should be acted on.
	ExternalRetry
	// ExternalStale means the document changed while the file was looked at (it was edited, saved or renamed):
	// the look is of no use and should be made again.
	ExternalStale
	// ExternalDeferred means a save of the document is going on: the look should be made again when it ends.
	ExternalDeferred
)

func (ExternalOutcome) String

func (o ExternalOutcome) String() string

String names the outcome.

type ExternalProbe

type ExternalProbe struct {
	// Exists reports that the file is there.
	Exists bool
	// Stat is the stat of the file (of the one that was read, when Read is set).
	Stat fileio.FileStat
	// Read is the file read again, set when it differs from what the document has and the document had no
	// unsaved changes.
	Read *fileio.ReadResult
	// Unstable reports that the file changed while it was looked at (a program is still writing it): the
	// next event of the watcher is the one to act on.
	Unstable bool
	// Err is a failure of the look or of the read; the document is left as it is and the look is tried again
	// at the next event.
	Err error
}

ExternalProbe is what a look at the file found.

type ExternalResult

type ExternalResult struct {
	// Outcome says what happened.
	Outcome ExternalOutcome
	// StateChanged reports that the orphaned or the conflicted state of the document changed.
	StateChanged bool
	// Err is the failure behind ExternalRetry, if there was one.
	Err error
}

ExternalResult is what ApplyExternal did.

type ExternalState

type ExternalState struct {
	// Orphaned reports that the file is gone from the disk (VS Code's TextFileEditorModelState.ORPHAN). The
	// document keeps its text; a save makes the file again.
	Orphaned bool
	// Conflicted reports that the file changed on the disk while the document has unsaved changes.
	Conflicted bool
}

ExternalState is what is known of the file of a document that the document itself does not show.

type HistoryResult

type HistoryResult struct {
	// Done reports whether there was anything to undo or redo.
	Done bool
	// Selections are the selections to put back: the ones from before the undone
	// group, or from after the redone one. They may be nil.
	Selections []buffer.Selection
}

HistoryResult is what an undo or a redo did.

type NewDecoration

type NewDecoration struct {
	Range   buffer.Range
	Options DecorationOptions
}

NewDecoration describes a decoration to add.

type OSDisk

type OSDisk struct{}

OSDisk is the Disk of the operating system.

func (OSDisk) Read

Read implements Disk.

func (OSDisk) Stat

func (OSDisk) Stat(ctx context.Context, path string) (fileio.FileStat, bool, error)

Stat implements Disk. It fails with the tag ExternalStatFailed (a failure that is not a missing file).

type Options

type Options struct {
	// LanguageID is the language; empty means "plaintext".
	LanguageID string
	// TabSize is editor.tabSize; zero means 4.
	TabSize int
	// InsertSpaces is editor.insertSpaces. Because false is also the zero value,
	// NewOptions starts from VS Code's true.
	InsertSpaces bool
	// LineEnding is the document's line ending; empty means LF.
	LineEnding fileio.LineEnding
	// ReadOnly makes the document refuse edits.
	ReadOnly bool
	// Label is the name the document is shown with when its URI does not say it (a virtual document, such as
	// "Default Settings"); empty means the title of the URI.
	Label string
}

Options are what a document starts with besides its text.

func NewOptions

func NewOptions() Options

NewOptions are Options with VS Code's defaults.

type RevertJob

type RevertJob struct {
	// contains filtered or unexported fields
}

RevertJob is a revert that was begun: the file to read and the encoding to read it in. Read may be called from any goroutine; nothing else of a job may.

func (*RevertJob) Read

func (j *RevertJob) Read(ctx context.Context) (fileio.ReadResult, error)

Read reads the file of the job; it gives an empty result for an untitled document. It fails with the tags of fileio.Read.

type SaveJob

type SaveJob struct {
	// contains filtered or unexported fields
}

SaveJob is a save that was begun: the text and the properties to write, and the version they belong to. Write may be called from any goroutine; nothing else of a job may.

func (*SaveJob) Abort

func (j *SaveJob) Abort()

Abort tells the document that the write of the job failed or will not be finished, so that the document is not taken for one that is being written. The window calls it when Write returns an error.

func (*SaveJob) As

func (j *SaveJob) As() bool

As reports that the job is a Save As.

func (*SaveJob) Document

func (j *SaveJob) Document() *Document

Document is the document the job saves.

func (*SaveJob) Path

func (j *SaveJob) Path() string

Path is the file the job writes.

func (*SaveJob) Write

func (j *SaveJob) Write(ctx context.Context) (fileio.FileStat, error)

Write writes the text of the job to its file and returns the FileStat of the result. It fails with the tags of fileio.Write: FileModifiedSince (another program changed the file since the document last read or wrote it), FileExists (a Save As over a file), FileReadOnly, FileNotFound (the folder is missing), FilePermissionDenied, FileWriteFailed, EncodingCannotRepresent and WriteCancelled. A file that was deleted since the document read it is made again.

type SaveOptions

type SaveOptions struct {
	// Reason says why the document is saved; participants get it.
	Reason SaveReason
	// Overwrite saves over a read-only file (its owner write permission is added), and lets SaveAs replace a
	// file that exists.
	Overwrite bool
	// IgnoreConflict saves although the file was changed by another program since the document read or wrote
	// it (files.saveConflictResolution "overwriteFileOnDisk", or the Overwrite button of the conflict).
	IgnoreConflict bool
	// Participate, when set, runs on the owner of the document before the text is taken, and may
	// edit the document: the save participants (trim trailing whitespace, final newlines). Nil
	// runs none ("Save without Formatting"). An error stops the save.
	Participate func(d *Document, reason SaveReason) error
	// DetectLanguage gives the language of a file from its path and first line, for SaveAs to find the
	// language of the new name; nil keeps the language.
	DetectLanguage func(path, firstLine string) string
}

SaveOptions say how a document is saved.

type SaveReason

type SaveReason int

SaveReason says why a document is saved; the participants behave differently for an automatic save.

const (
	// SaveExplicit is a save the user asked for (VS Code's SaveReason.EXPLICIT).
	SaveExplicit SaveReason = iota
	// SaveAuto is a save the editor makes by itself after a delay (files.autoSave "afterDelay"; VS Code's
	// SaveReason.AUTO). Only this reason keeps the white space in front of the cursors.
	SaveAuto
	// SaveFocusChange is an auto save because an editor lost the focus (files.autoSave "onFocusChange";
	// VS Code's SaveReason.FOCUS_CHANGE).
	SaveFocusChange
	// SaveWindowChange is an auto save because the window lost the focus (files.autoSave "onFocusChange" and
	// "onWindowChange"; VS Code's SaveReason.WINDOW_CHANGE).
	SaveWindowChange
)

func (SaveReason) String

func (r SaveReason) String() string

String names the reason as VS Code's SaveReason is named in its logs.

type SaveResult

type SaveResult struct {
	// Stat is the FileStat of the written file.
	Stat fileio.FileStat
	// Clean reports whether the document has no unsaved changes now.
	Clean bool
	// LanguageChanged reports that a Save As found another language for the new name.
	LanguageChanged bool
}

SaveResult is what a finished save did to the document.

type SavedEvent

type SavedEvent struct {
	// Path is the file that was written.
	Path string
	// Stat is the FileStat of the file after the write.
	Stat fileio.FileStat
	// Clean reports whether the document has no unsaved changes: false when it was edited while the
	// write went on.
	Clean bool
	// As reports that the write was a Save As, which gave the document the URI of the file.
	As bool
}

SavedEvent tells that the document was written to disk.

type Stickiness

type Stickiness int

Stickiness says how a decoration's ends move when text is typed at them (VS Code's TrackedRangeStickiness; the numbers are VS Code's).

const (
	// AlwaysGrowsWhenTypingAtEdges grows when text is typed at either edge.
	AlwaysGrowsWhenTypingAtEdges Stickiness = iota
	// NeverGrowsWhenTypingAtEdges does not grow when text is typed at either edge.
	NeverGrowsWhenTypingAtEdges
	// GrowsOnlyWhenTypingBefore grows when text is typed at its start (before it).
	GrowsOnlyWhenTypingBefore
	// GrowsOnlyWhenTypingAfter grows when text is typed at its end (after it).
	GrowsOnlyWhenTypingAfter
)

type URI

type URI struct {
	Scheme string
	Path   string
}

URI identifies a document. Its String form is an identity, not a web address: the path is not percent-encoded.

func FileURI

func FileURI(path string) URI

FileURI is the URI of a file on disk.

func LowestFreeUntitled

func LowestFreeUntitled(open []URI) URI

LowestFreeUntitled is the untitled URI with the lowest number that none of the open documents has.

func ParseURI

func ParseURI(s string) (URI, error)

ParseURI reads the form String gives. It fails with the tag URIInvalid.

func UntitledURI

func UntitledURI(n int) URI

UntitledURI is the URI of the untitled document with number n.

func VirtualURI

func VirtualURI(path string) URI

VirtualURI is the URI of generated read-only content; path says what it is.

func (URI) String

func (u URI) String() string

String is "file:///path", "untitled:3" or "emetos-virtual:path".

func (URI) Title

func (u URI) Title() string

Title is the name shown on a tab: the file name, "Untitled-n", or the last part of a virtual path.

type Unsaved

type Unsaved struct {
	// Text is the text the document had, with "\n" line endings.
	Text string
	// Encoding, HasBOM and LineEnding are the properties the file is saved with; an empty Encoding or
	// LineEnding keeps what the document has.
	Encoding   string
	HasBOM     bool
	LineEnding fileio.LineEnding
	// LanguageID is the language the document had; empty keeps the document's.
	LanguageID string
	// Stat, when not zero, is the stat of the file the text was based on. A document whose file changed since
	// takes it, so that a save fails with FileModifiedSince until the user chooses to overwrite.
	Stat fileio.FileStat
	// Orphaned reports that the file is gone: the document is orphaned and a save makes the file again.
	Orphaned bool
	// Conflict, when not nil, is the stat the file has on the disk now, which differs from Stat: the document
	// is conflicted (Conflicted).
	Conflict *fileio.FileStat
}

Unsaved is the unsaved state of a document that comes back from a backup (SPEC §10.10, hot exit).

type VirtualContent

type VirtualContent struct {
	// Text is the content, with "\n" lines.
	Text string
	// Label and Language are those of the provider.
	Label, Language string
}

VirtualContent is what a provider made.

type VirtualPrefixProvider

type VirtualPrefixProvider struct {
	// Label gives the name of the document in its tab for the rest of the path; the rest of the path is the
	// name when it is nil.
	Label func(rest string) string
	// Language gives the language id of the content for the rest of the path; plaintext when nil or empty.
	Language func(rest string) string
	// Text generates the content, with "\n" lines. It runs each time the document is opened and must stop when ctx
	// does.
	Text func(ctx context.Context, rest string) (string, error)
}

VirtualPrefixProvider generates the content of the virtual documents whose path starts with a prefix: the rest of the path says which content (the file a "Compare with Saved" shows, the number of a clipboard comparison). The functions get the rest of the path, which is what follows the prefix.

type VirtualProvider

type VirtualProvider struct {
	// Label is the name of the document in its tab ("Default Settings").
	Label string
	// Language is the language id of the content; plaintext when empty.
	Language string
	// Text generates the content, with "\n" lines. It runs each time the document is opened, so the content
	// reflects what the provider reads at that time. It must stop when ctx does.
	Text func(ctx context.Context) (string, error)
}

VirtualProvider generates the content of one read-only virtual document (SPEC §7.1, the `emetos-virtual:` scheme): the default settings JSON, for one.

type VirtualRegistry

type VirtualRegistry struct {
	// contains filtered or unexported fields
}

VirtualRegistry holds the providers of the virtual documents, by the path of their URI (`emetos-virtual:/defaultSettings.json`) or by the prefix of it (`emetos-virtual:/saved/home/me/main.go`). It is safe for concurrent use. There is no global one: the process makes its own.

func NewVirtualRegistry

func NewVirtualRegistry() *VirtualRegistry

NewVirtualRegistry makes an empty registry.

func NewVirtualRegistryOver added in v1.0.0

func NewVirtualRegistryOver(parent *VirtualRegistry) *VirtualRegistry

NewVirtualRegistryOver makes an empty registry that asks parent for every path it has no provider of its own for. The registry of a window tab is made so over the process's, and the providers an extension adds go to it and go away with it.

func (*VirtualRegistry) Generate

func (r *VirtualRegistry) Generate(ctx context.Context, uri URI) (VirtualContent, error)

Generate asks the provider of a URI for the content. It fails with the tags VirtualURIUnknown (not an `emetos-virtual:` URI, or no provider has the path) and VirtualGenerateFailed (the provider failed).

func (*VirtualRegistry) Has

func (r *VirtualRegistry) Has(uri URI) bool

Has tells whether a URI is a virtual one that a provider makes.

func (*VirtualRegistry) HasPrefix added in v1.0.0

func (r *VirtualRegistry) HasPrefix(prefix string) bool

HasPrefix tells whether this registry (not its parent) has a provider for the prefix.

func (*VirtualRegistry) Paths

func (r *VirtualRegistry) Paths() []string

Paths are the paths of the registered providers of single documents, sorted (not the prefixes).

func (*VirtualRegistry) Register

func (r *VirtualRegistry) Register(path string, p VirtualProvider) error

Register adds the provider of the virtual documents whose URI has the path. It fails with the tags VirtualProviderInvalid (no path, or no Text) and VirtualProviderDuplicate.

func (*VirtualRegistry) RegisterPrefix

func (r *VirtualRegistry) RegisterPrefix(prefix string, p VirtualPrefixProvider) error

RegisterPrefix adds the provider of the virtual documents whose path starts with prefix and has something after it. The prefix starts and ends with "/" and must not be "/"; a path that has a provider of its own (Register) uses that one, and of two prefixes the longer wins. It fails with the tags VirtualPrefixInvalid (a prefix that is not like that, or no Text) and VirtualPrefixDuplicate.

func (*VirtualRegistry) UnregisterPrefix added in v1.0.0

func (r *VirtualRegistry) UnregisterPrefix(prefix string) bool

UnregisterPrefix takes the provider of a prefix away; it reports whether there was one.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL