etherpad.org Open in urlscan Pro
185.199.109.153  Public Scan

Submitted URL: http://etherpad.org/doc/latest
Effective URL: https://etherpad.org/doc/latest/
Submission: On February 08 via manual from FR — Scanned from FR

Form analysis 0 forms found in the DOM

Text Content

ETHERPAD V1.8.18 MANUAL & DOCUMENTATION


TABLE OF CONTENTS

 * About this Documentation
 * Statistics
 * Localization
   * Translating
   * Implementation
     * Server-side
     * Client-side
   * Localizing plugins
     * 1. Mark the strings to translate
     * 2. Create translate files in the locales directory of your plugin
     * Overwrite core messages
   * Customization for Administrators
 * Docker
   * Downloading from Docker Hub
   * Build a personalized container
     * Rebuilding with custom settings
     * Rebuilding including some plugins
     * Rebuilding including export functionality for DOC/PDF/ODT
       * Via Abiword
       * Via Libreoffice
     * Examples
   * Running your instance:
   * Options available by default
     * General
     * Database
     * Pad Options
     * Shortcuts
     * Skins
     * Logging
     * Advanced
     * Examples
 * Skins
 * Embed parameters
   * showLineNumbers
   * showControls
   * showChat
   * useMonospaceFont
   * userName
   * userColor
   * noColors
   * alwaysShowChat
   * lang
   * rtl
   * #L
 * HTTP API
   * What can I do with this API?
     * OpenAPI
   * Examples
     * Example 1
     * Example 2
   * Usage
     * API version
     * Request Format
     * Response Format
     * Overview
   * Data Types
     * Authentication
     * Node Interoperability
   * API Methods
     * Groups
       * createGroup()
       * createGroupIfNotExistsFor(groupMapper)
       * deleteGroup(groupID)
       * listPads(groupID)
       * createGroupPad(groupID, padName [, text])
       * listAllGroups()
     * Author
       * createAuthor([name])
       * createAuthorIfNotExistsFor(authorMapper [, name])
       * listPadsOfAuthor(authorID)
       * getAuthorName(authorID)
     * Session
       * createSession(groupID, authorID, validUntil)
       * deleteSession(sessionID)
       * getSessionInfo(sessionID)
       * listSessionsOfGroup(groupID)
       * listSessionsOfAuthor(authorID)
     * Pad Content
       * getText(padID, [rev])
       * setText(padID, text)
       * appendText(padID, text)
       * getHTML(padID, [rev])
       * setHTML(padID, html)
       * getAttributePool(padID)
       * getRevisionChangeset(padID, [rev])
       * createDiffHTML(padID, startRev, endRev)
       * restoreRevision(padId, rev)
     * Chat
       * getChatHistory(padID, [start, end])
       * getChatHead(padID)
       * appendChatMessage(padID, text, authorID [, time])
     * Pad
       * createPad(padID [, text])
       * getRevisionsCount(padID)
       * getSavedRevisionsCount(padID)
       * listSavedRevisions(padID)
       * saveRevision(padID [, rev])
       * padUsersCount(padID)
       * padUsers(padID)
       * deletePad(padID)
       * copyPad(sourceID, destinationID[, force=false])
       * copyPadWithoutHistory(sourceID, destinationID[, force=false])
       * movePad(sourceID, destinationID[, force=false])
       * getReadOnlyID(padID)
       * getPadID(readOnlyID)
       * setPublicStatus(padID, publicStatus)
       * getPublicStatus(padID)
       * listAuthorsOfPad(padID)
       * getLastEdited(padID)
       * sendClientsMessage(padID, msg)
       * checkToken()
     * Pads
       * listAllPads()
     * Global
       * getStats()
 * Hooks
   * Registered hook functions
     * Arguments
     * Expected behavior
     * Return values
 * Client-side hooks
   * documentReady
   * aceDomLinePreProcessLineAttributes
   * aceDomLineProcessLineAttributes
   * aceCreateDomLine
   * acePostWriteDomLineHTML
   * aceAttribsToClasses
   * aceAttribClasses
   * aceGetFilterStack
   * aceEditorCSS
   * aceInitInnerdocbodyHead
   * aceEditEvent
   * aceRegisterNonScrollableEditEvents
   * aceRegisterBlockElements
   * aceInitialized
   * postAceInit
   * postToolbarInit
   * postTimesliderInit
   * goToRevisionEvent
   * userJoinOrUpdate
   * chatNewMessage
   * chatSendMessage
   * collectContentPre
   * collectContentImage
   * collectContentPost
   * handleClientMessage_name
   * aceStartLineAndCharForPoint-aceEndLineAndCharForPoint
   * aceKeyEvent
   * collectContentLineText
   * collectContentLineBreak
   * disableAuthorColorsForThisLine
   * aceSetAuthorStyle
   * aceSelectionChanged
 * Server-side hooks
   * loadSettings
   * shutdown
   * pluginUninstall
   * pluginInstall
   * init_<plugin name>
   * expressConfigure
   * expressCreateServer
   * expressCloseServer
   * eejsBlock_<name>
   * padInitToolbar
   * onAccessCheck
   * padCreate
   * padLoad
   * padUpdate
   * padCopy
   * padRemove
   * socketio
   * preAuthorize
   * authorize
   * authenticate
   * authFailure
   * preAuthzFailure
   * authnFailure
   * authzFailure
   * handleMessage
   * handleMessageSecurity
   * clientVars
   * getLineHTMLForExport
   * exportHTMLAdditionalContent
   * stylesForExport
   * aceAttribClasses
   * exportFileName
   * exportHtmlAdditionalTags
   * exportHtmlAdditionalTagsWithData
   * exportEtherpadAdditionalContent
   * import
   * userJoin
   * userLeave
   * chatNewMessage
 * editorInfo
   * editorInfo.ace_replaceRange(start, end, text)
   * editorInfo.ace_getRep()
   * editorInfo.ace_getAuthor()
   * editorInfo.ace_inCallStack()
   * editorInfo.ace_inCallStackIfNecessary(?)
   * editorInfo.ace_focus(?)
   * editorInfo.ace_importText(?)
   * editorInfo.ace_importAText(?)
   * editorInfo.ace_exportText(?)
   * editorInfo.ace_editorChangedSize(?)
   * editorInfo.ace_setOnKeyPress(?)
   * editorInfo.ace_setOnKeyDown(?)
   * editorInfo.ace_setNotifyDirty(?)
   * editorInfo.ace_dispose(?)
   * editorInfo.ace_setEditable(bool)
   * editorInfo.ace_execCommand(?)
   * editorInfo.ace_callWithAce(fn, callStack, normalize)
   * editorInfo.ace_setProperty(key, value)
   * editorInfo.ace_setBaseText(txt)
   * editorInfo.ace_setBaseAttributedText(atxt, apoolJsonObj)
   * editorInfo.ace_applyChangesToBase(c, optAuthor, apoolJsonObj)
   * editorInfo.ace_prepareUserChangeset()
   * editorInfo.ace_applyPreparedChangesetToBase()
   * editorInfo.ace_setUserChangeNotificationCallback(f)
   * editorInfo.ace_setAuthorInfo(author, info)
   * editorInfo.ace_fastIncorp(?)
   * editorInfo.ace_isCaret(?)
   * editorInfo.ace_getLineAndCharForPoint(?)
   * editorInfo.ace_performDocumentApplyAttributesToCharRange(?)
   * editorInfo.ace_setAttributeOnSelection(attribute, enabled)
   * editorInfo.ace_toggleAttributeOnSelection(?)
   * editorInfo.ace_getAttributeOnSelection(attribute, prevChar)
   * editorInfo.ace_performSelectionChange(?)
   * editorInfo.ace_doIndentOutdent(?)
   * editorInfo.ace_doUndoRedo(?)
   * editorInfo.ace_doInsertUnorderedList(?)
   * editorInfo.ace_doInsertOrderedList(?)
   * editorInfo.ace_performDocumentApplyAttributesToRange()
   * editorInfo.ace_getAuthorInfos()
   * editorInfo.ace_performDocumentReplaceRange(start, end, newText)
   * editorInfo.ace_performDocumentReplaceCharRange(startChar, endChar, newText)
   * editorInfo.ace_renumberList(lineNum)
   * editorInfo.ace_doReturnKey()
   * editorInfo.ace_isBlockElement(element)
   * editorInfo.ace_getLineListType(lineNum)
   * editorInfo.ace_caretLine()
   * editorInfo.ace_caretColumn()
   * editorInfo.ace_caretDocChar()
   * editorInfo.ace_isWordChar(?)
 * Changeset Library
   * Changeset
   * Attribute Pool
   * Further Reading
 * Plugin Framework
   * plugins.update
   * hooks.callAll
   * hooks.aCallAll
   * ...
 * Toolbar controller
   * button(opts)
   * selectButton(opts)
   * SelectButton.addOption(value, text, attributes)
   * registerButton(name, item)
   * isEnabled()
   * disable()
   * toggleDropDown(dropdown)
   * registerCommand(cmd, callback)
   * registerAceCommand(cmd, callback)
   * registerDropdownCommand(cmd, dropdown)
   * triggerCommand(cmd[, item])
 * Plugins
   * Folder structure
   * Plugin definition
     * Client hooks and server hooks
     * Styling
     * Parts
       * pre/post
   * Package definition
   * Templates
   * Writing and running front-end tests for your plugin
 * Cookies
 * Database structure
   * Keys and their values
     * groups
     * pad:$PADID
     * pad:$PADID:revs:$REVNUM
     * pad:$PADID:chat:$CHATNUM
     * pad2readonly:$PADID
     * readonly2pad:$READONLYID
     * token2author:$TOKENID
     * globalAuthor:$AUTHORID
     * mapper2group:$MAPPER
     * mapper2author:$MAPPER
     * group:$GROUPID
     * author2sessions:$AUTHORID
     * group2sessions:$GROUPID


ABOUT THIS DOCUMENTATION

The goal of this documentation is to comprehensively explain Etherpad, both from
a reference as well as a conceptual point of view.

Where appropriate, property types, method arguments, and the arguments provided
to event handlers are detailed in a list underneath the topic heading.

Every .html file is generated based on the corresponding .md file in the
doc/api/ folder in the source tree. The documentation is generated using the
src/bin/doc/generate.js program. The HTML template is located at
doc/template.html.


STATISTICS

Etherpad keeps track of the goings-on inside the edit machinery. If you'd like
to have a look at this, just point your browser to /stats.

We currently measure:

 * totalUsers (counter)
 * connects (meter)
 * disconnects (meter)
 * pendingEdits (counter)
 * edits (timer)
 * failedChangesets (meter)
 * httpRequests (timer)
 * http500 (meter)
 * memoryUsage (gauge)

Under the hood, we are happy to rely on measured for all our metrics needs.

To modify or simply access our stats in your plugin, simply
require('ep_etherpad-lite/stats') which is a measured.Collection.


LOCALIZATION

Etherpad provides a multi-language user interface, that's apart from your users'
content, so users from different countries can collaborate on a single document,
while still having the user interface displayed in their mother tongue.


TRANSLATING

We rely on https://translatewiki.net to handle the translation process for us,
so if you'd like to help...

 1. Sign up at https://translatewiki.net
 2. Visit our TWN project page
 3. Click on Translate Etherpad lite interface
 4. Choose a target language, you'd like to translate our interface to, and hit
    Fetch
 5. Start translating!

Translations will be send back to us regularly and will eventually appear in the
next release.


IMPLEMENTATION


SERVER-SIDE

/src/locales contains files for all supported languages which contain the
translated strings. Translation files are simple *.json files and look like
this:

{ "pad.modals.connected": "Connecté."
, "pad.modals.uderdup": "Ouvrir dans une nouvelle fenêtre."
, "pad.toolbar.unindent.title": "Dèsindenter"
, "pad.toolbar.undo.title": "Annuler (Ctrl-Z)"
, "timeslider.pageTitle": "{{appTitle}} Curseur temporel"
, ...
}


Each translation consists of a key (the id of the string that is to be
translated) and the translated string. Terms in curly braces must not be touched
but left as they are, since they represent a dynamically changing part of the
string like a variable. Imagine a message welcoming a user: Welcome,
{{userName}}! would be translated as Ahoy, {{userName}}! in pirate.


CLIENT-SIDE

We use a language cookie to save your language settings if you change them. If
you don't, we autodetect your locale using information from your browser. Then,
the preferred language is fed into a library called html10n.js, which loads the
appropriate translations and applies them to our templates. Its features include
translation params, pluralization, include rules and a nice javascript API.


LOCALIZING PLUGINS


1. MARK THE STRINGS TO TRANSLATE

In the template files of your plugin, change all hardcoded messages/strings...

from:

<option value="0">Heading 1</option>


to:

<option data-l10n-id="ep_heading.h1" value="0"></option>


In the javascript files of your plugin, change all hardcoded messages/strings...

from:

alert ('Chat');


to:

alert(window._('pad.chat'));



2. CREATE TRANSLATE FILES IN THE LOCALES DIRECTORY OF YOUR PLUGIN

 * The name of the file must be the language code of the language it contains
   translations for (see supported lang codes; e.g. en ? English, es ?
   Spanish...)
 * The extension of the file must be .json
 * The default language is English, so your plugin should always provide en.json
 * In order to avoid naming conflicts, your message keys should start with the
   name of your plugin followed by a dot (see below)

ep_your-plugin/locales/en.json

{ "ep_your-plugin.h1": "Heading 1"
}


ep_your-plugin/locales/es.json

{ "ep_your-plugin.h1": "Título 1"
}


Every time the http server is started, it will auto-detect your messages and
merge them automatically with the core messages.


OVERWRITE CORE MESSAGES

You can overwrite Etherpad's core messages in your plugin's locale files. For
example, if you want to replace Chat with Notes, simply add...

ep_your-plugin/locales/en.json

{ "ep_your-plugin.h1": "Heading 1"
, "pad.chat": "Notes"
}



CUSTOMIZATION FOR ADMINISTRATORS

As an Etherpad administrator, it is possible to overwrite core messages as well
as messages in plugins. These include error messages, labels, and user
instructions. Whereas the localization in the source code is in separate files
separated by locale, an administrator's custom localizations are in
settings.json under the customLocaleStrings key, with each locale separated by a
sub-key underneath.

For example, let's say you want to change the text on the "New Pad" button on
Etherpad's home page. If you look in locales/en.json (or locales/en-gb.json)
you'll see the key for this text is "index.newPad". You could add the following
to settings.json:

  "customLocaleStrings": {
    "fr": {
      "index.newPad": "Créer un document"
    },
    "en-gb": {
      "index.newPad": "Create a document"
    },
    "en": {
      "index.newPad": "Create a document"
    }
  }



DOCKER

The official Docker image is available on
https://hub.docker.com/r/etherpad/etherpad.


DOWNLOADING FROM DOCKER HUB

If you are ok downloading a prebuilt image from Docker Hub, these are the
commands:

# gets the latest published version
docker pull etherpad/etherpad

# gets a specific version
docker pull etherpad/etherpad:1.8.0



BUILD A PERSONALIZED CONTAINER

If you want to use a personalized settings file, you will have to rebuild your
image. All of the following instructions are as a member of the docker group. By
default, the Etherpad Docker image is built and run in production mode: no
development dependencies are installed, and asset bundling speeds up page load
time.


REBUILDING WITH CUSTOM SETTINGS

Edit <BASEDIR>/settings.json.docker at your will. When rebuilding the image,
this file will be copied inside your image and renamed to settings.json.

Each configuration parameter can also be set via an environment variable, using
the syntax "${ENV_VAR}" or "${ENV_VAR:default_value}". For details, refer to
settings.json.template.


REBUILDING INCLUDING SOME PLUGINS

If you want to install some plugins in your container, it is sufficient to list
them in the ETHERPAD_PLUGINS build variable. The variable value has to be a
space separated, double quoted list of plugin names (see examples).

Some plugins will need personalized settings. Just refer to the previous
section, and include them in your custom settings.json.docker.


REBUILDING INCLUDING EXPORT FUNCTIONALITY FOR DOC/PDF/ODT

If you want to be able to export your pads to DOC/PDF/ODT files, you can install
either Abiword or Libreoffice via setting a build variable.

VIA ABIWORD

For installing Abiword, set the INSTALL_ABIWORD build variable to any value.

Also, you will need to configure the path to the abiword executable via setting
the abiword property in <BASEDIR>/settings.json.docker to /usr/bin/abiword or
via setting the environment variable ABIWORD to /usr/bin/abiword.

VIA LIBREOFFICE

For installing Libreoffice instead, set the INSTALL_SOFFICE build variable to
any value.

Also, you will need to configure the path to the libreoffice executable via
setting the soffice property in <BASEDIR>/settings.json.docker to
/usr/bin/soffice or via setting the environment variable SOFFICE to
/usr/bin/soffice.


EXAMPLES

Build a Docker image from the currently checked-out code:

docker build --tag <YOUR_USERNAME>/etherpad .


Include two plugins in the container:

docker build --build-arg ETHERPAD_PLUGINS="ep_comments_page ep_author_neat" --tag <YOUR_USERNAME>/etherpad .



RUNNING YOUR INSTANCE:

To run your instance:

docker run --detach --publish <DESIRED_PORT>:9001 <YOUR_USERNAME>/etherpad


And point your browser to http://<YOUR_IP>:<DESIRED_PORT>


OPTIONS AVAILABLE BY DEFAULT

The settings.json.docker available by default allows to control almost every
setting via environment variables.


GENERAL

Variable Description Default TITLE The name of the instance Etherpad FAVICON
favicon default name, or a fully specified URL to your own favicon favicon.ico
DEFAULT_PAD_TEXT The default text of a pad Welcome to Etherpad! This pad text is
synchronized as you type, so that everyone viewing this page sees the same text.
This allows you to collaborate seamlessly on documents! Get involved with
Etherpad at https://etherpad.org IP IP which etherpad should bind at. Change to
:: for IPv6 0.0.0.0 PORT port which etherpad should bind at 9001 ADMIN_PASSWORD
the password for the admin user (leave unspecified if you do not want to create
it) USER_PASSWORD the password for the first user user (leave unspecified if you
do not want to create it)


DATABASE

Variable Description Default DB_TYPE a database supported by
https://www.npmjs.com/package/ueberdb2 not set, thus will fall back to DirtyDB
(please choose one instead) DB_HOST the host of the database DB_PORT the port of
the database DB_NAME the database name DB_USER a database user with sufficient
permissions to create tables DB_PASS the password for the database username
DB_CHARSET the character set for the tables (only required for MySQL)
DB_FILENAME in case DB_TYPE is DirtyDB or sqlite, the database file.
var/dirty.db, var/etherpad.sq3

If your database needs additional settings, you will have to use a personalized
settings.json.docker and rebuild the container (or otherwise put the updated
settings.json inside your image).


PAD OPTIONS

Variable Description Default PAD_OPTIONS_NO_COLORS false
PAD_OPTIONS_SHOW_CONTROLS true PAD_OPTIONS_SHOW_CHAT true
PAD_OPTIONS_SHOW_LINE_NUMBERS true PAD_OPTIONS_USE_MONOSPACE_FONT false
PAD_OPTIONS_USER_NAME false PAD_OPTIONS_USER_COLOR false PAD_OPTIONS_RTL false
PAD_OPTIONS_ALWAYS_SHOW_CHAT false PAD_OPTIONS_CHAT_AND_USERS false
PAD_OPTIONS_LANG en-gb


SHORTCUTS

Variable Description Default PAD_SHORTCUTS_ENABLED_ALT_F9 focus on the File Menu
and/or editbar true PAD_SHORTCUTS_ENABLED_ALT_C focus on the Chat window true
PAD_SHORTCUTS_ENABLED_CMD_S save a revision true PAD_SHORTCUTS_ENABLED_CMD_Z
undo/redo true PAD_SHORTCUTS_ENABLED_CMD_Y redo true PAD_SHORTCUTS_ENABLED_CMD_I
italic true PAD_SHORTCUTS_ENABLED_CMD_B bold true PAD_SHORTCUTS_ENABLED_CMD_U
underline true PAD_SHORTCUTS_ENABLED_CMD_H backspace true
PAD_SHORTCUTS_ENABLED_CMD_5 strike through true
PAD_SHORTCUTS_ENABLED_CMD_SHIFT_1 ordered list true
PAD_SHORTCUTS_ENABLED_CMD_SHIFT_2 shows a gritter popup showing a line author
true PAD_SHORTCUTS_ENABLED_CMD_SHIFT_L unordered list true
PAD_SHORTCUTS_ENABLED_CMD_SHIFT_N ordered list true
PAD_SHORTCUTS_ENABLED_CMD_SHIFT_C clear authorship true
PAD_SHORTCUTS_ENABLED_DELETE true PAD_SHORTCUTS_ENABLED_RETURN true
PAD_SHORTCUTS_ENABLED_ESC in mozilla versions 14-19 avoid reconnecting pad true
PAD_SHORTCUTS_ENABLED_TAB indent true PAD_SHORTCUTS_ENABLED_CTRL_HOME scroll to
top of pad true PAD_SHORTCUTS_ENABLED_PAGE_UP true
PAD_SHORTCUTS_ENABLED_PAGE_DOWN true


SKINS

You can use the UI skin variants builder at /p/test#skinvariantsbuilder

For the colibris skin only, you can choose how to render the three main
containers:

 * toolbar (top menu with icons)
 * editor (containing the text of the pad)
 * background (area outside of editor, mostly visible when using page style)

For each of the 3 containers you can choose 4 color combinations:

 * super-light
 * light
 * dark
 * super-dark

For the editor container, you can also make it full width by adding
full-width-editor variant (by default editor is rendered as a page, with a
max-width of 900px).

Variable Description Default SKIN_NAME either no-skin, colibris or an existing
directory under src/static/skins colibris SKIN_VARIANTS multiple skin variants
separated by spaces super-light-toolbar super-light-editor light-background


LOGGING

Variable Description Default LOGLEVEL valid values are DEBUG, INFO, WARN and
ERROR INFO DISABLE_IP_LOGGING Privacy: disable IP logging false


ADVANCED

Variable Description Default SHOW_SETTINGS_IN_ADMIN_PAGE hide/show the
settings.json in admin page true TRUST_PROXY set to true if you are using a
reverse proxy in front of Etherpad (for example: Traefik for SSL termination via
Let's Encrypt). This will affect security and correctness of the logs if not
done false IMPORT_MAX_FILE_SIZE maximum allowed file size when importing a pad,
in bytes. 52428800 (50 MB) IMPORT_EXPORT_MAX_REQ_PER_IP maximum number of
import/export calls per IP. 10 IMPORT_EXPORT_RATE_LIMIT_WINDOW the call rate for
import/export requests will be estimated in this time window (in milliseconds)
90000 COMMIT_RATE_LIMIT_DURATION duration of the rate limit window for commits
by individual users/IPs (in seconds) 1 COMMIT_RATE_LIMIT_POINTS maximum number
of changes per IP to allow during the rate limit window 10
SUPPRESS_ERRORS_IN_PAD_TEXT Should we suppress errors from being visible in the
default Pad Text? false REQUIRE_SESSION If this option is enabled, a user must
have a session to access pads. This effectively allows only group pads to be
accessed. false EDIT_ONLY Users may edit pads but not create new ones. Pad
creation is only via the API. This applies both to group pads and regular pads.
false MINIFY If true, all css & js will be minified before sending to the
client. This will improve the loading performance massively, but makes it
difficult to debug the javascript/css true MAX_AGE How long may clients use
served javascript code (in seconds)? Not setting this may cause problems during
deployment. Set to 0 to disable caching. 21600 (6 hours) ABIWORD Absolute path
to the Abiword executable. Abiword is needed to get advanced import/export
features of pads. Setting it to null disables Abiword and will only allow plain
text and HTML import/exports. null SOFFICE This is the absolute path to the
soffice executable. LibreOffice can be used in lieu of Abiword to export pads.
Setting it to null disables LibreOffice exporting. null TIDY_HTML Path to the
Tidy executable. Tidy is used to improve the quality of exported pads. Setting
it to null disables Tidy. null ALLOW_UNKNOWN_FILE_ENDS Allow import of file
types other than the supported ones: txt, doc, docx, rtf, odt, html & htm true
REQUIRE_AUTHENTICATION This setting is used if you require authentication of all
users. Note: "/admin" always requires authentication. false
REQUIRE_AUTHORIZATION Require authorization by a module, or a user with is_admin
set, see below. false AUTOMATIC_RECONNECTION_TIMEOUT Time (in seconds) to
automatically reconnect pad when a "Force reconnect" message is shown to user.
Set to 0 to disable automatic reconnection. 0 FOCUS_LINE_PERCENTAGE_ABOVE
Percentage of viewport height to be additionally scrolled. e.g. 0.5, to place
caret line in the middle of viewport, when user edits a line above of the
viewport. Set to 0 to disable extra scrolling 0 FOCUS_LINE_PERCENTAGE_BELOW
Percentage of viewport height to be additionally scrolled. e.g. 0.5, to place
caret line in the middle of viewport, when user edits a line below of the
viewport. Set to 0 to disable extra scrolling 0 FOCUS_LINE_PERCENTAGE_ARROW_UP
Percentage of viewport height to be additionally scrolled when user presses
arrow up in the line of the top of the viewport. Set to 0 to let the scroll to
be handled as default by Etherpad 0 FOCUS_LINE_DURATION Time (in milliseconds)
used to animate the scroll transition. Set to 0 to disable animation 0
FOCUS_LINE_CARET_SCROLL Flag to control if it should scroll when user places the
caret in the last line of the viewport false SOCKETIO_MAX_HTTP_BUFFER_SIZE The
maximum size (in bytes) of a single message accepted via Socket.IO. If a client
sends a larger message, its connection gets closed to prevent DoS (memory
exhaustion) attacks. 10000 LOAD_TEST Allow Load Testing tools to hit the
Etherpad Instance. WARNING: this will disable security on the instance. false
DUMP_ON_UNCLEAN_EXIT Enable dumping objects preventing a clean exit of Node.js.
WARNING: this has a significant performance impact. false EXPOSE_VERSION Expose
Etherpad version in the web interface and in the Server http header. Do not
enable on production machines. false


EXAMPLES

Use a Postgres database, no admin user enabled:

docker run -d \
    --name etherpad         \
    -p 9001:9001            \
    -e 'DB_TYPE=postgres'   \
    -e 'DB_HOST=db.local'   \
    -e 'DB_PORT=4321'       \
    -e 'DB_NAME=etherpad'   \
    -e 'DB_USER=dbusername' \
    -e 'DB_PASS=mypassword' \
    etherpad/etherpad


Run enabling the administrative user admin:

docker run -d \
    --name etherpad \
    -p 9001:9001 \
    -e 'ADMIN_PASSWORD=supersecret' \
    etherpad/etherpad


Run a test instance running DirtyDB on a persistent volume:

docker run -d \
    -v etherpad_data:/opt/etherpad-lite/var \
    -p 9001:9001 \
    etherpad/etherpad



SKINS

You can customize Etherpad appearance using skins. A skin is a directory located
under static/skins/<skin_name>, with the following contents:

 * index.js: javascript that will be run in /
 * index.css: stylesheet affecting /
 * pad.js: javascript that will be run in /p/:padid
 * pad.css: stylesheet affecting /p/:padid
 * timeslider.js: javascript that will be run in /p/:padid/timeslider
 * timeslider.css: stylesheet affecting /p/:padid/timeslider
 * favicon.ico: overrides the default favicon
 * robots.txt: overrides the default robots.txt

You can choose a skin changing the parameter skinName in settings.json.

Since Etherpad 1.7.5, two skins are included:

 * no-skin: an empty skin, leaving the default Etherpad appearance unchanged,
   that you can use as a guidance to develop your own.
 * colibris: a new, experimental skin, that will become the default in Etherpad
   2.0.


EMBED PARAMETERS

You can easily embed your etherpad-lite into any webpage by using iframes. You
can configure the embedded pad using embed parameters.

Example:

Cut and paste the following code into any webpage to embed a pad. The parameters
below will hide the chat and the line numbers and will auto-focus on Line 4.

<iframe src='http://pad.test.de/p/PAD_NAME#L4?showChat=false&showLineNumbers=false' width=600 height=400></iframe>



SHOWLINENUMBERS

 * Boolean

Default: true


SHOWCONTROLS

 * Boolean

Default: true


SHOWCHAT

 * Boolean

Default: true


USEMONOSPACEFONT

 * Boolean

Default: false


USERNAME

 * String

Default: "unnamed"

Example: userName=Etherpad%20User


USERCOLOR

 * String (css hex color value)

Default: randomly chosen by pad server

Example: userColor=%23ff9900


NOCOLORS

 * Boolean

Default: false


ALWAYSSHOWCHAT

 * Boolean

Default: false


LANG

 * String

Default: en

Example: lang=ar (translates the interface into Arabic)


RTL

 * Boolean

Default: true Displays pad text from right to left.


#L

 * Int

Default: 0 Focuses pad at specific line number and places caret at beginning of
this line Special note: Is not a URL parameter but instead of a Hash value


HTTP API


WHAT CAN I DO WITH THIS API?

The API gives another web application control of the pads. The basic functions
are

 * create/delete pads
 * grant/forbid access to pads
 * get/set pad content

The API is designed in a way, so you can reuse your existing user system with
their permissions, and map it to Etherpad. Means: Your web application still has
to do authentication, but you can tell Etherpad via the api, which visitors
should get which permissions. This allows Etherpad to fit into any web
application and extend it with real-time functionality. You can embed the pads
via an iframe into your website.

Take a look at HTTP API client libraries to check if a library in your favorite
programming language is available.


OPENAPI

OpenAPI (formerly swagger) definitions are exposed under /api/openapi.json
(latest) and /api/{version}/openapi.json. You can use official tools like
Swagger Editor to view and explore them.


EXAMPLES


EXAMPLE 1

A portal (such as WordPress) wants to give a user access to a new pad. Let's
assume the user have the internal id 7 and his name is michael.

Portal maps the internal userid to an etherpad author.

> Request:
> http://pad.domain/api/1/createAuthorIfNotExistsFor?apikey=secret&name=Michael&authorMapper=7
> 
> Response: {code: 0, message:"ok", data: {authorID: "a.s8oes9dhwrvt0zif"}}

Portal maps the internal userid to an etherpad group:

> Request:
> http://pad.domain/api/1/createGroupIfNotExistsFor?apikey=secret&groupMapper=7
> 
> Response: {code: 0, message:"ok", data: {groupID: "g.s8oes9dhwrvt0zif"}}

Portal creates a pad in the userGroup

> Request:
> http://pad.domain/api/1/createGroupPad?apikey=secret&groupID=g.s8oes9dhwrvt0zif&padName=samplePad&text=This
> is the first sentence in the pad
> 
> Response: {code: 0, message:"ok", data: null}

Portal starts the session for the user on the group:

> Request:
> http://pad.domain/api/1/createSession?apikey=secret&groupID=g.s8oes9dhwrvt0zif&authorID=a.s8oes9dhwrvt0zif&validUntil=1312201246
> 
> Response: {"data":{"sessionID": "s.s8oes9dhwrvt0zif"}}

Portal places the cookie "sessionID" with the given value on the client and
creates an iframe including the pad.


EXAMPLE 2

A portal (such as WordPress) wants to transform the contents of a pad that
multiple admins edited into a blog post.

Portal retrieves the contents of the pad for entry into the db as a blog post:

> Request:
> http://pad.domain/api/1/getText?apikey=secret&padID=g.s8oes9dhwrvt0zif$123
> 
> Response: {code: 0, message:"ok", data: {text:"Welcome Text"}}

Portal submits content into new blog post

> Portal.AddNewBlog(content)


USAGE


API VERSION

The latest version is 1.2.14

The current version can be queried via /api.


REQUEST FORMAT

The API is accessible via HTTP. Starting from 1.8, API endpoints can be invoked
indifferently via GET or POST.

The URL of the HTTP request is of the form: /api/$APIVERSION/$FUNCTIONNAME.
$APIVERSION depends on the endpoint you want to use. Depending on the verb you
use (GET or POST) parameters can be passed differently.

When invoking via GET (mandatory until 1.7.5 included), parameters must be
included in the query string (example:
/api/$APIVERSION/$FUNCTIONNAME?apikey=<APIKEY>&param1=value1). Please note that
starting with nodejs 8.14+ the total size of HTTP request headers has been
capped to 8192 bytes. This limits the quantity of data that can be sent in an
API request.

Starting from Etherpad 1.8 it is also possible to invoke the HTTP API via POST.
In this case, querystring parameters will still be accepted, but any parameter
with the same name sent via POST will take precedence. If you need to send large
chunks of text (for example, for setText()) it is advisable to invoke via POST.

Example with cURL using GET (toy example, no encoding):

curl "http://pad.domain/api/1/setText?apikey=secret&padID=padname&text=this_text_will_NOT_be_encoded_by_curl_use_next_example"


Example with cURL using GET (better example, encodes text):

curl "http://pad.domain/api/1/setText?apikey=secret&padID=padname" --get --data-urlencode "text=Text sent via GET with proper encoding. For big documents, please use POST"


Example with cURL using POST:

curl "http://pad.domain/api/1/setText?apikey=secret&padID=padname" --data-urlencode "text=Text sent via POST with proper encoding. For big texts (>8 KB), use this method"



RESPONSE FORMAT

Responses are valid JSON in the following format:

{
  "code": number,
  "message": string,
  "data": obj
}


 * code a return code
   * 0 everything ok
   * 1 wrong parameters
   * 2 internal error
   * 3 no such function
   * 4 no or wrong API Key
 * message a status message. It's ok if everything is fine, else it contains an
   error message
 * data the payload


OVERVIEW




DATA TYPES

 * groupID a string, the unique id of a group. Format is g.16RANDOMCHARS, for
   example g.s8oes9dhwrvt0zif
 * sessionID a string, the unique id of a session. Format is s.16RANDOMCHARS,
   for example s.s8oes9dhwrvt0zif
 * authorID a string, the unique id of an author. Format is a.16RANDOMCHARS, for
   example a.s8oes9dhwrvt0zif
 * readOnlyID a string, the unique id of a readonly relation to a pad. Format is
   r.16RANDOMCHARS, for example r.s8oes9dhwrvt0zif
 * padID a string, format is GROUPID$PADNAME, for example the pad test of group
   g.s8oes9dhwrvt0zif has padID g.s8oes9dhwrvt0zif$test


AUTHENTICATION

Authentication works via a token that is sent with each request as a post
parameter. There is a single token per Etherpad deployment. This token will be
random string, generated by Etherpad at the first start. It will be saved in
APIKEY.txt in the root folder of Etherpad. Only Etherpad and the requesting
application knows this key. Token management will not be exposed through this
API.


NODE INTEROPERABILITY

All functions will also be available through a node module accessible from other
node.js applications.


API METHODS


GROUPS

Pads can belong to a group. The padID of grouppads is starting with a groupID
like g.asdfasdfasdfasdf$test

CREATEGROUP()

 * API >= 1

creates a new group

Example returns:

 * {code: 0, message:"ok", data: {groupID: g.s8oes9dhwrvt0zif}}

CREATEGROUPIFNOTEXISTSFOR(GROUPMAPPER)

 * API >= 1

this functions helps you to map your application group ids to Etherpad group ids

Example returns:

 * {code: 0, message:"ok", data: {groupID: g.s8oes9dhwrvt0zif}}

DELETEGROUP(GROUPID)

 * API >= 1

deletes a group

Example returns:

 * {code: 0, message:"ok", data: null}
 * {code: 1, message:"groupID does not exist", data: null}

LISTPADS(GROUPID)

 * API >= 1

returns all pads of this group

Example returns:

 * {code: 0, message:"ok", data: {padIDs : ["g.s8oes9dhwrvt0zif$test",
   "g.s8oes9dhwrvt0zif$test2"]}
 * {code: 1, message:"groupID does not exist", data: null}

CREATEGROUPPAD(GROUPID, PADNAME [, TEXT])

 * API >= 1

creates a new pad in this group

Example returns:

 * {code: 0, message:"ok", data: null}
 * {code: 1, message:"pad does already exist", data: null}
 * {code: 1, message:"groupID does not exist", data: null}

LISTALLGROUPS()

 * API >= 1.1

lists all existing groups

Example returns:

 * {code: 0, message:"ok", data: {groupIDs: ["g.mKjkmnAbSMtCt8eL",
   "g.3ADWx6sbGuAiUmCy"]}}
 * {code: 0, message:"ok", data: {groupIDs: []}}


AUTHOR

These authors are bound to the attributes the users choose (color and name).

CREATEAUTHOR([NAME])

 * API >= 1

creates a new author

Example returns:

 * {code: 0, message:"ok", data: {authorID: "a.s8oes9dhwrvt0zif"}}

CREATEAUTHORIFNOTEXISTSFOR(AUTHORMAPPER [, NAME])

 * API >= 1

this functions helps you to map your application author ids to Etherpad author
ids

Example returns:

 * {code: 0, message:"ok", data: {authorID: "a.s8oes9dhwrvt0zif"}}

LISTPADSOFAUTHOR(AUTHORID)

 * API >= 1

returns an array of all pads this author contributed to

Example returns:

 * {code: 0, message:"ok", data: {padIDs: ["g.s8oes9dhwrvt0zif$test",
   "g.s8oejklhwrvt0zif$foo"]}}
 * {code: 1, message:"authorID does not exist", data: null}

GETAUTHORNAME(AUTHORID)

 * API >= 1.1

Returns the Author Name of the author

Example returns:

 * {code: 0, message:"ok", data: {authorName: "John McLear"}}

-> can't be deleted cause this would involve scanning all the pads where this
author was


SESSION

Sessions can be created between a group and an author. This allows an author to
access more than one group. The sessionID will be set as a cookie to the client
and is valid until a certain date. The session cookie can also contain multiple
comma-separated sessionIDs, allowing a user to edit pads in different groups at
the same time. Only users with a valid session for this group, can access group
pads. You can create a session after you authenticated the user at your web
application, to give them access to the pads. You should save the sessionID of
this session and delete it after the user logged out.

CREATESESSION(GROUPID, AUTHORID, VALIDUNTIL)

 * API >= 1

creates a new session. validUntil is an unix timestamp in seconds

Example returns:

 * {code: 0, message:"ok", data: {sessionID: "s.s8oes9dhwrvt0zif"}}
 * {code: 1, message:"groupID doesn't exist", data: null}
 * {code: 1, message:"authorID doesn't exist", data: null}
 * {code: 1, message:"validUntil is in the past", data: null}

DELETESESSION(SESSIONID)

 * API >= 1

deletes a session

Example returns:

 * {code: 0, message:"ok", data: null}
 * {code: 1, message:"sessionID does not exist", data: null}

GETSESSIONINFO(SESSIONID)

 * API >= 1

returns information about a session

Example returns:

 * {code: 0, message:"ok", data: {authorID: "a.s8oes9dhwrvt0zif", groupID:
   g.s8oes9dhwrvt0zif, validUntil: 1312201246}}
 * {code: 1, message:"sessionID does not exist", data: null}

LISTSESSIONSOFGROUP(GROUPID)

 * API >= 1

returns all sessions of a group

Example returns:

 * {"code":0,"message":"ok","data":{"s.oxf2ras6lvhv2132":{"groupID":"g.s8oes9dhwrvt0zif","authorID":"a.akf8finncvomlqva","validUntil":2312905480}}}
 * {code: 1, message:"groupID does not exist", data: null}

LISTSESSIONSOFAUTHOR(AUTHORID)

 * API >= 1

returns all sessions of an author

Example returns:

 * {"code":0,"message":"ok","data":{"s.oxf2ras6lvhv2132":{"groupID":"g.s8oes9dhwrvt0zif","authorID":"a.akf8finncvomlqva","validUntil":2312905480}}}
 * {code: 1, message:"authorID does not exist", data: null}


PAD CONTENT

Pad content can be updated and retrieved through the API

GETTEXT(PADID, [REV])

 * API >= 1

returns the text of a pad

Example returns:

 * {code: 0, message:"ok", data: {text:"Welcome Text"}}
 * {code: 1, message:"padID does not exist", data: null}

SETTEXT(PADID, TEXT)

 * API >= 1

Sets the text of a pad.

If your text is long (>8 KB), please invoke via POST and include text parameter
in the body of the request, not in the URL (since Etherpad 1.8).

Example returns:

 * {code: 0, message:"ok", data: null}
 * {code: 1, message:"padID does not exist", data: null}
 * {code: 1, message:"text too long", data: null}

APPENDTEXT(PADID, TEXT)

 * API >= 1.2.13

Appends text to a pad.

If your text is long (>8 KB), please invoke via POST and include text parameter
in the body of the request, not in the URL (since Etherpad 1.8).

Example returns:

 * {code: 0, message:"ok", data: null}
 * {code: 1, message:"padID does not exist", data: null}
 * {code: 1, message:"text too long", data: null}

GETHTML(PADID, [REV])

 * API >= 1

returns the text of a pad formatted as HTML

Example returns:

 * {code: 0, message:"ok", data: {html:"Welcome Text<br>More Text"}}
 * {code: 1, message:"padID does not exist", data: null}

SETHTML(PADID, HTML)

 * API >= 1

sets the text of a pad based on HTML, HTML must be well-formed. Malformed HTML
will send a warning to the API log.

If html is long (>8 KB), please invoke via POST and include html parameter in
the body of the request, not in the URL (since Etherpad 1.8).

Example returns:

 * {code: 0, message:"ok", data: null}
 * {code: 1, message:"padID does not exist", data: null}

GETATTRIBUTEPOOL(PADID)

 * API >= 1.2.8

returns the attribute pool of a pad

Example returns:

 * `{ "code":0, "message":"ok", "data": {
   
    "pool":{
      "numToAttrib":{
        "0":["author","a.X4m8bBWJBZJnWGSh"],
        "1":["author","a.TotfBPzov54ihMdH"],
        "2":["author","a.StiblqrzgeNTbK05"],
        "3":["bold","true"]
      },
      "attribToNum":{
        "author,a.X4m8bBWJBZJnWGSh":0,
        "author,a.TotfBPzov54ihMdH":1,
        "author,a.StiblqrzgeNTbK05":2,
        "bold,true":3
      },
      "nextNum":4
    }
   
   
   } }`
 * {"code":1,"message":"padID does not exist","data":null}

GETREVISIONCHANGESET(PADID, [REV])

 * API >= 1.2.8

get the changeset at a given revision, or last revision if 'rev' is not defined.

Example returns:

 * { "code" : 0, "message" : "ok", "data" : "Z:1>6b|5+6b$Welcome to
   Etherpad!\n\nThis pad text is synchronized as you type, so that everyone
   viewing this page sees the same text. This allows you to collaborate
   seamlessly on documents!\n\nGet involved with Etherpad at
   https://etherpad.org\n" }
 * {"code":1,"message":"padID does not exist","data":null}
 * {"code":1,"message":"rev is higher than the head revision of the
   pad","data":null}

CREATEDIFFHTML(PADID, STARTREV, ENDREV)

 * API >= 1.2.7

returns an object of diffs from 2 points in a pad

Example returns:

 * {"code":0,"message":"ok","data":{"html":"<style>\n.authora_HKIv23mEbachFYfH
   {background-color: #a979d9}\n.authora_n4gEeMLsv1GivNeh {background-color:
   #a9b5d9}\n.removed {text-decoration: line-through;
   -ms-filter:'progid:DXImageTransform.Microsoft.Alpha(Opacity=80)'; filter:
   alpha(opacity=80); opacity: 0.8; }\n</style>Welcome to Etherpad!<br><br>This
   pad text is synchronized as you type, so that everyone viewing this page sees
   the same text. This allows you to collaborate seamlessly on
   documents!<br><br>Get involved with Etherpad at <a
   href=\"http&#x3a;&#x2F;&#x2F;etherpad&#x2e;org\">http:&#x2F;&#x2F;etherpad.org</a><br><span
   class=\"authora_HKIv23mEbachFYfH\">aw</span><br><br>","authors":["a.HKIv23mEbachFYfH",""]}}
 * {"code":4,"message":"no or wrong API Key","data":null}

RESTOREREVISION(PADID, REV)

 * API >= 1.2.11

Restores revision from past as new changeset

Example returns:

 * {code:0, message:"ok", data:null}
 * {code: 1, message:"padID does not exist", data: null}


CHAT

GETCHATHISTORY(PADID, [START, END])

 * API >= 1.2.7

returns

 * a part of the chat history, when start and end are given
 * the whole chat history, when no extra parameters are given

Example returns:

 * {"code":0,"message":"ok","data":{"messages":[{"text":"foo","userId":"a.foo","time":1359199533759,"userName":"test"},{"text":"bar","userId":"a.foo","time":1359199534622,"userName":"test"}]}}
 * {code: 1, message:"start is higher or equal to the current chatHead", data:
   null}
 * {code: 1, message:"padID does not exist", data: null}

GETCHATHEAD(PADID)

 * API >= 1.2.7

returns the chatHead (last number of the last chat-message) of the pad

Example returns:

 * {code: 0, message:"ok", data: {chatHead: 42}}
 * {code: 1, message:"padID does not exist", data: null}

APPENDCHATMESSAGE(PADID, TEXT, AUTHORID [, TIME])

 * API >= 1.2.12

creates a chat message, saves it to the database and sends it to all connected
clients of this pad

Example returns:

 * {code: 0, message:"ok", data: null}
 * {code: 1, message:"text is no string", data: null}


PAD

Group pads are normal pads, but with the name schema GROUPID$PADNAME. A security
manager controls access of them and it's forbidden for normal pads to include a
$ in the name.

CREATEPAD(PADID [, TEXT])

 * API >= 1

creates a new (non-group) pad. Note that if you need to create a group Pad, you
should call createGroupPad. You get an error message if you use one of the
following characters in the padID: "/", "?", "&" or "#".

Example returns:

 * {code: 0, message:"ok", data: null}
 * {code: 1, message:"padID does already exist", data: null}
 * {code: 1, message:"malformed padID: Remove special characters", data: null}

GETREVISIONSCOUNT(PADID)

 * API >= 1

returns the number of revisions of this pad

Example returns:

 * {code: 0, message:"ok", data: {revisions: 56}}
 * {code: 1, message:"padID does not exist", data: null}

GETSAVEDREVISIONSCOUNT(PADID)

 * API >= 1.2.11

returns the number of saved revisions of this pad

Example returns:

 * {code: 0, message:"ok", data: {savedRevisions: 42}}
 * {code: 1, message:"padID does not exist", data: null}

LISTSAVEDREVISIONS(PADID)

 * API >= 1.2.11

returns the list of saved revisions of this pad

Example returns:

 * {code: 0, message:"ok", data: {savedRevisions: [2, 42, 1337]}}
 * {code: 1, message:"padID does not exist", data: null}

SAVEREVISION(PADID [, REV])

 * API >= 1.2.11

saves a revision

Example returns:

 * {code: 0, message:"ok", data: null}
 * {code: 1, message:"padID does not exist", data: null}

PADUSERSCOUNT(PADID)

 * API >= 1

returns the number of user that are currently editing this pad

Example returns:

 * {code: 0, message:"ok", data: {padUsersCount: 5}}

PADUSERS(PADID)

 * API >= 1.1

returns the list of users that are currently editing this pad

Example returns:

 * {code: 0, message:"ok", data: {padUsers:
   [{colorId:"#c1a9d9","name":"username1","timestamp":1345228793126,"id":"a.n4gEeMLsvg12452n"},{"colorId":"#d9a9cd","name":"Hmmm","timestamp":1345228796042,"id":"a.n4gEeMLsvg12452n"}]}}
 * {code: 0, message:"ok", data: {padUsers: []}}

DELETEPAD(PADID)

 * API >= 1

deletes a pad

Example returns:

 * {code: 0, message:"ok", data: null}
 * {code: 1, message:"padID does not exist", data: null}

COPYPAD(SOURCEID, DESTINATIONID[, FORCE=FALSE])

 * API >= 1.2.8

copies a pad with full history and chat. If force is true and the destination
pad exists, it will be overwritten.

Example returns:

 * {code: 0, message:"ok", data: null}
 * {code: 1, message:"padID does not exist", data: null}

COPYPADWITHOUTHISTORY(SOURCEID, DESTINATIONID[, FORCE=FALSE])

 * API >= 1.2.15

copies a pad without copying the history and chat. If force is true and the
destination pad exists, it will be overwritten. Note that all the revisions will
be lost! In most of the cases one should use copyPad API instead.

Example returns:

 * {code: 0, message:"ok", data: null}
 * {code: 1, message:"padID does not exist", data: null}

MOVEPAD(SOURCEID, DESTINATIONID[, FORCE=FALSE])

 * API >= 1.2.8

moves a pad. If force is true and the destination pad exists, it will be
overwritten.

Example returns:

 * {code: 0, message:"ok", data: null}
 * {code: 1, message:"padID does not exist", data: null}

GETREADONLYID(PADID)

 * API >= 1

returns the read only link of a pad

Example returns:

 * {code: 0, message:"ok", data: {readOnlyID: "r.s8oes9dhwrvt0zif"}}
 * {code: 1, message:"padID does not exist", data: null}

GETPADID(READONLYID)

 * API >= 1.2.10

returns the id of a pad which is assigned to the readOnlyID

Example returns:

 * {code: 0, message:"ok", data: {padID: "p.s8oes9dhwrvt0zif"}}
 * {code: 1, message:"padID does not exist", data: null}

SETPUBLICSTATUS(PADID, PUBLICSTATUS)

 * API >= 1

sets a boolean for the public status of a pad

Example returns:

 * {code: 0, message:"ok", data: null}
 * {code: 1, message:"padID does not exist", data: null}

GETPUBLICSTATUS(PADID)

 * API >= 1

return true of false

Example returns:

 * {code: 0, message:"ok", data: {publicStatus: true}}
 * {code: 1, message:"padID does not exist", data: null}

LISTAUTHORSOFPAD(PADID)

 * API >= 1

returns an array of authors who contributed to this pad

Example returns:

 * {code: 0, message:"ok", data: {authorIDs : ["a.s8oes9dhwrvt0zif",
   "a.akf8finncvomlqva"]}
 * {code: 1, message:"padID does not exist", data: null}

GETLASTEDITED(PADID)

 * API >= 1

returns the timestamp of the last revision of the pad

Example returns:

 * {code: 0, message:"ok", data: {lastEdited: 1340815946602}}
 * {code: 1, message:"padID does not exist", data: null}

SENDCLIENTSMESSAGE(PADID, MSG)

 * API >= 1.1

sends a custom message of type msg to the pad

Example returns:

 * {code: 0, message:"ok", data: {}}
 * {code: 1, message:"padID does not exist", data: null}

CHECKTOKEN()

 * API >= 1.2

returns ok when the current api token is valid

Example returns:

 * {"code":0,"message":"ok","data":null}
 * {"code":4,"message":"no or wrong API Key","data":null}


PADS

LISTALLPADS()

 * API >= 1.2.1

lists all pads on this epl instance

Example returns:

 * {code: 0, message:"ok", data: {padIDs: ["testPad", "thePadsOfTheOthers"]}}


GLOBAL

GETSTATS()

 * API >= 1.2.14

get stats of the etherpad instance

Example returns

 * {"code":0,"message":"ok","data":{"totalPads":3,"totalSessions":
   2,"totalActivePads": 1}}


HOOKS

A hook function is registered with a hook via the plugin's ep.json file. See the
Plugins section for details. A hook may have many registered functions from
different plugins.

Some hooks call their registered functions one at a time until one of them
returns a value. Others always call all of their registered functions and
combine the results (if applicable).


REGISTERED HOOK FUNCTIONS

Note: The documentation in this section applies to every hook unless the
hook-specific documentation says otherwise.


ARGUMENTS

Hook functions are called with three arguments:

 1. hookName - The name of the hook being invoked.
 2. context - An object with some relevant information about the context of the
    call. See the hook-specific documentation for details.
 3. cb - For asynchronous operations this callback can be called to signal
    completion and optionally provide a return value. The callback takes a
    single argument, the meaning of which depends on the hook (see the "Return
    values" section for general information that applies to most hooks). This
    callback always returns undefined.


EXPECTED BEHAVIOR

The presence of a callback parameter suggests that every hook function can run
asynchronously. While that is the eventual goal, there are some legacy hooks
that expect their hook functions to provide a value synchronously. For such
hooks, the hook functions must do one of the following:

 * Call the callback with a non-Promise value (undefined is acceptable) and
   return undefined, in that order.
 * Return a non-Promise value other than undefined (null is acceptable) and
   never call the callback. Note that async functions always return a Promise,
   so they must never be used for synchronous hooks.
 * Only have two parameters (hookName and context) and return any non-Promise
   value (undefined is acceptable).

For hooks that permit asynchronous behavior, the hook functions must do one or
more of the following:

 * Return undefined and call the callback, in either order.
 * Return something other than undefined (null is acceptable) and never call the
   callback. Note that async functions always return a Promise, so they must
   never call the callback.
 * Only have two parameters (hookName and context).

Note that the acceptable behaviors for asynchronous hook functions is a superset
of the acceptable behaviors for synchronous hook functions.

WARNING: The number of parameters is determined by examining Function.length,
which does not count default parameters or "rest" parameters. To avoid problems,
do not use default or rest parameters when defining hook functions.


RETURN VALUES

A hook function can provide a value to Etherpad in one of the following ways:

 * Pass the desired value as the first argument to the callback.
 * Return the desired value directly. The value must not be undefined unless the
   hook function only has two parameters. (Hook functions with three parameters
   that want to provide undefined should instead use the callback.)
 * For hooks that permit asynchronous behavior, return a Promise that resolves
   to the desired value.
 * For hooks that permit asynchronous behavior, pass a Promise that resolves to
   the desired value as the first argument to the callback.

Examples:

exports.exampleOne = (hookName, context, callback) => {
  return 'valueOne';
};

exports.exampleTwo = (hookName, context, callback) => {
  callback('valueTwo');
  return;
};

// ONLY FOR HOOKS THAT PERMIT ASYNCHRONOUS BEHAVIOR
exports.exampleThree = (hookName, context, callback) => {
  return new Promise('valueThree');
};

// ONLY FOR HOOKS THAT PERMIT ASYNCHRONOUS BEHAVIOR
exports.exampleFour = (hookName, context, callback) => {
  callback(new Promise('valueFour'));
  return;
};

// ONLY FOR HOOKS THAT PERMIT ASYNCHRONOUS BEHAVIOR
exports.exampleFive = async (hookName, context) => {
  // Note that this function is async, so it actually returns a Promise that
  // is resolved to 'valueFive'.
  return 'valueFive';
};


Etherpad collects the values provided by the hook functions into an array,
filters out all undefined values, then flattens the array one level. Flattening
one level makes it possible for a hook function to behave as if it were multiple
separate hook functions.

For example: Suppose a hook has eight registered functions that return the
following values: 1, [2], ['3a', '3b'] [[4]], undefined, [undefined], [], and
null. The value returned to the caller of the hook is [1, 2, '3a', '3b', [4],
undefined, null].


CLIENT-SIDE HOOKS

Most of these hooks are called during or in order to set up the formatting
process.


DOCUMENTREADY

Called from: src/templates/pad.html

Things in context:

nothing

This hook proxies the functionality of jQuery's $(document).ready event.


ACEDOMLINEPREPROCESSLINEATTRIBUTES

Called from: src/static/js/domline.js

Things in context:

 1. domline - The current DOM line being processed
 2. cls - The class of the current block element (useful for styling)

This hook is called for elements in the DOM that have the "lineMarkerAttribute"
set. You can add elements into this category with the aceRegisterBlockElements
hook above. This hook is run BEFORE the numbered and ordered lists logic is
applied.

The return value of this hook should have the following structure:

{ preHtml: String, postHtml: String, processedMarker: Boolean }

The preHtml and postHtml values will be added to the HTML display of the
element, and if processedMarker is true, the engine won't try to process it any
more.


ACEDOMLINEPROCESSLINEATTRIBUTES

Called from: src/static/js/domline.js

Things in context:

 1. domline - The current DOM line being processed
 2. cls - The class of the current block element (useful for styling)

This hook is called for elements in the DOM that have the "lineMarkerAttribute"
set. You can add elements into this category with the aceRegisterBlockElements
hook above. This hook is run AFTER the ordered and numbered lists logic is
applied.

The return value of this hook should have the following structure:

{ preHtml: String, postHtml: String, processedMarker: Boolean }

The preHtml and postHtml values will be added to the HTML display of the
element, and if processedMarker is true, the engine won't try to process it any
more.


ACECREATEDOMLINE

Called from: src/static/js/domline.js

Things in context:

 1. domline - the current DOM line being processed
 2. cls - The class of the current element (useful for styling)

This hook is called for any line being processed by the formatting engine,
unless the aceDomLineProcessLineAttributes hook from above returned true, in
which case this hook is skipped.

The return value of this hook should have the following structure:

{ extraOpenTags: String, extraCloseTags: String, cls: String }

extraOpenTags and extraCloseTags will be added before and after the element in
question, and cls will be the new class of the element going forward.


ACEPOSTWRITEDOMLINEHTML

Called from: src/static/js/domline.js

Things in context:

 1. node - the DOM node that just got written to the page

This hook is for right after a node has been fully formatted and written to the
page.


ACEATTRIBSTOCLASSES

Called from: src/static/js/linestylefilter.js

Things in context:

 1. linestylefilter - the JavaScript object that's currently processing the ace
    attributes
 2. key - the current attribute being processed
 3. value - the value of the attribute being processed

This hook is called during the attribute processing procedure, and should be
used to translate key, value pairs into valid HTML classes that can be inserted
into the DOM.

The return value for this function should be a list of classes, which will then
be parsed into a valid class string.


ACEATTRIBCLASSES

Called from: src/static/js/linestylefilter.js

Things in context:

 1. Attributes - Object of Attributes

This hook is called when attributes are investigated on a line. It is useful if
you want to add another attribute type or property type to a pad.

Example:

exports.aceAttribClasses = function(hook_name, attr, cb){
  attr.sub = 'tag:sub';
  cb(attr);
}



ACEGETFILTERSTACK

Called from: src/static/js/linestylefilter.js

Things in context:

 1. linestylefilter - the JavaScript object that's currently processing the ace
    attributes
 2. browser - an object indicating which browser is accessing the page

This hook is called to apply custom regular expression filters to a set of
styles. The one example available is the ep_linkify plugin, which adds internal
links. They use it to find the telltale [[ ]] syntax that signifies internal
links, and finding that syntax, they add in the internalHref attribute to be
later used by the aceCreateDomLine hook (documented above).


ACEEDITORCSS

Called from: src/static/js/ace.js

Things in context: None

This hook is provided to allow custom CSS files to be loaded. The return value
should be an array of resource urls or paths relative to the plugins directory.


ACEINITINNERDOCBODYHEAD

Called from: src/static/js/ace.js

Things in context:

 1. iframeHTML - the HTML of the editor iframe up to this point, in array format

This hook is called during the creation of the editor HTML. The array should
have lines of HTML added to it, giving the plugin author a chance to add in
meta, script, link, and other tags that go into the <head> element of the editor
HTML document.


ACEEDITEVENT

Called from: src/static/js/ace2_inner.js

Things in context:

 1. callstack - a bunch of information about the current action
 2. editorInfo - information about the user who is making the change
 3. rep - information about where the change is being made
 4. documentAttributeManager - information about attributes in the document
    (this is a mystery to me)

This hook is made available to edit the edit events that might occur when
changes are made. Currently you can change the editor information, some of the
meanings of the edit, and so on. You can also make internal changes (internal to
your plugin) that use the information provided by the edit event.


ACEREGISTERNONSCROLLABLEEDITEVENTS

Called from: src/static/js/ace2_inner.js

Things in context: None

When aceEditEvent (documented above) finishes processing the event, it scrolls
the viewport to make caret visible to the user, but if you don't want that
behavior to happen you can use this hook to register which edit events should
not scroll viewport. The return value of this hook should be a list of event
names.

Example:

exports.aceRegisterNonScrollableEditEvents = function(){
  return [ 'repaginate', 'updatePageCount' ];
}



ACEREGISTERBLOCKELEMENTS

Called from: src/static/js/ace2_inner.js

Things in context: None

The return value of this hook will add elements into the "lineMarkerAttribute"
category, making the aceDomLineProcessLineAttributes hook (documented below)
call for those elements.


ACEINITIALIZED

Called from: src/static/js/ace2_inner.js

Things in context:

 1. editorInfo - information about the user who will be making changes through
    the interface, and a way to insert functions into the main ace object (see
    ep_headings)
 2. rep - information about where the user's cursor is
 3. documentAttributeManager - some kind of magic

This hook is for inserting further information into the ace engine, for later
use in formatting hooks.


POSTACEINIT

Called from: src/static/js/pad.js

Things in context:

 1. ace - the ace object that is applied to this editor.
 2. clientVars - Object containing client-side configuration such as author ID
    and plugin settings. Your plugin can manipulate this object via the
    clientVars server-side hook.
 3. pad - the pad object of the current pad.


POSTTOOLBARINIT

Called from: src/static/js/pad_editbar.js

Things in context:

 1. ace - the ace object that is applied to this editor.
 2. toolbar - Editbar instance. See below for the Editbar documentation.

Can be used to register custom actions to the toolbar.

Usage examples:

 * https://github.com/tiblu/ep_authorship_toggle


POSTTIMESLIDERINIT

Called from: src/static/js/timeslider.js

There doesn't appear to be any example available of this particular hook being
used, but it gets fired after the timeslider is all set up.


GOTOREVISIONEVENT

Called from: src/static/js/broadcast.js

Things in context:

 1. rev - The newRevision

This hook gets fired both on timeslider load (as timeslider shows a new
revision) and when the new revision is showed to a user. There doesn't appear to
be any example available of this particular hook being used.


USERJOINORUPDATE

Called from: src/static/js/pad_userlist.js

Things in context:

 1. info - the user information

This hook is called on the client side whenever a user joins or changes. This
can be used to create notifications or an alternate user list.


CHATNEWMESSAGE

Called from: src/static/js/chat.js

This hook runs on the client side whenever a chat message is received from the
server. It can be used to create different notifications for chat messages. Hook
functions can modify the author, authorName, duration, rendered, sticky, text,
and timeStr context properties to change how the message is processed. The text
and timeStr properties may contain HTML and come pre-sanitized; plugins should
be careful to sanitize any added user input to avoid introducing an XSS
vulnerability.

Context properties:

 * authorName: The display name of the user that wrote the message.
 * author: The author ID of the user that wrote the message.
 * text: Sanitized message HTML, with URLs wrapped like <a href="url">url</a>.
   (Note that message.text is not sanitized or processed in any way.)
 * message: The raw message object as received from the server, except with time
   correction and a default authorId property if missing. Plugins must not
   modify this object. Warning: Unlike text, message.text is not pre-sanitized
   or processed in any way.
 * rendered - Used to override the default message rendering. Initially set to
   null. If the hook function sets this to a DOM element object or a jQuery
   object, then that object will be used as the rendered message UI. Otherwise,
   if this is set to null, then Etherpad will render a default UI for the
   message using the other context properties.
 * sticky (boolean): Whether the gritter notification should fade out on its own
   or just sit there until manually closed.
 * timestamp: When the chat message was sent (milliseconds since epoch),
   corrected using the difference between the local clock and the server's
   clock.
 * timeStr: The message timestamp as a formatted string.
 * duration: How long (in milliseconds) to display the gritter notification (0
   to disable).


CHATSENDMESSAGE

Called from: src/static/js/chat.js

This hook runs on the client side whenever the user sends a new chat message.
Plugins can mutate the message object to change the message text or add metadata
to control how the message will be rendered by the chatNewMessage hook.

Context properties:

 * message: The message object that will be sent to the Etherpad server.


COLLECTCONTENTPRE

Called from: src/static/js/contentcollector.js

Things in context:

 1. cc - the contentcollector object
 2. state - the current state of the change being made
 3. tname - the tag name of this node currently being processed
 4. styl - the style applied to the node (probably CSS) -- Note the typo
 5. cls - the HTML class string of the node

This hook is called before the content of a node is collected by the usual
methods. The cc object can be used to do a bunch of things that modify the
content of the pad. See, for example, the heading1 plugin for etherpad original.

E.g. if you need to apply an attribute to newly inserted characters, call
cc.doAttrib(state, "attributeName") which results in an attribute
attributeName=true.

If you want to specify also a value, call cc.doAttrib(state,
"attributeName::value") which results in an attribute attributeName=value.


COLLECTCONTENTIMAGE

Called from: src/static/js/contentcollector.js

Things in context:

 1. cc - the contentcollector object
 2. state - the current state of the change being made
 3. tname - the tag name of this node currently being processed
 4. style - the style applied to the node (probably CSS)
 5. cls - the HTML class string of the node
 6. node - the node being modified

This hook is called before the content of an image node is collected by the
usual methods. The cc object can be used to do a bunch of things that modify the
content of the pad.

Example:

exports.collectContentImage = function(name, context){
  context.state.lineAttributes.img = context.node.outerHTML;
}



COLLECTCONTENTPOST

Called from: src/static/js/contentcollector.js

Things in context:

 1. cc - the contentcollector object
 2. state - the current state of the change being made
 3. tname - the tag name of this node currently being processed
 4. style - the style applied to the node (probably CSS)
 5. cls - the HTML class string of the node

This hook is called after the content of a node is collected by the usual
methods. The cc object can be used to do a bunch of things that modify the
content of the pad. See, for example, the heading1 plugin for etherpad original.


HANDLECLIENTMESSAGE_NAME

Called from: src/static/js/collab_client.js

Things in context:

 1. payload - the data that got sent with the message (use it for custom message
    content)

This hook gets called every time the client receives a message of type name.
This can most notably be used with the new HTTP API call, "sendClientsMessage",
which sends a custom message type to all clients connected to a pad. You can
also use this to handle existing types.

collab_client.js has a pretty extensive list of message types, if you want to
take a look.


ACESTARTLINEANDCHARFORPOINT-ACEENDLINEANDCHARFORPOINT

Called from: src/static/js/ace2_inner.js

Things in context:

 1. callstack - a bunch of information about the current action
 2. editorInfo - information about the user who is making the change
 3. rep - information about where the change is being made
 4. root - the span element of the current line
 5. point - the starting/ending element where the cursor highlights
 6. documentAttributeManager - information about attributes in the document

This hook is provided to allow a plugin to turn DOM node selection into
[line,char] selection. The return value should be an array of [line,char]


ACEKEYEVENT

Called from: src/static/js/ace2_inner.js

Things in context:

 1. callstack - a bunch of information about the current action
 2. editorInfo - information about the user who is making the change
 3. rep - information about where the change is being made
 4. documentAttributeManager - information about attributes in the document
 5. evt - the fired event

This hook is provided to allow a plugin to handle key events. The return value
should be true if you have handled the event.


COLLECTCONTENTLINETEXT

Called from: src/static/js/contentcollector.js

Things in context:

 1. cc - the contentcollector object
 2. state - the current state of the change being made
 3. tname - the tag name of this node currently being processed
 4. text - the text for that line

This hook allows you to validate/manipulate the text before it's sent to the
server side. To change the text, either:

 * Set the text context property to the desired value and return undefined.
 * (Deprecated) Return a string. If a hook function changes the text context
   property, the return value is ignored. If no hook function changes text but
   multiple hook functions return a string, the first one wins.

Example:

exports.collectContentLineText = (hookName, context) => {
  context.text = tweakText(context.text);
};



COLLECTCONTENTLINEBREAK

Called from: src/static/js/contentcollector.js

Things in context:

 1. cc - the contentcollector object
 2. state - the current state of the change being made
 3. tname - the tag name of this node currently being processed

This hook is provided to allow whether the br tag should induce a new magic
domline or not. The return value should be either true(break the line) or false.


DISABLEAUTHORCOLORSFORTHISLINE

Called from: src/static/js/linestylefilter.js

Things in context:

 1. linestylefilter - the JavaScript object that's currently processing the ace
    attributes
 2. text - the line text
 3. class - line class

This hook is provided to allow whether a given line should be deliniated with
multiple authors. Multiple authors in one line cause the creation of magic span
lines. This might not suit you and now you can disable it and handle your own
deliniation. The return value should be either true(disable) or false.


ACESETAUTHORSTYLE

Called from: src/static/js/ace2_inner.js

Things in context:

 1. dynamicCSS - css manager for inner ace
 2. outerDynamicCSS - css manager for outer ace
 3. parentDynamicCSS - css manager for parent document
 4. info - author style info
 5. author - author info
 6. authorSelector - css selector for author span in inner ace

This hook is provided to allow author highlight style to be modified. Registered
hooks should return 1 if the plugin handles highlighting. If no plugin returns
1, the core will use the default background-based highlighting.


ACESELECTIONCHANGED

Called from: src/static/js/ace2_inner.js

Things in context:

 1. rep - information about where the user's cursor is
 2. documentAttributeManager - information about attributes in the document

This hook allows a plugin to react to a cursor or selection change, perhaps to
update a UI element based on the style at the cursor location.


SERVER-SIDE HOOKS

These hooks are called on server-side.


LOADSETTINGS

Called from: src/node/server.js

Things in context:

 1. settings - the settings object

Use this hook to receive the global settings in your plugin.


SHUTDOWN

Called from: src/node/server.js

Things in context: None

This hook runs before shutdown. Use it to stop timers, close sockets and files,
flush buffers, etc. The database is not available while this hook is running.
The shutdown function must not block for long because there is a short timeout
before the process is forcibly terminated.

The shutdown function must return a Promise, which must resolve to undefined.
Returning callback(value) will return a Promise that is resolved to value.

Example:

// using an async function
exports.shutdown = async (hookName, context) => {
  await flushBuffers();
};



PLUGINUNINSTALL

Called from: src/static/js/pluginfw/installer.js

Things in context:

 1. plugin_name - self-explanatory

If this hook returns an error, the callback to the uninstall function gets an
error as well. This mostly seems useful for handling additional features added
in based on the installation of other plugins, which is pretty cool!


PLUGININSTALL

Called from: src/static/js/pluginfw/installer.js

Things in context:

 1. plugin_name - self-explanatory

If this hook returns an error, the callback to the install function gets an
error, too. This seems useful for adding in features when a particular plugin is
installed.


INIT_<PLUGIN NAME>

Called from: src/static/js/pluginfw/plugins.js

Run during startup after the named plugin is initialized.

Context properties: None


EXPRESSCONFIGURE

Called from: src/node/hooks/express.js

Things in context:

 1. app - the main application object

This is a helpful hook for changing the behavior and configuration of the
application. It's called right after the application gets configured.


EXPRESSCREATESERVER

Called from: src/node/hooks/express.js

Things in context:

 1. app - the main express application object (helpful for adding new paths and
    such)
 2. server - the http server object

This hook gets called after the application object has been created, but before
it starts listening. This is similar to the expressConfigure hook, but it's not
guaranteed that the application object will have all relevant configuration
variables.


EXPRESSCLOSESERVER

Called from: src/node/hooks/express.js

Things in context: Nothing

This hook is called when the HTTP server is closing, which happens during
shutdown (see the shutdown hook) and when the server restarts (e.g., when a
plugin is installed via the /admin/plugins page). The HTTP server may or may not
already be closed when this hook executes.

Example:

exports.expressCloseServer = async () => {
  await doSomeCleanup();
};



EEJSBLOCK_<NAME>

Called from: src/node/eejs/index.js

Things in context:

 1. content - the content of the block

This hook gets called upon the rendering of an ejs template block. For any
specific kind of block, you can change how that block gets rendered by modifying
the content object passed in.

Available blocks in pad.html are:

 * htmlHead - after <html> and immediately before the title tag
 * styles - the style <link>s
 * body - the contents of the body tag
 * editbarMenuLeft - the left tool bar (consider using the toolbar controller
   instead of manually adding html here)
 * editbarMenuRight - right tool bar
 * afterEditbar - allows you to add stuff immediately after the toolbar
 * userlist - the contents of the userlist dropdown
 * loading - the initial loading message
 * mySettings - the left column of the settings dropdown ("My view"); intended
   for adding checkboxes only
 * mySettings.dropdowns - add your dropdown settings here
 * globalSettings - the right column of the settings dropdown ("Global view")
 * importColumn - import form
 * exportColumn - export form
 * modals - Contains all connectivity messages
 * embedPopup - the embed dropdown
 * scripts - Add your script tags here, if you really have to (consider use
   client-side hooks instead)

timeslider.html blocks:

 * timesliderStyles
 * timesliderScripts
 * timesliderBody
 * timesliderTop
 * timesliderEditbarRight
 * modals

index.html blocks:

 * indexCustomStyles - contains the index.css <link> tag, allows you to add your
   own or to customize the one provided by the active skin
 * indexWrapper - contains the form for creating new pads
 * indexCustomScripts - contains the index.js <script> tag, allows you to add
   your own or to customize the one provided by the active skin


PADINITTOOLBAR

Called from: src/node/hooks/express/specialpages.js

Things in context:

 1. toolbar - the toolbar controller that will render the toolbar eventually

Here you can add custom toolbar items that will be available in the toolbar
config in settings.json. For more about the toolbar controller see the API
section.

Usage examples:

 * https://github.com/tiblu/ep_authorship_toggle


ONACCESSCHECK

Called from: src/node/db/SecurityManager.js

Things in context:

 1. padID - the real ID (never the read-only ID) of the pad the user wants to
    access
 2. token - the token of the author
 3. sessionCookie - the session the use has

This hook gets called when the access to the concrete pad is being checked.
Return false to deny access.


PADCREATE

Called from: src/node/db/Pad.js

Things in context:

 1. pad - the pad instance
 2. author - the id of the author who created the pad

This hook gets called when a new pad was created.


PADLOAD

Called from: src/node/db/PadManager.js

Called when a pad is loaded, including after new pad creation.

Context properties:

 * pad: The Pad object.


PADUPDATE

Called from: src/node/db/Pad.js

Things in context:

 1. pad - the pad instance
 2. author - the id of the author who updated the pad
 3. revs - the index of the new revision
 4. changeset - the changeset of this revision (see Changeset Library)

This hook gets called when an existing pad was updated.


PADCOPY

Called from: src/node/db/Pad.js

Things in context:

 1. originalPad - the source pad instance
 2. destinationID - the id of the pad copied from originalPad

This hook gets called when an existing pad was copied.

Usage examples:

 * https://github.com/ether/ep_comments


PADREMOVE

Called from: src/node/db/Pad.js

Things in context:

 1. padID

This hook gets called when an existing pad was removed/deleted.

Usage examples:

 * https://github.com/ether/ep_comments


SOCKETIO

Called from: src/node/hooks/express/socketio.js

Things in context:

 1. app - the application object
 2. io - the socketio object
 3. server - the http server object

I have no idea what this is useful for, someone else will have to add this
description.


PREAUTHORIZE

Called from: src/node/hooks/express/webaccess.js

Things in context:

 1. req - the request object
 2. res - the response object
 3. next - bypass callback. If this is called instead of the normal callback
    then all remaining access checks are skipped.

This hook is called for each HTTP request before any authentication checks are
performed. Example uses:

 * Always grant access to static content.
 * Process an OAuth callback.
 * Drop requests from IP addresses that have failed N authentication checks
   within the past X minutes.

A preAuthorize function is always called for each request unless a preAuthorize
function from another plugin (if any) has already explicitly granted or denied
the request.

You can pass the following values to the provided callback:

 * [] defers the access decision to the normal authentication and authorization
   checks (or to a preAuthorize function from another plugin, if one exists).
 * [true] immediately grants access to the requested resource, unless the
   request is for an /admin page in which case it is treated the same as [].
   (This prevents buggy plugins from accidentally granting admin access to the
   general public.)
 * [false] immediately denies the request. The preAuthnFailure hook will be
   called to handle the failure.

Example:

exports.preAuthorize = (hookName, context, cb) => {
  if (ipAddressIsFirewalled(context.req)) return cb([false]);
  if (requestIsForStaticContent(context.req)) return cb([true]);
  if (requestIsForOAuthCallback(context.req)) return cb([true]);
  return cb([]);
};



AUTHORIZE

Called from: src/node/hooks/express/webaccess.js

Things in context:

 1. req - the request object
 2. res - the response object
 3. next - ?
 4. resource - the path being accessed

This hook is called to handle authorization. It is especially useful for
controlling access to specific paths.

A plugin's authorize function is only called if all of the following are true:

 * The request is not for static content or an API endpoint. (Requests for
   static content and API endpoints are always authorized, even if
   unauthenticated.)
 * The requireAuthentication and requireAuthorization settings are both true.
 * The user has already successfully authenticated.
 * The user is not an admin (admin users are always authorized).
 * The path being accessed is not an /admin path (/admin paths can only be
   accessed by admin users, and admin users are always authorized).
 * An authorize function from a different plugin has not already caused
   authorization to pass or fail.

Note that the authorize hook cannot grant access to /admin pages. If admin
access is desired, the is_admin user setting must be set to true. This can be
set in the settings file or by the authenticate hook.

You can pass the following values to the provided callback:

 * [true] or ['create'] will grant access to modify or create the pad if the
   request is for a pad, otherwise access is simply granted. Access to a pad
   will be downgraded to modify-only if settings.editOnly is true or the user's
   canCreate setting is set to false, and downgraded to read-only if the user's
   readOnly setting is true.
 * ['modify'] will grant access to modify but not create the pad if the request
   is for a pad, otherwise access is simply granted. Access to a pad will be
   downgraded to read-only if the user's readOnly setting is true.
 * ['readOnly'] will grant read-only access.
 * [false] will deny access.
 * [] or undefined will defer the authorization decision to the next
   authorization plugin (if any, otherwise deny).

Example:

exports.authorize = (hookName, context, cb) => {
  const user = context.req.session.user;
  const path = context.req.path;  // or context.resource
  if (isExplicitlyProhibited(user, path)) return cb([false]);
  if (isExplicitlyAllowed(user, path)) return cb([true]);
  return cb([]);  // Let the next authorization plugin decide
};



AUTHENTICATE

Called from: src/node/hooks/express/webaccess.js

Things in context:

 1. req - the request object
 2. res - the response object
 3. users - the users object from settings.json (possibly modified by plugins)
 4. next - ?
 5. username - the username used (optional)
 6. password - the password used (optional)

This hook is called to handle authentication.

Plugins that supply an authenticate function should probably also supply an
authnFailure function unless falling back to HTTP basic authentication is
appropriate upon authentication failure.

This hook is only called if either the requireAuthentication setting is true or
the request is for an /admin page.

Calling the provided callback with [true] or [false] will cause authentication
to succeed or fail, respectively. Calling the callback with [] or undefined will
defer the authentication decision to the next authentication plugin (if any,
otherwise fall back to HTTP basic authentication).

If you wish to provide a mix of restricted and anonymous access (e.g., some pads
are private, others are public), you can "authenticate" (as a guest account)
users that have not yet logged in, and rely on other hooks (e.g., authorize,
onAccessCheck, handleMessageSecurity) to authorize specific privileged actions.

If authentication is successful, the authenticate function MUST set
context.req.session.user to the user's settings object. The username property of
this object should be set to the user's username. The settings object should
come from global settings (context.users[username]).

Example:

exports.authenticate = (hook_name, context, cb) => {
  if (notApplicableToThisPlugin(context)) {
    return cb([]);  // Let the next authentication plugin decide
  }
  const username = authenticate(context);
  if (!username) {
    console.warn(`ep_myplugin.authenticate: Failed authentication from IP ${context.req.ip}`);
    return cb([false]);
  }
  console.info(`ep_myplugin.authenticate: Successful authentication from IP ${context.req.ip} for user ${username}`);
  const users = context.users;
  if (!(username in users)) users[username] = {};
  users[username].username = username;
  context.req.session.user = users[username];
  return cb([true]);
};



AUTHFAILURE

Called from: src/node/hooks/express/webaccess.js

Things in context:

 1. req - the request object
 2. res - the response object
 3. next - ?

DEPRECATED: Use authnFailure or authzFailure instead.

This hook is called to handle an authentication or authorization failure.

Plugins that supply an authenticate function should probably also supply an
authnFailure function unless falling back to HTTP basic authentication is
appropriate upon authentication failure.

A plugin's authFailure function is only called if all of the following are true:

 * There was an authentication or authorization failure.
 * The failure was not already handled by an authFailure function from another
   plugin.
 * For authentication failures: The failure was not already handled by the
   authnFailure hook.
 * For authorization failures: The failure was not already handled by the
   authzFailure hook.

Calling the provided callback with [true] tells Etherpad that the failure was
handled and no further error handling is required. Calling the callback with []
or undefined defers error handling to the next authFailure plugin (if any,
otherwise fall back to HTTP basic authentication for an authentication failure
or a generic 403 page for an authorization failure).

Example:

exports.authFailure = (hookName, context, cb) => {
  if (notApplicableToThisPlugin(context)) {
    return cb([]);  // Let the next plugin handle the error
  }
  context.res.redirect(makeLoginURL(context.req));
  return cb([true]);
};



PREAUTHZFAILURE

Called from: src/node/hooks/express/webaccess.js

Things in context:

 1. req - the request object
 2. res - the response object

This hook is called to handle a pre-authentication authorization failure.

A plugin's preAuthzFailure function is only called if the pre-authentication
authorization failure was not already handled by a preAuthzFailure function from
another plugin.

Calling the provided callback with [true] tells Etherpad that the failure was
handled and no further error handling is required. Calling the callback with []
or undefined defers error handling to a preAuthzFailure function from another
plugin (if any, otherwise fall back to a generic 403 error page).

Example:

exports.preAuthzFailure = (hookName, context, cb) => {
  if (notApplicableToThisPlugin(context)) return cb([]);
  context.res.status(403).send(renderFancy403Page(context.req));
  return cb([true]);
};



AUTHNFAILURE

Called from: src/node/hooks/express/webaccess.js

Things in context:

 1. req - the request object
 2. res - the response object

This hook is called to handle an authentication failure.

Plugins that supply an authenticate function should probably also supply an
authnFailure function unless falling back to HTTP basic authentication is
appropriate upon authentication failure.

A plugin's authnFailure function is only called if the authentication failure
was not already handled by an authnFailure function from another plugin.

Calling the provided callback with [true] tells Etherpad that the failure was
handled and no further error handling is required. Calling the callback with []
or undefined defers error handling to an authnFailure function from another
plugin (if any, otherwise fall back to the deprecated authFailure hook).

Example:

exports.authnFailure = (hookName, context, cb) => {
  if (notApplicableToThisPlugin(context)) return cb([]);
  context.res.redirect(makeLoginURL(context.req));
  return cb([true]);
};



AUTHZFAILURE

Called from: src/node/hooks/express/webaccess.js

Things in context:

 1. req - the request object
 2. res - the response object

This hook is called to handle a post-authentication authorization failure.

A plugin's authzFailure function is only called if the authorization failure was
not already handled by an authzFailure function from another plugin.

Calling the provided callback with [true] tells Etherpad that the failure was
handled and no further error handling is required. Calling the callback with []
or undefined defers error handling to an authzFailure function from another
plugin (if any, otherwise fall back to the deprecated authFailure hook).

Example:

exports.authzFailure = (hookName, context, cb) => {
  if (notApplicableToThisPlugin(context)) return cb([]);
  if (needsPremiumAccount(context.req) && !context.req.session.user.premium) {
    context.res.status(200).send(makeUpgradeToPremiumAccountPage(context.req));
    return cb([true]);
  }
  // Use the generic 403 forbidden response.
  return cb([]);
};



HANDLEMESSAGE

Called from: src/node/handler/PadMessageHandler.js

Things in context:

 1. message - the message being handled
 2. socket - the socket.io Socket object
 3. client - deprecated synonym of socket

This hook allows plugins to drop or modify incoming socket.io messages from
clients, before Etherpad processes them.

The handleMessage function must return a Promise. If the Promise resolves to
null, the message is dropped. Returning callback(value) will return a Promise
that is resolved to value.

Examples:

// Using an async function:
exports.handleMessage = async (hookName, {message, socket}) => {
  if (message.type === 'USERINFO_UPDATE') {
    // Force the display name to the name associated with the account.
    const user = socket.client.request.session.user || {};
    if (user.name) message.data.userInfo.name = user.name;
  }
};

// Using a regular function:
exports.handleMessage = (hookName, {message, socket}, callback) => {
  if (message.type === 'USERINFO_UPDATE') {
    // Force the display name to the name associated with the account.
    const user = socket.client.request.session.user || {};
    if (user.name) message.data.userInfo.name = user.name;
  }
  return callback();
};



HANDLEMESSAGESECURITY

Called from: src/node/handler/PadMessageHandler.js

Things in context:

 1. message - the message being handled
 2. socket - the socket.io Socket object
 3. client - deprecated synonym of socket

This hook allows plugins to grant temporary write access to a pad. It is called
for each incoming message from a client. If write access is granted, it applies
to the current message and all future messages from the same socket.io
connection until the next CLIENT_READY message. Read-only access is reset after
each CLIENT_READY message, so granting write access has no effect for those
message types.

The handleMessageSecurity function must return a Promise. If the Promise
resolves to true, write access is granted as described above. Returning
callback(value) will return a Promise that is resolved to value.

Examples:

// Using an async function:
exports.handleMessageSecurity = async (hookName, {message, socket}) => {
  if (shouldGrantWriteAccess(message, socket)) return true;
  return;
};

// Using a regular function:
exports.handleMessageSecurity = (hookName, {message, socket}, callback) => {
  if (shouldGrantWriteAccess(message, socket)) return callback(true);
  return callback();
};



CLIENTVARS

Called from: src/node/handler/PadMessageHandler.js

Things in context:

 1. clientVars - the basic clientVars built by the core
 2. pad - the pad this session is about
 3. socket - the socket.io Socket object

This hook is called after a client connects but before the initial configuration
is sent to the client. Plugins can use this hook to manipulate the
configuration. (Example: Add a tracking ID for an external analytics tool that
is used client-side.)

You can manipulate clientVars in two different ways:

 * Return an object. The object will be merged into clientVars via
   Object.assign(), so any keys that already exist in clientVars will be
   overwritten by the values in the returned object.
 * Modify context.clientVars. Beware: Other plugins might also be reading or
   manipulating the same context.clientVars object. To avoid race conditions,
   you are encouraged to return an object rather than modify context.clientVars.

If needed, you can access the user's account information (if authenticated) via
context.socket.client.request.session.user.

Examples:

// Using an async function
exports.clientVars = async (hookName, context) => {
  const user = context.socket.client.request.session.user || {};
  return {'accountUsername': user.username || '<unknown>'}
};

// Using a regular function
exports.clientVars = (hookName, context, callback) => {
  const user = context.socket.client.request.session.user || {};
  return callback({'accountUsername': user.username || '<unknown>'});
};



GETLINEHTMLFOREXPORT

Called from: src/node/utils/ExportHtml.js

Things in context:

 1. apool - pool object
 2. attribLine - line attributes
 3. text - line text

This hook will allow a plug-in developer to re-write each line when exporting to
HTML.

Example:

var Changeset = require("ep_etherpad-lite/static/js/Changeset");

exports.getLineHTMLForExport = function (hook, context) {
  var header = _analyzeLine(context.attribLine, context.apool);
  if (header) {
    return "<" + header + ">" + context.lineContent + "</" + header + ">";
  }
}

function _analyzeLine(alineAttrs, apool) {
  var header = null;
  if (alineAttrs) {
    var opIter = Changeset.opIterator(alineAttrs);
    if (opIter.hasNext()) {
      var op = opIter.next();
      header = Changeset.opAttributeValue(op, 'heading', apool);
    }
  }
  return header;
}



EXPORTHTMLADDITIONALCONTENT

Called from: src/node/utils/ExportHtml.js

Things in context:

 1. padId

This hook will allow a plug-in developer to include additional HTML content in
the body of the exported HTML.

Example:

exports.exportHTMLAdditionalContent = async (hookName, {padId}) => {
  return 'I am groot in ' + padId;
};



STYLESFOREXPORT

Called from: src/node/utils/ExportHtml.js

Things in context:

 1. padId - The Pad Id

This hook will allow a plug-in developer to append Styles to the Exported HTML.

Example:

exports.stylesForExport = function(hook, padId, cb){
  cb("body{font-size:13.37em !important}");
}



ACEATTRIBCLASSES

Called from: src/static/js/linestylefilter.js

This hook is called when attributes are investigated on a line. It is useful if
you want to add another attribute type or property type to a pad.

An attributes object is passed to the aceAttribClasses hook functions instead of
the usual context object. A hook function can either modify this object directly
or provide an object whose properties will be assigned to the attributes object.

Example:

exports.aceAttribClasses = (hookName, attrs, cb) => {
  return cb([{
    sub: 'tag:sub',
  }]);
};



EXPORTFILENAME

Called from src/node/handler/ExportHandler.js

Things in context:

 1. padId

This hook will allow a plug-in developer to modify the file name of an exported
pad. This is useful if you want to export a pad under another name and/or hide
the padId under export. Note that the doctype or file extension cannot be
modified for security reasons.

Example:

exports.exportFileName = function(hook, padId, callback){
  callback("newFileName"+padId);
}



EXPORTHTMLADDITIONALTAGS

Called from src/node/utils/ExportHtml.js

Things in context:

 1. Pad object

This hook will allow a plug-in developer to include more properties and
attributes to support during HTML Export. If tags are stored as ['color', 'red']
on the attribute pool, use exportHtmlAdditionalTagsWithData instead. An Array
should be returned.

Example:

// Add the props to be supported in export
exports.exportHtmlAdditionalTags = function(hook, pad, cb){
  var padId = pad.id;
  cb(["massive","jugs"]);
};



EXPORTHTMLADDITIONALTAGSWITHDATA

Called from src/node/utils/ExportHtml.js

Things in context:

 1. Pad object

Identical to exportHtmlAdditionalTags, but for tags that are stored with a
specific value (not simply true) on the attribute pool. For example ['color',
'red'], instead of ['bold', true]. This hook will allow a plug-in developer to
include more properties and attributes to support during HTML Export. An Array
of arrays should be returned. The exported HTML will contain tags like <span
data-color="red"> for the content where attributes are ['color', 'red'].

Example:

// Add the props to be supported in export
exports.exportHtmlAdditionalTagsWithData = function(hook, pad, cb){
  var padId = pad.id;
  cb([["color", "red"], ["color", "blue"]]);
};



EXPORTETHERPADADDITIONALCONTENT

Called from src/node/utils/ExportEtherpad.js and
src/node/utils/ImportEtherpad.js

Things in context: Nothing

Useful for exporting and importing pad metadata that is stored in the database
but not in the pad's content or attributes. For example, in ep_comments_page the
comments are stored as comments:padId:uniqueIdOfComment so a complete export of
all pad data to an .etherpad file must include the comments:padId:* records.

Example:

// Add support for exporting comments metadata
exports.exportEtherpadAdditionalContent = () => ['comments'];



IMPORT

Called from: src/node/handler/ImportHandler.js

Called when a user submits a document for import, before the document is
converted to HTML. The hook function should return a truthy value if the hook
function elected to convert the document to HTML.

Context properties:

 * destFile: The destination HTML filename.
 * fileEnding: The lower-cased filename extension from srcFile with leading
   period (examples: '.docx', '.html', '.etherpad').
 * padId: The identifier of the destination pad.
 * srcFile: The document to convert.


USERJOIN

Called from: src/node/handler/PadMessageHandler.js

Called after users have been notified that a new user has joined the pad.

Context properties:

 * authorId: The user's author identifier.
 * displayName: The user's display name.
 * padId: The real (not read-only) identifier of the pad the user joined. This
   MUST NOT be shared with any users that are connected with read-only access.
 * readOnly: Whether the user only has read-only access.
 * readOnlyPadId: The read-only identifier of the pad the user joined.
 * socket: The socket.io Socket object.

Example:

exports.userJoin = async (hookName, {authorId, displayName, padId}) => {
  console.log(`${authorId} (${displayName}) joined pad ${padId});
};



USERLEAVE

Called from: src/node/handler/PadMessageHandler.js

Called when a user disconnects from a pad. This is useful if you want to perform
certain actions after a pad has been edited.

Context properties:

 * authorId: The user's author ID.
 * padId: The pad's real (not read-only) identifier.
 * readOnly: If truthy, the user only has read-only access.
 * readOnlyPadId: The pad's read-only identifier.
 * socket: The socket.io Socket object.

Example:

exports.userLeave = async (hookName, {author, padId}) => {
  console.log(`${author} left pad ${padId}`);
};



CHATNEWMESSAGE

Called from: src/node/handler/PadMessageHandler.js

Called when a user (or plugin) generates a new chat message, just before it is
saved to the pad and relayed to all connected users.

Context properties:

 * message: The chat message object. Plugins can mutate this object to change
   the message text or add custom metadata to control how the message will be
   rendered by the chatNewMessage client-side hook. The message's authorId
   property can be trusted (the server overwrites any client-provided author ID
   value with the user's actual author ID before this hook runs).
 * padId: The pad's real (not read-only) identifier.
 * pad: The pad's Pad object.


EDITORINFO


EDITORINFO.ACE_REPLACERANGE(START, END, TEXT)

This function replaces a range (from start to end) with text.


EDITORINFO.ACE_GETREP()

Returns the rep object.


EDITORINFO.ACE_GETAUTHOR()


EDITORINFO.ACE_INCALLSTACK()


EDITORINFO.ACE_INCALLSTACKIFNECESSARY(?)


EDITORINFO.ACE_FOCUS(?)


EDITORINFO.ACE_IMPORTTEXT(?)


EDITORINFO.ACE_IMPORTATEXT(?)


EDITORINFO.ACE_EXPORTTEXT(?)


EDITORINFO.ACE_EDITORCHANGEDSIZE(?)


EDITORINFO.ACE_SETONKEYPRESS(?)


EDITORINFO.ACE_SETONKEYDOWN(?)


EDITORINFO.ACE_SETNOTIFYDIRTY(?)


EDITORINFO.ACE_DISPOSE(?)


EDITORINFO.ACE_SETEDITABLE(BOOL)


EDITORINFO.ACE_EXECCOMMAND(?)


EDITORINFO.ACE_CALLWITHACE(FN, CALLSTACK, NORMALIZE)


EDITORINFO.ACE_SETPROPERTY(KEY, VALUE)


EDITORINFO.ACE_SETBASETEXT(TXT)


EDITORINFO.ACE_SETBASEATTRIBUTEDTEXT(ATXT, APOOLJSONOBJ)


EDITORINFO.ACE_APPLYCHANGESTOBASE(C, OPTAUTHOR, APOOLJSONOBJ)


EDITORINFO.ACE_PREPAREUSERCHANGESET()


EDITORINFO.ACE_APPLYPREPAREDCHANGESETTOBASE()


EDITORINFO.ACE_SETUSERCHANGENOTIFICATIONCALLBACK(F)


EDITORINFO.ACE_SETAUTHORINFO(AUTHOR, INFO)


EDITORINFO.ACE_FASTINCORP(?)


EDITORINFO.ACE_ISCARET(?)


EDITORINFO.ACE_GETLINEANDCHARFORPOINT(?)


EDITORINFO.ACE_PERFORMDOCUMENTAPPLYATTRIBUTESTOCHARRANGE(?)


EDITORINFO.ACE_SETATTRIBUTEONSELECTION(ATTRIBUTE, ENABLED)

Sets an attribute on current range. Example:
`call.editorInfo.ace_setAttributeOnSelection("turkey::balls", true); // turkey
is the attribute here, balls is the value Notes: to remove the attribute pass
enabled as false


EDITORINFO.ACE_TOGGLEATTRIBUTEONSELECTION(?)


EDITORINFO.ACE_GETATTRIBUTEONSELECTION(ATTRIBUTE, PREVCHAR)

Returns a boolean if an attribute exists on a selected range. prevChar value
should be true if you want to get the previous Character attribute instead of
the current selection for example if the caret is at position 0,1 (after first
character) it's probable you want the attributes on the character at 0,0 The
attribute should be the string name of the attribute applied to the selection IE
subscript Example usage: Apply the activeButton Class to a button if an
attribute is on a highlighted/selected caret position or range. Example var
isItThere = documentAttributeManager.getAttributeOnSelection("turkey::balls",
true);

See the ep_subscript plugin for an example of this function in action. Notes:
Does not work on first or last character of a line. Suffers from a race
condition if called with aceEditEvent.


EDITORINFO.ACE_PERFORMSELECTIONCHANGE(?)


EDITORINFO.ACE_DOINDENTOUTDENT(?)


EDITORINFO.ACE_DOUNDOREDO(?)


EDITORINFO.ACE_DOINSERTUNORDEREDLIST(?)


EDITORINFO.ACE_DOINSERTORDEREDLIST(?)


EDITORINFO.ACE_PERFORMDOCUMENTAPPLYATTRIBUTESTORANGE()


EDITORINFO.ACE_GETAUTHORINFOS()

Returns an info object about the author. Object key = author_id and info
includes author's bg color value. Use to define your own authorship.


EDITORINFO.ACE_PERFORMDOCUMENTREPLACERANGE(START, END, NEWTEXT)

This function replaces a range (from [x1,y1] to [x2,y2]) with newText.


EDITORINFO.ACE_PERFORMDOCUMENTREPLACECHARRANGE(STARTCHAR, ENDCHAR, NEWTEXT)

This function replaces a range (from y1 to y2) with newText.


EDITORINFO.ACE_RENUMBERLIST(LINENUM)

If you delete a line, calling this method will fix the line numbering.


EDITORINFO.ACE_DORETURNKEY()

Forces a return key at the current caret position.


EDITORINFO.ACE_ISBLOCKELEMENT(ELEMENT)

Returns true if your passed element is registered as a block element


EDITORINFO.ACE_GETLINELISTTYPE(LINENUM)

Returns the line's html list type.


EDITORINFO.ACE_CARETLINE()

Returns X position of the caret.


EDITORINFO.ACE_CARETCOLUMN()

Returns Y position of the caret.


EDITORINFO.ACE_CARETDOCCHAR()

Returns the Y offset starting from [x=0,y=0]


EDITORINFO.ACE_ISWORDCHAR(?)


CHANGESET LIBRARY

The changeset library provides tools to create, read, and apply changesets.


CHANGESET

const Changeset = require('ep_etherpad-lite/static/js/Changeset');


A changeset describes the difference between two revisions of a document. When a
user edits a pad, the browser generates and sends a changeset to the server,
which relays it to the other users and saves a copy (so that every past revision
is accessible).

A transmitted changeset looks like this:

'Z:z>1|2=m=b*0|1+1$\n'



ATTRIBUTE POOL

const AttributePool = require('ep_etherpad-lite/static/js/AttributePool');


Changesets do not include any attribute key–value pairs. Instead, they use
numeric identifiers that reference attributes kept in an attribute pool. This
attribute interning reduces the transmission overhead of attributes that are
used many times.

There is one attribute pool per pad, and it includes every current and
historical attribute used in the pad.


FURTHER READING

Detailed information about the changesets & Easysync protocol:

 * Easysync Protocol
 * Etherpad and EasySync Technical Manual


PLUGIN FRAMEWORK

require("ep_etherpad-lite/static/js/plugingfw/plugins")


PLUGINS.UPDATE

require("ep_etherpad-lite/static/js/plugingfw/plugins").update() will use npm to
list all installed modules and read their ep.json files, registering the
contained hooks. A hook registration is a pair of a hook name and a function
reference (filename for require() plus function name)


HOOKS.CALLALL

require("ep_etherpad-lite/static/js/plugingfw/hooks").callAll("hook_name",
{argname:value}) will call all hook functions registered for hook_name with
{argname:value}.


HOOKS.ACALLALL

?


...


TOOLBAR CONTROLLER

src/node/utils/toolbar.js


BUTTON(OPTS)

 * {Object} opts
   * command - this command fill be fired on the editbar on click
   * localizationId - will be set as data-l10-id
   * class - here you can add additional classes to the button

Returns: {Button}

Example:

var orderedlist = toolbar.button({
  command: "insertorderedlist",
  localizationId: "pad.toolbar.ol.title",
  class: "buttonicon buttonicon-insertorderedlist"
})


You can also create buttons with text:

var myButton = toolbar.button({
  command: "myButton",
  localizationId: "myPlugin.toolbar.myButton",
  class: "buttontext"
})



SELECTBUTTON(OPTS)

 * {Object} opts
   * id - id of the menu item
   * selectId - id of the select element
   * command - this command fill be fired on the editbar on change

Returns: {SelectButton}


SELECTBUTTON.ADDOPTION(VALUE, TEXT, ATTRIBUTES)

 * {String} value - The value of this option
 * {String} text - the label text used for this option
 * {Object} attributes - any additional html attributes go here (e.g.
   data-l10n-id)


REGISTERBUTTON(NAME, ITEM)

 * {String} name - used to reference the item in the toolbar config in
   settings.json
 * {Button|SelectButton} item - the button to add
   
   
   EDITBAR
   
   src/static/js/pad_editbar.js


ISENABLED()


DISABLE()


TOGGLEDROPDOWN(DROPDOWN)

Shows the dropdown div.popup whose id equals dropdown.


REGISTERCOMMAND(CMD, CALLBACK)

Register a handler for a specific command. Commands are fired if the
corresponding button is clicked or the corresponding select is changed.


REGISTERACECOMMAND(CMD, CALLBACK)

Creates an ace callstack and calls the callback with an ace instance (and a
toolbar item, if applicable): callback(cmd, ace, item).

Example:

toolbar.registerAceCommand("insertorderedlist", function (cmd, ace) {
  ace.ace_doInsertOrderedList();
});



REGISTERDROPDOWNCOMMAND(CMD, DROPDOWN)

Ties a div.popup where id equals dropdown to a command fired by clicking a
button.


TRIGGERCOMMAND(CMD[, ITEM])

Triggers a command (optionally with some internal representation of the toolbar
item that triggered it).


PLUGINS

Etherpad allows you to extend its functionality with plugins. A plugin registers
hooks (functions) for certain events (thus certain features) in Etherpad to
execute its own functionality based on these events.

Publicly available plugins can be found in the npm registry (see
https://npmjs.org). Etherpad's naming convention for plugins is to prefix your
plugins with ep_. So, e.g. it's ep_flubberworms. Thus you can install plugins
from npm, using npm install --no-save --legacy-peer-deps ep_flubberworm in
Etherpad's root directory.

You can also browse to http://yourEtherpadInstan.ce/admin/plugins, which will
list all installed plugins and those available on npm. It even provides
functionality to search through all available plugins.


FOLDER STRUCTURE

Ideally a plugin has the following folder structure:

ep_<plugin>/
 ├ .github/
 │  └ workflows/
 │     └ npmpublish.yml  ◄─ GitHub workflow to auto-publish on push
 ├ static/
 │  ├ css/               ◄─ static .css files
 │  ├ images/            ◄─ static image files
 │  ├ js/
 │  │  └ index.js        ◄─ static client-side code
 │  └ tests/
 │     ├ backend/
 │     │  └ specs/       ◄─ backend (server) tests
 │     └ frontend/
 │        └ specs/       ◄─ frontend (client) tests
 ├ templates/            ◄─ EJS templates (.html, .js, .css, etc.)
 ├ locales/
 │  ├ en.json            ◄─ English (US) strings
 │  └ qqq.json           ◄─ optional hints for translators
 ├ .travis.yml           ◄─ Travis CI config
 ├ LICENSE
 ├ README.md
 ├ ep.json               ◄─ Etherpad plugin definition
 ├ index.js              ◄─ server-side code
 ├ package.json
 └ package-lock.json


If your plugin includes client-side hooks, put them in static/js/. If you're
adding in CSS or image files, you should put those files in static/css/ and
static/image/, respectively, and templates go into templates/. Translations go
into locales/. Tests go in static/tests/backend/specs/ and
static/tests/frontend/specs/.

A Standard directory structure like this makes it easier to navigate through
your code. That said, do note, that this is not actually required to make your
plugin run. If you want to make use of our i18n system, you need to put your
translations into locales/, though, in order to have them integrated. (See
"Localization" for more info on how to localize your plugin.)


PLUGIN DEFINITION

Your plugin definition goes into ep.json. In this file you register your hook
functions, indicate the parts of your plugin and the order of execution. (A
documentation of all available events to hook into can be found in chapter
hooks.)

{
  "parts": [
    {
      "name": "nameThisPartHoweverYouWant",
      "hooks": {
        "authenticate": "ep_<plugin>/<file>:functionName1",
        "expressCreateServer": "ep_<plugin>/<file>:functionName2"
      },
      "client_hooks": {
        "acePopulateDOMLine": "ep_<plugin>/<file>:functionName3"
      }
    }
  ]
}


A hook function registration maps a hook name to a hook function specification.
The hook function specification looks like ep_example/file.js:functionName. It
consists of two parts separated by a colon: a module name to require() and the
name of a function exported by the named module. See module.exports for how to
export a function.

For the module name you can omit the .js suffix, and if the file is index.js you
can use just the directory name. You can also omit the module name entirely, in
which case it defaults to the plugin name (e.g., ep_example).

You can also omit the function name. If you do, Etherpad will look for an
exported function whose name matches the name of the hook (e.g., authenticate).

If either the module name or the function name is omitted (or both), the colon
may also be omitted unless the provided module name contains a colon. (So if the
module name is C:\foo.js then the hook function specification with the function
name omitted would be "C:\\foo.js:".)

Examples: Suppose the plugin name is ep_example. All of the following are
equivalent, and will cause the authorize hook to call the exports.authorize
function in index.js from the ep_example plugin:

 * "authorize": "ep_example/index.js:authorize"
 * "authorize": "ep_example/index.js:"
 * "authorize": "ep_example/index.js"
 * "authorize": "ep_example/index:authorize"
 * "authorize": "ep_example/index:"
 * "authorize": "ep_example/index"
 * "authorize": "ep_example:authorize"
 * "authorize": "ep_example:"
 * "authorize": "ep_example"
 * "authorize": ":authorize"
 * "authorize": ":"
 * "authorize": ""


CLIENT HOOKS AND SERVER HOOKS

There are server hooks, which will be executed on the server (e.g.
expressCreateServer), and there are client hooks, which are executed on the
client (e.g. acePopulateDomLine). Be sure to not make assumptions about the
environment your code is running in, e.g. don't try to access process, if you
know your code will be run on the client, and likewise, don't try to access
window on the server...


STYLING

When you install a client-side plugin (e.g. one that implements at least one
client-side hook), the plugin name is added to the class attribute of the div
#editorcontainerbox in the main window. This gives you the opportunity of tuning
the appearance of the main UI in your plugin.

For example, this is the markup with no plugins installed:

<div id="editorcontainerbox" class="">


and this is the contents after installing someplugin:

<div id="editorcontainerbox" class="ep_someplugin">


This feature was introduced in Etherpad 1.8.


PARTS

As your plugins become more and more complex, you will find yourself in the need
to manage dependencies between plugins. E.g. you want the hooks of a certain
plugin to be executed before (or after) yours. You can also manage these
dependencies in your plugin definition file ep.json:

{
  "parts": [
    {
      "name": "onepart",
      "pre": [],
      "post": ["ep_onemoreplugin/partone"]
      "hooks": {
        "storeBar": "ep_monospace/plugin:storeBar",
        "getFoo": "ep_monospace/plugin:getFoo",
      }
    },
    {
      "name": "otherpart",
      "pre": ["ep_my_example/somepart", "ep_otherplugin/main"],
      "post": [],
      "hooks": {
        "someEvent": "ep_my_example/otherpart:someEvent",
        "another": "ep_my_example/otherpart:another"
      }
    }
  ]
}


Usually a plugin will add only one functionality at a time, so it will probably
only use one part definition to register its hooks. However, sometimes you have
to put different (unrelated) functionalities into one plugin. For this you will
want use parts, so other plugins can depend on them.

PRE/POST

The "pre" and "post" definitions, affect the order in which parts of a plugin
are executed. This ensures that plugins and their hooks are executed in the
correct order.

"pre" lists parts that must be executed before the defining part. "post" lists
parts that must be executed after the defining part.

You can, on a basic level, think of this as double-ended dependency listing. If
you have a dependency on another plugin, you can make sure it loads before yours
by putting it in "pre". If you are setting up things that might need to be used
by a plugin later, you can ensure proper order by putting it in "post".

Note that it would be far more sane to use "pre" in almost any case, but if you
want to change config variables for another plugin, or maybe modify its
environment, "post" could definitely be useful.

Also, note that dependencies should also be listed in your package.json, so they
can be npm install'd automagically when your plugin gets installed.


PACKAGE DEFINITION

Your plugin must also contain a package definition file, called package.json, in
the project root - this file contains various metadata relevant to your plugin,
such as the name and version number, author, project hompage, contributors, a
short description, etc. If you publish your plugin on npm, these metadata are
used for package search etc., but it's necessary for Etherpad plugins, even if
you don't publish your plugin.

{
  "name": "ep_PLUGINNAME",
  "version": "0.0.1",
  "description": "DESCRIPTION",
  "author": "USERNAME (REAL NAME) <MAIL@EXAMPLE.COM>",
  "contributors": [],
  "dependencies": {"MODULE": "0.3.20"},
  "engines": {"node": ">=12.13.0"}
}



TEMPLATES

If your plugin adds or modifies the front end HTML (e.g. adding buttons or
changing their functions), you should put the necessary HTML code for such
operations in templates/, in files of type ".ejs", since Etherpad uses EJS for
HTML templating. See the following link for more information about EJS:
https://github.com/visionmedia/ejs.


WRITING AND RUNNING FRONT-END TESTS FOR YOUR PLUGIN

Etherpad allows you to easily create front-end tests for plugins.

 1. Create a new folder: %your_plugin%/static/tests/frontend/specs
 2. Put your spec file in there. (Example spec files are visible in
    %etherpad_root_folder%/frontend/tests/specs.)
 3. Visit http://yourserver.com/frontend/tests and your front-end tests will
    run.


COOKIES

Cookies used by Etherpad.

Name Sample value Domain Path Expires/max-age Http-only Secure Usage description
express_sid s%3A7yCNjRmTW8ylGQ53I2IhOwYF9... example.org / Session true true
Session ID of the Express web framework. When Etherpad is behind a reverse
proxy, and an administrator wants to use session stickiness, he may use this
cookie. If you are behind a reverse proxy, please remember to set trustProxy:
true in settings.json. Set in webaccess.js#L131. language en example.org /
Session false true The language of the UI (e.g.: en-GB, it). Set in
pad_editor.js#L111. prefs / prefsHttp %7B%22epThemesExtTheme%22... example.org
/p year 3000 false true Client-side preferences (e.g.: font family, chat always
visible, show authorship colors, ...). Set in pad_cookie.js#L49. prefs is used
if Etherpad is accessed over HTTPS, prefsHttp if accessed over HTTP. For more
info see https://github.com/ether/etherpad-lite/issues/3179. token
t.tFzkihhhBf4xKEpCK3PU example.org / 60 days false true A random token
representing the author, of the form t.randomstring_of_lenght_20. The random
string is generated by the client, at (pad.js#L55-L66). This cookie is always
set by the client (at pad.js#L153-L158) without any solicitation from the
server. It is used for all the pads accessed via the web UI (not used for the
HTTP API). On the server side, its value is accessed at SecurityManager.js#L33.

For more info, visit the related discussion at
https://github.com/ether/etherpad-lite/issues/3563.

Etherpad HTTP API clients may make use (if they choose so) to send another
cookie:

Name Sample value Domain Usage description sessionID
s.1c70968b333b25476a2c7bdd0e0bed17 example.org Sessions can be created between a
group and an author. This allows an author to access more than one group. The
sessionID will be set as a cookie to the client and is valid until a certain
date. The session cookie can also contain multiple comma-separated sessionIDs,
allowing a user to edit pads in different groups at the same time. More info -
https://github.com/ether/etherpad-lite/blob/develop/doc/api/http_api.md#session


DATABASE STRUCTURE


KEYS AND THEIR VALUES


GROUPS

A list of all existing groups (a JSON object with groupIDs as keys and 1 as
values).


PAD:$PADID

Contains all information about pads

 * atext - the latest attributed text
 * pool - the attribute pool
 * head - the number of the latest revision
 * chatHead - the number of the latest chat entry
 * public - flag that disables security for this pad
 * passwordHash - string that contains a salted sha512 sum of this pad's
   password


PAD:$PADID:REVS:$REVNUM

Saves a revision $REVNUM of pad $PADID

 * meta
   * author - the autorID of this revision
   * timestamp - the timestamp of when this revision was created
 * changeset - the changeset of this revision


PAD:$PADID:CHAT:$CHATNUM

Saves a chat entry with num $CHATNUM of pad $PADID

 * text - the text of this chat entry
 * userId - the authorID of this chat entry
 * time - the timestamp of this chat entry


PAD2READONLY:$PADID

Translates a padID to a readonlyID


READONLY2PAD:$READONLYID

Translates a readonlyID to a padID


TOKEN2AUTHOR:$TOKENID

Translates a token to an authorID


GLOBALAUTHOR:$AUTHORID

Information about an author

 * name - the name of this author as shown in the pad
 * colorID - the colorID of this author as shown in the pad


MAPPER2GROUP:$MAPPER

Maps an external application identifier to an internal group


MAPPER2AUTHOR:$MAPPER

Maps an external application identifier to an internal author


GROUP:$GROUPID

a group of pads

 * pads - object with pad names in it, values are 1
   
   
   SESSION:$SESSIONID
   
   a session between an author and a group

 * groupID - the groupID the session belongs too

 * authorID - the authorID the session belongs too

 * validUntil - the timestamp until this session is valid


AUTHOR2SESSIONS:$AUTHORID

saves the sessions of an author

 * sessionsIDs - object with sessionIDs in it, values are 1


GROUP2SESSIONS:$GROUPID

 * sessionsIDs - object with sessionIDs in it, values are 1