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:
Note
These terms are equivalent: format, MIME type, media type
Execute Script
The scripts can be executed from:
Action or Command dialogs (F5, F6 shortcuts), if the first line starts with
copyq:
command line as
copyq eval '<SCRIPT>'
command line as
cat script.js | copyq eval -
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 called2 - 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.
- Returns
Version string.
- Return type
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.
- Returns
Help string.
- Return type
string
- /*search*/ help(searchString, ...)
Returns help for matched commands.
- Returns
Help string.
- Return type
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.
- Returns
true
only if main window is being shown, otherwisefalse
.- Return type
bool
Opens context menu.
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.
- monitoring()
Returns true only if clipboard storing is enabled.
- Returns
true
if clipboard storing is enabled, otherwisefalse
.- Return type
bool
- visible()
Returns true only if main window is visible.
- Returns
true
if main window is visible, otherwisefalse
.- Return type
bool
- focused()
Returns true only if main window has focus.
- Returns
true
if main window has focus, otherwisefalse
.- Return type
bool
- focusPrevious()
Activates window that was focused before the main window.
- Throws
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.
- Returns
Current filter.
- Return type
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.- Returns
Clipboard data.
- Return type
- selection([mimeType])
Same as
clipboard()
for Linux mouse selection.- Returns
Selection data.
- Return type
- hasClipboardFormat(mimeType)
Returns true only if clipboard contains MIME type.
- Returns
true
if clipboad contains the format, otherwisefalse
.- Return type
bool
- hasSelectionFormat(mimeType)
Same as
hasClipboardFormat()
for Linux mouse selection.- Returns
true
if selection contains the format, otherwisefalse
.- Return type
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.
- Returns
true
if current automatic command is triggered by clipboard change, otherwisefalse
.- Return type
bool
- copy(text)
Sets clipboard plain text.
Same as
copy(mimeText, text)
.- Throws
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.
- Throws
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.
- Throws
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.- Throws
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.- Throws
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.
- Throws
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.
- Returns
Array with names of existing tab.
- Return type
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.
- Returns
Path to icon for tab.
- Return type
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.
- Returns
Array of successfully unloaded tabs.
- Return type
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.
- Returns
Item count.
- Return type
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.
- Throws
Error()
– Thrown if space for the items cannot be allocated.
- remove(row, ...)
Removes items in current tab.
- Throws
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 current tab.
Opens external editor if set, otherwise opens internal editor.
- 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.- Returns
Concatenated data in the rows.
- Return type
- write(row, mimeType, data, [mimeType, data]...)
Inserts new item to current tab.
- Throws
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).
- Returns
Current separator.
- Return type
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.
- popup(title, message[, time=8000])
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.
- Throws
Error()
– Thrown if export fails.
- importTab(fileName)
Imports items from file to a new tab.
- Throws
Error()
– Thrown if import fails.
- exportData(fileName)
Exports all tabs and configuration into file.
- Throws
Error()
– Thrown if export fails.
- importData(fileName)
Imports all tabs and configuration from file.
- Throws
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 correspondingcopyq.ini
orcopyq.conf
file (copyq.ini
is used on Windows).- Returns
Available options.
- Return type
string
- /*get*/ config(optionName)
Returns value of given application option.
- Returns
Current value of the option.
- Return type
string
- Throws
Error()
– Thrown if the option is invalid.
- /*set*/ config(optionName, value)
Sets application option and returns new value.
- Returns
New value of the option.
- Return type
string
- Throws
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
.- Returns
New values of the options.
- Return type
string
- Throws
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.
- Returns
New value of the option.
- Return type
bool
- info([pathName])
Returns paths and flags used by the application.
- Returns
Path for given identifier.
- Return type
string
Example – print path to the configuration file:
info('config')
- eval(script)
Evaluates script and returns result.
- Returns
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.
- Returns
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.
- Returns
Current path.
- Return type
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`.
- Returns
Value as string.
- Return type
string
- input()
Returns standard input passed to the script.
- Returns
Data on stdin.
- Return type
- toUnicode(ByteArray)
Returns string for bytes with encoding detected by checking Byte Order Mark (BOM).
- Returns
Value as string.
- Return type
string
- /*encoding*/ toUnicode(ByteArray, encodingName)
Returns string for bytes with given encoding.
- Returns
Value as string.
- Return type
string
- fromUnicode(String, encodingName)
Returns encoded text.
- Returns
Value as ByteArray.
- Return type
- 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.
- Returns
Data for the format.
- Return type
- 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.
- Returns
true
if data were set,false
if parsing data failed (in case ofmimeItems
).- Return type
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')
- dataFormats()
Returns formats available for
data()
.- Returns
Array of data formats.
- Return type
array of strings
- print(value)
Prints value to standard output.
- serverLog(value)
Prints value to application log.
- logs()
Returns application logs.
- Returns
Application logs.
- Return type
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.
- Returns
Currently selected tab name, empty if called outside the main window context (see Selected Items).
- Return type
string
- selectedItems()
Returns selected rows in current tab.
- Returns
Currently selected rows, empty if called outside the main window context (see Selected Items).
- Return type
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.
- Returns
Currently selected items, empty if called outside the main window context (see Selected Items).
- Return type
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.
- Returns
true
if data were set, otherwisefalse
.- Return type
bool
- selectedItemsData()
Returns data for all selected items.
Some data can be empty if the item was removed during execution of the script.
- Returns
Currently selected item data, empty if called outside the main window context (see Selected Items).
- Return type
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.
- Returns
Current row,
-1
if called outside the main window context (see Selected Items).- Return type
int
- escapeHtml(text)
Returns text with special HTML characters escaped.
- Returns
Escaped HTML text.
- Return type
string
- unpack(data)
Returns deserialized object from serialized items.
- Returns
Deserialize item.
- Return type
- pack(Item)
Returns serialized item.
- Returns
Serialize item.
- Return type
- getItem(row)
Returns an item in current tab.
- Returns
Item data for the row.
- Return type
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) }
See also
- setItem(row, text|Item)
Inserts item to current tab.
Same as
insert(row, something)
.See also
- toBase64(data)
Returns base64-encoded data.
- Returns
Base64-encoded data.
- Return type
string
- fromBase64(base64String)
Returns base64-decoded data.
- Returns
Base64-decoded data.
- Return type
- md5sum(data)
Returns MD5 checksum of data.
- Returns
MD5 checksum of the data.
- Return type
- sha1sum(data)
Returns SHA1 checksum of data.
- Returns
SHA1 checksum of the data.
- Return type
- sha256sum(data)
Returns SHA256 checksum of data.
- Returns
SHA256 checksum of the data.
- Return type
- sha512sum(data)
Returns SHA512 checksum of data.
- Returns
SHA512 checksum of the data.
- Return type
- open(url, ...)
Tries to open URLs in appropriate applications.
- Returns
true
if all URLs were successfully opened, otherwisefalse
.- Return type
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.
- Returns
Finished command properties or
undefined
if executable was not found or could not be executed.- Return type
FinishedCommand()
orundefined
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.
- Returns
Current window title.
- Return type
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)
- Returns
Value or values from accepted dialog or
undefined
if dialog was canceled.
dialog( '.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')
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.
- Returns
Selected item or empty string if menu was canceled.
- Return type
string
var selectedText = menuItems('x', 'y', 'z') if (selectedText) popup('Selected', selectedText)
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 frommimeIcon
format.- Returns
Selected item index or -1 if menu was canceled.
- Return type
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 correspondingcopyq-scripts.ini
file. But if an option is named likegroup/...
, then it is written to a section named[group]
instead. By grouping options like this, we can avoid potential naming collisions with other commands.- Returns
Available custom options.
- Return type
array of strings
- /*get*/ Value settings(optionName)
Returns value for a custom user option.
- Returns
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.
- Returns
Current date and time as string.
- Return type
string
Example:
var now = dateString('yyyy-MM-dd HH:mm:ss')
- commands()
Return list of all commands.
- Returns
Array of all commands.
- Return type
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.
- Returns
Array of commands loaded from a file path.
- Return type
array of
Command()
- String exportCommands(Command[])
Return exported command text.
- Returns
Serialized commands.
- Return type
string
- addCommands(Command[])
Opens Command dialog, adds commands and waits for user to confirm the dialog.
- NetworkReply networkGet(url)
Sends HTTP GET request.
- Returns
HTTP reply.
- Return type
- NetworkReply networkPost(url, postData)
Sends HTTP POST request.
- Returns
HTTP reply.
- Return type
- 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.
- Returns
HTTP reply.
- Return type
- 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.
- Returns
HTTP reply.
- Return type
- env(name)
Returns value of environment variable with given name.
- Returns
Value of the environment variable.
- Return type
- setEnv(name, value)
Sets environment variable with given name to given value.
- Returns
true
if the variable was set, otherwisefalse
.- Return type
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.
- Returns
Available screen names.
- Return type
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
withscreenNames()
.- Returns
Image data.
- Return type
Example:
copy('image/png', screenshot())
- screenshotSelect(format='png'[, screenName])
Same as
screenshot()
but allows to select an area on screen.- Returns
Image data.
- Return type
- queryKeyboardModifiers()
Returns list of currently pressed keyboard modifiers which can be ‘Ctrl’, ‘Shift’, ‘Alt’, ‘Meta’.
- Returns
Currently pressed keyboard modifiers.
- Return type
array of strings
- pointerPosition()
Returns current mouse pointer position (x, y coordinates on screen).
- Returns
Current mouse pointer coordinates.
- Return type
array of ints (with two elements)
- setPointerPosition(x, y)
Moves mouse pointer to given coordinates on screen.
- Throws
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.
- Returns
Current icon color.
- Return type
string
- /*set*/ iconColor(colorName)
Set current tray and window icon color name (examples: ‘orange’, ‘#ffa500’, ‘#09f’).
Resets color if color name is empty string.
- Throws
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) }
See also
- iconTag()
Get current tray and window icon tag text.
- Returns
Current icon tag.
- Return type
string
- /*set*/ iconTag(tag)
Set current tray and window tag text.
- iconTagColor()
Get current tray and window tag color name.
- Returns
Current icon tag color.
- Return type
string
- /*set*/ iconTagColor(colorName)
Set current tray and window tag color name.
- Throws
Error()
– Thrown if the color name is invalid.
- loadTheme(path)
Loads theme from an INI file.
- Throws
Error()
– Thrown if the file cannot be read or is not valid INI format.
- onClipboardChanged()
Called when clipboard or Linux mouse selection changes.
Default implementation is:
if (!hasData()) { updateClipboardData(); } else if (runAutomaticCommands()) { saveData(); updateClipboardData(); } else { clearClipboardData(); }
- onOwnClipboardChanged()
Called when clipboard or Linux mouse selection changes by a CopyQ instance.
Owned clipboard data contains
mimeOwner
format.Default implementation calls
updateClipboardData()
.
- onHiddenClipboardChanged()
Called when hidden clipboard or Linux mouse selection changes.
Hidden clipboard data contains
mimeHidden
format set to1
.Default implementation calls
updateClipboardData()
.
- 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 returnsfalse
. Otherwisetrue
is returned.- Returns
true
if clipboard data should be stored, otherwisefalse
.- Return type
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.
- Returns
Formats to get and save automatically from clipboard.
- Return type
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.)
- Returns
true
if there are some data, otherwisefalse
.- Return type
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.- Returns
Style identifiers.
- Return type
array of strings
To change or update style use:
config("style", styleName)
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 withselect*()
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(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.
- Returns
self
- Return type
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
andmimeType
is set, this select items not containing the MIME type.- Returns
self
- Return type
ItemSelection
- ItemSelection.selectRemovable()
Select only items that can be removed.
- Returns
self
- Return type
ItemSelection
- ItemSelection.invert()
Select only items not in the selection.
- Returns
self
- Return type
ItemSelection
- ItemSelection.deselectIndexes(int[])
Deselect items at given indexes in the selection.
- Returns
self
- Return type
ItemSelection
- ItemSelection.deselectSelection(ItemSelection)
Deselect items in other selection.
- Returns
self
- Return type
ItemSelection
- ItemSelection.current()
Deselects all and selects only the items which were selected when the command was triggered.
See Selected Items.
- Returns
self
- Return type
ItemSelection
- ItemSelection.removeAll()
Delete all items in the selection (if possible).
- Returns
self
- Return type
ItemSelection
- ItemSelection.move(row)
Move all items in the selection to the target row.
- Returns
self
- Return type
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.
- Returns
self
- Return type
ItemSelection
- ItemSelection.copy()
Clone the selection object.
- Returns
cloned object
- Return type
ItemSelection
- ItemSelection.rows()
Returns selected rows.
- Returns
Selected rows
- Return type
array of ints
- ItemSelection.itemAtIndex(index)
Returns item data at given index in the selection.
- Returns
Item data
- Return type
- ItemSelection.setItemAtIndex(index, Item)
Sets data to the item at given index in the selection.
- Returns
self
- Return type
ItemSelection
- ItemSelection.items()
Return list of data from selected items.
- Returns
Selected item data
- Return type
array of
Item()
- ItemSelection.setItems(Item[])
Set data for selected items.
- Returns
self
- Return type
ItemSelection
- ItemSelection.itemsFormat(mimeType)
Return list of data from selected items containing specified MIME type.
- Returns
Selected item data containing only the format
- Return type
array of
Item()
- ItemSelection.setItemsFormat(mimeType, data)
Set data for given MIME type for the selected items.
- Returns
self
- Return type
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()
oradd()
.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
.
Note
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"
- 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.
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.
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.