Scripting API

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

Supported language features and base function can be found at ECMAScript Reference. The language is mostly equivalent to modern JavaScript. Some features may be missing but feel free to use for example JavaScript reference on MDN.

CopyQ-specific features described in this document:

Bemerkung

These terms are equivalent: format, MIME type, media type

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

copyq <FUNCTION1> <FUNCTION1_ARGUMENT_1> <FUNCTION1_ARGUMENT_2> \
          <FUNCTION2> <FUNCTION2_ARGUMENT> \
              <FUNCTION3> <FUNCTION3_ARGUMENTS> ...

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

Example:

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).

Functions

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

Comment /*set*/ in function declaration indicates a specific function overload.

Item row values in scripts always start from 0 (like array index), unlike in GUI, where row numbers start from 1 by default.

version()

Returns version string.

Rückgabe:

Version string.

Rückgabetyp:

string

Example of the version string:

CopyQ Clipboard Manager v4.0.0-19-g93d95a7f
Qt: 5.15.2
KNotifications: 5.79.0
Compiler: GCC
Arch: x86_64-little_endian-lp64
OS: Fedora 33 (Workstation Edition)
help()

Returns help string.

Rückgabe:

Help string.

Rückgabetyp:

string

/*search*/ help(searchString, ...)

Returns help for matched commands.

Rückgabe:

Help string.

Rückgabetyp:

string

show()

Shows main window.

This uses the last window position and size which is updated whenever the window is moved or resized.

/*tab*/ show(tabName)

Shows tab.

This uses the last window position and size which is updated whenever the window is moved or resized.

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

Shows main window with given geometry.

The new window position and size will not be stored for show().

/*cursor*/ showAt()

Shows main window under mouse cursor.

The new window position will not be stored for show().

/*tab*/ showAt(x, y, width, height, tabName)

Shows tab with given geometry.

The new window position and size will not be stored for show().

hide()

Hides main window.

toggle()

Shows or hides main window.

This uses the last window position and size which is updated whenever the window is moved or resized.

Rückgabe:

true only if main window is being shown, otherwise false.

Rückgabetyp:

bool

Opens context menu.

/*tab*/ 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.

exit()

Exits server.

disable()
enable()

Disables or enables clipboard content storing.

monitoring()

Returns true only if clipboard storing is enabled.

Rückgabe:

true if clipboard storing is enabled, otherwise false.

Rückgabetyp:

bool

visible()

Returns true only if main window is visible.

Rückgabe:

true if main window is visible, otherwise false.

Rückgabetyp:

bool

focused()

Returns true only if main window has focus.

Rückgabe:

true if main window has focus, otherwise false.

Rückgabetyp:

bool

focusPrevious()

Activates window that was focused before the main window.

Wirft:

Error() – Thrown if previous window cannot be activated.

preview([true|false])

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

Example – toggle the preview:

preview(false) || preview(true)
filter()

Returns the current text for filtering items in main window.

Rückgabe:

Current filter.

Rückgabetyp:

string

/*set*/ filter(filterText)

Sets text for filtering items in main window.

ignore()

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.

clipboard([mimeType])

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

Pass argument "?" to list available MIME types.

Rückgabe:

Clipboard data.

Rückgabetyp:

ByteArray()

selection([mimeType])

Same as clipboard() for Linux mouse selection.

Rückgabe:

Selection data.

Rückgabetyp:

ByteArray()

hasClipboardFormat(mimeType)

Returns true only if clipboard contains MIME type.

Rückgabe:

true if clipboard contains the format, otherwise false.

Rückgabetyp:

bool

hasSelectionFormat(mimeType)

Same as hasClipboardFormat() for Linux mouse selection.

Rückgabe:

true if selection contains the format, otherwise false.

Rückgabetyp:

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 mouse selection change.

Rückgabe:

true if current automatic command is triggered by clipboard change, otherwise false.

Rückgabetyp:

bool

copy(text)

Sets clipboard plain text.

Same as copy(mimeText, text).

Wirft:

Error() – Thrown if clipboard fails to be set.

/*data*/ 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.

All other data formats are dropped from clipboard.

Wirft:

Error() – Thrown if clipboard fails to be set.

Example – set both text and rich text:

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

Function override with an item argument.

Wirft:

Error() – Thrown if clipboard fails to be set.

Example – set both text and rich text:

var item = {}
item[mimeText] = 'Hello, World!'
item[mimeHtml] = '<p>Hello, World!</p>'
copy(item)
/*window*/ copy()

Sends Ctrl+C to current window.

Wirft:

Error() – Thrown if clipboard doesn’t change (clipboard is reset before sending the shortcut).

Example:

try {
    copy(arguments)
} catch (e) {
    // Coping failed!
    popup('Coping Failed', e)
    abort()
}
var text = str(clipboard())
popup('Copied Text', text)
copySelection(...)

Same as copy() for Linux mouse selection.

There is no copySelection() without parameters.

Wirft:

Error() – Thrown if selection fails to be set.

paste()

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.

Wirft:

Error() – Thrown if paste operation fails.

Example:

try {
    paste()
} catch (e) {
    // Pasting failed!
    popup('Pasting Failed', e)
    abort()
}
popup('Pasting Successful')
tab()

Returns tab names.

Rückgabe:

Array with names of existing tab.

Rückgabetyp:

array of strings

/*set*/ tab(tabName)

Sets current tab for the script.

Example – select third item at index 2 from tab „Notes“:

tab('Notes')
select(2)
removeTab(tabName)

Removes tab.

renameTab(tabName, newTabName)

Renames tab.

tabIcon(tabName)

Returns path to icon for tab.

Rückgabe:

Path to icon for tab.

Rückgabetyp:

string

/*set*/ tabIcon(tabName, iconPath)

Sets icon for tab.

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.

Rückgabe:

Array of successfully unloaded tabs.

Rückgabetyp:

array of strings

forceUnload([tabNames...])

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.

Rückgabe:

Item count.

Rückgabetyp:

int

select(row)

Copies item in the row to clipboard.

Additionally, moves selected item to top depending on settings.

next()

Copies next item from current tab to clipboard.

previous()

Copies previous item from current tab to clipboard.

add(text|Item...)

Same as insert(0, ...).

insert(row, text|Item...)

Inserts new items to current tab.

Wirft:

Error() – Thrown if space for the items cannot be allocated.

remove(row, ...)

Removes items in current tab.

Wirft:

Error() – Thrown if some items cannot be removed.

move(row)

Moves selected items to given row in same tab.

edit([row|text] ...)

Edits items in the current tab.

Opens external editor if set, otherwise opens internal editor.

If row is -1 (or other negative number) edits clipboard instead and creates new item.

editItem(row[, mimeType[, data]])

Edits specific format for the item.

Opens external editor if set, otherwise opens internal editor.

If row is -1 (or other negative number) edits clipboard instead and creates new item.

read([mimeType])

Same as clipboard().

/*row*/ read(mimeType, row, ...)

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

Pass argument "?" to list available MIME types.

Rückgabe:

Concatenated data in the rows.

Rückgabetyp:

ByteArray()

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

Inserts new item to current tab.

Wirft:

Error() – Thrown if space for the items cannot be allocated.

/*item*/ write(row, Item...)

Function override with one or more item arguments.

/*items*/ 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.

/*item*/ change(row, Item...)

Function override with one or more item arguments.

/*items*/ change(row, Item[])

Function override with item list argument.

separator()

Returns item separator (used when concatenating item data).

Rückgabe:

Current separator.

Rückgabetyp:

string

/*set*/ separator(separator)

Sets item separator for concatenating item data.

action()

Opens action dialog.

/*row*/ action([rows, ..., ]command[, outputItemSeparator])

Runs command for items in current tab.

If rows arguments is specified, %1 in the command will be replaced with concatenated text of the rows.

If no rows are specified, %1 in the command will be replaced with clipboard text.

The concatenated text (if rows are defined) or clipboard text is also passed on standard input of the command.

Shows popup message for given time in milliseconds.

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

notification(...)

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)

Example:

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

Exports current tab into file.

Wirft:

Error() – Thrown if export fails.

importTab(fileName)

Imports items from file to a new tab.

Wirft:

Error() – Thrown if import fails.

exportData(fileName)

Exports all tabs and configuration into file.

Wirft:

Error() – Thrown if export fails.

importData(fileName)

Imports all tabs and configuration from file.

Wirft:

Error() – Thrown if import fails.

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).

Rückgabe:

Available options.

Rückgabetyp:

string

/*get*/ config(optionName)

Returns value of given application option.

Rückgabe:

Current value of the option.

Rückgabetyp:

string

Wirft:

Error() – Thrown if the option is invalid.

/*set*/ config(optionName, value)

Sets application option and returns new value.

Rückgabe:

New value of the option.

Rückgabetyp:

string

Wirft:

Error() – Thrown if the option is invalid.

/*set-more*/ config(optionName, value, ...)

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

Rückgabe:

New values of the options.

Rückgabetyp:

string

Wirft:

Error() – Thrown if there is an invalid option in which case it won’t set any options.

toggleConfig(optionName)

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

Rückgabe:

New value of the option.

Rückgabetyp:

bool

info([pathName])

Returns paths and flags used by the application.

Rückgabe:

Path for given identifier.

Rückgabetyp:

string

Example – print path to the configuration file:

info('config')
eval(script)

Evaluates script and returns result.

Rückgabe:

Result of the last expression.

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.

Rückgabe:

Result of the last expression.

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

Get current path.

Rückgabe:

Current path.

Rückgabetyp:

string

cd /tmp
copyq currentPath
# Prints: /tmp
/*set*/ currentPath(path)

Set current path.

str(value)

Converts a value to string.

If ByteArray object is the argument, it assumes UTF8 encoding. To use different encoding, use :js:func`toUnicode`.

Rückgabe:

Value as string.

Rückgabetyp:

string

input()

Returns standard input passed to the script.

Rückgabe:

Data on stdin.

Rückgabetyp:

ByteArray()

toUnicode(ByteArray)

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

Rückgabe:

Value as string.

Rückgabetyp:

string

/*encoding*/ toUnicode(ByteArray, encodingName)

Returns string for bytes with given encoding.

Rückgabe:

Value as string.

Rückgabetyp:

string

fromUnicode(String, encodingName)

Returns encoded text.

Rückgabe:

Value as ByteArray.

Rückgabetyp:

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.

Rückgabe:

Data for the format.

Rückgabetyp:

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.

Rückgabe:

true if data were set, false if parsing data failed (in case of mimeItems).

Rückgabetyp:

bool

Example – automatic command that adds a creation time data and tag to new items:

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

Example – menu command that adds a tag to selected items:

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

Removes data for data() and new clipboard item.

dataFormats()

Returns formats available for data().

Rückgabe:

Array of data formats.

Rückgabetyp:

array of strings

print(value)

Prints value to standard output.

serverLog(value)

Prints value to application log.

logs()

Returns application logs.

Rückgabe:

Application logs.

Rückgabetyp:

string

abort()

Aborts script evaluation.

fail()

Aborts script evaluation with nonzero exit code.

setCurrentTab(tabName)

Focus tab without showing main window.

selectItems(row, ...)

Selects items in current tab.

selectedTab()

Returns tab that was selected when script was executed.

Rückgabe:

Currently selected tab name (see Selected Items).

Rückgabetyp:

string

selectedItems()

Returns selected rows in current tab.

Rückgabe:

Currently selected rows (see Selected Items).

Rückgabetyp:

array of ints

selectedItemData(index)

Returns data for given selected item.

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

Rückgabe:

Currently selected items (see Selected Items).

Rückgabetyp:

array of Item()

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.

Rückgabe:

true if data were set, otherwise false.

Rückgabetyp:

bool

selectedItemsData()

Returns data for all selected items.

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

Rückgabe:

Currently selected item data (see Selected Items).

Rückgabetyp:

array of Item()

setSelectedItemsData(Item[])

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.

currentItem()
index()

Returns current row in current tab.

See Selected Items.

Rückgabe:

Current row (see Selected Items).

Rückgabetyp:

int

escapeHtml(text)

Returns text with special HTML characters escaped.

Rückgabe:

Escaped HTML text.

Rückgabetyp:

string

unpack(data)

Returns deserialized object from serialized items.

Rückgabe:

Deserialize item.

Rückgabetyp:

Item()

pack(Item)

Returns serialized item.

Rückgabe:

Serialize item.

Rückgabetyp:

ByteArray()

getItem(row)

Returns an item in current tab.

Rückgabe:

Item data for the row.

Rückgabetyp:

Item()

Example – show data of the first item in a tab in popups:

tab('work')  // change current tab for the script to 'work'
var item = getItem(0)
for (var format in item) {
    var data = item[format]
    popup(format, data)
}

Siehe auch

setItem(row, text|Item)

Inserts item to current tab.

Same as insert(row, something).

toBase64(data)

Returns base64-encoded data.

Rückgabe:

Base64-encoded data.

Rückgabetyp:

string

fromBase64(base64String)

Returns base64-decoded data.

Rückgabe:

Base64-decoded data.

Rückgabetyp:

ByteArray()

md5sum(data)

Returns MD5 checksum of data.

Rückgabe:

MD5 checksum of the data.

Rückgabetyp:

ByteArray()

sha1sum(data)

Returns SHA1 checksum of data.

Rückgabe:

SHA1 checksum of the data.

Rückgabetyp:

ByteArray()

sha256sum(data)

Returns SHA256 checksum of data.

Rückgabe:

SHA256 checksum of the data.

Rückgabetyp:

ByteArray()

sha512sum(data)

Returns SHA512 checksum of data.

Rückgabe:

SHA512 checksum of the data.

Rückgabetyp:

ByteArray()

open(url, ...)

Tries to open URLs in appropriate applications.

Rückgabe:

true if all URLs were successfully opened, otherwise false.

Rückgabetyp:

bool

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.

An exception is thrown if executable was not found or could not be executed.

Rückgabe:

Finished command properties.

Rückgabetyp:

FinishedCommand()

Example – 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.

Rückgabe:

Current window title.

Rückgabetyp:

string

String currentClipboardOwner()

Returns name of the current clipboard owner.

The default implementation returns currentWindowTitle().

This is used to set mimeWindowTitle format for the clipboard data in automatic commands and filtering by window title.

Depending on the current system, option update_clipboard_owner_delay_ms can introduce a delay before any new owner value return by this function is used. The reason is to avoid using an incorrect clipboard owner from the current window title if the real clipboard owner set the clipboard after or just before hiding its window (like with some password managers).

Rückgabe:

Current clipboard owner name.

Rückgabetyp:

string

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)

Rückgabe:

Value or values from accepted dialog or undefined if dialog was canceled.

dialog(
  '.title', 'Command Finished',
  '.label', 'Command <b>successfully</b> finished.'
  )

Accepting a dialog containing only a question returns true (rejecting/cancelling the dialog returns undefined).

const remove = dialog(
  '.title', 'Remove Items',
  '.label', 'Do you really want to remove all items?'
  )
if (!remove)
    abort();

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')

A combo box with an editable custom text/value can be created by passing an array argument. The default text can be provided using .defaultChoice (by default it’s the first item).

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

A combo box with non-editable text can be created by prefixing the label argument with .combo:.

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

An item list can be created by prefixing the label argument with .list:.

var items = ['a', 'b', 'c']
var selected_index = dialog('.list:Select', items)
if (selected_index !== undefined)
    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.

Rückgabe:

Selected item or empty string if menu was canceled.

Rückgabetyp:

string

var selectedText = menuItems('x', 'y', 'z')
if (selectedText)
    popup('Selected', selectedText)
/*items*/ menuItems(items[])

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.

Rückgabe:

Selected item index or -1 if menu was canceled.

Rückgabetyp:

int

var items = selectedItemsData()
var selectedIndex = menuItems(items)
if (selectedIndex != -1)
    popup('Selected', items[selectedIndex][mimeText])
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.

Rückgabe:

Available custom options.

Rückgabetyp:

array of strings

/*get*/ Value settings(optionName)

Returns value for a custom user option.

Rückgabe:

Current value of the custom options, undefined if the option was not set.

/*set*/ settings(optionName, value)

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

dateString(format)

Returns text representation of current date and time.

See Date QML Type for details on formatting date and time.

Rückgabe:

Current date and time as string.

Rückgabetyp:

string

Example:

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

Return list of all commands.

Rückgabe:

Array of all commands.

Rückgabetyp:

array of Command()

setCommands(Command[])

Clear previous commands and set new ones.

To add new command:

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

Return list of commands from exported commands text.

Rückgabe:

Array of commands loaded from a file path.

Rückgabetyp:

array of Command()

String exportCommands(Command[])

Return exported command text.

Rückgabe:

Serialized commands.

Rückgabetyp:

string

addCommands(Command[])

Opens Command dialog, adds commands and waits for user to confirm the dialog.

NetworkReply networkGet(url)

Sends HTTP GET request.

Rückgabe:

HTTP reply.

Rückgabetyp:

NetworkReply()

NetworkReply networkPost(url, postData)

Sends HTTP POST request.

Rückgabe:

HTTP reply.

Rückgabetyp:

NetworkReply()

NetworkReply networkGetAsync(url)

Same as networkGet() but the request is asynchronous.

The request is handled asynchronously and may not be finished until you get a property of the reply.

Rückgabe:

HTTP reply.

Rückgabetyp:

NetworkReply()

NetworkReply networkPostAsync(url, postData)

Same as networkPost() but the request is asynchronous.

The request is handled asynchronously and may not be finished until you get a property of the reply.

Rückgabe:

HTTP reply.

Rückgabetyp:

NetworkReply()

env(name)

Returns value of environment variable with given name.

Rückgabe:

Value of the environment variable.

Rückgabetyp:

ByteArray()

setEnv(name, value)

Sets environment variable with given name to given value.

Rückgabe:

true if the variable was set, otherwise false.

Rückgabetyp:

bool

sleep(time)

Wait for given time in milliseconds.

afterMilliseconds(time, function)

Executes function after given time in milliseconds.

screenNames()

Returns list of available screen names.

Rückgabe:

Available screen names.

Rückgabetyp:

array of strings

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().

Rückgabe:

Image data.

Rückgabetyp:

ByteArray()

Example:

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

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

Rückgabe:

Image data.

Rückgabetyp:

ByteArray()

queryKeyboardModifiers()

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

Rückgabe:

Currently pressed keyboard modifiers.

Rückgabetyp:

array of strings

pointerPosition()

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

Rückgabe:

Current mouse pointer coordinates.

Rückgabetyp:

array of ints (with two elements)

setPointerPosition(x, y)

Moves mouse pointer to given coordinates on screen.

Wirft:

Error() – Thrown if the pointer position couldn’t be set (for example, unsupported on current the system).

iconColor()

Get current tray and window icon color name.

Rückgabe:

Current icon color.

Rückgabetyp:

string

/*set*/ iconColor(colorName)

Set current tray and window icon color name (examples: ‚orange‘, ‚#ffa500‘, ‚#09f‘).

Resets color if color name is empty string.

Wirft:

Error() – Thrown 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) {
  iconColor("red")
  sleep(500)
  iconColor(color)
  sleep(500)
}

Siehe auch

mimeColor

iconTag()

Get current tray and window icon tag text.

Rückgabe:

Current icon tag.

Rückgabetyp:

string

/*set*/ iconTag(tag)

Set current tray and window tag text.

iconTagColor()

Get current tray and window tag color name.

Rückgabe:

Current icon tag color.

Rückgabetyp:

string

/*set*/ iconTagColor(colorName)

Set current tray and window tag color name.

Wirft:

Error() – Thrown if the color name is invalid.

loadTheme(path)

Loads theme from an INI file.

Wirft:

Error() – Thrown if the file cannot be read or is not valid INI format.

onClipboardChanged()

Called when clipboard or Linux mouse selection changes and is not set by CopyQ, is not marked as hidden nor secret (see the other callbacks).

Default implementation is:

if (!hasData()) {
    updateClipboardData();
} else if (runAutomaticCommands()) {
    saveData();
    updateClipboardData();
} else {
    clearClipboardData();
}
onOwnClipboardChanged()

Called when clipboard or Linux mouse selection is set by CopyQ and is not marked as hidden nor secret (see the other callbacks).

Owned clipboard data contains mimeOwner format.

Default implementation calls updateClipboardData().

onHiddenClipboardChanged()

Called when clipboard or Linux mouse selection changes and is marked as hidden but not secret (see the other callbacks).

Hidden clipboard data contains mimeHidden format set to 1.

Default implementation calls updateClipboardData().

onSecretClipboardChanged()

Called if the clipboard or Linux mouse selection changes and contains a password or other secret (for example, copied from clipboard manager).

The default implementation clears all data, so they are not accessible using data() and dataFormats(), except mimeSecret, and calls updateClipboardData().

Be careful overriding this function (via a Script command). Calling onClipboardChanged() without clearing the data and without any further checks can cause storing and processing secrets from password managers. On the other hand, it can help to get access to the data copied, for example from a web browser in private mode.

onClipboardUnchanged()

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

Default implementation does nothing.

onStart()

Called when application starts.

onExit()

Called just before application exists.

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.

Rückgabe:

true if clipboard data should be stored, otherwise false.

Rückgabetyp:

bool

clearClipboardData()

Clear clipboard visibility in GUI.

Default implementation is:

if (isClipboard()) {
    setTitle();
    hideDataNotification();
}
updateTitle()

Update main window title and tool tip from current data.

Called when clipboard changes.

updateClipboardData()

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

Default implementation is:

if (isClipboard()) {
    updateTitle();
    showDataNotification();
    setClipboardData();
}
setTitle([title])

Set main window title and tool tip.

synchronizeToSelection(text)

Synchronize current data from clipboard to Linux mouse selection.

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

Default implementation calls provideSelection().

synchronizeFromSelection(text)

Synchronize current data from Linux mouse selection to clipboard.

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

Default implementation calls provideClipboard().

clipboardFormatsToSave()

Returns list of clipboard format to save automatically.

Rückgabe:

Formats to get and save automatically from clipboard.

Rückgabetyp:

array of strings

Override the function, 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([
        "text/uri-list",
        "text/xml"
    ])
}
saveData()

Save current data (depends on mimeOutputTab).

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.)

Rückgabe:

true if there are some data, otherwise false.

Rückgabetyp:

bool

showDataNotification()

Show notification for current data.

hideDataNotification()

Hide notification for current data.

setClipboardData()

Sets clipboard data for menu commands.

styles()

List available styles for style option.

Rückgabe:

Style identifiers.

Rückgabetyp:

array of strings

To change or update style use:

config("style", styleName)
onItemsAdded()

Called when items are added to a tab.

The target tab is returned by selectedTab().

The new items can be accessed with selectedItemsData(), selectedItemData(), selectedItems() and ItemSelection().current().

onItemsRemoved()

Called when items are being removed from a tab.

The target tab is returned by selectedTab().

The items scheduled for removal can be accessed with selectedItemsData(), selectedItemData(), selectedItems() and ItemSelection().current().

If the exit code is non-zero (for example fail() is called), items will not be removed. But this can also cause a new items not to be added if the tab is full.

onItemsChanged()

Called when data in items change.

The target tab is returned by selectedTab().

The modified items can be accessed with selectedItemsData(), selectedItemData(), selectedItems() and ItemSelection().current().

onTabSelected()

Called when another tab is opened.

The newly selected tab is returned by selectedTab().

The changed items can be accessed with selectedItemsData(), selectedItemData(), selectedItems() and ItemSelection().current().

onItemsLoaded()

Called when all items are loaded into a tab.

The target tab is returned by selectedTab().

Types

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 „README.md“ file from current directory:

var f = new File('README.md')
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.
f.close()
class Dir()

Wrapper for QDir Qt class.

Use forward slash as path separator, for example „D:/Documents/“.

See QDir.

class TemporaryFile()

Wrapper for QTemporaryFile Qt class.

See QTemporaryFile.

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

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

class Settings()

Reads and writes INI configuration files. Wrapper for QSettings Qt class.

See QSettings.

// Open INI file
var configPath = Dir().homePath() + '/copyq.ini'
var settings = new Settings(configPath)

// Save an option
settings.setValue('option1', 'test')

// Store changes to the config file now instead of at the end of
// executing the script
settings.sync()

// Read the option value
var value = settings.value('option1')

Working with arrays:

// Write array
var settings = new Settings(configPath)
settings.beginWriteArray('array1')
settings.setArrayIndex(0)
settings.setValue('some_option', 1)
settings.setArrayIndex(1)
settings.setValue('some_option', 2)
settings.endArray()
settings.sync()

// Read array
var settings = new Settings(configPath)
const arraySize = settings.beginReadArray('array1')
for (var i = 0; i < arraySize; i++) {
    settings.setArrayIndex(i);
    print('Index ' + i + ': ' + settings.value('some_option') + '\n')
}
class Item()

Object with MIME types of an item.

Each property is MIME type with data.

Example:

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

List of items from given tab.

An item in the list represents the same item in tab even if it is moved to a different row.

New items in the tab are not added automatically into the selection.

To create new empty selection use ItemSelection() then add items with select*() methods.

Example - move matching items to the top of the tab:

ItemSelection().select(/^prefix/).move(0)

Example - remove all items from given tab but keep pinned items:

ItemSelection(tabName).selectRemovable().removeAll();

Example - modify items containing „needle“ text:

var sel = ItemSelection().select(/needle/, mimeText);
for (var index = 0; index < sel.length; ++index) {
    var item = sel.itemAtIndex(index);
    item[mimeItemNotes] = 'Contains needle';
    sel.setItemAtIndex(index, item);
}

Example - selection with new items only:

var sel = ItemSelection().selectAll()
add("New Item 1")
add("New Item 2")
sel.invert()
sel.items();

Example - sort items alphabetically:

var sel = ItemSelection().selectAll();
const texts = sel.itemsFormat(mimeText);
sel.sort(function(i,j){
    return texts[i] < texts[j];
});
ItemSelection.tab

Tab name

ItemSelection.length

Number of filtered items in the selection

ItemSelection.selectAll()

Select all items in the tab.

Rückgabe:

self

Rückgabetyp:

ItemSelection

ItemSelection.select(regexp[, mimeType])

Select additional items matching the regular expression.

If regexp is a valid regular expression and mimeType is not set, this selects items with matching text.

If regexp matches empty strings and mimeType is set, this selects items containing the MIME type.

If regexp is undefined and mimeType is set, this select items not containing the MIME type.

Rückgabe:

self

Rückgabetyp:

ItemSelection

ItemSelection.selectRemovable()

Select only items that can be removed.

Rückgabe:

self

Rückgabetyp:

ItemSelection

ItemSelection.invert()

Select only items not in the selection.

Rückgabe:

self

Rückgabetyp:

ItemSelection

ItemSelection.deselectIndexes(int[])

Deselect items at given indexes in the selection.

Rückgabe:

self

Rückgabetyp:

ItemSelection

ItemSelection.deselectSelection(ItemSelection)

Deselect items in other selection.

Rückgabe:

self

Rückgabetyp:

ItemSelection

ItemSelection.current()

Deselects all and selects only the items which were selected when the command was triggered.

See Selected Items.

Rückgabe:

self

Rückgabetyp:

ItemSelection

ItemSelection.removeAll()

Delete all items in the selection (if possible).

Rückgabe:

self

Rückgabetyp:

ItemSelection

ItemSelection.move(row)

Move all items in the selection to the target row.

Rückgabe:

self

Rückgabetyp:

ItemSelection

ItemSelection.sort(row)

Sort items with a comparison function.

The comparison function takes two arguments, indexes to the selection, and returns true only if the item in the selection under the first index should be sorted above the item under the second index.

Items will be reordered in the tab and in the selection object.

Rückgabe:

self

Rückgabetyp:

ItemSelection

ItemSelection.copy()

Clone the selection object.

Rückgabe:

cloned object

Rückgabetyp:

ItemSelection

ItemSelection.rows()

Returns selected rows.

Rückgabe:

Selected rows

Rückgabetyp:

array of ints

ItemSelection.itemAtIndex(index)

Returns item data at given index in the selection.

Rückgabe:

Item data

Rückgabetyp:

Item()

ItemSelection.setItemAtIndex(index, Item)

Sets data to the item at given index in the selection.

Rückgabe:

self

Rückgabetyp:

ItemSelection

ItemSelection.items()

Return list of data from selected items.

Rückgabe:

Selected item data

Rückgabetyp:

array of Item()

ItemSelection.setItems(Item[])

Set data for selected items.

Rückgabe:

self

Rückgabetyp:

ItemSelection

ItemSelection.itemsFormat(mimeType)

Return list of data from selected items containing specified MIME type.

Rückgabe:

Selected item data containing only the format

Rückgabetyp:

array of Item()

ItemSelection.setItemsFormat(mimeType, data)

Set data for given MIME type for the selected items.

Rückgabe:

self

Rückgabetyp:

ItemSelection

class FinishedCommand()

Properties of finished command.

FinishedCommand.stdout

Standard output

FinishedCommand.stderr

Standard error output

FinishedCommand.exit_code

Exit code

class NetworkReply()

Received network reply object.

NetworkReply.data

Reply data

NetworkReply.status

HTTP status

NetworkReply.error``

Error string (set only if an error occurred)

NetworkReply.redirect

URL for redirection (set only if redirection is needed)

NetworkReply.headers

Reply headers (array of pairs with header name and header content)

NetworkReply.finished

True only if request has been completed, false only for unfinished asynchronous requests

class Command()

Wrapper for a command (from Command dialog).

Properties are same as members of Command struct.

Objects

arguments

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

global

Object allowing to modify global scope which contains all functions like copy() or add().

This is useful for Script Commands.

console

Allows some logging and debugging.

// Print a message if COPYQ_LOG_LEVEL=DEBUG
// environment variable is set
console.log(
    'Supported console properties/functions:',
    Object.getOwnPropertyNames(console))
console.warn('Changing clipboard...')

// Elapsed time
console.time('copy')
copy('TEST')
console.timeEnd('copy')

// Ensure a condition is true before continuing
console.assert(str(clipboard()) == 'TEST')

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.

Bemerkung

Content for following types is UTF-8 encoded.

mimeText

Data contains plain text content. Value: ‚text/plain‘.

mimeHtml

Data contains HTML content. Value: ‚text/html‘.

mimeUriList

Data contains list of links to files, web pages etc. Value: ‚text/uri-list‘.

mimeWindowTitle

Current window title for copied clipboard. Value: ‚application/x-copyq-owner-window-title‘.

mimeItems

Serialized items. Value: ‚application/x-copyq-item‘.

mimeItemNotes

Data contains notes for item. Value: ‚application/x-copyq-item-notes‘.

mimeIcon

Data contains icon for item. Value: ‚application/x-copyq-item-icon‘.

mimeOwner

If available, the clipboard was set from CopyQ (from script or copied items). Value: ‚application/x-copyq-owner‘.

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.

mimeClipboardMode

Contains selection if data is from Linux mouse selection. Value: ‚application/x-copyq-clipboard-mode‘.

mimeCurrentTab

Current tab name when invoking command from main window. Value: ‚application/x-copyq-current-tab‘.

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

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

Selected items when invoking command from main window. Value: ‚application/x-copyq-selected-items‘.

mimeCurrentItem

Current item when invoking command from main window. Value: ‚application/x-copyq-current-item‘.

mimeHidden

If set to 1, the clipboard or item content will be hidden in GUI. Value: ‚application/x-copyq-hidden‘.

This won’t hide notes and tags.

Example – clear window title and tool tip:

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

If set to 1, the clipboard contains a password or other secret (for example, copied from clipboard manager).

mimeShortcut

Application or global shortcut which activated the command. Value: ‚application/x-copyq-shortcut‘.

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

Item color (same as the one used by themes). Value: ‚application/x-copyq-color‘.

Examples:

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

Name of the tab where to store new item. Value: ‚application/x-copyq-output-tab‘.

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.

Example – automatic command that avoids storing clipboard data:

removeData(mimeOutputTab)

Valid only in automatic commands.

mimeDisplayItemInMenu

Indicates if display commands run for a menu. Value: ‚application/x-copyq-display-item-in-menu‘.

Set to „1“ for display commands if the item data is related to a menu item instead of an item list.

Selected Items

The internal state for currently evaluated script/command stores references (not rows or item data) to the current and selected items and it do not change after the state is retrieved from GUI.

The state is retrieved before the script/command starts if it is invoked from the application with a shortcut, from menu, toolbar or the Action dialog. Otherwise, the state is retrieved when needed (for example the first selectedItems() call) for scripts/commands run externally (for example from command line or from automatic commands on clipboard content change).

If a selected or current item is moved, script functions will return the new rows. For example selectedItems() returning [0,1] will return [1,0] after the items are swapped. Same goes for selected item data.

If a selected or current item is removed, their references in the internal state are invalidated. These references will return -1 for row and empty object for item data. For example selectedItems() returning [0,1] will return [0,-1] after the item on the second row is removed.

If tab is renamed, all references to current and selected items are invalidated because the tab data need to be initiated again.

Linux Mouse Selection

In many application on Linux, if you select a text with mouse, it’s possible to paste it with middle mouse button.

The text is stored separately from normal clipboard content.

On non-Linux system, functions that support mouse selection will do nothing (for example copySelection()) or return undefined (in case of selection()).

Plugins

Use plugins object to access functionality of plugins.

plugins.itemsync.selectedTabPath()

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 that maps tab name to synchronization path.

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

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

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

plugins.itemtags.userTags

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.

plugins.itemtags.mimeTags

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.

plugins.itempinned.pin(rows, ...)

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.

plugins.itempinned.mimePinned

Presence of the format in an item indicates that it is pinned.