Editor Plugin Development Guide for bluerig
=========================================

This document describes how to write an editor plugin for bluerig: a
module that registers with the editor and adds commands, menu entries
and key handling of its own.

The authoritative declarations live in:

- lib/editor-plugin.h        the plugin API
- lib/editor-plugin.c        the registry and the loader

This guide reflects the current API only.  When in doubt, the header
is the source of truth.

Scripts written in Lua are a different mechanism: they are run by the
Lua runtime plugin and need no compiler.  See doc/LUA_PLUGINS.md and
doc/LUA_API_REFERENCE.md.


1. General Rules
----------------

- Keep the editor core plugin-agnostic.
  Core must not branch on a plugin's name; expose a capability flag or
  callback instead.
- Use the host callbacks (mc_editor_host_t) rather than reaching into
  editor internals where a callback exists.
- Return explicit status codes:
  MC_EPR_OK / MC_EPR_FAILED / MC_EPR_NOT_SUPPORTED.
- Keep activate() for the main action and configure() for the settings
  dialog; do not overload activate() with a configuration dialog.


2. In-tree Plugins
------------------

The plugins that come with bluerig are built into the program (see
src/meson.build, which compiles them into the internal library):

  src/plugins/ctags/      self-registered menu entries, named
                                 actions, dynamic shortcut resolver;
                         the index of the project in the
                         background; the "ctags" service
  src/plugins/spell/      activate + configure + query_state +
                                 handle_key
  src/plugins/etags/      handle_action only
  src/plugins/project/    the project of a file: its files at hand,
                         the recent ones, its tree; the "project"
                         service
  src/plugins/build/      builds the project, marks the lines the
                         compiler names and goes to them; the
                         "build" service
  src/plugins/git/        the window Git: the status of the work
                         tree, the log, the diffs; the messages of
                         the commits written in a file window

src/plugins/builtin-plugins.c (compiled as part of
src/editor/editcmd.c) holds their descriptors (and that
of the "scripts" entry) and registers them with
mc_editor_plugin_add() from editor_plugins_register_all().

Three plugins come with bluerig as modules, loaded the way any other
module is (section 3), and are examples of one:

  src/plugins/debugger/   debugger.so: the Debug menu, the marks of
                                 the breakpoints and of the program in
                                 the gutter, the panel, the window of
                                 the instructions; GDB/MI, and the
                                 debug adapters of the Debug Adapter
                                 Protocol when json-glib is found.
                                 Built when GModule is found.

  src/plugins/terminal/   terminal.so: a window of its own
                                 (section 9), the shell in the
                                 terminal of mc, shown and hidden by
                                 Ctrl-o through handle_action; the
                                 service "terminal": the terminal of
                                 the program of the debugger, and a
                                 command typed into the shell, its end
                                 told by the signal "finished" (the
                                 git plugin pushes there).  Built
                                 when openpty() and GModule are
                                 found, installed into the system
                                 directory of the plugins.
  src/plugins/viewer/     viewer.so: the Preview, Ctrl-Alt-P,
                                 of whatever file has the focus, and
                                 the service "viewer" (section 10),
                                 windows that show the text a script
                                 or a plugin gives them, with the
                                 overstrikes of nroff and ANSI colors.
                                 Its methods and signals are listed in
                                 viewer.c.  The Preview asks the
                                 renderers what types they know with
                                 the signal "types" (they answer
                                 with add_type: the type, the ends of
                                 the names, the starts of the texts)
                                 and for the view of a file with the
                                 signal "render"; the Lua scripts
                                 render-markdown, render-json and
                                 render-xml are renderers.  Built
                                 when GModule is found.

The terminal module holds the terminal of mc as well (src/mcterm and
src/viewer).  The modules call the functions of the editor, which the
program exports; what the program itself does not call it links whole
(libforplugins in src/meson.build).  The test module_symbols checks
that the program gives every function a module calls.

The help of a plugin (build.md, ctags.md, debugger.md, etags.md, git.md, project.md,
query.md, spell.md, terminal.md) is installed into $(pkgdatadir)/help next to the help of the
program.


3. Lifecycle and Location
-------------------------

When the editor starts, it first registers the built-in plugins and
then calls mc_editor_plugins_load(), which scans the directories of the
environment variable BLUERIG_PLUGINS_DIR, separated by ':', then two
directories:

    $(libdir)/bluerig/plugins          (MC_PLUGINS_DIR)
    ~/.local/lib/bluerig/plugins

A plugin whose name is registered already is not loaded again, so the
first directory that has it wins.  The build sets BLUERIG_PLUGINS_DIR to
the directories the modules are built in, for the program of the build
to run with them rather than with those installed:

    meson devenv -C build bluerig

The system directory is set at build time:

    meson setup build -Dplugins_dir=DIR

Every file directly in these directories whose name ends in .so (or
.dylib, .bundle, .dll) is opened with g_module_open(); there are no
subdirectories.  The loader resolves the symbol
"mc_editor_plugin_register" (MC_EDITOR_PLUGIN_ENTRY), calls it, and
passes the descriptor it returns to mc_editor_plugin_add().  A module
whose descriptor is accepted is made resident.  Loading needs GModule;
a build without it has the built-in plugins only.

mc_editor_plugin_add() rejects a descriptor

- whose api_version differs from MC_EDITOR_PLUGIN_API_VERSION
  (currently 6), with a message on stderr;
- that has no name, no open() or no close(), with a message on stderr;
- whose name was disabled in Options -> Manage plugins;
- whose name is already registered.  The built-in plugins are
  registered first, so a module cannot replace one of them.

For every editor dialog, the editor calls open() of each registered
plugin that is not disabled.  A plugin whose open() returns NULL gets
no instance in that dialog.  close() receives the value open()
returned.

Options -> Manage plugins switches plugins on and off; the state is
kept in ~/.config/bluerig/plugins.ini, section [DisabledPlugins], one key
"editor/<name>" per disabled plugin.  Options -> Plugin info lists the
registered plugins and the callbacks each one has.


4. API Entry Point
------------------

A plugin module must export:

    const mc_editor_plugin_t *mc_editor_plugin_register (void);

The descriptor minimum:

- api_version = MC_EDITOR_PLUGIN_API_VERSION
- a unique name
- display_name (the menu label; name is used when it is NULL)
- the required callbacks open and close

    void *(*open) (mc_editor_host_t *host, void *editor_dialog);
    void (*close) (void *plugin_data);


5. Capability Flags (mc_ep_flags_t)
-----------------------------------

  MC_EPF_NONE
  MC_EPF_HAS_MENU            the plugin has an entry of its own in the
                             Plugins menu.  The entry is shown only when
                             the plugin also has activate()


6. Host Services (mc_editor_host_t)
-----------------------------------

What the editor provides to the plugin, passed to open():

  redraw(host)
                             redraw the editor window
  message(host, flags, title, text)
                             modal message box
  get_cursor_word(host, edit)
                             word under cursor; NULL if not on a word.
                             Caller frees with g_free()
  get_current_file(host, edit)
                             absolute path of the open file or NULL;
                             caller frees
  get_cursor_line(host, edit)
                             1-based line number; 0 if unavailable
  jump_to(host, edit, file, line)
                             open file at line; pushes the current
                             position onto the navigation stack
  insert_text(host, edit, text, remove_before)
                             insert at cursor after deleting
                             remove_before bytes backwards
  window_area(host, &rect)
                             the part of the screen the windows take:
                             all of it but the menu bar and the button
                             bar
  window_add(host, window)
                             put a window of the plugin on the screen,
                             on top of the others and selected; see
                             section 9
  window_show(host, window)
                             show a hidden window as it was when it
                             was hidden, on top and selected
  window_hide(host, window)
                             hide a window as it is; the next window
                             is selected
  window_make_room(host, window)
                             the topmost fullscreen window stops being
                             fullscreen and takes the area above the
                             window, which does not fill the screen
  window_give_room_back(host, window)
                             that window is made fullscreen again,
                             unless the user has moved, resized or
                             zoomed it since
  window_current(host)
                             the window with the focus, or NULL
  window_top_file(host)
                             the topmost file window seen on the
                             screen, or NULL
  get_text(host, edit, &len)
                             all the text of a file window; caller
                             frees
  get_revision(host, edit)
                             the revision of that text, which grows
                             with every change
  service_register(host, name, call, data, &error)
  service_unregister(host, name)
  service_call(host, name, method, args, &error)
  service_connect(host, name, fn, user_data)
  service_disconnect(host, id)
  service_emit(host, name, signal, args)
                             the services plugins and scripts offer
                             one another; see section 10
  marker_kind(host, kind)    register a kind of gutter mark (a
                             mc_ep_marker_kind_t: its name, the
                             [widget-editor] key of its glyph and the
                             [editor] keys of its colours); the same
                             name gives the same id
  set_marker(host, file, line, kind, enabled)
                             put or take a mark of that kind on a line
                             of every window of the file; the mark is a
                             bookmark of the plugin and moves with its
                             line as lines are inserted or deleted
  clear_markers(host, file, kind)
                             take the marks of a kind off a file, or
                             (file NULL) off all files
  marker_lines(host, file, kind)
                             the lines the marks of a kind are on now,
                             NULL when no window has the file
  commands_register(host, section, title, commands)
                             the commands of the plugin (mc_ep_command_t:
                             name, N_() description, default keys "f5;
                             ctrl-r"; a NULL name ends them) in a section
                             of the keymap of its own, which the keymap
                             files may set and Options > Key bindings
                             shows under that title
  command_id(host, name)     the number of a command; a command of the
                             plugin that comes to the editor, from the
                             button bar for one, goes to handle_action()
  command_lookup(host, section, key)
                             the command a key is bound to in a section
  command_label(host, name, label)
                             the label ("ButtonBar|Build") of a command:
                             while the modifiers of a key of it are held
                             (Ctrl of Ctrl-F9) the button bar shows it,
                             over the editor's command; NULL: none.  Given
                             only while the plugin takes the key, it may
                             change with the state of the plugin
  open_file(host, file)      the window of a file to the front, or a new
                             one with the cursor where it was
  set_line_note(host, file, line, text)
                             a note after the text of a line, in the
                             editnote color of the skin; NULL takes it
                             off
  clear_line_notes(host, file)
                             all the notes off a file, or off all files
  startup_option(host, name)  an option the program was started with:
                             "debug", the directory of bluerig --debug
  call_later(host, fn, data)  fn(data) once the editor is idle: what a
                             plugin opens when it starts, windows and
                             files, goes so, not from open() or an event
  window_close(host, window)  close a window as the user would; from
                             call_later(), not from an event of it
  show_location(host, file, line)
                             open a source location without pushing
                             each debugger step onto navigation history
  save_modified_files(host, project_root)
                             offer to save all modified editor files
                             within that root; FALSE cancels the launch
  window_kind(host, kind, data)
                             a window the plugin opens, in the Window
                             menu, from open(): mc_ep_window_kind_t
                             with its label, the keymap section and
                             command whose key the menu shows (else a
                             shortcut text), and state(), show() and
                             close() called with data.  state() says
                             MC_EP_WINDOW_CLOSED, _OPEN (behind another)
                             or _FOCUSED; the entry shows a closed
                             window, brings one behind to the front,
                             and closes the one in front.  An open one
                             is marked with '*'.  The menu is made again
                             whenever it drops.  Its name ("project.tree")
                             and window() (the window when it is open)
                             let the layouts of the editor open, close
                             and place it.
  window_dock_bottom(host, window, lines)
                             a window added in the row at the bottom,
                             under the windows of the files: a tab, the
                             one seen.  window_dock_right() puts one in
                             the column at the right; window_hide() and
                             window_give_room_back() take it out
  layout_push(host, name)    the windows as the layout name has them,
                             those of the moment kept; FALSE when the
                             user has it off ("Debug") or one is kept
  layout_pop(host)           the windows kept put back, the tabs of the
                             bottom staying

Fields:

  host_data                  opaque, owned by the editor core

The edit and editor_dialog arguments are opaque to the plugin.


7. Plugin Callbacks
-------------------

All are optional except open and close.

  activate(plugin_data, edit)
                             the primary action, run when the plugin's
                             entry in the Plugins menu is picked
  configure(plugin_data, edit)
                             open the settings dialog
  handle_action(plugin_data, command, edit)
                             called for the plugin's own Plugins menu
                             command when it has no activate(), and
                             offered every editor command (CK_*) the
                             editor executes
  query_state(plugin_data, edit, &state)
                             fill mc_ep_state_t; checked before
                             activate() from the Plugins menu
  handle_key(plugin_data, key, edit)
                             raw key interception.  Called for every
                             key before the macro hotkeys and the
                             keymaps of the editor and of its windows,
                             so a plugin may take F9 and F10 too;
                             return MC_EPR_OK to consume the key.
                             With a window that is no file in front,
                             the terminal for one, it is called with
                             edit NULL before the window gets the key:
                             a plugin that needs a file returns
                             MC_EPR_NOT_SUPPORTED, and the key is the
                             window's
  handle_event(plugin_data, edit, event_id, payload)
                             MC_EP_EVENT_TEXT_CHANGED and
                             MC_EP_EVENT_CURSOR_MOVED, below
  on_file_open(plugin_data, edit)
  on_file_close(plugin_data, edit)
                             called when a source file window opens or
                             closes
  ok_to_quit(plugin_data)
                             return FALSE to cancel editor shutdown;
                             useful for confirming a live debug session

State contract (mc_ep_state_t):

  available                  plugin can operate in the current
                             environment (binaries present, etc.)
  enabled                    action is currently usable
  reason                     optional explanation shown to the user
                             when the action is refused

Event ids reserved for handle_event():

  MC_EP_EVENT_FILE_SAVED      file written; payload = const char *path
  MC_EP_EVENT_FILE_RENAMED    Save As completed; payload = new path
  MC_EP_EVENT_FOCUS_IN        a file window got the focus; the editor
                              has put its button bar labels, and a
                              plugin may put its own over them
  MC_EP_EVENT_FOCUS_OUT       a file window lost the focus
  MC_EP_EVENT_TEXT_CHANGED    the text of edit changed; payload = NULL
  MC_EP_EVENT_CURSOR_MOVED    the cursor of edit is on another line;
                              payload = NULL

The last two are called: once the editor is idle after the keys that
came together, for the file window with the focus, and both when
another file window comes to the front.  get_text() and get_revision()
of the host give the text and its revision; the Lua scripts hear the
same as editor.change and editor.cursor.


8. Actions and Menu Entries
---------------------------

A plugin exposes named actions through:

    const mc_ep_action_t *actions;
    int action_count;

Each entry has a label and a direct callback:

    mc_ep_result_t (*callback) (void *plugin_data, void *edit);

The callback is invoked directly when the user picks the menu item;
activate / handle_action are not used for it.  A plugin has at most
MC_EDITOR_PLUGIN_ACTIONS_MAX (256) actions.

Top-level menu integration:

    const mc_ep_cmd_menu_entry_t *cmd_menu_entries;
    int cmd_menu_entry_count;

Each entry sets:

    menu_name        MC_EP_MENU_FILE, MC_EP_MENU_COMMAND,
                     MC_EP_MENU_NAVIGATE, or MC_EP_MENU_PLUGINS for
                     entries after the plugins of the Plugins menu (a
                     window goes to the Window menu with window_kind()
                     instead); any other name is a menu of
                     the plugins' own, made before Window, with that
                     name as its title: N_("&Debug"), whose & letter
                     with Alt drops it.  The scripts add to it by the
                     name without the &
    label            menu text (with & accelerator, translated with
                     gettext); NULL = separator
    action_index     index into actions[]
    shortcut         display string for the shortcut column; NULL =
                     omit.  Overridden at menu-build time if the plugin
                     defines get_menu_shortcut().

Optional dynamic shortcut resolver:

    char *(*get_menu_shortcut) (int action_index);

Returns a newly-allocated string (caller frees with g_free) or NULL to
fall back to the static shortcut text.

Command ids: the Plugins menu entry of the plugin at position N of the
registry is MC_EDITOR_PLUGIN_CMD_BASE + N; action A of that plugin is
MC_EDITOR_PLUGIN_ACTION_BASE + N * MC_EDITOR_PLUGIN_ACTIONS_MAX + A.


9. Windows
----------

A plugin can put a window of its own on the editor screen, next to the
windows of the files.  A window is a WEditWindow (src/editor/editwindow.h),
and the screen treats all windows alike: they have a frame, are moved and
resized, shown full screen, listed in Window -> List, selected with
Window -> Next and Previous, and closed.  What a window shows and does is
given by its class, edit_window_class_t:

  callback                   the messages of the window (MSG_DRAW,
                             MSG_KEY, MSG_DESTROY, ...); the unhandled
                             ones go to group_default_callback().  On
                             MSG_FOCUS the class puts its labels on
                             the button bar (buttonbar_set_label());
                             the editor draws the bar then, so that it
                             is always the one of the window with the
                             focus
  mouse_callback             mouse events inside the window that its
                             frame does not take; NULL passes them to
                             the widgets of the window
  get_title                  the name of the window in the list of
                             windows; caller frees
  is_modified                whether the window holds unsaved changes;
                             may be NULL
  close                      close the window, asking first when it has
                             to; TRUE when the window was destroyed
  min_lines, min_cols        the smallest size, with the frame

A window is a group, as a window of Turbo Vision is: it may hold widgets
of its own, added with group_add_widget_autopos() at places relative to
the window.  They move and resize with the window, get the focus with
it, and are destroyed with it.

The plugin allocates the window, fills it in with edit_window_init()
and gives it to window_add().  A window starts full screen and keeps the
rectangle it was made with to go back to; one that should start at that
rectangle is made with its fullscreen field cleared before window_add().
The class draws the frame with edit_window_frame_color(),
edit_window_draw_frame() and edit_window_draw_icons().

Once added, the window belongs to the editor.  It is destroyed when the
user closes it - close() of the class destroys it with
edit_window_destroy(), which selects the window left on top - and when
the editor ends, and the class learns of that by MSG_DESTROY, where the
plugin forgets the window.  The plugin never frees an added window.
When the editor ends, its windows are destroyed before close() of the
plugin is called.

A hidden window keeps its place, size, full screen state and contents,
and window_show() brings it back as it was.  Window -> List shows the
hidden windows too, and picking one shows it.

A key goes to the current window first.  A key the window does not
handle goes to the editor screen, which looks it up in the keymap of the
editor, so F9, F10 and the other keys of the screen work in a window of a
plugin unless the window takes them itself.


10. Services
------------

A plugin can offer a service to other plugins and to the Lua scripts:
the viewer plugin, for one, shows the text a script gives it.  The
declarations are in lib/plugin-service.h; a plugin reaches them through
the host.

A service has a name and one function every call goes through:

    GVariant *call (void *data, const char *method, GVariant *args,
                    GError **error);

The arguments and the answer are GVariant dictionaries, a{sv}, of
simple values: strings, integers, booleans, numbers, arrays of
strings.  The same call comes from a plugin in C, which builds the
dictionary itself, and from a script, whose table becomes one.  A
method the service does not have is an MC_SERVICE_ERROR_METHOD error,
arguments it does not take MC_SERVICE_ERROR_ARGS.

  service_register()         offer the service, from open(); a name
                             taken already is MC_SERVICE_ERROR_EXISTS
  service_unregister()       take it back, in close()
  service_call()             call a method of a service; the answer
                             is a new reference the caller unrefs, or
                             NULL with the error.  A service that is
                             not there is MC_SERVICE_ERROR_NOT_FOUND
  service_emit()             tell those who listen that something
                             happened: a window of the service closed
  service_connect()          listen to the signals of a service,
  service_disconnect()       whether it is there yet or not

The editor passes the calls and the signals on and knows nothing of
what they mean.


11. Registry
------------

  mc_editor_plugin_add(plugin)
  mc_editor_plugin_list()
  mc_editor_plugin_find_by_name(name)


12. Minimal Skeleton
--------------------

A plugin that registers and reacts to its Plugins menu entry (no extra
menus, no named actions):

    #include <config.h>

    #include "lib/global.h"
    #include "lib/editor-plugin.h"

    static void *
    my_open (mc_editor_host_t *host, void *editor_dialog)
    {
        (void) editor_dialog;
        return host;  /* any non-NULL opaque handle */
    }

    static void
    my_close (void *plugin_data)
    {
        (void) plugin_data;
    }

    static mc_ep_result_t
    my_activate (void *plugin_data, void *edit)
    {
        mc_editor_host_t *host = (mc_editor_host_t *) plugin_data;
        (void) edit;
        if (host->message != NULL)
            host->message (host, 0, "My Plugin", "Hello from the editor.");
        return MC_EPR_OK;
    }

    static const mc_editor_plugin_t my_plugin = {
        .api_version  = MC_EDITOR_PLUGIN_API_VERSION,
        .name         = "myedit",
        .display_name = "My Editor Plugin",
        .flags        = MC_EPF_HAS_MENU,

        .open         = my_open,
        .close        = my_close,
        .activate     = my_activate,
    };

    const mc_editor_plugin_t *
    mc_editor_plugin_register (void)
    {
        return &my_plugin;
    }

The headers come from the source tree, and config.h from a configured
build tree of the same version.  With the source in $SRC and the build
tree in $BUILD, a module can be compiled like this:

    cc -shared -fPIC -I"$BUILD" -I"$SRC" \
        $(pkg-config --cflags glib-2.0) \
        -o myedit.so myedit.c

The program is linked with -export-dynamic when GModule is available,
so the module can use the functions of the editor without linking
against them.  Copy myedit.so into ~/.local/lib/bluerig/plugins
and start bluerig again: the plugin appears in the Plugins menu, and
selecting it calls my_activate().

The descriptor is checked against MC_EDITOR_PLUGIN_API_VERSION, and a
module built against headers of another API version is not loaded.
Rebuild plugins when bluerig is upgraded.


13. Testing Checklist
---------------------

- the plugin appears in the Plugins menu, and in Options -> Plugin info
- activate() runs the primary action
- configure() opens settings only
- query_state() reflects backend / runtime availability
- self-registered menu entries land in the right top-level menu
- missing dependencies are reported via a clear user message
- switching the plugin off in Options -> Manage plugins keeps it out
  after a restart


14. Troubleshooting
-------------------

- Plugin not loaded:
  - verify the module is installed directly in one of the plugin
    directories, with a .so suffix
  - verify the exported symbol name (mc_editor_plugin_register)
  - verify api_version matches the header constant
  - run bluerig from a terminal and read what the loader writes to
    stderr
  - check that the plugin is not disabled in Options -> Manage plugins
  - check that no other plugin, built-in or not, has the same name

- Plugin listed but does nothing:
  - check that the required callbacks are non-NULL
  - confirm correct return codes (NOT_SUPPORTED vs FAILED)
  - for a Plugins menu entry, set MC_EPF_HAS_MENU and provide
    activate()

- Key does not trigger:
  - handle_key() sees the raw key code before the keymap; compare
    against the key code, not a CK_* command
