K-Meleon

KMeleonWiki > Documentation > EndUserDocs > MacroLanguage > MacroLanguage2


K-Meleon Macro Language 2

(Current version. For outdated functions like layers and macros.cfg read the previous version)



Contents


See also:


Comments

A line starting with # is a comment and is ignored.

# this is a comment


Variables and Macros

Variables are not declared explicitly, but must have a name starting with a dollar sign. A variable can either be global, accessible from any macro, or local to a specific macro. Before a variable can be used in an expression, it must be assigned a value. Integer and string values are available.

They can hold data up to some MegaBytes?. Over 6MB tested.

    $x = 0; 
    $y = "A text string";


Macro declarations consist of a macro name followed by a compound of statements enclosed in curly braces to execute for that macro.

my_example1{ 
        macroinfo="Just a little test";
        $_x = "Hello World!\nHave a nice day :-)";
        alert($_x,"Hi!");
    }

This macro can then be used for menus, toolbar buttons, keyboard shortcuts (accel), mouse gestures etc.:
macros(my_example1);
Other macros can call it the same way, or optional shorter: &my_example1;


  macroinfo = string ;                                                           Since version 1.5

Presents the string in the status bar whenever the mouse hovers over the item in a menu which calls the macro. Use this statement in the first lines of the macro function.


Expressions

The following operators are available:

Operator Meaning Sample Statement Result (int, string, bool)
= assignment $x = 7; $x = 7
. string concatenation $x = 7 . 3; $x = 73
+ integer addition $x = 7 + 3; $x = 10
- integer subtraction $x = 7 - 3; $x = 4
* integer multiplication $x = 7 * 3; $x = 21
/ integer division $x = 7 / 3; $x = 2
% integer remainder $x = 7 % 3; $x = 1
== equality $x = 7; $x == 3; false
!= unequality $x = 7; $x != 3; true
<, <=, >, >= string comparison 10 > 2 false
<, <=, >, >= integer comparison 10+0 > 2+0 true
and comparison join
for if(), and while()
$x=3; $y=2;
$x>=$y and $y<7
true
or comparison join
for if(), and while()
$x=3; $y=2;
$x>=$y or $y>7
true
? : conditional expression $x==1 ? true : false; if $x equals 1 true,
otherwise false

Parentheses can be used to alter the evaluation order. By default, addition and subtraction have higher precedence than multiplication, division and remainder operations.

When needed, a variable is automatically converted from a string to an integer, or vice versa.

    $x = 1 + "2";                       $x = 3  
    $y = "The value of x is " . x;      $y = "The value of x is 3"

When comparing variables the type of comparison, string or integer, is based on the type of variable to the left of the expression.

Special Strings

Strings should be enclosed in double quotes although not required unless the string contains operators. A backslash is used to escape special characters:

\\ backslash (\)
\n newline character
\t tabulator
\" quotation mark (")

The string values "true" and "false" are recognized as boolean values and can be used in place of a conditional expression.

    $z = "false";
    $z ? $x = 1 : $x = 0;               $x = 0
    $z = "true";
    $z ? $x = 1 : $x = 0;               $x = 1


Special Global Variables

There is a number of predefined global variables to let K-Meleon macros access some global state information.

Variable type Value Version ReadOnly
$ARG STRING Argument given from caller plugin (not from caller macro). 0.9 YES
$CHARSET STRING Character encoding used for the current page. 1.0 NO
$CommandLine STRING The command line which started K-Meleon. 1.5.2 YES
$FrameURL STRING URL for the current frame. 0.8.2 YES
$ImageURL STRING URL for the current image. 0.8 YES
$LinkURL STRING URL for the current link. 0.8 YES
$macroModules STRING Semicolon separated list of active kmm modules (if they contain this line) ? NO
$SelectedText STRING Selected text in the current page. 1.0 YES
$TabNumber INT The number of tabs in the current window. 1.5 YES
$TextZoom INT Text zoom factor for the current page. 1.0. NO
$TITLE STRING Title for the current page. 0.9 NO
$URL STRING URL for the current page. 0.7 YES
$URLBAR STRING Contents of the URL bar. 1.0 NO
$WindowNumber INT The number of windows in the current session. 1.5 YES
$VERSION INT The version of K-Meleon. 75.0 YES(?)

Special Global Variables are case sensitive.

   $VERSION                                         Since version 75.0 

This is the same number as in version.ini in your profile folder. This is in hex format, and does NOT match the official version. For example "33685507" converts to decimal "2.2.0003" (used in KM75.1beta)

  
   $ARG                                             Since version 0.9 

K-Meleon's keyboard accelerators, its menu system and its plugins (but not the macros plugin itself) can call a macro with an argument:

setmenu("&Tools",macro,"Prefer English","PageLang(en)",0);
setmenu("&Tools",macro,"Prefer Russian","PageLang(ru)",0);

A macro called this way, can get the argument reading the $ARG variable:

     PageLang{
     if ($ARG == "en") $_x= "en,en-us,ru";
     if ($ARG == "ru") $_x= "ru,en,en-us";
     setpref(STRING,"intl.accept_languages",$_x);
     }

Actually there's a little workaround for macros to call other macros with an $ARG:
plugin(macros,"myMacro_useCSS(dark)");

Never read $ARG after opening one of the Modal Windows (alert, confirm etc. / there's a bug).
Assign the value of $ARG to a local variable instead (e.g. $_ARG=$ARG)


Events

The Macro Extension Plugin provides a variety of events.

Event Is triggered
OnInit When the Default Configuration Files have been parsed.
OnSetup When the User Configuration Files have been parsed.
OnStartup When the first window is opened.
OnOpenWindow When a window is opened.
OnOpenTab When a tab is opened.
OnSwitchTab When a tab gets the focus (new in KM76 except main.kmm)
OnActivateWindow When a window gets the focus.
OnLoadOnce When the 1st document after filling the $OnLoadOnce variable has finished loading. (1)
OnLoad When a document has finished loading.
OnCloseTab When a tab is closed.
OnCloseWindow When a window is closed.
(OnCloseGroup) When a multi-layered window is closed (obsolete since KM1.5).
(OnWMAppExit) When ID_APP_EXIT is called to terminate the application. (broken?)
OnQuit When the macro plugin (the browser) is being closed.

Not all of these events are supported by all versions of K-Meleon.

(1) Macros in the $OnLoadOnce string will run only 1x, then this string is cleared again. They run prior to those in $OnLoad.

Event Handling

Whenever <event> is triggered, the Macro Extension Plugin will look for a macro named On<event> and execute it if found. The appropriate On<event> macros are provided by default in the main macro module (main.kmm). It provides global $On<event> variables which you can use in your own modules to get code executed whenever <event> is triggered:

           myMacro{
           # your On<event> code
           }
           $On<event>=$On<event>."myMacro;";

On<event> macros are executed in the context of the window that triggered the event.

Event Cascade

          Startup is always followed by Load or OpenWindow.
          OpenWindow is always followed by Load.
          Init, Setup, and Quit are only fired once a session.(1)
          ActivateWindow is usually fired multiple times, each time a browser window is focused.

            Startup Order of Precedence
                 Init
                 Setup
                 Startup(1)
                 OpenWindow(2)
                 OpenTab(2)
                 LoadOnce
                 Load(2)(3)(4)

(1) When the browser is opening a group or folder at startup, the Load event is fired before Startup and Startup is fired multiple times (once for each opened layer).

(2) The use of sessions or groups may fire these events multiple times.

(3) The code on some websites may fire this event multiple times.

(4) LoadOnce runs before Load.

            Shutdown Order of Precedence
                 CloseGroup or WMAppExit(1)
                 CloseWindow
                 Quit

(1) WMAppExit seems currently not to be fired at all.


Statements

Statements should be finished by a semicolon. With version prior to 1.5, statements may not span several lines! Strings can't never span several lines.

    # THIS CODE IS INVALID
    $error = 1 +
        1;

Several statements can be lined up on the same line with a semicolon in between.

    $x = 0; $y = "A text string";

Version 1.5 has a new macro parser. This one is more strict and will notify about errors that weren't discovered in previous versions (especially in regard to missing semicolons and malformed strings). Macros have to be encoded in UTF-8 now.

FINDING ERRORS:
Open menu Tools > Error Console (or click toolbar button for JS console, or URL chrome://console2/content/console2.xul)
Switch on "KMM" errors.
Check in about:config if you have this pref, otherwise create it:
kmeleon.plugins.macros.debug (BOOL) true
Use an editor with syntax highlighting (like NPP etc., search forum for tips, e.g. Scite)


Conditional statements

The conditional expression operator (? :) can be used to execute a single statement depending on a certain condition.

A complete "If ... Then ... Else ..." statement would look like this:

    CONDITION ? STATEMENT_CONDITION_TRUE : STATEMENT_CONDITION_FALSE;

A simple "If ... Then ..." statement would look like this:

    CONDITION ? STATEMENT_CONDITION_TRUE : 0;

In the example above, nothing (0 = zero) is executed when the condition is false.

To execute multiple statements depending on a certain condition, these have to be encapsulated in helper macros:

    CONDITION ? &ConditionTrue : &ConditionFalse;

    ConditionTrue {
        ...
    }
    ConditionFalse {
        ...
    }


Alternative conditional statements since version 1.5

   if (condition) { statement1; [statement2; [...]] } else { statementA; [statementB; [...]] } 

May have multiple conditions joined by 'and' or 'or'.                                                        

   if ((condition) and (condition)) { statement1; [statement2; [...]] } else { statementA; [statementB; [...]] }  
   if ((condition) or (condition)) { statement1; [statement2; [...]] } else { statementA; [statementB; [...]] }  

If the boolean expression in parentheses is true, the statements in the if block are executed. Otherwise the statements in the else block are executed. The else block is optional. Surrounding curly braces can be omitted for a block that contains only one statement.

Examples:

        if (condition) statement;

        if (condition) {
                statement1;
                statement2;
        } else {
                statement3;
                statement4;
        }

        if (condition) statement1; else statement2; statement3;

In the last example, statement3 is executed whatever the value of condition may be since the if-else statement is finished after statement2. If statement3 is meant to belong to the else block, statement2 and statement3 have to be enclosed in curly braces.


Documents


Document Manipulation


   forcecharset( [charset] );                                                   Since version 0.9

Sets the character set (detection) for the current window. See encoding.kmm for a usage demonstration.

Parameter Required Type Value Meaning
charset NO(1) STRING A charset The name of the desired character set.

(1) When omitted, the character set auto detection is enabled. The used method is determined by the value of the intl.charset.detector preference.

Example: forcecharset("UTF-8");
(Note: using this $OnLoad may cause an endless loop?)

  
   injectCSS( CSS );                                                             Since version 1.0

Injects a Cascading Style Sheet into the current page.
This method is most beneficially used in conjunction with the readfile() method (see readfile() for file size limits notes). Note that this method is intended for an on demand application of CSS code only, do not use it in an event based manner. Make use of the userContent.css file to permanently apply your own styles to the documents you view.

Parameter Required Type Value Meaning
CSS YES STRING CSS code The Cascading Style Sheet code to be injected.

Example: injectCSS("html, body { background-color: darkgreen !important; }");


   injectJS( JS );                                                               Since version 1.0

Injects a JavaScript into the current page.

The scope of the scripts runs out of the page context so, even if JavaScript is globally disabled, subsequent injectJS interaction with the same page can use the already used variables, but executing injected functions would need JavaScript enabled.

The injectJS method is most beneficially used in conjunction with the readfile() method (see readfile() for file size limits notes). Note that this method is intended for an on demand application of JavaScript code, avoid its usage in an event based manner to keep K-Meleon stable and responsive.

   injectJS( JS [, location ]);                                                 Since version 1.5

Injects JavaScript code into the current document, into the current frame or into all tabs of the current window.

   $value = injectJS( JS [, location ]);                                        Since version 1.6

Returns the result of the script (when applicable). Note: broken in some builds (KM1.7a, KM74 etc.) or unless the value isn't returned as string, using toString() Javascript function.

The string value returned from injectJS() was limited to 127 characters in 1.6 and to 4096 characters between 74.x and 76RC.
Since K-Meleon76 RC2 (version.ini 33751047) the limit is 32768 characters.

example:
$_code="(function(){var x=navigator.userAgent; return x;})()";
$_ua=injectJS($_code);

Parameter Required Type Value Meaning
JS YES STRING JS code The JavaScript code to be injected.
location NO(1) PREDEFINED alltabs(2) Address all tabs in the current window.
frame Address the current frame only.
hidden Since 75, run in an hidden window (no interraction with current page).

(1) When omitted, the specified code is injected into the current document which may be a frame set. So, subframes have to be handled by the injected code itself. Same when injecting into all tabs.
(2) For version 1.5


Opening Documents

   open( URL );                                                                  Since version 0.4

Opens URL in the current page.

Example 1: open("http://example.com/info/page.html");
Example 2: open("file:///d:/test/examples/page1.html");
Example 3: $_x="about:config?filter=useragent" ; open($_x);

   opennew( URL );                                                               Since version 0.4

Opens URL in a new browser window.

   openbg( URL );                                                                Since version 0.4

Opens URL in a new background window.

   opentab( URL );                                                               Since version 1.5

Opens the specified URL in a new tab. This new tab gets the focus.

   openbgtab( URL );                                                             Since version 1.5

Opens the specified URL in a new tab. This new tab is opened in the background (the current tab keeps the focus).

Note for KM75.1 or newer:
some formerly popular open-methods, created in main.kmm, are now obsolete.
A new helper macro, compat75.kmm, provides workarounds, but is reported to conflict with debugger pref "kmeleon.plugins.macros.debug=true"
In affected macros...
replace &OpenURL_InNew() with opentab();
replace &OpenURL_InNewWindow() with opennew();
replace &OpenURL_InBg() with openbgtab();
replace &OpenURL_Selected() with openSelected();
replace &OpenURL_Typed() with openTyped();
(To do: check new method for $cmdline=getExtensionHandler($ext);)
or
much easier:
copy the middle and end part of compat75.kmm into main.kmm, at the end.
Catch: at next update the file main.kmm will be overwritten again, your changes lost :-(


String Handling

General

    $I = index( s, t );                                                          Since version 0.7

Returns the index of the string t in the string s, or -1 if t is not present.
Example: $_x=index($URL,"www"); (will be 7 for http or 8 for https URLs)

    $LEN = length( s );                                                          Since version 0.7

Returns the length of the string s.

    $SUB = substr( s, i [, n] );                                                Since version 0.7

Returns the at most n-character substring of s starting at i. If n is omitted, the rest of s is used.
That simply means: cut a string either at the beginning or end or both
$_x=substr(string, cut x characters at begin, this max length)
$_x=substr("abcdefgh",2,4) will become $_x="cdef"


Substitution

    $TRANSLATION = _( TEXT );                                                    Since version 1.0

Replaces TEXT by the specified translation, if any.
As example look inside macro cfg.kmm.
You can provide own translations in a kml-file in locales folder (encoding UTF-8). KM finds matching translations in all files there, regardless the file name. That means they are not connected to specific macros, but it's recommended to give your own file the same name as your macro.
Note: no _() necessary for setmenu lines, KM translates them automatically.


    $SUB = gensub( r, s, h, t );                                                 Since version 0.7

Searches the target string t for matches of the string r. If h is a string beginning with g or G, then all matches of r are replace with s. Otherwise, h is a number indicating which match of r to replace. The modified string is returned.


    $SUB = gsub( r, s, t );                                                      Since version 0.7

Substitutes the string s for each substring matching the string r in the string t, and returns the modified string. This is equivalent to gensub( r, s, "G", t).
That means: $_x=gsub(replace every This , withThis , inThisString)
Example: $_x=gsub("color","colour",$_abc);


    $SUB = sub( r, s, t );                                                       Since version 0.7

Just like gsub(), but only the first matching substring is replaced. This is equivalent to gensub( r, s, 1, t).


URLs

    $BASE = basename( URL [, SUFFIX] );                                         Since version 0.7

Returns URL with any leading directory components removed. If specified, also remove a trailing SUFFIX.


    $DIR = dirname( URL );                                                       Since version 0.7

Returns URL with its trailing /component removed. If URL contains no '/', output '.' (meaning the current directory).


    $HOST = hostname( URL );                                                     Since version 0.7

Returns the hostname of the given URL.


    $VALID_URL = urlencode( TEXT );                                              Since version 1.0

Encodes TEXT for use in an URL.


    $TEXT = urldecode( VALID_URL );                                              Since version 1.5

Decodes an encoded URL.


Iteration

    while( CONDITION ) STATEMENT ;                                               Since version 1.0 

Executes a single STATEMENT while the CONDITION is true. To execute multiple statements, these have to be encapsulated in a helper macro:

    while( CONDITION ) &Loop;
Loop { ... }
    while( CONDITION ) { STATEMENT1 ; [STATEMENT2 ; [ ... ]] }                  Since version 1.5

The syntax was extended to support execution of multiple statements.
May have multiple conditions joined by 'and' or 'or'.

while( (CONDITION) and (CONDITION) ) { STATEMENT1 ; [STATEMENT2 ; [ ... ]] } while( (CONDITION) or (CONDITION) ) { STATEMENT1 ; [STATEMENT2 ; [ ... ]] }

    while ( CONDITION ) { 
    STATEMENT1 ;
    STATEMENT2 ;
    }    

Example:
_hotlinksALT_SetAccels{
$_nr=0; while($_nr<10) {
setaccel("ALT ".$_nr,"macros(hotlinkALT(".$_nr."))");
$_nr=$_nr+1;
}}


Interfaces to


The User


Simple Dialogs / Modal Windows

 alert( MESSAGE [, TITLE [, ICON]] );                                        Since version 0.8

Shows a messagebox.
Example: alert($TITLE,"Page Title:",INFO);

ICON = EXCLAIM | INFO | STOP | QUESTION


 $RESULT = confirm( MESSAGE [, TITLE [, BUTTONS [, ICON]]] );                Since version 0.9

Shows a messagebox and asks for confirmation.
Example: $_do=confirm($SelectedText,"Copy to clipboard?",YESNOCANCEL,QUESTION);

BUTTONS = OKCANCEL | YESNO | YESNOCANCEL | RETRYCANCEL | ABORTRETRYIGNORE
ICON = EXCLAIM | INFO | STOP | QUESTION
RESULT = OK | YES | NO |ABORT | RETRY | IGNORE | 0


    $VALUE = prompt( MESSAGE [, TITLE [, DEFAULT]] );                           Since version 0.7

Shows a modal 'prompt' dialog and returns a string value.
Example: $_col=prompt("Examples: yellow red blue","Which color?","red");

Parameter Required Type Value Meaning
message YES STRING A message(3) The text to be displayed in the dialog's body.
title NO STRING A title(2) The text to be displayed in the dialog's title bar.
default NO(1) STRING A preset The text to be displayed in the dialog's input field.

The value returned from Prompt() is limited to 254 characters.

(1) When a <default> value is specified, <title> must be specified too.
(2) The title cannot span several lines.
(3) The message cannot span several lines

Tip: If you do need several lines, try a pure javascript prompt.
It can handle linebreaks, allows almost unlimited output length (e.g. to copy a JS result), but the input field may be much shorter and the title can't be set.
Example for JS:
$_js="var col=prompt('Which color? Some examples:\\n1=yellow\\n2=red\\n3=blue','red'); col == ''? col='canceled!' : 0; return col;" ;
$_x=injectJS("(function(){".$_js."})()");

But a pure macro-prompt can show several info-lines too, just a bit hacky: if you're familiar with popular ResHacker tool, open macros.dll with it and click on the "dialog", then pull the prompt-borders as high and wide as you like (try at own risk, only tested with KM1.6 on very old system ;-)


Setting Accelerator Key Definitions

   setaccel( keys [,command]);                                                  Since version 1.1

This method can be used to set keyboard accelerators instead of editing accel.cfg.

Parameter Required Type Value Meaning
keys YES STRING A key combination(1) The addressed key combination.
command YES STRING A command(2) The command to be associated with the key combination.

(1) A space-separated list of predefined key names.

(2) Command can be "ID_..." or "pluginName(pluginCommand)". If command is an empty string, this is a deletion.

Example: setaccel("CTRL ALT O","macros(OpenURL)");
Example: setaccel("CTRL SHIFT VK_F9","ID_TAB_NEXT");
More examples in native macro accel.kmm and others.
Default shortcuts are mostly defined in accel.cfg, and also listed in commands.html (partly outdated)


Menus

    setmenu( MENU_NAME, ITEM_TYPE [, LABEL [, COMMAND]] [, WHERE]);            Since version 1.1
Parameter Type Meaning
MENU_NAME string Specifies the name of the addressed menu (required).
ITEM_TYPE predefined Specifies the nature of the addressed item (required).
Can be one of the strings: inline, popup, command, macro, separator.
LABEL (1) string Specifies the name of the addressed item inside the addressed menu.
COMMAND (2) string Specifies the command associated with the addressed item.
WHERE (3) string or integer
string
-1
n=0,1,2,...
Specifies where to insert the addressed item.
Insert before an item specified either by label or by command
Insert at the end of the addressed menu
Insert at position n of the addressed menu (1st position: 0)

(1) LABEL must be specified for all item types except "separator". If LABEL is an empty string, this is a deletion.
(2) COMMAND must be specified for item types "command" and "macro". If COMMAND is an empty string and LABEL is not, this is a deletion.
(3) WHERE can be omitted for all item types except "separator" (-1 is the default).

Note1: Do not use translation brackets _() inside setmenu, KM translates it automatically.
Note2: Do not forget any of the 5 parameters of this command or the icon won't be shown on menus for the entry with the missing parameter.

Example: setmenu("_Config_Settings",macro,"Co&mmands List",cfg_Commands,-1);
Many more examples are found in the native macros, like cfg.kmm, main.kmm etc.
How to figure out the (parent) menu names, to place your additions inside:
If visible, just use the english menu name.
If a character is underlined, precede it with "&" (e.g. "&Tools" or "Pr&eferences")
A menu can also contain several "inline" submenus, which may also be used as parent menu for your own additions.
Inline-menu names are not visible, but the structure of the Default menus is found in the global menus.cfg
Menus created by other macros can also be used.
If you'd like an icon with your menu line, read below at "setcmdicon"
To create your menu lines at browser start, add your buildmenu-macro to the "$OnInit" event.
(Hint: if you only want to customize menus for own use, that's often simpler done by just editing menus.cfg)


  menugrayed =  boolean expression ;                                            Since version 1.1

This statement is used inside a macro to enable and disable (gray out) this macro's menu representations. The enabled/disabled state is dynamically updated according to the value of the boolean expression. The latter is evaluated whenever a menu item representing this macro becomes visible.
Use this statement in the first lines of the macro function.
Note that local variables are out of scope here, only globally defined variables can be used.

Example: menugrayed=(index($URL,"wyciwyg:")==0);


  menuchecked = boolean expression ;                                             Since version 1.1

This statement is used inside a macro to set a checkmark for this macro's menu representations. The checkmark's state is dynamically updated according to the value of the boolean expression. The latter is evaluated whenever a menu item representing this macro becomes visible.
Use this statement in the first lines of the macro function.
Note that local variables are out of scope here, only globally defined variables can be used.

Example1: menuchecked=(getpref(INT,"permissions.default.image")==2);
Example2: menuchecked=!getpref(BOOL,"javascript.enabled");
Example3: menuchecked=(getpref(STRING,"general.useragent.override")==getpref(STRING,"kmeleon.privacy.useragent".$ARG.".string"));
The condition at the right side gets calculated to true(1) or false(0).
Several conditions can be combined, e.g. using multiplication (true * false = 1 * 0 => 0 => false)
Very advanced examples are found in main.kmm


    setcheck( COMMAND, STATE );                                                  Since version 0.9 
Parameter Required Type Value Meaning
COMMAND YES STRING A command The command associated with the addressed menu item.
STATE YES BOOL A boolean expression The checkmark's state (true=visible, false=hidden).

This method is used to set a checkmark for command's menu representations.
To handle checkmarks of menu items representing macros, use instead the "menuchecked" statement above.


  rebuildmenu (menuName);                                                        Since version 1.1        

Rebuildmenu is deprecated in later versions of K-Meleon.

This method is used to rebuild a menu that was created by a setmenu() statement. Note that a menu must be rebuilt by rebuildmenu() inside the same macro where it was built by setmenu(). The rebuildmenu() statement takes effect only when the hosting macro is (directly or indirectly) called from the menus. See proxy.kmm for a usage demonstration.

Parameter Required Type Value Meaning
menuName YES STRING A menu name The name of the menu to be rebuilt.


    $RETURN = popupmenu( MENU NAME, VALUE ) ;                                    Since version 75.0

Displays the named menu in actionable or view-only mode.
If VALUE is true, then $RETURN is 1 if successful or 0 if not. (see false below)

Value Results
true (1) The menu is shown in actionable mode.
false (0) The menu is shown in view-only mode and $RETURN will have the menu's numeric id.

Note: A menu's numeric id may be used in the id() statement.

Example: popupmenu("&Help");
Older KM-versions could only use the rebarmenu-plugin, which had a bug with outdated (wrong) checkmarks:
plugin("rebarmenu","&Help");


Toolbars

Note: for versions older as KM75 look here: PluginCommands.
This older method still works in newer KM-versions too, only the syntax is more complicated.

   addtoolbar( TOOLBAR_NAME );                                                   Since version 75.0                                                          

Create a new toolbar

   addbutton( TOOLBAR_NAME, COMMAND[, MENU[, TOOLTIP]] );                       Since version 75.0                                                           

Add a button to a toolbar

   removebutton( TOOLBAR_NAME, COMMAND );                                         Since version 75.0                                                            

Remove a button from a toolbar

   setcmdicon( COMMAND, COLD[, HOT[, DEAD]] );                                   Since version 75.0                                                           

Set the image for menus and the default image for toolbar buttons.
Put your images into the "/skins/shared/" folder, to be available in all skins.
Example: setcmdicon("macros(mymacro)", "mymacro.bmp");
Example: setcmdicon("macros(FileOpenDir_last)", "menu1.png[4,16,16]");

   setbuttonimg( TOOLBAR_NAME, COMMAND, COLD[, HOT[, DEAD]] );                   Since version 75.0                                                           

Set the image of a button. Only needed in rare cases, if you want to change ONLY the button image during a session, for example after toggling something.

    $RETURN = enablebutton( TOOLBAR NAME, BUTTON id, VALUE ) ;                    Since version 75.0 

Make the button enabled or disabled depending on value.

$RETURN is 1 if successful or 0 if not.
BUTTON id is the command associated with the button.
Value Results
true (1) Enables the button and shows the cold image.
false (0) Disables the button and shows the dead image.

    $RETURN = checkbutton( TOOLBAR NAME, BUTTON id, VALUE ) ;                     Since version 75.0 

Allows the button to appear checked depending on value.

$RETURN is 1 if successful or 0 if not.
BUTTON id is the command associated with the button.
Value Results
true (1) The button's hot image is displayed checked.
false (0) The button's cold image is displayed normally.



The Operating System


     
    $DATESTRING = date( FORMAT [, time]);                                        Since version 75.0

Returns a date string based on the current or a given Unix time stamp.
If time is left blank then the current time is used.

Some example formats are:

FORMAT Results
"%Y-%m-%d" 2001-08-23
"%H:%M:%S" 14:55:02
"%c" 9/28/2015 1:29:59 PM

Additional formats can be seen here: C++ Ref.
Not every format in the external reference will work.
It is best to verify before using.

   exec( COMMAND_LINE );                                                         Since version 0.6

Executes an external program.
The path must contain double \\ (or single / seem to work too)
Example1: exec("C:\\progs\\app.exe");
Example2: exec("\"C:\\my progs\\mempad.exe\" \"D:\\data folder\\\"");
More examples in the Forum (here)

   $VALUE = iniread( SECTION, KEY, VALUE, PATH );                                Since version 1.5.3       

Returns the value of the specified key in the specified section from the ini file in the path.
Example: $_i = iniread("Version","LastVersion","", getfolder(ProfileFolder)."\\version.ini");

   iniwrite( SECTION, KEY, VALUE, PATH );                                        Since version 1.5.3

Writes the key and value in the section to the ini file specified in path. If the file, section, or key does not exist, it is created. If the key exists the value is overwritten. An ini file has the following format.

        [SECTION]
        KEY=VALUE  

                                
   $PATH = promptforfile( INITIAL_FOLDER, FILE_TYPE_DESCRIPTION, FILE_EXTENSION_PATTERN ); 
                                                                                     Since version 1.0

Prompts the user for a file, displaying only the files matching the pattern.
Example:
$_path=promptforfile("c:\\K-Meleon\\browser\\defaults\\preferences","your useragents file","*agent*.js");


    $PATH = promptforfolder( CAPTION [, INITIAL_FOLDER] );                      Since version 1.0

Prompts the user for a folder.
Example:
$_x=getpref(STRING,"kmeleon.download.saveDir");
# crop the "\" at end, or starts with Desktop:
$_x=substr($_x,0,length($_x)-1);
$_x=promptforfolder("View local folder as link-list",$_x);
$_x>"" ? opentab("file:///".$_x) : 0;


    $CONTENT = readfile( PATH );                                                  Since version 1.0

Returns the contents of the specified file (32 kB maximum). Only for little text files.
Limit increased to 64 kB maximum in version 75.0 and later.
(and again far bigger since version 76RC2?)


    $VALUE = readreg( ROOT, PATH );                                              Since version 1.0

Returns the value of the specified registry key.
ROOT = HKLM | HKCU | HKCC | HKCR | HKU


     
    $UNIXTIME = time();                                                          Since version 75.0

Returns a Unix time stamp.

The number of seconds that have elapsed since 00:00:00 Coordinated Universal Time, Thursday, 1 January 1970, not counting leap seconds.


       
    $TIMERID = settimer( MACRO, DURATION  [  , TYPE ] ) ;                       Since version 75.0 

Runs the code in the named macro after a delay of the number of seconds in duration, in the context of the current tab/window. There can only be 25 timers active at the same time.
DURATION must be a positive integer.
Returns the timer identifier to use with killtimer() or 0 if failed.

Type Results
(empty) Runs the code only one time after duration seconds if the contextual tab/window was not closed.
continuous Repeats the code each duration seconds until stopped by a killtimer action or until the contextual tab/window is closed.
free Runs the code only one time after duration seconds without any context.


       
   killtimer(  [ TIMERID ]  ) ;                                                 Since version 75.0 

Stops the running of the timer, TIMERID, after the current code finishes.
killtimer() with no timer stops all settimer operations for the current tab/window.



The File System


    $RETURN = appendfile(FILEPATH, DATA);                                        Since version 75.0

Appends the DATA to the file specified in FILEPATH.
Returns the length if successful or false if file not found.
If the file in FILEPATH does not exist, appendfile will create it.


    $RETURN = copyfile(SOURCEPATH, TARGETPATH);                                  Since version 75.0

Copies the file specified in SOURCEPATH to the file specified in TARGETPATH.
Returns true if successful or false if failed.


    $RETURN = deletefile(FILEPATH);                                              Since version 75.0

Deletes the file specified in FILEPATH.
Returns true if successful.


    $EXISTS = fileexists( PATH );                                                Since version 75.0

Returns true if the specified file exists.


    $RETURN = mkdir(FOLDERPATH(1));                                          Since version 75.0

Creates the folder specified in FOLDERPATH.
(1)A folderpath must end with the new folder name followed by //.
Important- Returns an integer 0 if successful or an integer > 1 if failed.
An attempt to create an existing folder will return integer = 1.


    $RETURN = renamefile(OLDFILEPATH, NEWFILEPATH);                              Since version 75.0

Renames the file specified in OLDFILEPATH to the file specified in NEWFILEPATH.
Returns true if successful.


    $writeReturn = writefile(FILEPATH, DATA);                                    Since version 75.0

Writes the DATA to the file specified in FILEPATH.
Returns the length if successful or false if file not found.
Important- If FILEPATH exists, writefile will overwrite without notice being given.


The Browser

 
   $PATH = getfolder( FOLDER_TYPE );                                             Since version 1.1

Returns the path of the specified folder.
FOLDER_TYPE = RootFolder | SettingsFolder | ProfileFolder | ResFolder | SkinFolder | MacroFolder | UserMacroFolder


 
   id( COMMAND_ID );                                                             Since version 0.7

Sends a message ID to the current window. See the complete list of command IDs.
(1)Since K-Meleon 1.6, command names may be used in place of command IDs.


 
   logmsg( MESSAGE TEXT [ , TYPE ] ) ;                                          Since version 75.0

Sends a message which shows in the Error Console.

TYPE Results
error Classes the log as a KMM error and includes a timestamp.
warning Classes the log as a KMM warning and includes a timestamp.
none Does not class the log and does not include a timestamp.



   macros( MACRO1 );                                                             Since version 0.7

Executes another macro.

    &MACRO;

Equivalent to macros( MACRO ).

   macros( MACRO1 [,MACRO2 [,MACRO3 [...]]] );                                  Since version 1.1 

Expanded to handle Multiple macro execution in version 1.1



    $SUCCESS = addperm( URL, TYPE, PERMISSION [, SESSION_ONLY] );               Since version 75.0

Add a new permission for the specified site and return true when successful.
TYPE = "cookie", "image", "popup", "subdocument"?, "script"?, "media"?, "stylesheet"?, ...
PERMISSION = "allow", "deny", "prompt"
SESSION_ONLY = For cookies only. If true, permission will be deleted when k-meleon exit

Prompt means ask each time, possible only for certain types.
Note: for viewing or resetting those permissions, other tools must be used. Some are accessible via Tools > Privacy > Permissions, or F2 > Javascript, or addon ExExceptions etc.


The Browser Preference System

   delpref( prefName );                                                          Since version 0.9

Deletes any user set value of the specified preference. This restores the preference's default value if one is set, otherwise the preference is expunged.

   
   $VALUE = getpref( TYPE, "user.preference.variable" );                             Since version 0.7

Gets a user preference.
TYPE = BOOL | INT | STRING

    
   setpref( TYPE, "user.preference.variable", VALUE );                                     Since version 0.6

Sets a user preference.
TYPE = BOOL | INT | STRING

 
   togglepref( TYPE, "user.preference.variable"[, VALUE1, VALUE2, ... ]);       Since version 0.6        

Toggles a user preference between a series of values (booleans always toggle between true and false).
TYPE = BOOL | INT | STRING
Example: togglepref(INT,"permissions.default.image",1,2,3);

The K-Meleon Plugins

    plugin( PLUGIN, COMMAND );                                                                          Since version 0.7

   pluginmsg( PLUGIN, COMMAND, ARGS );                                                     Since version 0.7

    $REPLY = pluginmsgex( PLUGIN, COMMAND, ARGS, TYPE );                  Since version 0.7

Runs a plugin command. The possible values of COMMAND, ARGS and TYPE depend on the specific plugin. See the complete list of plugin commands.

    $EXIST = pluginexist( PLUGIN NAME );                                                          Since version 75.0

Returns true if the plugin file exists in either root/kplugins or profile/kplugins, and the
plugin is loaded.
Example: $EXIST = pluginexist( fullscreen ); sets $EXIST to true if fullscreen.dll exists
in a kplugins folder and the pref "kmeleon.plugins.fullscreen.load" is true.


The Network

   $RETURN = download( URL [, FUNCTION NAME, ARGUMENT ]);                     Since version 75.1

$RETURN is true if the download has started.
Example:

---
function afterdownload($ARG) {
     alert("Download complete : ".$ARG);
}

download("http://something",  afterdownload, "Something");
---

The first argument is the url. The next two arguments are optional.
The second argument is the name of the function to call when download is finished.
The third argument is the argument to use when calling the function.


The Clipboard

    $TEXT = getclipboard();                                                      Since version 0.7

Gets data from the clipboard.

    setclipboard( TEXT );                                                        Since version 0.7

Sets data to the clipboard.

Note: Those clipboard commands are only necessary for exchange with other programs. For use inside KM itself use $SelectedText instead. KM fills this variable automatically if any text is selected in the current page. This way the user doesn't lose his own clipboard contents.


The Statusbar

    statusbar( TEXT );                                                           Since version 0.7

Shows the message text on the status bar.

Alphabetical Index

  
 * $ARG                         
 * $CHARSET                        
 * $FrameURL                                
 * $ImageURL                        
 * $LinkURL                        
 * $SelectedText        
 * $TextZoom        
 * $TITLE                        
 * $URL                        
 * $URLBAR
 * $VERSION
 * _()                        
 * addbutton()
 * addtoolbar() 
 * addperm()  
 * alert()
 * appendfile()
 * basename()
 * checkbutton()         
 * confirm()
 * copyfile()
 * date()
 * deletefile()
 * delpref()                        
 * dirname()
 * download()
 * enablebutton()         
 * exec()
 * fileexists()         
 * forcecharset()        
 * gensub()
 * getclipboard()        
 * getfolder()                
 * getpref()        
 * gsub()
 * hostname()
 * id()
 * if() 
 * index()
 * iniread()
 * iniwrite()        
 * injectCSS()        
 * injectJS()
 * killtimer() 
 * length()
 * logmsg()        
 * macroinfo
 * macros()        
 * menuchecked        
 * menugrayed
 * mkdir()
 * OnActivateWindow
 * OnCloseGroup
 * OnCloseTab
 * OnCloseWindow
 * OnInit
 * OnLoad
 * OnLoadOnce
 * OnOpenTab
 * OnOpenWindow
 * OnQuit
 * OnSetup
 * OnStartup
 * OnSwitchTab
 * OnWMAppExit
 * open()        
 * openbg() 
 * openbgtab() 
 * opennew() 
 * opentab() 
 * plugin()
 * pluginexist()
 * pluginmsg()
 * pluginmsgex()
 * popupmenu()        
 * prompt()                
 * promptforfile()        
 * promptforfolder()        
 * readfile()
 * readreg()        
 * rebuildmenu()
 * removebutton()
 * renamefile()
 * setaccel()
 * setbuttonimg()
 * setcheck()          
 * setclipboard()        
 * setcmdicon() 
 * setmenu()        
 * setpref()        
 * settimer()        
 * statusbar()        
 * sub()        
 * substr()
 * time()        
 * togglepref()
 * urldecode()
 * urlencode()
 * while()
 * writefile()         
K-Meleon

(c) 2000-2010 kmeleonbrowser.org. All rights reserved.
design by splif.