Scripting API

CopyQ provides scripting capabilities to automatically handle clipboard changes, organize items, change settings and much more.

In addition to features provided by Qt Script there are following functions, types, objects and MIME types.

Execute Script

The scripts can be executed from:

  1. Action or Command dialogs (F5, F6 shortcuts), if the first line starts with copyq:
  2. command line as copyq eval '<SCRIPT>'
  3. command line as cat script.js | copyq eval -
  4. command line as copyq <SCRIPT_FUNCTION> <FUNCTION_ARGUMENT_1> <FUNCTION_ARGUMENT_2> ...

When run from command line, result of last expression is printed on stdout.

Command exit values are:

  • 0 - script finished without error
  • 1 - fail() was called
  • 2 - bad syntax
  • 3 - exception was thrown

Command Line

If number of arguments that can be passed to function is limited you can use

              <FUNCTION3> <FUNCTION3_ARGUMENTS> ...

where <FUNCTION1> and <FUNCTION2> are scripts where result of last expression is functions that take two and one arguments respectively.


copyq tab clipboard separator "," read 0 1 2

After eval no arguments are treated as functions since it can access all arguments.

Arguments recognize escape sequences \n (new line), \t (tabulator character) and \\ (backslash).

Argument -e is identical to eval.

Argument - is replaced with data read from stdin.

Argument -- is skipped and all the remaining arguments are interpreted as they are (escape sequences are ignored and -e, -, -- are left unchanged).


Argument list parts ... and [...] are optional and can be omitted.

String version()

Returns version string.

String help()

Returns help string.

String help(searchString, ...)

Returns help for matched commands.


Shows main window.


Shows tab.


Shows main window under mouse cursor.

showAt(x, y[, width, height])

Shows main window with given geometry.

showAt(x, y, width, height, tabName)

Shows tab with given geometry.


Hides main window.

bool toggle()

Shows or hides main window.

Returns true only if main window is being shown.

Opens context menu.

menu(tabName[, maxItemCount[, x, y]])

Shows context menu for given tab.

This menu doesn’t show clipboard and doesn’t have any special actions.

Second argument is optional maximum number of items. The default value same as for tray (i.e. value of config('tray_items')).

Optional arguments x, y are coordinates in pixels on screen where menu should show up. By default menu shows up under the mouse cursor.


Exits server.

disable(), enable()

Disables or enables clipboard content storing.

bool monitoring()

Returns true only if clipboard storing is enabled.

bool visible()

Returns true only if main window is visible.

bool focused()

Returns true only if main window has focus.


Activates window that was focused before the main window.

Throws an exception when previous window cannot be activated.

bool preview([true|false])

Shows/hides item preview and returns true only if preview was visible.

To toggle the preview:

preview(false) || preview(true)

Sets text for filtering items in main window.

String filter()

Returns current text for filtering items in main window.


Ignores current clipboard content (used for automatic commands).

This does all of the below.

  • Skips any next automatic commands.
  • Omits changing window title and tray tool tip.
  • Won’t store content in clipboard tab.
ByteArray clipboard([mimeType])

Returns clipboard data for MIME type (default is text).

Pass argument "?" to list available MIME types.

ByteArray selection([mimeType])

Same as clipboard() for Linux/X11 mouse selection.

bool hasClipboardFormat(mimeType)

Returns true only if clipboard contains MIME type.

bool hasSelectionFormat(mimeType)

Same as hasClipboardFormat() for Linux/X11 mouse selection.

bool isClipboard()

Returns true only in automatic command triggered by clipboard change.

This can be used to check if current automatic command was triggered by clipboard and not Linux/X11 mouse selection change.


Sets clipboard plain text.

Same as copy(mimeText, text).

copy(mimeType, data, [mimeType, data]...)

Sets clipboard data.

This also sets mimeOwner format so automatic commands are not run on the new data and it’s not stored in clipboard tab.

Throws an exception if clipboard fails to be set.

Example (set both text and rich text):

copy(mimeText, 'Hello, World!',
     mimeHtml, '<p>Hello, World!</p>')

Function override with an item argument.


Sends Ctrl+C to current window.

Throws an exception if clipboard doesn’t change (clipboard is reset before sending the shortcut).


Same as copy(...) for Linux/X11 mouse selection.


Pastes current clipboard.

This is basically only sending Shift+Insert shortcut to current window.

Correct functionality depends a lot on target application and window manager.

String[] tab()

Returns array of tab names.


Sets current tab for the script.

E.g. following script selects third item (index is 2) from tab “Notes”:


Removes tab.

renameTab(tabName, newTabName)

Renames tab.

String tabIcon(tabName)

Returns path to icon for tab.

tabIcon(tabName, iconPath)

Sets icon for tab.

String[] unload([tabNames...])

Unload tabs (i.e. items from memory).

If no tabs are specified, unloads all tabs.

If a tab is open and visible or has an editor open, it won’t be unloaded.

Returns list of successfully unloaded tabs.


Force-unload tabs (i.e. items from memory).

If no tabs are specified, unloads all tabs.

Refresh button needs to be clicked to show the content of a force-unloaded tab.

If a tab has an editor open, the editor will be closed first even if it has unsaved changes.

count(), length(), size()

Returns amount of items in current tab.


Copies item in the row to clipboard.

Additionally, moves selected item to top depending on settings.


Copies next item from current tab to clipboard.


Copies previous item from current tab to clipboard.


Same as insert(0, ...).

insert(row, text|Item...)

Inserts new items to current tab.

Throws an exception if space for the items cannot be allocated.

remove(row, ...)

Removes items in current tab.

Throws an exception if some items cannot be removed.


Moves selected items to given row in same tab.

edit([row|text] ...)

Edits items in current tab.

Opens external editor if set, otherwise opens internal editor.

ByteArray read([mimeType])

Same as clipboard().

ByteArray read(mimeType, row, ...)

Returns concatenated data from items, or clipboard if row is negative.

Pass argument "?" to list available MIME types.

write(row, mimeType, data, [mimeType, data]...)

Inserts new item to current tab.

Throws an exception if space for the items cannot be allocated.

write(row, Item...)

Function override with one or more item arguments.

write(row, Item[])

Function override with item list argument.

change(row, mimeType, data, [mimeType, data]...)

Changes data in item in current tab.

If data is undefined the format is removed from item.

change(row, Item...)

Function override with one or more item arguments.

change(row, Item[])

Function override with item list argument.

String separator()

Returns item separator (used when concatenating item data).


Sets item separator for concatenating item data.


Opens action dialog.

action(row, ..., command, outputItemSeparator)

Runs command for items in current tab.

Shows popup message for given time in milliseconds.

If time argument is set to -1, the popup is hidden only after mouse click.


Shows popup message with icon and buttons.

Each button can have script and data.

If button is clicked the notification is hidden and script is executed with the data passed as stdin.

The function returns immediately (doesn’t wait on user input).

Special arguments:

  • ‘.title’ - notification title
  • ‘.message’ - notification message (can contain basic HTML)
  • ‘.icon’ - notification icon (path to image or font icon)
  • ‘.id’ - notification ID - this replaces notification with same ID
  • ‘.time’ - duration of notification in milliseconds (default is -1, i.e. waits for mouse click)
  • ‘.button’ - adds button (three arguments: name, script and data)


      '.title', 'Example',
      '.message', 'Notification with button',
      '.button', 'Cancel', '', '',
      '.button', 'OK', 'copyq:popup(input())', 'OK Clicked'

Exports current tab into file.

Throws an exception if export fails.


Imports items from file to a new tab.

Throws an exception if import fails.


Exports all tabs and configuration into file.

Throws an exception if export fails.


Imports all tabs and configuration from file.

Throws an exception if import fails.

String config()

Returns help with list of available application options.

Users can change most of these options via the CopyQ GUI, mainly via the “Preferences” window.

These options are persisted within the [Options] section of a corresponding copyq.ini or copyq.conf file (copyq.ini is used on Windows).

String config(optionName)

Returns value of given application option.

Throws an exception if the option is invalid.

String config(optionName, value)

Sets application option and returns new value.

Throws an exception if the option is invalid.

String config(optionName, value, ...)

Sets multiple application options and return list with values in format optionName=newValue.

Throws an exception if there is an invalid option in which case it won’t set any options.

bool toggleConfig(optionName)

Toggles an option (true to false and vice versa) and returns the new value.

String info([pathName])

Returns paths and flags used by the application.

E.g. following command prints path to configuration file:

copyq info config
Value eval(script)

Evaluates script and returns result.

Value source(fileName)

Evaluates script file and returns result of last expression in the script.

This is useful to move some common code out of commands.

// File: c:/copyq/replace_clipboard_text.js
replaceClipboardText = function(replaceWhat, replaceWith)
    var text = str(clipboard())
    var newText = text.replace(replaceWhat, replaceWith)
    if (text != newText)
replaceClipboardText('secret', '*****')

Set current path.

String currentPath()

Get current path.

String str(value)

Converts a value to string.

If ByteArray object is the argument, it assumes UTF8 encoding. To use different encoding, use toUnicode().

ByteArray input()

Returns standard input passed to the script.

String toUnicode(ByteArray, encodingName)

Returns string for bytes with given encoding.

String toUnicode(ByteArray)

Returns string for bytes with encoding detected by checking Byte Order Mark (BOM).

ByteArray fromUnicode(String, encodingName)

Returns encoded text.

ByteArray data(mimeType)

Returns data for automatic commands or selected items.

If run from menu or using non-global shortcut the data are taken from selected items.

If run for automatic command the data are clipboard content.

ByteArray setData(mimeType, data)

Modifies data for data() and new clipboard item.

Next automatic command will get updated data.

This is also the data used to create new item from clipboard.

E.g. following automatic command will add creation time data and tag to new items:

var timeFormat = 'yyyy-MM-dd hh:mm:ss'
setData('application/x-copyq-user-copy-time', dateString(timeFormat))
setData(mimeTags, 'copied: ' + time)

E.g. following menu command will add tag to selected items:

setData('application/x-copyq-tags', 'Important')
ByteArray removeData(mimeType)

Removes data for data() and new clipboard item.

String[] dataFormats()

Returns formats available for data().


Prints value to standard output.


Prints value to application log.

String logs()

Returns application logs.


Aborts script evaluation.


Aborts script evaluation with nonzero exit code.


Focus tab without showing main window.

selectItems(row, ...)

Selects items in current tab.

String selectedTab()

Returns tab that was selected when script was executed.

See Selected Items.

int[] selectedItems()

Returns selected rows in current tab.

See Selected Items.

Item selectedItemData(index)

Returns data for given selected item.

The data can empty if the item was removed during execution of the script.

See Selected Items.

bool setSelectedItemData(index, Item)

Set data for given selected item.

Returns false only if the data cannot be set, usually if item was removed.

See Selected Items.

Item[] selectedItemsData()

Returns data for all selected items.

Some data can be empty if the item was removed during execution of the script.

See Selected Items.


Set data to all selected items.

Some data may not be set if the item was removed during execution of the script.

See Selected Items.

int currentItem(), int index()

Returns current row in current tab.

See Selected Items.

String escapeHtml(text)

Returns text with special HTML characters escaped.

Item unpack(data)

Returns deserialized object from serialized items.

ByteArray pack(Item)

Returns serialized item.

Item getItem(row)

Returns an item in current tab.

setItem(row, text|Item)

Inserts item to current tab.

String toBase64(data)

Returns base64-encoded data.

ByteArray fromBase64(base64String)

Returns base64-decoded data.

ByteArray md5sum(data)

Returns MD5 checksum of data.

ByteArray sha1sum(data)

Returns SHA1 checksum of data.

ByteArray sha256sum(data)

Returns SHA256 checksum of data.

ByteArray sha512sum(data)

Returns SHA512 checksum of data.

bool open(url, ...)

Tries to open URLs in appropriate applications.

Returns true only if all URLs were successfully opened.

FinishedCommand execute(argument, ..., null, stdinData, ...)

Executes a command.

All arguments after null are passed to standard input of the command.

If argument is function it will be called with array of lines read from stdout whenever available.

E.g. create item for each line on stdout:

execute('tail', '-f', 'some_file.log',
        function(lines) { add.apply(this, lines) })

Returns object for the finished command or undefined on failure.

String currentWindowTitle()

Returns window title of currently focused window.

Value dialog(...)

Shows messages or asks user for input.

Arguments are names and associated values.

Special arguments:

  • ‘.title’ - dialog title
  • ‘.icon’ - dialog icon (see below for more info)
  • ‘.style’ - Qt style sheet for dialog
  • ‘.height’, ‘.width’, ‘.x’, ‘.y’ - dialog geometry
  • ‘.label’ - dialog message (can contain basic HTML)
  '.title', 'Command Finished',
  '.label', 'Command <b>successfully</b> finished.'

Other arguments are used to get user input.

var amount = dialog('.title', 'Amount?', 'Enter Amount', 'n/a')
var filePath = dialog('.title', 'File?', 'Choose File', new File('/home'))

If multiple inputs are required, object is returned.

var result = dialog(
  'Enter Amount', 'n/a',
  'Choose File', new File(str(currentPath))
print('Amount: ' + result['Enter Amount'] + '\n')
print('File: ' + result['Choose File'] + '\n')

Editable combo box can be created by passing array. Current value can be provided using .defaultChoice (by default it’s the first item).

var text = dialog('.defaultChoice', '', 'Select', ['a', 'b', 'c'])

List can be created by prefixing name/label with .list: and passing array.

var items = ['a', 'b', 'c']
var selected_index = dialog('.list:Select', items)
if (selected_index)
    print('Selected item: ' + items[selected_index])

Icon for custom dialog can be set from icon font, file path or theme. Icons from icon font can be copied from icon selection dialog in Command dialog or dialog for setting tab icon (in menu ‘Tabs/Change Tab Icon’).

var search = dialog(
  '.title', 'Search',
  '.icon', 'search', // Set icon 'search' from theme.
  'Search', ''

Opens menu with given items and returns selected item or an empty string.

Opens menu with given items and returns index of selected item or -1.

Menu item label is taken from mimeText format an icon is taken from mimeIcon format.

String[] settings()

Returns array with names of all custom user options.

These options can be managed by various commands, much like cookies are used by web applications in a browser. A typical usage is to remember options lastly selected by user in a custom dialog displayed by a command.

These options are persisted within the [General] section of a corresponding copyq-scripts.ini file. But if an option is named like group/..., then it is written to a section named [group] instead. By grouping options like this, we can avoid potential naming collisions with other commands.

Value settings(optionName)

Returns value for a custom user option.

settings(optionName, value)

Sets value for a new custom user option or overrides existing one.

String dateString(format)

Returns text representation of current date and time.

See QDateTime::toString() for details on formatting date and time.


var now = dateString('yyyy-MM-dd HH:mm:ss')
Command[] commands()

Return list of all commands.


Clear previous commands and set new ones.

To add new command:

var cmds = commands()
        name: 'New Command',
        automatic: true,
        input: 'text/plain',
        cmd: 'copyq: popup("Clipboard", input())'
Command[] importCommands(String)

Return list of commands from exported commands text.

String exportCommands(Command[])

Return exported command text.

NetworkReply networkGet(url)

Sends HTTP GET request.

Returns reply.

NetworkReply networkPost(url, postData)

Sends HTTP POST request.

Returns reply.

ByteArray env(name)

Returns value of environment variable with given name.

bool setEnv(name, value)

Sets environment variable with given name to given value.

Returns true only if the variable was set.


Wait for given time in milliseconds.

afterMilliseconds(time, function)

Executes function after given time in milliseconds.

String[] screenNames()

Returns list of available screen names.

ByteArray screenshot(format='png'[, screenName])

Returns image data with screenshot.

Default screenName is name of the screen with mouse cursor.

You can list valid values for screenName with screenNames().


copy('image/png', screenshot())
ByteArray screenshotSelect(format='png'[, screenName])

Same as screenshot() but allows to select an area on screen.

String[] queryKeyboardModifiers()

Returns list of currently pressed keyboard modifiers which can be ‘Ctrl’, ‘Shift’, ‘Alt’, ‘Meta’.

int[] pointerPosition()

Returns current mouse pointer position (x, y coordinates on screen).

setPointerPosition(x, y)

Moves mouse pointer to given coordinates on screen.

Throws an exception if the pointer position couldn’t be set (e.g. unsupported on current the system).

String iconColor()

Get current tray and window icon color name.


Set current tray and window icon color name (e.g. ‘orange’, ‘#ffa500’, ‘#09f’).

Resets color if color name is empty string.

Throws an exception if the color name is empty or invalid.

// Flash icon for few moments to get attention.
var color = iconColor()
for (var i = 0; i < 10; ++i) {
String iconTag()

Get current tray and window tag text.


Set current tray and window tag text.

String iconTagColor()

Get current tray and window tag color name.


Set current tray and window tag color name.

Throws an exception if the color name is invalid.


Loads theme from an INI file.

Throws an exception if the file cannot be read or is not valid INI format.


Called when clipboard or X11 selection changes.

Default implementation is:

if (!hasData()) {
} else if (runAutomaticCommands()) {
} else {

Called when clipboard or X11 selection changes by a CopyQ instance.

Owned clipboard data contains mimeOwner format.

Default implementation calls updateClipboardData().


Called when hidden clipboard or X11 selection changes.

Hidden clipboard data contains mimeHidden format set to 1.

Default implementation calls updateClipboardData().


Called when clipboard or X11 selection changes but data remained the same.

Default implementation does nothing.


Called when application starts.


Called just before application exists.

bool runAutomaticCommands()

Executes automatic commands on current data.

If an executed command calls ignore() or have “Remove Item” or “Transform” check box enabled, following automatic commands won’t be executed and the function returns false. Otherwise true is returned.


Clear clipboard visibility in GUI.

Default implementation is:

if (isClipboard()) {

Update main window title and tool tip from current data.

Called when clipboard changes.


Sets current clipboard data for tray menu, window title and notification.

Default implementation is:

if (isClipboard()) {

Set main window title and tool tip.


Synchronize current data from clipboard to X11 selection.

Called automatically from clipboard monitor process if option copy_clipboard is enabled.

Default implementation calls provideSelection().


Synchronize current data from X11 selection to clipboard.

Called automatically from clipboard monitor process if option copy_selection is enabled.

Default implementation calls provideClipboard().

String[] clipboardFormatsToSave()

Returns list of clipboard format to save automatically.

Override the funtion, for example, to save only plain text:

global.clipboardFormatsToSave = function() {
    return ["text/plain"]

Or to save additional formats:

var originalFunction = global.clipboardFormatsToSave;
global.clipboardFormatsToSave = function() {
    return originalFunction().concat([

Save current data (depends on mimeOutputTab).

bool hasData()

Returns true only if some non-empty data can be returned by data().

Empty data is combination of whitespace and null characters or some internal formats (mimeWindowTitle, mimeClipboardMode etc.)


Show notification for current data.


Hide notification for current data.


Sets clipboard data for menu commands.


class ByteArray()

Wrapper for QByteArray Qt class.

See QByteArray.

ByteArray is used to store all item data (image data, HTML and even plain text).

Use str() to convert it to string. Strings are usually more versatile. For example to concatenate two items, the data need to be converted to strings first.

var text = str(read(0)) + str(read(1))
class File()

Wrapper for QFile Qt class.

See QFile.

To open file in different modes use:

  • open() - read/write
  • openReadOnly() - read only
  • openWriteOnly() - write only, truncates the file
  • openAppend() - write only, appends to the file

Following code reads contents of “” file from current directory:

var f = new File('')
if (!f.openReadOnly())
  throw 'Failed to open the file: ' + f.errorString()
var bytes = f.readAll()

Following code writes to a file in home directory:

var dataToWrite = 'Hello, World!'
var filePath = Dir().homePath() + '/copyq.txt'
var f = new File(filePath)
if (!f.openWriteOnly() || f.write(dataToWrite) == -1)
  throw 'Failed to save the file: ' + f.errorString()

// Always flush the data and close the file,
// before opening the file in other application.
class Dir()

Wrapper for QDir Qt class.

Use forward slash as path separator, e.g. “D:/Documents/”.

See QDir.

class TemporaryFile()

Wrapper for QTemporaryFile Qt class.

See QTemporaryFile.

var f = new TemporaryFile()
popup('New temporary file', f.fileName())

To open file in different modes, use same open methods as for File.

class Item(Object)

Object with MIME types of an item.

Each property is MIME type with data.


var item = {}
item[mimeText] = 'Hello, World!'
item[mimeHtml] = '<p>Hello, World!</p>'
write(mimeItems, pack(item))
class FinishedCommand(Object)

Properties of finished command.

Properties are:

  • stdout - standard output
  • stderr - standard error output
  • exit_code - exit code
class NetworkReply(Object)

Received network reply object.

Properties are:

  • data - reply data
  • error - error string (set only if an error occurred)
  • redirect - URL for redirection (set only if redirection is needed)
  • headers - reply headers (array of pairs with header name and header content)
class Command(Object)

Wrapper for a command (from Command dialog).

Properties are same as members of Command struct.



Array for accessing arguments passed to current function or the script (arguments[0] is the script itself).


Object allowing to modify global scope which contains all functions like copy() or add(). This is useful for Script Commands.

MIME Types

Item and clipboard can provide multiple formats for their data. Type of the data is determined by MIME type.

Here is list of some common and builtin (start with application/x-copyq-) MIME types.

These MIME types values are assigned to global variables prefixed with mime.


Content for following types is UTF-8 encoded.


Data contains plain text content.


Data contains HTML content.


Data contains list of links to files, web pages etc.


Current window title for copied clipboard.


Serialized items.


Data contains notes for item.


Data contains icon for item.


If available, the clipboard was set from CopyQ (from script or copied items).

Such clipboard is ignored in CopyQ, i.e. it won’t be stored in clipboard tab and automatic commands won’t be executed on it.


Contains selection if data is from X11 mouse selection.


Current tab name when invoking command from main window.

Following command print the tab name when invoked from main window:

copyq data application/x-copyq-current-tab
copyq selectedTab

Selected items when invoking command from main window.


Current item when invoking command from main window.


If set to 1, the clipboard or item content will be hidden in GUI.

This won’t hide notes and tags.

E.g. if you run following, window title and tool tip will be cleared:

copyq copy application/x-copyq-hidden 1 plain/text "This is secret"

Application or global shortcut which activated the command.

var shortcut = data(mimeShortcut)
popup("Shortcut Pressed", shortcut)

Item color (same as the one used by themes).

Examples: #ffff00 rgba(255,255,0,0.5) bg - #000099


Name of the tab where to store new item.

The clipboard data will be stored in tab with this name after all automatic commands are run.

Clear or remove the format to omit storing the data.

E.g. to omit storing the clipboard data use following in an automatic command:


Valid only in automatic commands.

Selected Items

Functions that get and set data for selected items and current tab are only available if called from Action dialog or from a command which is in menu.

Selected items are indexed from top to bottom as they appeared in the current tab at the time the command is executed.


Use plugins object to access functionality of plugins.


Returns synchronization path for current tab (mimeCurrentTab).

var path = plugins.itemsync.selectedTabPath()
var baseName = str(data(plugins.itemsync.mimeBaseName))
var absoluteFilePath = Dir(path).absoluteFilePath(baseName)
// NOTE: Known file suffix/extension can be missing in the full path.
class plugins.itemsync.tabPaths(Object)

Object that maps tab name to synchronization path.

var tabName = 'Downloads'
var path = plugins.itemsync.tabPaths[tabName]

MIME type for accessing base name (without full path).

Known file suffix/extension can be missing in the base name.


List of user-defined tags.

plugins.itemtags.tags(row, ...)

List of tags for items in given rows.

plugins.itemtags.tag(tagName[, rows, ...])

Add given tag to items in given rows or selected items.

See Selected Items.

plugins.itemtags.untag(tagName[, rows, ...])

Remove given tag from items in given rows or selected items.

See Selected Items.

plugins.itemtags.clearTags([rows, ...])

Remove all tags from items in given rows or selected items.

See Selected Items.

plugins.itemtags.hasTag(tagName[, rows, ...])

Return true if given tag is present in any of items in given rows or selected items.

See Selected Items.


MIME type for accessing list of tags.

Tags are separated by comma.

plugins.itempinned.isPinned(rows, ...)

Returns true only if any item in given rows is pinned., ...)

Pin items in given rows or selected items or new item created from clipboard (if called from automatic command).

plugins.itempinned.unpin(rows, ...)

Unpin items in given rows or selected items.