mg

package
v0.0.0-...-063aa45 Latest Latest
Warning

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

Go to latest
Published: Jun 26, 2019 License: MIT Imports: 36 Imported by: 0

Documentation

Index

Constants

View Source
const (
	UnknownTag  = CompletionTag("·?")
	SnippetTag  = CompletionTag("·ʂ")
	VariableTag = CompletionTag("·ν")
	TypeTag     = CompletionTag("·ʈ")
	ConstantTag = CompletionTag("·Ɩ")
	FunctionTag = CompletionTag("·ƒ")
	PackageTag  = CompletionTag("·ρ")
)
View Source
const (
	Error   = IssueTag("error")
	Warning = IssueTag("warning")
	Notice  = IssueTag("notice")
)
View Source
const (
	// RcActuate is the command that's run when a user triggeres an action
	// at the cursor, primarily via the mouse e.g. goto.definition
	//
	// Args:
	// -button="": the action wasn't triggered by a mouse click
	// -button="left": the action was triggered by the by a left-click
	// -button="right": the action was triggered by the by a right-click
	RcActuate = ".actuate"
)

Variables

View Source
var (
	// DefaultCodec is the name of the default codec used for IPC communication
	DefaultCodec = "json"

	// CodecNames is the list of names of all valid codec handles
	CodecNames = func() []string {
		l := make([]string, 0, len(codecHandles))
		for k, _ := range codecHandles {
			if k != "" {
				l = append(l, k)
			}
		}
		sort.Strings(l)
		return l
	}()

	// CodecNamesStr is the list of names of all valid codec handles in the form `a, b or c`
	CodecNamesStr = func() string {
		i := len(CodecNames) - 1
		return strings.Join(CodecNames[:i], ", ") + " or " + CodecNames[i]

	}()
)
View Source
var (
	ActionCreators = (&actions.Registry{}).
		Register("QueryCompletions", QueryCompletions{}).
		Register("QueryCmdCompletions", QueryCmdCompletions{}).
		Register("QueryIssues", QueryIssues{}).
		Register("Restart", Restart{}).
		Register("Shutdown", Shutdown{}).
		Register("ViewActivated", ViewActivated{}).
		Register("ViewFmt", ViewFmt{}).
		Register("DisplayIssues", DisplayIssues{}).
		Register("ViewLoaded", ViewLoaded{}).
		Register("ViewModified", ViewModified{}).
		Register("ViewPosChanged", ViewPosChanged{}).
		Register("ViewPreSave", ViewPreSave{}).
		Register("ViewSaved", ViewSaved{}).
		Register("QueryUserCmds", QueryUserCmds{}).
		Register("QueryTestCmds", QueryTestCmds{}).
		Register("RunCmd", RunCmd{}).
		Register("QueryTooltips", QueryTooltips{})
)
View Source
var (
	// Builtins is the set of pre-defined builtin commands
	Builtins = &builtins{}
)
View Source
var (
	// DefaultReducers enables the automatic registration of reducers to the Agent's store
	//
	// This can be used to register reducers without user-interaction
	// but where possible, it should not be used.
	//
	// its methods should only be callsed during init()
	// any calls after this may ignored
	DefaultReducers = &defaultReducers{
		before: reducerList{
			&issueKeySupport{},
			Builtins,
		},
		after: reducerList{
			&issueStatusSupport{},
			&cmdSupport{},
			&restartSupport{},
			&clientActionSupport{},
		},
	}
)
View Source
var (
	// ErrNoSettings is the error returned from EditorProps.Settings()
	// when there was no settings sent from the editor
	ErrNoSettings = fmt.Errorf("no editor settings")
)

Functions

func ActionLabel

func ActionLabel(act Action) string

ActionLabel returns a label for the actions act. It takes into account mg.Render being an alias for nil.

func AddCommonPatterns

func AddCommonPatterns(lang Lang, l ...*regexp.Regexp)

func BytePos

func BytePos(src []byte, charPos int) int

func CommonPatterns

func CommonPatterns(langs ...Lang) []*regexp.Regexp

func IsParentDir

func IsParentDir(parentDir, childPath string) bool

IsParentDir is an alias of mgutil.IsParentDir

func MkTempDir

func MkTempDir(name string) (string, error)

func PathList

func PathList(s string) []string

PathList is an alias of mgutil.PathList

func ReducerLabel

func ReducerLabel(r Reducer) string

ReducerLabel returns a label for the reducer r. It takes into account the Reducer.RLabel method.

func SrcHash

func SrcHash(s []byte) string

Types

type Action

type Action = actions.Action
var Render Action = nil

type ActionType

type ActionType = actions.ActionType

type Activate

type Activate struct {
	ActionType

	Path string
	Name string
	Row  int
	Col  int
}

func (Activate) ClientAction

func (a Activate) ClientAction() actions.ClientData

type Agent

type Agent struct {
	Name  string
	Done  <-chan struct{}
	Log   *Logger
	Store *Store
	// contains filtered or unexported fields
}

func NewAgent

func NewAgent(cfg AgentConfig) (*Agent, error)

NewAgent returns a new Agent, initialised using the settings in cfg. If cfg.Codec is invalid (see CodecNames), `DefaultCodec` will be used as the codec and an error returned. An initialised, usable agent object is always returned.

For tests, NewTestingAgent(), NewTestingStore() and NewTestingCtx() are preferred to creating a new agent directly

func (*Agent) Args

func (ag *Agent) Args() Args

Args returns a new copy of agent's Args.

func (*Agent) Run

func (ag *Agent) Run() error

Run starts the Agent's event loop. It returns immediately on the first error.

type AgentConfig

type AgentConfig struct {
	// the name of the agent as used in the command `margo.sh [start...] $AgentName`
	AgentName string

	// Codec is the name of the codec to use for IPC
	// Valid values are json, cbor or msgpack
	// Default: json
	Codec string

	// Stdin is the stream through which the client sends encoded request data
	// It's closed when Agent.Run() returns
	Stdin io.ReadCloser

	// Stdout is the stream through which the server (the Agent type) sends encoded responses
	// It's closed when Agent.Run() returns
	Stdout io.WriteCloser

	// Stderr is used for logging
	// Clients are encouraged to leave it open until the process exits
	// to allow for logging to keep working during process shutdown
	Stderr io.Writer
}

type Args

type Args struct {
	*Store
	Log *Logger
}

type BuiltinCmd

type BuiltinCmd struct {
	// Name is the name of the name.
	Name string

	// Desc is a description of what the command does
	Desc string

	// Run is called to carry out the operation of the command
	Run BuiltinCmdRunFunc
}

BuiltinCmd describes a builtin command

type BuiltinCmdList

type BuiltinCmdList []BuiltinCmd

BuiltinCmdList is a list of BuiltinCmds

func (BuiltinCmdList) Filter

func (bcl BuiltinCmdList) Filter(filter func(BuiltinCmd) bool) BuiltinCmdList

Filter returns a copy of the list consisting only of commands for which filter returns true

func (BuiltinCmdList) Lookup

func (bcl BuiltinCmdList) Lookup(name string) (cmd BuiltinCmd, found bool)

Lookup looks up the builtin command `name` in the list. If the command is not found, it returns `Builtins.Commands().Lookup(".exec")`. In either case, `found` indicates whether or not `name` was actually found.

type BuiltinCmdRunFunc

type BuiltinCmdRunFunc func(*CmdCtx) *State

BuiltinCmdRunFunc is the BuiltinCmd.Run function

Where possible, implementations should prefer to do real work in a goroutine.

type CmdCtx

type CmdCtx struct {
	// Ctx is the underlying Ctx for the current reduction
	*Ctx

	// RunCmd is the action that was dispatched
	RunCmd

	// Output is the `stdout` of the command.
	// Commands must close it when are done.
	Output OutputStream
}

CmdCtx holds details about a command execution

func (*CmdCtx) Copy

func (cx *CmdCtx) Copy(updaters ...func(*CmdCtx)) *CmdCtx

Copy returns a shallow copy of the CmdCtx

func (*CmdCtx) Run

func (cx *CmdCtx) Run() *State

Run runs the list of builtin commands with name CmtCtx.RunCmd.Name. If no commands exist with that name, it calls Builtins.ExecCmd instead.

func (*CmdCtx) RunProc

func (cx *CmdCtx) RunProc()

RunProc is a convenience function that: * calls StartProc() * waits for the process to complete * and logs any returned error to CmdCtx.Output

func (*CmdCtx) StartProc

func (cx *CmdCtx) StartProc() (*Proc, error)

StartProc creates a new Proc and starts the underlying process. It always returns an initialised Proc.

func (*CmdCtx) WithCmd

func (cx *CmdCtx) WithCmd(name string, args ...string) *CmdCtx

WithCmd returns a copy of cx RunCmd updated with Name name and Args args

type CmdOut

type CmdOut struct {
	Fd       string
	Dispatch Dispatcher
	// contains filtered or unexported fields
}

func (*CmdOut) Close

func (w *CmdOut) Close() error

Close closes the writer. It returns os.ErrClosed if Close has already been called.

func (*CmdOut) Flush

func (w *CmdOut) Flush() error

Flush implements OutputStream.Flush

If w.Dispatch is set, it's used to dispatch Output{} actions. It never returns an error.

func (*CmdOut) Output

func (w *CmdOut) Output() CmdOutput

Output returns the data buffered from previous calls to w.Write() and clears the buffer.

func (*CmdOut) Write

func (w *CmdOut) Write(p []byte) (int, error)

type CmdOutput

type CmdOutput struct {
	ActionType

	Fd     string
	Output []byte
	Close  bool
}

func (CmdOutput) ClientAction

func (out CmdOutput) ClientAction() actions.ClientData

type Completion

type Completion struct {
	Query string
	Title string
	Src   string
	Tag   CompletionTag
}

type CompletionTag

type CompletionTag string

type Ctx

type Ctx struct {
	// State is the current state of the world
	*State

	// Action is the action that was dispatched.
	// It's a hint telling reducers about some action that happened,
	// e.g. that the view is about to be saved or that it was changed.
	Action Action `mg.Nillable:"true"`

	// KVMap is an in-memory cache of data with for the lifetime of the Ctx.
	*KVMap

	// Store is the global store
	Store *Store

	// Log is the global logger
	Log *Logger

	Cookie string

	Profile *mgpf.Profile

	VFS *vfs.FS
	// contains filtered or unexported fields
}

Ctx holds data about the current request/reduction.

To create a new instance, use Store.NewCtx()

NOTE: Ctx should be treated as readonly and users should not assign to any of its fields or the fields of any of its members. If a field must be updated, you should use one of the methods like Copy

Unless a field is tagged with `mg.Nillable:"true"`, it will never be nil and if updated, no field should be set to nil

func (*Ctx) ActionIs

func (mx *Ctx) ActionIs(actions ...Action) bool

ActionIs returns true if Ctx.Action is the same type as any of those in actions for convenience, it returns true if actions is nil

func (*Ctx) AgentName

func (mx *Ctx) AgentName() string

AgentName returns the name of the agent if set if set, it's usually the agent name as used in the command `margo.sh [run...] $agent`

func (*Ctx) Begin

func (mx *Ctx) Begin(t Task) *TaskTicket

Begin is a short-hand for Ctx.Store.Begin

func (*Ctx) Cancel

func (mx *Ctx) Cancel()

Cancel cancels the ctx by arranging for the Ctx.Done() channel to be closed. Canceling this Ctx cancels all other Ctxs Copy()ed from it.

func (*Ctx) CommonPatterns

func (mx *Ctx) CommonPatterns() []*regexp.Regexp

CommonPatterns is equivalent to View.CommonPatterns()

func (*Ctx) Copy

func (mx *Ctx) Copy(updaters ...func(*Ctx)) *Ctx

Copy create a shallow copy of the Ctx.

It applies the functions in updaters to the new object. Updating the new Ctx via these functions is preferred to assigning to the new object

func (*Ctx) Deadline

func (*Ctx) Deadline() (time.Time, bool)

Deadline implements context.Context.Deadline

func (*Ctx) Defer

func (mx *Ctx) Defer(f ReduceFn)

func (*Ctx) Done

func (mx *Ctx) Done() <-chan struct{}

Done implements context.Context.Done()

func (*Ctx) Err

func (mx *Ctx) Err() error

Err implements context.Context.Err()

func (*Ctx) LangIs

func (mx *Ctx) LangIs(langs ...Lang) bool

LangIs is equivalent to View.LangIs(langs...)

func (*Ctx) SetState

func (mx *Ctx) SetState(st *State) *Ctx

func (*Ctx) SetView

func (mx *Ctx) SetView(v *View) *Ctx

func (*Ctx) Value

func (mx *Ctx) Value(k interface{}) interface{}

Value implements context.Context.Value() but always returns nil

type Dispatcher

type Dispatcher func(Action)

Dispatcher is the signature of the Store.Dispatch method

type DisplayIssues

type DisplayIssues struct{ ActionType }

func (DisplayIssues) ClientAction

func (di DisplayIssues) ClientAction() actions.ClientData

type EditorClientProps

type EditorClientProps struct {
	// Name is the name of the client
	Name string

	// Tag is the client's version
	Tag string
}

type EditorConfig

type EditorConfig interface {
	// EditorConfig returns data to be sent to the editor.
	EditorConfig() interface{}

	// EnabledForLangs is a hint to the editor listing the languages
	// for which actions should be dispatched.
	//
	// To request actions for all languages, use `"*"` (the default)
	EnabledForLangs(langs ...Lang) EditorConfig
}

EditorConfig is the common interface between internally supported editors.

The main implementation is `sublime.Config`

type EditorProps

type EditorProps struct {
	// Name is the name of the editor
	Name string

	// Version is the editor's version
	Version string

	// Client hold details about client (the editor plugin)
	Client EditorClientProps
	// contains filtered or unexported fields
}

EditorProps holds data about the text editor

func (*EditorProps) Ready

func (ep *EditorProps) Ready() bool

Ready returns true if the editor state has synced

Reducers can call Ready in their RCond method to avoid mounting until the editor has communicated its state. Before the editor is ready, State.View, State.Editor, etc. might not contain usable data.

func (*EditorProps) Settings

func (ep *EditorProps) Settings(v interface{}) error

Settings unmarshals the internal settings sent from the editor into v. If no settings were sent, it returns ErrNoSettings, otherwise it returns any error from unmarshalling.

type EnvMap

type EnvMap = mgutil.EnvMap

type ErrorList

type ErrorList []error

func (ErrorList) Error

func (el ErrorList) Error() string

func (ErrorList) Filter

func (el ErrorList) Filter() ErrorList

func (ErrorList) First

func (el ErrorList) First() error

type HUDState

type HUDState struct {
	Articles []string
}

func (HUDState) AddArticle

func (h HUDState) AddArticle(heading htm.IElement, content ...htm.Element) HUDState

type Issue

type Issue struct {
	Path    string
	Name    string
	Row     int
	Col     int
	End     int
	Tag     IssueTag
	Label   string
	Message string
}

func (*Issue) Equal

func (isu *Issue) Equal(p Issue) bool

func (*Issue) InView

func (isu *Issue) InView(v *View) bool

func (*Issue) SameFile

func (isu *Issue) SameFile(p Issue) bool

func (*Issue) Valid

func (isu *Issue) Valid() bool

type IssueKey

type IssueKey struct {
	Key  interface{}
	Name string
	Path string
	Dir  string
}

type IssueOut

type IssueOut struct {
	Patterns []*regexp.Regexp
	Base     Issue
	Dir      string
	Done     chan<- struct{}
	// contains filtered or unexported fields
}

func (*IssueOut) Close

func (w *IssueOut) Close() error

func (*IssueOut) Flush

func (w *IssueOut) Flush() error

func (*IssueOut) Issues

func (w *IssueOut) Issues() IssueSet

func (*IssueOut) Write

func (w *IssueOut) Write(p []byte) (n int, err error)

type IssueSet

type IssueSet []Issue

func (IssueSet) Add

func (s IssueSet) Add(l ...Issue) IssueSet

func (IssueSet) AllInView

func (is IssueSet) AllInView(v *View) IssueSet

func (IssueSet) Equal

func (s IssueSet) Equal(issues IssueSet) bool

func (IssueSet) Has

func (s IssueSet) Has(p Issue) bool

func (IssueSet) Remove

func (s IssueSet) Remove(l ...Issue) IssueSet

type IssueTag

type IssueTag string

type KVMap

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

KVMap implements a KVStore using a map. The zero-value is safe for use with all operations.

NOTE: All operations are no-ops on a nil KVMap

func (*KVMap) Clear

func (m *KVMap) Clear()

Clear removes all values from the store

func (*KVMap) Del

func (m *KVMap) Del(k interface{})

Del implements KVStore.Del

func (*KVMap) Get

func (m *KVMap) Get(k interface{}) interface{}

Get implements KVStore.Get

func (*KVMap) Put

func (m *KVMap) Put(k interface{}, v interface{})

Put implements KVStore.Put

func (*KVMap) Values

func (m *KVMap) Values() map[interface{}]interface{}

Values returns a copy of all values stored

type KVStore

type KVStore interface {
	// Put stores the value in the store with identifier key
	// NOTE: use Del instead of storing nil
	Put(key, value interface{})

	// Get returns the value stored using identifier key
	// NOTE: if the value doesn't exist, nil is returned
	Get(key interface{}) interface{}

	// Del removes the value identified by key from the store
	Del(key interface{})
}

KVStore represents a generic key value store.

All operations are safe for concurrent access.

The main implementation in this and related packages is Store.

type KVStores

type KVStores []KVStore

KVStores implements a KVStore that duplicates its operations on a list of k/v stores

NOTE: All operations are no-ops for nil KVStores

func (KVStores) Del

func (kvl KVStores) Del(k interface{})

Del removed the value identified by k from all k/v stores in the list

func (KVStores) Get

func (kvl KVStores) Get(k interface{}) interface{}

Get returns the first value identified by k found in the list of k/v stores

func (KVStores) Put

func (kvl KVStores) Put(k, v interface{})

Put calls .Put on each of k/v stores in the list

type Lang

type Lang string

Lang is the lower-case name of a language i.e. "go", not "Go" where possible, the predefined instances in should be used

const (
	AllLangs Lang = "*"

	ActionScript Lang = "actionscript"
	AppleScript  Lang = "applescript"
	ASP          Lang = "asp"
	C            Lang = "c"
	Clojure      Lang = "clojure"
	CPP          Lang = "c++"
	CSharp       Lang = "cs"
	CSS          Lang = "css"
	D            Lang = "d"
	Diff         Lang = "diff"
	DosBatch     Lang = "dosbatch"
	Dot          Lang = "dot"
	Empty        Lang = "empty"
	Erl          Lang = "erl"
	Erlang       Lang = "erlang"
	Go           Lang = "go"
	GoMod        Lang = "go.mod"
	GoSum        Lang = "go.sum"
	Groovy       Lang = "groovy"
	Haskell      Lang = "haskell"
	Java         Lang = "java"
	JS           Lang = "js"
	JSON         Lang = "json"
	JSX          Lang = "JSX"
	LaTeX        Lang = "latex"
	LISP         Lang = "lisp"
	Lua          Lang = "lua"
	Makefile     Lang = "makefile"
	Matlab       Lang = "matlab"
	ObjC         Lang = "objc"
	Ocaml        Lang = "ocaml"
	Octave       Lang = "octave"
	Pascal       Lang = "pascal"
	Perl         Lang = "perl"
	PHP          Lang = "php"
	Plist        Lang = "plist"
	Python       Lang = "python"
	Rlang        Lang = "r"
	Ruby         Lang = "ruby"
	Rust         Lang = "rust"
	Scala        Lang = "scala"
	ShellScript  Lang = "shell"
	SQL          Lang = "sql"
	Tcl          Lang = "tcl"
	TS           Lang = "ts"
	TSX          Lang = "tsx"
	Yaml         Lang = "yaml"
)

type Linter

type Linter struct {
	ReducerType

	Langs   []Lang
	Actions []Action

	Name string
	Args []string

	IssueKey func(*Ctx) IssueKey
	Tag      IssueTag
	Label    string
	TempDir  []string
	// contains filtered or unexported fields
}

func (*Linter) RCond

func (lt *Linter) RCond(mx *Ctx) bool

func (*Linter) RMount

func (lt *Linter) RMount(mx *Ctx)

func (*Linter) RUnmount

func (lt *Linter) RUnmount(mx *Ctx)

func (*Linter) Reduce

func (lt *Linter) Reduce(mx *Ctx) *State

type Logger

type Logger struct {
	*log.Logger
	Dbg *log.Logger
}

func NewLogger

func NewLogger(w io.Writer) *Logger

type MOTD

type MOTD struct {
	ReducerType

	// Endpoint is the URL to check for new messages
	// By default it's https://api.margo.sh/motd.json
	Endpoint string

	// Interval, if set, specifies how often to automatically fetch messages from Endpoint
	Interval time.Duration
	// contains filtered or unexported fields
}

MOTD keeps you updated about new versions and important announcements

It adds a new command `motd.sync` available via the UserCmd palette as `Sync MOTD`

Interval can be set in order to enable automatic update fetching.

When new updates are found, it displays the message in the status bar e.g. `★ margo.sh/cl/18.09.14 ★` a url where you see the upcoming changes before updating

It sends the following data to the url https://api.margo.sh/motd.json:

  • current editor plugin name e.g. `?client=gosublime` this tells us which editor plugin's changelog to check
  • current editor plugin version e.g. `?tag=r18.09.14-1` this allows us to determine if there any updates
  • whether or not this is the first request of the day e.g. `?firstHit=1` this allows us to get an estimated count of active users without storing any personally identifiable data

No other data is sent. For more info contact privacy at kuroku.io

func (*MOTD) RCond

func (m *MOTD) RCond(mx *Ctx) bool

func (*MOTD) RInit

func (m *MOTD) RInit(mx *Ctx)

func (*MOTD) RMount

func (m *MOTD) RMount(mx *Ctx)

func (*MOTD) Reduce

func (m *MOTD) Reduce(mx *Ctx) *State

type MargoFunc

type MargoFunc func(Args)

type OutputStream

type OutputStream interface {
	io.Writer
	io.Closer
	Flush() error
}

OutputStream describes an object that's capable of dispatching command output.

An OutputSream is safe for concurrent use.

The main implementation is CmdOut.

type OutputStreams

type OutputStreams []OutputStream

OutputStreams delegates to a list of OutputStreams.

For each method (Write, Close, Flush):

If none of the underlying methods return an error, a nil error is returned.

Otherwise an ErrorList length == len(OutputStreams) is returned. For each entry OutputStreams[i], ErrorList[i] contains the error returned for the method called on that OutputStream.

func (OutputStreams) Close

func (sl OutputStreams) Close() error

Close calls Close() on all each OutputStream

func (OutputStreams) Flush

func (sl OutputStreams) Flush() error

Flush calls Flush() on all each OutputStream

func (OutputStreams) Write

func (sl OutputStreams) Write(p []byte) (int, error)

Write calls Write() on all each OutputStream

type Proc

type Proc struct {
	Title string
	// contains filtered or unexported fields
}

func (*Proc) Cancel

func (p *Proc) Cancel()

func (*Proc) Wait

func (p *Proc) Wait() error

type QueryCmdCompletions

type QueryCmdCompletions struct {
	ActionType

	Pos  int
	Src  string
	Name string
	Args []string
}

type QueryCompletions

type QueryCompletions struct{ ActionType }

type QueryIssues

type QueryIssues struct{ ActionType }

type QueryTestCmds

type QueryTestCmds struct{ ActionType }

QueryTestCmds is the action dispatched to get a list of UserCmds for testing, benchmarking, etc.

type QueryTooltips

type QueryTooltips struct {
	ActionType

	Row int
	Col int
}

type QueryUserCmds

type QueryUserCmds struct{ ActionType }

QueryUserCmds is the action dispatched to get a list of UserCmds.

type RFunc

type RFunc struct {
	ReducerType

	// Label is an optional string that may be used as a name for the reducer.
	// If unset, a name based on the Func type will be used.
	Label string

	// Func is the equivalent of Reducer.Reduce
	// If Func is nil, the current state is returned as-is
	Func ReduceFn

	// Init is the equivalent of Reducer.RInit
	Init func(mx *Ctx)

	// Cond is the equivalent of Reducer.RCond
	Cond func(mx *Ctx) bool

	// RCnfig is the equivalent of Reducer.RConfig
	Config func(mx *Ctx) EditorConfig

	// Rount is the equivalent of Reducer.RMount
	Mount func(mx *Ctx)

	// RUnount is the equivalent of Reducer.RUnmount
	Unmount func(mx *Ctx)
}

RFunc wraps a function to be used as a reducer New instances should ideally be created using the global NewReducer() function

func NewReducer

func NewReducer(reduce ReduceFn, options ...func(*RFunc)) *RFunc

NewReducer creates a new RFunc reduce can be nil, in which case RFunc.Reduce method will simply return the current state each function in options is called on the newly created RFunc

func (*RFunc) RCond

func (rf *RFunc) RCond(mx *Ctx) bool

RCond delegates to RFunc.Cond if it's not nil

func (*RFunc) RConfig

func (rf *RFunc) RConfig(mx *Ctx) EditorConfig

RConfig delegates to RFunc.Config if it's not nil

func (*RFunc) RInit

func (rf *RFunc) RInit(mx *Ctx)

RInit delegates to RFunc.Init if it's not nil

func (*RFunc) RLabel

func (rf *RFunc) RLabel() string

RLabel implements Reducer.RLabel

func (*RFunc) RMount

func (rf *RFunc) RMount(mx *Ctx)

RMount delegates to RFunc.Mount if it's not nil

func (*RFunc) RUnmount

func (rf *RFunc) RUnmount(mx *Ctx)

RUnmount delegates to RFunc.Unmount if it's not nil

func (*RFunc) Reduce

func (rf *RFunc) Reduce(mx *Ctx) *State

Reduce implements the Reducer interface, delegating to RFunc.Func if it's not nil

type ReduceFn

type ReduceFn func(*Ctx) *State

type ReduceFunc

type ReduceFunc = RFunc

ReduceFunc is an alias for RFunc

type Reducer

type Reducer interface {
	// Reduce takes as input a Ctx describing the current state of the world
	// and an Action describing some action that happened.
	// Based on this action, the reducer returns a new state of the world.
	//
	// Reducers are called sequentially in the order they were registered
	// with Store.Before(), Store.Use() or Store.After().
	//
	// A reducer should not call Store.State().
	//
	// Reducers should complete their work as quickly as possible,
	// ideally only updating the state and not doing any work in the reducer itself.
	//
	// If a reducer is slow it might block the editor UI because some actions like
	// fmt'ing the view must wait for the new src before the user
	// can continue editing or saving the file.
	//
	// e.g. during the ViewFmt or ViewPreSave action, a reducer that knows how to
	// fmt the file might update the state to hold a fmt'd copy of the view's src.
	//
	// or it can implement a linter that kicks off a goroutine to try to compile
	// a package when one of its files when the ViewSaved action is dispatched.
	Reduce(*Ctx) *State

	// RLabel returns a string that can be used to name the reducer
	// in pf.Profile and other display scenarios
	RLabel() string
	ReducerLabel() string

	// RInit is called for the first reduction
	// * it's only called once and can be used to initialise reducer state
	//   e.g. for initialising an embedded type
	// * it's called before RConfig()
	RInit(*Ctx)
	ReducerInit(*Ctx)

	// RConfig is called on each reduction, before RCond
	// if it returns a new EditorConfig, it's equivalent to State.SetConfig()
	// but is always run before RCond() so is usefull for making sure
	// configuration changes are always applied, even if Reduce() isn't called
	RConfig(*Ctx) EditorConfig
	ReducerConfig(*Ctx) EditorConfig

	// RCond is called before Reduce and RMount is called
	// if it returns false, no other methods are called
	//
	// It can be used as a pre-condition in combination with Reducer(Un)Mount
	RCond(*Ctx) bool
	ReducerCond(*Ctx) bool

	// RMount is called once, after the first time that RCond returns true
	RMount(*Ctx)
	ReducerMount(*Ctx)

	// RUnmount is called when communication with the client will stop
	// it is only called if RMount was called
	//
	// It can be used to clean up any resources created in RMount
	//
	// After this method is called, Reduce will never be called again
	RUnmount(*Ctx)
	ReducerUnmount(*Ctx)
	// contains filtered or unexported methods
}

A Reducer is the main method of state transitions in margo.

The methods are called in the order listed below:

  • RInit this is called during the first action (initAction{} FKA Started{})
  • RConfig this is called on each reduction
  • RCond this is called on each reduction if it returns false, no other method is called
  • RMount this is called once, after the first time RCond returns true
  • Reduce this is called on each reduction until the agent begins shutting down
  • RUnmount this is called once when the agent is shutting down, iif RMount was called

For simplicity and the ability to extend the interface in the future, users should embed `ReducerType` in their types to complete the interface.

For convenience, it also implements all optional (non-Reduce()) methods.

The method prefix `^R[A-Z]\w+` and name `Reduce` are reserved, and should not be used.

For backwards compatibility the legacy methods: ReducerInit, ReducerConfig, ReducerCond, ReducerMount and ReducerUnmount will be called if the reducer does *not* defined the corresponding lifecycle method. i.e. if a reducer defines `ReducerInit` but not `RInit`, `ReducerInit` will be called.

NewReducer() can be used to convert a function to a reducer.

For reducers that are backed by goroutines that are only interested in the *last* of some value e.g. *Ctx, mgutil.ChanQ might be of use.

type ReducerType

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

ReducerType implements all optional methods of a reducer

func (*ReducerType) RCond

func (rt *ReducerType) RCond(mx *Ctx) bool

RCond implements Reducer.RCond

func (*ReducerType) RConfig

func (rt *ReducerType) RConfig(mx *Ctx) EditorConfig

RConfig implements Reducer.RConfig

func (*ReducerType) RInit

func (rt *ReducerType) RInit(mx *Ctx)

RInit implements Reducer.RInit

func (*ReducerType) RLabel

func (rt *ReducerType) RLabel() string

RLabel implements Reducer.RLabel

func (*ReducerType) RMount

func (rt *ReducerType) RMount(mx *Ctx)

RMount implements Reducer.RMount

func (*ReducerType) RUnmount

func (rt *ReducerType) RUnmount(mx *Ctx)

RUnmount implements Reducer.RUnmount

func (*ReducerType) ReducerCond

func (rt *ReducerType) ReducerCond(*Ctx) bool

ReducerCond implements Reducer.ReducerCond

func (*ReducerType) ReducerConfig

func (rt *ReducerType) ReducerConfig(*Ctx) EditorConfig

ReducerConfig implements Reducer.ReducerConfig

func (*ReducerType) ReducerInit

func (rt *ReducerType) ReducerInit(*Ctx)

ReducerInit implements Reducer.ReducerInit

func (*ReducerType) ReducerLabel

func (rt *ReducerType) ReducerLabel() string

ReducerLabel implements Reducer.ReducerLabel

func (*ReducerType) ReducerMount

func (rt *ReducerType) ReducerMount(*Ctx)

ReducerMount implements Reducer.ReducerMount

func (*ReducerType) ReducerUnmount

func (rt *ReducerType) ReducerUnmount(*Ctx)

ReducerUnmount implements Reducer.ReducerUnmount

type Restart

type Restart struct{ ActionType }

Restart is the action dispatched to initiate a graceful restart of the agent

func (Restart) ClientAction

func (r Restart) ClientAction() actions.ClientData

type RunCmd

type RunCmd struct {
	ActionType

	Fd       string
	Input    bool
	Name     string
	Args     []string
	CancelID string
	Prompts  []string
}

func (RunCmd) BoolFlag

func (rc RunCmd) BoolFlag(name string, value bool) bool

func (RunCmd) Flags

func (rc RunCmd) Flags() RunCmdFlagSet

func (RunCmd) IntFlag

func (rc RunCmd) IntFlag(name string, value int) int

func (RunCmd) Interpolate

func (rc RunCmd) Interpolate(mx *Ctx) RunCmd

func (RunCmd) StringFlag

func (rc RunCmd) StringFlag(name, value string) string

type RunCmdFlagSet

type RunCmdFlagSet struct {
	RunCmd RunCmd
	*flag.FlagSet
}

func (RunCmdFlagSet) Parse

func (fs RunCmdFlagSet) Parse() error

type RunDmc

type RunDmc = RunCmd

type Shutdown

type Shutdown struct{ ActionType }

Shutdown is the action dispatched to initiate a graceful shutdown of the agent

func (Shutdown) ClientAction

func (s Shutdown) ClientAction() actions.ClientData

type State

type State struct {
	// StickyState holds the current state of the editor
	StickyState

	// Status holds the list of status messages to show in the view
	Status StrSet

	// Errors hold the list of error to display to the user
	Errors StrSet

	// Completions holds the list of completions to show to the user
	Completions []Completion

	// Issues holds the list of issues to present to the user
	Issues IssueSet

	// BuiltinCmds holds the list of builtin commands.
	// It's usually populated during the RunCmd action.
	BuiltinCmds BuiltinCmdList

	// UserCmds holds the list of user commands.
	// It's usually populated during the QueryUserCmds and QueryTestCmds actions.
	UserCmds UserCmdList

	// Tooltips is a list of tips to show the user
	Tooltips []Tooltip

	// HUD contains information to the displayed to the user
	HUD HUDState
	// contains filtered or unexported fields
}

State holds data about the state of the editor, and transformations made by reducers

All fields are readonly and should only be assigned to during a call to State.Copy() Methods on this object that return *State, return a new object. As an optimization/implementation details, the methods may choose to return the input state object if no updates are done.

New instances can be obtained through Store.NewCtx()

Except StickyState, all fields are cleared at the start of a new dispatch. Fields that to be present for some time, e.g. Status and Issues, Should be populated at each call to the reducer even if the action is not its primary action. e.g. for linters, they should kill off a goroutine to do a compilation after the file has been saved (ViewSaved) but always return its cached issues.

If a reducer fails to return their state unless their primary action is dispatched it could result in flickering in the editor for visible elements like the status

func (*State) AddBuiltinCmds

func (st *State) AddBuiltinCmds(l ...BuiltinCmd) *State

AddBuiltinCmds adds the list of builtin commands in l to State.BuiltinCmds

func (*State) AddCompletions

func (st *State) AddCompletions(l ...Completion) *State

AddCompletions adds the completions in l to State.Completions

func (*State) AddError

func (st *State) AddError(l ...error) *State

AddError adds the non-nil errors in l to State.Errors.

func (*State) AddErrorf

func (st *State) AddErrorf(format string, a ...interface{}) *State

AddErrorf is equivalent to State.AddError(fmt.Sprintf())

func (*State) AddHUD

func (st *State) AddHUD(heading htm.IElement, content ...htm.Element) *State

AddHUD adds a new article to State.HUD

func (*State) AddIssues

func (st *State) AddIssues(l ...Issue) *State

AddIssues adds the list of issues in l to State.Issues

func (*State) AddStatus

func (st *State) AddStatus(l ...string) *State

AddStatus adds the list of messages in l to State.Status.

func (*State) AddStatusf

func (st *State) AddStatusf(format string, a ...interface{}) *State

AddStatusf is equivalent to State.AddStatus(fmt.Sprintf())

func (*State) AddTooltips

func (st *State) AddTooltips(l ...Tooltip) *State

AddTooltips add the list of tooltips l to State.Tooltips

func (*State) AddUserCmds

func (st *State) AddUserCmds(l ...UserCmd) *State

AddUserCmds adds the list of user commands in l to State.userCmds

func (*State) Copy

func (st *State) Copy(updaters ...func(*State)) *State

Copy create a shallow copy of the State.

It applies the functions in updaters to the new object. Updating the new State via these functions is preferred to assigning to the new object

func (*State) SetConfig

func (st *State) SetConfig(c EditorConfig) *State

SetConfig updates the State.Config.

func (*State) SetEnv

func (st *State) SetEnv(m EnvMap) *State

SetEnv updates State.Env.

func (*State) SetView

func (st *State) SetView(v *View) *State

func (*State) SetViewSrc

func (st *State) SetViewSrc(src []byte) *State

SetSrc is a wrapper around View.SetSrc(). If `len(src) == 0` it does nothing because this is almost always a bug.

type StickyState

type StickyState struct {
	// View describes the current state of the view.
	// When constructed correctly (through Store.NewCtx()), View is never nil.
	View *View

	// Env holds environment variables sent from the editor.
	// For "go" views in the "margo.sh" tree and "margo" package,
	// "GOPATH" is set to the GOPATH that was used to build the agent.
	Env EnvMap

	// Editor holds data about the editor
	Editor EditorProps

	// Config holds config data for the editor to use
	Config EditorConfig `mg.Nillable:"true"`
}

StickyState is state that's persisted from one reduction to the next. It holds the current state of the editor.

All fields are readonly and should only be assigned to during a call to State.Copy(). Child fields esp. View should not be assigned to.

type Store

type Store struct {
	// KVMap is an in-memory cache of data with automatic eviction.
	// Eviction might happen if the active view changes.
	//
	// NOTE: it's not safe to store values with *Ctx objects here; use *Ctx.KVMap instead
	KVMap
	// contains filtered or unexported fields
}

Store holds global, shared state

func (*Store) After

func (sto *Store) After(reducers ...Reducer) *Store

After adds reducers to the list of reducers they're are called after normal (Store.Use) reducers

func (*Store) Before

func (sto *Store) Before(reducers ...Reducer) *Store

Before adds reducers to the list of reducers they're are called before normal (Store.Use) reducers

func (*Store) Begin

func (sto *Store) Begin(t Task) *TaskTicket

Begin starts a new task and returns its ticket

func (*Store) Dispatch

func (sto *Store) Dispatch(act Action)

Dispatch schedules a new reduction with Action act

* actions coming from the editor has a higher priority * as a result, if Shutdown is dispatched, the action might be dropped

func (*Store) NewCtx

func (sto *Store) NewCtx(act Action) *Ctx

NewCtx returns a new Ctx initialized using the internal StickyState. The caller is responsible for calling Ctx.Cancel() when done with the Ctx

func (*Store) SetBaseConfig

func (sto *Store) SetBaseConfig(cfg EditorConfig) *Store

SetBaseConfig sets the EditorConfig on which State.Config is based

this method is made available for use by editor/client integration normal users should use State.SetConfig instead

func (*Store) Subscribe

func (sto *Store) Subscribe(sub Subscriber) (unsubscribe func())

Subscribe arranges for sub to be called after each reduction takes place the function returned can be used to unsubscribe from further notifications

func (*Store) Use

func (sto *Store) Use(reducers ...Reducer) *Store

Use adds reducers to the list of reducers they're called after reducers added with Store.Before and before reducers added with Store.After

type StoreIssues

type StoreIssues struct {
	ActionType

	IssueKey
	Issues IssueSet
}

type StrSet

type StrSet = mgutil.StrSet

type Subscriber

type Subscriber func(*Ctx)

Subscriber is the signature of the function accepted by Store.Subscribe

type Task

type Task struct {
	Title    string
	Cancel   func()
	CancelID string
	ShowNow  bool
	NoEcho   bool
}

type TaskTicket

type TaskTicket struct {
	Task
	ID    string
	Start time.Time
	// contains filtered or unexported fields
}

func (*TaskTicket) Cancel

func (ti *TaskTicket) Cancel()

func (*TaskTicket) Cancellable

func (ti *TaskTicket) Cancellable() bool

func (*TaskTicket) Done

func (ti *TaskTicket) Done()

type Tooltip

type Tooltip struct {
	Content string
}

type UserCmd

type UserCmd struct {
	// Title is the name of the command displayed to the user
	Title string

	// Desc describes what the command invocation does
	Desc string

	// Name is the name of the command to run
	Name string

	// Args is a list of args to pass to the command
	Args []string

	// Prompts is a list of titles for prompting the user for input before running the command.
	// The user is prompted once for each entry.
	// The inputs are assigned directly to RunCmd.Prompts for command consumption.
	Prompts []string
}

UserCmd represents a command that may be displayed in the editor ui.

type UserCmdList

type UserCmdList []UserCmd

UserCmdList is a list of UserCmd

func (UserCmdList) Len

func (uc UserCmdList) Len() int

Len implements sort.Interface

func (UserCmdList) Less

func (uc UserCmdList) Less(i, j int) bool

Len implements sort.Interface using UserCmd.Title for comparison

func (UserCmdList) Swap

func (uc UserCmdList) Swap(i, j int)

Len implements sort.Interface

type View

type View struct {
	Path  string
	Wd    string
	Name  string
	Hash  string
	Src   []byte
	Pos   int
	Row   int
	Col   int
	Dirty bool
	Ext   string
	Lang  Lang
	// contains filtered or unexported fields
}

func (*View) Basename

func (v *View) Basename() string

func (*View) CommonPatterns

func (v *View) CommonPatterns() []*regexp.Regexp

CommonPatterns is equivalent to CommonPatterns(View.Lang)

func (*View) Copy

func (v *View) Copy(updaters ...func(*View)) *View

func (*View) Dir

func (v *View) Dir() string

func (*View) Filename

func (v *View) Filename() string

func (*View) LangIs

func (v *View) LangIs(langs ...Lang) bool

func (*View) Open

func (v *View) Open() (r io.ReadCloser, err error)

func (*View) ReadAll

func (v *View) ReadAll() ([]byte, error)

func (*View) SetSrc

func (v *View) SetSrc(s []byte) *View

func (*View) ShortFilename

func (v *View) ShortFilename() string

func (*View) SrcPos

func (v *View) SrcPos() ([]byte, int)

SrcPos returns the view's src and pos taking care of reading src and clamping pos

func (*View) Valid

func (v *View) Valid() bool

type ViewActivated

type ViewActivated struct{ ActionType }

type ViewFmt

type ViewFmt struct{ ActionType }

type ViewLoaded

type ViewLoaded struct{ ActionType }

type ViewModified

type ViewModified struct{ ActionType }

type ViewPosChanged

type ViewPosChanged struct{ ActionType }

type ViewPreSave

type ViewPreSave struct{ ActionType }

type ViewSaved

type ViewSaved struct{ ActionType }

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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