Last Updated On: April 28, 2023

Welcome

Welcome to Onetastic Macro Documentation. Start with one of the following topics:

Getting Started with Macros

Macros are small programs that can be used to perform simple repetitive tasks in OneNote very quickly. The idea is similar to macros in other Office applications which use VBA language. OneNote does not support VBA and Onetastic add-in provides a simple macro language and an editor to build macros.

The main mechanism under which macros operate is as following:

  1. Read data from OneNote (e.g. page content or notebook/section/page hierarchy)
  2. Modify this data
  3. Save the data back to OneNote

Macro Structure

A macro consist of a list of statements which may look like this:

ExpandForEach ($Paragraph in QueryObjects("Paragraph", GetCurrentPage())) ExpandIf (String_Contains($Paragraph.author, "John")) $Paragraph.highlightColor = "yellow"

The above macro will highlight all paragraphs that is last edited by someone named John.

Macro Editor

Macro Editor

Macro Editor can be accessed from Edit Macros and New Macro buttons on the ribbon. It can be used for:

User Interface

Macro Editor

See Menus and Toolbar for an explanation of how to use the editor

Menus and Toolbar

Macro Editor has menus and a toolbar to edit and debug the macro. The toolbar contains the most used actions:

Macro Editor Toolbar

Menus contain all these buttons and additional items for editing the macro:

Editing Macro Statements

Inserting, Removing and Moving Macro Statements

Macro Editor has a set of statement buttons and a large pane that contains the contents of the current macro. You can use the statement buttons (Alt+1 to Alt+9) to insert new statements to the macro and use Delete key to remove them from the macro. You can also use the up/down buttons on the right to move the statements up and down as well as in an out of parent statements. The statements can be collapsed/expanded using the little arrows to the left of them.

Editing Individual Statements

Each statement has one or more editable parts. To edit them click on those parts or use the keyboard shortcuts explained below. Below image shows the editable parts of the statement in red rectangles.

Editable areas in statements

Keyboard Shortcuts

Most statements contain a single expression which can be edited by pressing the Enter key. For statement consists of 3 expressions, each of which can be edited by Enter, Ctrl+Enter and Ctrl+Alt+Enter keys respectively. ForEach statement consists of a loop variable and a array expression. The loop variable can be edited by the Enter key while the array expression can be edited by Ctrl+Enter key. There are some other keyboard shortcuts for various operations:

Shortcut Action
1 to 9 Insert statement
Enter Edit the expression in the selected statement
Ctrl+Enter Edit the conditional expression of the selected For statement or the array expression of the selected ForEach statement
Ctrl+Alt+Enter Edit the increment expression of the selected For statement
Ctrl+Up Move selected statement up
Ctrl+Down Move selected statement down
Left Arrow Collapse selected statement
Right Arrow Expand selected statement
Delete Delete the selected statement

Expression Editor

After clicking on an expression or using the corresponding shortcut key, the Expression Editor is displayed which allows editing the expression, checking its syntax and compiling back into the macro. The Expression Editor displays any syntax errors or the correctly parsed expression and a function reference where you can see the signatures of the functions that exist in the expression to help with development.

Expression Editor

Macro Debugging

Macro Editor allows running macros step by step under the debugger via the
Debug > Start Debugging (F10) command or the Debug > Run under Debugger (F5) command. This will switch the editor into the debugger mode and will display the next statement with a  yellow background, activate the Object Browser with local variables:

Macro Debugger

Once in the debugger mode, you can step through the macro and see the local variables in the Object Browser. Following menu and toolbar will appear in debug mode:

Macro Editor Debug Toolbar

Breakpoints

You can set a breakpoint on a statement using Toggle Breakpoint button or the F9 key. This works both in the editor and in the debugger. The statements with a breakpoint will show with a  maroon background  and the debugger will stop when it hits one of the breakpoints.

Object Browser

Macro Debugger automatically displays the Object Browser on the right. Object Browser allows browsing OneNote hierarchy under Current Page, Section, Section Group, Notebook and under all notebooks. This way you can look into how the objects and their properties are stored in OneNote. This is also useful while editing a macro and can be activated using View > Object Browser (Ctrl+J). Object Browser displays local variables currently in use in the macro under Locals section, allowing you to see the types and values of them.

Demonstration

Watch the short video here to learn more about how to use these tools.

How To

Using variables

Macro language has variables, for temporarily storing and manipulating information. Variables can be of various types including objects and arrays. Variables are named with a dollar sign ($) followed by an identifier. The valid characters in the variable name are a-z, A-Z, 0-9 and underscore (_). Following macro demonstrate use of variables to store the list of cells in a page and to store the text of the first cell to fill the rest of the cells with:

$Cells = QueryObjects("Cell", GetCurrentPage()) $i = 0 ExpandForEach ($Cell in $Cells) ExpandIf ($i == 0) $TextOfFirstCell = $Cell.text ExpandElse $Cell.text = $TextOfFirstCell $i += 1

Here $Cells, $Cell, $i, $TextOfFirstCell are all variables storing an array of Cell objects, a Cell object, an integer, and a string respectively.

Finding and modifying objects

Macros typically work by finding objects in OneNote and modifying their properties. There are several functions that provide direct access to notebooks, sections and pages in OneNote as well as provide ability to search through them. Following macro demonstrates these functions:

// Functions to get the current page, section, section group or notebook $CurrentPage = GetCurrentPage() $CurrentSection = GetCurrentSection() $CurrentSectionGroup = GetCurrentSectionGroup() $CurrentNotebook = GetCurrentNotebook() // You can also access the notebook root which stores all the notebooks $NotebookRoot = GetNotebookRoot() // If you want to search some objects, you can do so $Images = QueryObjects("Image", $CurrentPage) // You can also search text // Case sensitive $AllInstancesOfTheWordOnetastic = QueryText($CurrentPage, "Onetastic", true) // Case insensitive $AllInstancesOfTheWordOnetastic = QueryText($CurrentPage, "Onetastic", false) // Once you have an object, you can go up to find its parent or ancestors $FirstOnetastic = $AllInstancesOfTheWordOnetastic[0] ExpandIf (GetParentOfType($FirstOnetastic, "Paragraph", $ParentParagraph)) // Found the parent paragraph ExpandIf (GetAncestorOfType($FirstOnetastic, "Notebook", $ContainingNotebook)) // Found the containing notebook

Accessing object properties

To read or modify properties of objects, you can use the property accessor operator (.).

// Get the name of the current section $Name = GetCurrentPage().name // Modify the section name and color $CurrentSection = GetCurrentSection() $CurrentSection.name = "new name" $CurrentSection.color = "yellow" // Get the second section in the first notebook $Section = GetNotebookRoot().notebooks[0].sections[1]

Creating new page content

With macros you can create new pages and new content on pages in OneNote. The InsertObject function allows creating new pages, outlines, paragraphs and tables.

Creating new pages

To create a new page, you need to insert a new Page object to a Section object. You can specify where in the section you want to create the new page:

// Create a new page at the top of the current section // The last parameter is position and it is 0 based index InsertObject(GetCurrentSection(), "Page", 0) // Now create another one at the bottom InsertObject(GetCurrentSection(), "Page", -1) // Now create another one after 3rd page. It will be the // 4th page in the section, so specify the position #3 InsertObject(GetCurrentSection(), "Page", 3)

Creating new page content

You can create new page content in an existing page or a newly created page. Simply add more InsertObject functions to create the new objects. After creating each object, you can modify its properties or create more content below it:

// Create an Outline and a Paragraph in the current page $Page = GetCurrentPage() $Outline = InsertObject($Page, "Outline", -1) $Paragraph = InsertObject($Outline, "Paragraph", 0) $Paragraph.text = "Below is a table" // Now create a table $Table = InsertObject($Outline, "Table", -1) $Row = InsertObject($Table, "Row", -1) $Cell = InsertObject($Row, "Cell", -1) $Paragraph = InsertObject($Cell, "Paragraph", -1) $Text = InsertObject($Paragraph, "Text", -1) $Text.value = "First" $Text.bold = true // Add More text in this paragraph InsertObject($Paragraph, "Text", -1).value = " cell" // Add more cells InsertObject($Row, "Cell", -1).text = "A second cell"

Asking for user input

You can ask user for input during macro execution to modify behavior of the macro or you can display a message box to the user. For instance if you are building a macro that will search for some text (e.g. Search & Replace) you may ask the user for the search term or use a message box to display the number of words in a Word Count macro. To do so, you can use Dialog Box functions. Following demonstrates an example:

// Create a new dialog box $dialog_box = DialogBox_Create("") // Now add some controls // Text box with label "Find what", stored at $dialog_box.controls["Search"], // initial value empty string ("") and it is NOT OK for user to leave it empty DialogBox_AddTextBox($dialog_box, "&Find what", "Search", "", false) // Text box with label "Replace with", stored at $dialog_box.controls["Replace"], // initial value empty string ("") and it is OK for user to leave it empty DialogBox_AddTextBox($dialog_box, "&Replace with", "Replace", "", true) // Drop down with label "Scope", stored at $dialog_box.controls["Scope"], // initial value of "Current section" with a two other possible options $Options = Array("Current page", "Current section", "Current notebook") DialogBox_AddDropDown($dialog_box, "&Scope", "Scope", "Current section", $Options) // Check box with label "Match case", stored at $dialog_box.controls["MatchCase"], // initially unchecked (false) DialogBox_AddCheckBox($dialog_box, "Match &case", "MatchCase", false) // Now show the dialog box DialogBox_Show($dialog_box) // We can now use the values for the controls using $dialog_box.controls $Search = $dialog_box.controls["Search"]

This is part of the Search & Replace macro and it will display the following dialog box:

User Prompt

Here the DialogBox_Create function creates a new dialog box object. Then we add some controls to it. Text boxes, drop down controls and check boxes can be added. Finally DialogBox_Show function displays the dialog box.

Labels for the controls

Here we are adding some labels to each of these controls. "Find what", "Replace with" and "Scope" are displayed to the left of the text box and drop down controls. "Match case" is displayed to the right of the check box control. The ampersand (&) character specifies the shortcut key for the corresponding control. For instance Alt+F in the dialog will focus on the "Find what" text box, Alt+R will focus on the "Replace with" text box and so on.

Providing possible values

For drop down controls, you can specify a set of possible values in the form of an array of strings.

Providing initial values

You can provide an initial value to each of these controls. An initial value for the text box will show as text in the text box as string. An intial value for the drop down control must be one of the provided possible values and will show as the selected value for it. An initial value for a check box must be a bool value, true for checked and false for unchecked.

Making text boxes required

You can make a text box required, such that the user cannot leave it empty. For instance in this dialog above, the "Find what" text box is made required, by providing false on the last parameter. If user leaves it empty the OK button on the dialog will remain disabled.

Reading the values the user has provided

The values the user has provided in the dialog box is being stored in the "controls" member of the dialog box object. This member will be empty until the DialogBox_Show function is called and after that it will be an array that contains the values provided by the user

Displaying messages

If you wish to only display a message, you can use ShowMessage function:

ShowMessage("No instances of the search term is found")
Message Box

Task dialogs

If you want user to pick form a few actions and no other input is required, a task dialog may be a suitable option.

Task Dialog

See ShowTaskDialog API for example usage.

Storing persistent data

You can store and retrieve data for a particular macro on the local computer by using the LocalStore_Write and LocalStore_Read functions. The data stored by LocalStore_Write can be read back on a separate execution of the same macro, allowing data to be persisted accross multiple executions. Data cannot be shared between different macros.

Improving dialog boxes with persistent data

One very useful way to use persistent data is to store and remember user input for subsequent executions of a macro. For instance Search & Replace macro remembers the values user entered in the dialog box so that it can present those same values when the user runs the macro again. Similarly settings in a macro, like which day of the week the calendar should start for Insert Monthly Calendar macro, can be stored and retrieved.
// Check if we have values stored from a previous run // If so, we will use them as initial values of dialogbox controls ExpandIf (!LocalStore_Read("LastSearch", $Search)) $Search = "" ExpandIf (!LocalStore_Read("LastReplace", $Replace)) $Replace = "" ExpandIf (!LocalStore_Read("LastScope", $Scope)) $Scope = "Current section" ExpandIf (!LocalStore_Read("LastMatchCase", $MatchCase)) $MatchCase = false // Create a new dialog box $dialog_box = DialogBox_Create("") // Now add some controls DialogBox_AddTextBox($dialog_box, "&Find what", "Search", $LastSearch, false) DialogBox_AddTextBox($dialog_box, "&Replace with", "Replace", $LastReplace, true) $Options = Array("Current page", "Current section", "Current notebook") DialogBox_AddDropDown($dialog_box, "&Scope", "Scope", $LastScope, $Options) DialogBox_AddCheckBox($dialog_box, "Match &case", "MatchCase", $LastMatchCase) // Now show the dialog box DialogBox_Show($dialog_box) // We can now use the values for the controls using $dialog_box.controls $Search = $dialog_box.controls["Search"] $Replace = $dialog_box.controls["Replace"] $Scope = $dialog_box.controls["Scope"] $MatchCase = $dialog_box.controls["MatchCase"] // Now store these values so that we can read them back in a subsequent run LocalStore_Write("LastSearch", $Search) LocalStore_Write("LastReplace", $Replace) LocalStore_Write("LastScope", $Scope) LocalStore_Write("LastMatchCase", $MatchCase)

Using binary data

OneNote pages can contain external files in the form of Images and EmbeddedFiles. These objects store the actual data for the image or the embedded file in their data properties. You can duplicate an image by copying the data property:

// Find an existing image on a page $page = GetCurrentPage() $existingImage = $page.images[0] // Create a new image $newImage = InsertObject($page, "Image", -1) // Copy the binary data $newImage.data = $existingImage.data

This macro will create a second image on the same page and copy the existing image data to it, creating a copy of the image.

Binary Store

In order to create new images or embedded files, the data property must be set to a valid binary data. While macros can copy such data from existing content, as seen above, they can also store such data and use it to create new content. Binary store is where macros can store files to be used to create images and embedded files.

To access binary store for a macro you can go to Storage > Edit Binary Storage on the menu. This will display the Binary Store window:

Binary Store

You can use Add Files button to choose one or more files to add to the binary store. After adding files, you can rename them or remove any files you don't need:

Binary Store with Files

Using files from Binary Store

You can use files from binary store via the BinaryStore_Read function. Pass the name of the file in the binary store to access it:

$page = GetCurrentPage() // Create a new image $newImage = InsertObject($page, "Image", -1) // Set the binary data $newImage.data = BinaryStore_Read("flower.png")

This will create a new image using the flower.png file in the binary store. Binary store is per macro. You cannot access files from binary store of one macro from another macro. If you need to use the same files, simply add them to each macro.

Sorting objects

Macros can sort a set of objects by any property or value. This is done throught the SortObjects function. A simple sort macro looks like this:

$Paragraphs = QueryObjects("Paragraph", GetCurrentPage()) SortObjects($Paragraphs, "text", true)

This macro will sort every paragraph in the current page alphabetically (property "text" was provided in the second parameter) in ascending order (true was provided in the last parameter).

Custom Sort Orders

You can also define custom sort orders by making use of arrays. Below macro will sort each paragraph by the second letter that appears in the paragraph:

$Paragraphs = QueryObjects("Paragraph", GetCurrentPage()) $SecondLetters = Array() ExpandForEach ($Paragraph in $Paragraphs) Array_PushBack($SecondLetters, String_SubString($Paragraph.text, 1, 1)) SortObjects($Paragraphs, $SecondLetters, true)

For the custom sorting, the second parameter to SortObjects must be an array that has indices 0 to number of elements being sorted. Each corresponding value in the array will then be compared to determine the order.

Sorting Objects that aren't Siblings

When sorting objects that are not under the same parent object, they are sorted only within their siblings. For instance if you try to sort all pages in current notebook, they will be sorted within each section and they won't move between sections. Similarly if you sort paragraphs in a page, paragraphs in same outline will be sorted together but not across outlines. This is the desired behavior for most cases and will prevent simple mistakes to mix everything up on your pages or notebooks.

Macro menus

Each macro adds a button to the ribbon to run the macro. Optionally, macros can display a menu in the ribbon for more options. For example, Function macro displays the following menu:

Function macro menu

Macro menus can be static or dynamically generated based on user's usage patterns. For instance a macro like Search and Replace may display the recently used search and replace terms in the menu.

Setup function

Both static and dynamic menus are created by the Setup function. Setup function is a user defined function in a macro which will get called whenever Onetastic needs to get a macro's menu to be displayed in the ribbon. Below is a sample Setup function:

ExpandFunction Setup(byref $menu) MacroMenu_AddItem($menu, "arg1", "Menu Item 1", "Description for Menu Item 1") MacroMenu_AddItem($menu, "arg2", "Menu Item 2", "Description for Menu Item 2") MacroMenu_AddItem($menu, "arg3", "Menu Item 3", "Description for Menu Item 3")

Setup function always has a single parameter byref $menu. This parameter is an object of type MacroMenu. You can then use the MacroMenu_AddItem function to add menu items. A macro with this Setup function will have the following menu:

A macro menu

Each menu item is associated with an argument that will be passed to Main function when user clicks on that menu item. In this case if user clicks the first menu item, Main function for this macro will be called with the argument "arg1".

Performance Considerations

Setup function will get called every time Onetastic needs to refresh the menu for each macro. This can be after a macro execution, after a macro is edited, or after a new macro is downloaded. To avoid performance problems, Setup function should do minimal work and should not be running for a long time. Setup function for a macro will get aborted if it runs long and the menu for that macro will not be visible. Setup function also cannot access OneNote content or show dialog boxes.

Creating and Editing Setup Function

Macro editor makes it easy to create a setup function quickly via the following menu:

Create Macro Menu

This will create a sample Setup function which you can use to quickly edit. If a Setup function already exists, this will switch to it.

Debugging Menu Items

As macro menu items pass arguments to the main function, you may want to debug the execution of your macro with such arguments. The debug button in the Macro Editor toolbar has a split menu that makes it easy to pick the menu items and debug their execution:

Debugging Macro Menu

This menu will display each menu item and clicking on one of them will start the debugger with the associated argument passed to the Main function.

Bulleted and Numbered Lists

Paragraph objects can be part of bulleted or numbered lists. To check whether a paragraph is part of a bulleted or numbered list, you can use one of the following properties:

You can set isPartOfBulletedList or isPartOfNumberedList property to true to create a bulleted or numbered paragraph. Setting them to false will remove the bullet or number.

Bullet Types

Paragraph objects that are part of a bulleted list have the bulletType property indicating what type of bullet they are displaying. Valid bullet type values are given below:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33

Below is an example of how to create bulleted lists:

// Get the first outline in the current page $outline = GetCurrentPage().outlines[0] // Insert a new paragraph $p = InsertObject($outline, "Paragraph", -1) $p.indent = 1 $p.text = "Main Item 1" $p.isPartOfBulletedList = true $p.bulletType = 2 // Insert a new paragraph $p = InsertObject($outline, "Paragraph", -1) $p.indent = 2 $p.text = "Sub Item 1" $p.isPartOfBulletedList = true $p.bulletType = 3 // Insert a new paragraph $p = InsertObject($outline, "Paragraph", -1) $p.indent = 2 $p.text = "Sub Item 2" $p.isPartOfBulletedList = true $p.bulletType = 3 // Insert a new paragraph $p = InsertObject($outline, "Paragraph", -1) $p.indent = 1 $p.text = "Main Item 2" $p.isPartOfBulletedList = true $p.bulletType = 2 // Result will be like this: // ● Main Item 1 // ○ Sub Item 1 // ○ Sub Item 2 // ● Main Item 2

Number Sequences

Paragraph objects that are part of a numbered list have the numberSequence property indicating what type of number sequence they are displaying. Valid number sequence values are given below:

Seq Name Example
English (Expand)
0 Arabic 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
1 Roman Capital I, II, III, IV, V, VI, VII, VIII, IX, X, XI, XII, XIII, XIV, XV, XVI, XVII, XVIII, XIX, XX, XXI, XXII, XXIII, XXIV, XXV, XXVI, XXVII, XXVIII, XXIX, XXX
2 Roman Small i, ii, iii, iv, v, vi, vii, viii, ix, x, xi, xii, xiii, xiv, xv, xvi, xvii, xviii, xix, xx, xxi, xxii, xxiii, xxiv, xxv, xxvi, xxvii, xxviii, xxix, xxx
3 Letter Capital A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, AA, BB, CC, DD
4 Letter Small a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, aa, bb, cc, dd
5 Ordinal 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th, 11th, 12th, 13th, 14th, 15th, 16th, 17th, 18th, 19th, 20th, 21st, 22nd, 23rd, 24th, 25th, 26th, 27th, 28th, 29th, 30th
6 Cardinal Text One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Eleven, Twelve, Thirteen, Fourteen, Fifteen, Sixteen, Seventeen, Eighteen, Nineteen, Twenty, Twenty-one, Twenty-two, Twenty-three, Twenty-four, Twenty-five, Twenty-six, Twenty-seven, Twenty-eight, Twenty-nine, Thirty
7 Ordinal Text First, Second, Third, Fourth, Fifth, Sixth, Seventh, Eighth, Ninth, Tenth, Eleventh, Twelfth, Thirteenth, Fourteenth, Fifteenth, Sixteenth, Seventeenth, Eighteenth, Nineteenth, Twentieth, Twenty-first, Twenty-second, Twenty-third, Twenty-fourth, Twenty-fifth, Twenty-sixth, Twenty-seventh, Twenty-eighth, Twenty-ninth, Thirtieth
8 Hexadecimal 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1A, 1B, 1C, 1D, 1E
9 Chicago Manual of Style *, †, ‡, §, **, ††, ‡‡, §§, ***, †††, ‡‡‡, §§§, ****, ††††, ‡‡‡‡, §§§§, *****, †††††, ‡‡‡‡‡, §§§§§, ******, ††††††, ‡‡‡‡‡‡, §§§§§§, *******, †††††††, ‡‡‡‡‡‡‡, §§§§§§§, ********, ††††††††
22 Decimal Leading Zero 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
57 Number in Dash - 1 -, - 2 -, - 3 -, - 4 -, - 5 -, - 6 -, - 7 -, - 8 -, - 9 -, - 10 -, - 11 -, - 12 -, - 13 -, - 14 -, - 15 -, - 16 -, - 17 -, - 18 -, - 19 -, - 20 -, - 21 -, - 22 -, - 23 -, - 24 -, - 25 -, - 26 -, - 27 -, - 28 -, - 29 -, - 30 -
Japanese (Expand)
10 Ideograph Digital 一, 二, 三, 四, 五, 六, 七, 八, 九, 一〇, 一一, 一二, 一三, 一四, 一五, 一六, 一七, 一八, 一九, 二〇, 二一, 二二, 二三, 二四, 二五, 二六, 二七, 二八, 二九, 三〇
11 Japanese Counting 一, 二, 三, 四, 五, 六, 七, 八, 九, 十, 十一, 十二, 十三, 十四, 十五, 十六, 十七, 十八, 十九, 二十, 二十一, 二十二, 二十三, 二十四, 二十五, 二十六, 二十七, 二十八, 二十九, 三十
12 Aiueo ア, イ, ウ, エ, オ, カ, キ, ク, ケ, コ, サ, シ, ス, セ, ソ, タ, チ, ツ, テ, ト, ナ, ニ, ヌ, ネ, ノ, ハ, ヒ, フ, ヘ, ホ
13 Iroha イ, ロ, ハ, ニ, ホ, ヘ, ト, チ, リ, ヌ, ル, ヲ, ワ, カ, ヨ, タ, レ, ソ, ツ, ネ, ナ, ラ, ム, ウ, ヰ, ノ, オ, ク, ヤ, マ
14 Decimal Full Width 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
15 Decimal Half Width 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
16 Japanese Legal 壱, 弐, 参, 四, 伍, 六, 七, 八, 九, 壱拾, 壱拾壱, 壱拾弐, 壱拾参, 壱拾四, 壱拾伍, 壱拾六, 壱拾七, 壱拾八, 壱拾九, 弐拾, 弐拾壱, 弐拾弐, 弐拾参, 弐拾四, 弐拾伍, 弐拾六, 弐拾七, 弐拾八, 弐拾九, 参拾
17 Japanese Digital Ten Thousand 一, 二, 三, 四, 五, 六, 七, 八, 九, 一〇, 一一, 一二, 一三, 一四, 一五, 一六, 一七, 一八, 一九, 二〇, 二一, 二二, 二三, 二四, 二五, 二六, 二七, 二八, 二九, 三〇
18 Decimal Enclosed Circle ①, ②, ③, ④, ⑤, ⑥, ⑦, ⑧, ⑨, ⑩, ⑪, ⑫, ⑬, ⑭, ⑮, ⑯, ⑰, ⑱, ⑲, ⑳, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
19 Decimal Full Width 2 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
20 Aiueo Full Width ア, イ, ウ, エ, オ, カ, キ, ク, ケ, コ, サ, シ, ス, セ, ソ, タ, チ, ツ, テ, ト, ナ, ニ, ヌ, ネ, ノ, ハ, ヒ, フ, ヘ, ホ
21 Iroha Full Width イ, ロ, ハ, ニ, ホ, ヘ, ト, チ, リ, ヌ, ル, ヲ, ワ, カ, ヨ, タ, レ, ソ, ツ, ネ, ナ, ラ, ム, ウ, ヰ, ノ, オ, ク, ヤ, マ
Chinese (Expand)
26 Decimal Enclosed Full stop ⒈, ⒉, ⒊, ⒋, ⒌, ⒍, ⒎, ⒏, ⒐, ⒑, ⒒, ⒓, ⒔, ⒕, ⒖, ⒗, ⒘, ⒙, ⒚, ⒛, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
27 Decimal Enclosed Parenthesis ⑴, ⑵, ⑶, ⑷, ⑸, ⑹, ⑺, ⑻, ⑼, ⑽, ⑾, ⑿, ⒀, ⒁, ⒂, ⒃, ⒄, ⒅, ⒆, ⒇, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
28 Decimal Enclosed Circle ①, ②, ③, ④, ⑤, ⑥, ⑦, ⑧, ⑨, ⑩, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
29 Ideograph Enclosed Circle ㈠, ㈡, ㈢, ㈣, ㈤, ㈥, ㈦, ㈧, ㈨, ㈩, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
30 Ideograph Traditional 甲, 乙, 丙, 丁, 戊, 己, 庚, 辛, 壬, 癸, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
31 Ideograph Zodiac 子, 丑, 寅, 卯, 辰, 巳, 午, 未, 申, 酉, 戍, 亥, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
32 Ideograph Zodiac Traditional 甲子, 乙丑, 丙寅, 丁卯, 戊辰, 己巳, 庚午, 辛未, 壬申, 癸酉, 甲戍, 乙亥, 丙子, 丁丑, 戊寅, 己卯, 庚辰, 辛巳, 壬午, 癸未, 甲申, 乙酉, 丙戍, 丁亥, 戊子, 己丑, 庚寅, 辛卯, 壬辰, 癸巳
33 Taiwanese Counting 一, 二, 三, 四, 五, 六, 七, 八, 九, 十, 十一, 十二, 十三, 十四, 十五, 十六, 十七, 十八, 十九, 二十, 二十一, 二十二, 二十三, 二十四, 二十五, 二十六, 二十七, 二十八, 二十九, 三十
34 Ideograph Legal Traditional 壹, 貳, 參, 肆, 伍, 陸, 柒, 捌, 玖, 壹拾, 壹拾壹, 壹拾貳, 壹拾參, 壹拾肆, 壹拾伍, 壹拾陸, 壹拾柒, 壹拾捌, 壹拾玖, 貳拾, 貳拾壹, 貳拾貳, 貳拾參, 貳拾肆, 貳拾伍, 貳拾陸, 貳拾柒, 貳拾捌, 貳拾玖, 參拾
35 Taiwanese Counting Thousand 一, 二, 三, 四, 五, 六, 七, 八, 九, 十, 十一, 十二, 十三, 十四, 十五, 十六, 十七, 十八, 十九, 二十, 二十一, 二十二, 二十三, 二十四, 二十五, 二十六, 二十七, 二十八, 二十九, 三十
36 Taiwanese Digital 一, 二, 三, 四, 五, 六, 七, 八, 九, 一○, 一一, 一二, 一三, 一四, 一五, 一六, 一七, 一八, 一九, 二○, 二一, 二二, 二三, 二四, 二五, 二六, 二七, 二八, 二九, 三○
37 Chinese Counting 一, 二, 三, 四, 五, 六, 七, 八, 九, 十, 十一, 十二, 十三, 十四, 十五, 十六, 十七, 十八, 十九, 二十, 二十一, 二十二, 二十三, 二十四, 二十五, 二十六, 二十七, 二十八, 二十九, 三十
38 Chinese Legal Simplified 壹, 贰, 叁, 肆, 伍, 陆, 柒, 捌, 玖, 壹拾, 壹拾壹, 壹拾贰, 壹拾叁, 壹拾肆, 壹拾伍, 壹拾陆, 壹拾柒, 壹拾捌, 壹拾玖, 贰拾, 贰拾壹, 贰拾贰, 贰拾叁, 贰拾肆, 贰拾伍, 贰拾陆, 贰拾柒, 贰拾捌, 贰拾玖, 叁拾
39 Chinese Counting Thousand 一, 二, 三, 四, 五, 六, 七, 八, 九, 十, 十一, 十二, 十三, 十四, 十五, 十六, 十七, 十八, 十九, 二十, 二十一, 二十二, 二十三, 二十四, 二十五, 二十六, 二十七, 二十八, 二十九, 三十
40 Decimal 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
Korean (Expand)
24 Ganada

가, 나, 다, 라, 마, 바, 사, 아, 자, 차, 카, 타, 파, 하, 가, 나, 다, 라, 마, 바, 사, 아, 자, 차, 카, 타, 파, 하, 가, 나

25 Chosung

ㄱ, ㄴ, ㄷ, ㄹ, ㅁ, ㅂ, ㅅ, ㅇ, ㅈ, ㅊ, ㅋ, ㅌ, ㅍ, ㅎ, ㄱ, ㄴ, ㄷ, ㄹ, ㅁ, ㅂ, ㅅ, ㅇ, ㅈ, ㅊ, ㅋ, ㅌ, ㅍ, ㅎ, ㄱ, ㄴ

41 Korean Digital

일, 이, 삼, 사, 오, 육, 칠, 팔, 구, 일영, 일일, 일이, 일삼, 일사, 일오, 일육, 일칠, 일팔, 일구, 이영, 이일, 이이, 이삼, 이사, 이오, 이육, 이칠, 이팔, 이구, 삼영

42 Korean Counting

일, 이, 삼, 사, 오, 육, 칠, 팔, 구, 십, 십일, 십이, 십삼, 십사, 십오, 십육, 십칠, 십팔, 십구, 이십, 이십일, 이십이, 이십삼, 이십사, 이십오, 이십육, 이십칠, 이십팔, 이십구, 삼십

43 Korean Legal

하나, 둘, 셋, 넷, 다섯, 여섯, 일곱, 여덟, 아홉, 열, 열하나, 열둘, 열셋, 열넷, 열다섯, 열여섯, 열일곱, 열여덟, 열아홉, 스물, 스물하나, 스물둘, 스물셋, 스물넷, 스물다섯, 스물여섯, 스물일곱, 스물여덟, 스물아홉, 서른

44 Korean Digital 2

一, 二, 三, 四, 五, 六, 七, 八, 九, 一零, 一一, 一二, 一三, 一四, 一五, 一六, 一七, 一八, 一九, 二零, 二一, 二二, 二三, 二四, 二五, 二六, 二七, 二八, 二九, 三零

Hebrew (Expand)
45 Hebrew 1 א, ב, ג, ד, ה, ו, ז, ח, ט, י, יא, יב, יג, יד, טו, טז, יז, יח, יט, כ, כא, כב, כג, כד, כה, כו, כז, כח, כט, ל
47 Hebrew 2 א, ב, ג, ד, ה, ו, ז, ח, ט, י, כ, ל, מ, נ, ס, ע, פ, צ, ק, ר, ש, ת, תא, תב, תג, תד, תה, תו, תז, תח
Arabic (Expand)
46 Arabic Letters أ‌, ب‌, ت‌, ث‌, ج‌, ح‌, خ‌, د‌, ذ‌, ر‌, ز‌, س‌, ش‌, ص‌, ض‌, ط‌, ظ‌, ع‌, غ‌, ف‌, ق‌, ك‌, ل‌, م‌, ن‌, ه‌, و‌, ي‌, أ‌أ‌, ب‌ب‌
48 Arabic Abjad ‌أ, ‌ب, ‌ج, ‌د, ‌ه, ‌و, ‌ز, ‌ح, ‌ط, ‌ي, ‌ك, ‌ل, ‌م, ‌ن, ‌س, ‌ع, ‌ف, ‌ص, ‌ق, ‌ر, ‌ش, ‌ت, ‌ث, ‌خ, ‌ذ, ‌ض, ‌ظ, ‌غ, ‌أ‌أ, ‌ب‌ب
Hindi (Expand)
49 Hindi Vowels , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
50 Hindi Consonants , , , , , , , , , , , , , , , , अं, अः, अअ, आआ, इइ, ईई, उउ, ऊऊ, ऋऋ, ऌऌ, ऍऍ, ऎऎ, एए, ऐऐ
51 Hindi Numbers १, २, ३, ४, ५, ६, ७, ८, ९, १०, ११, १२, १३, १४, १५, १६, १७, १८, १९, २०, २१, २२, २३, २४, २५, २६, २७, २८, २९, ३०
52 Hindi Counting एक, दो, तीन, चार, पाँच, छः, सात, आठ, नौ, दस, ग्यारह, बारह, तेरह, चौदह, पंद्रह, सोलह, सत्रह, अठ्ठारह, उन्नीस, बीस, इक्कीस, बाईस, तेईस, चौबीस, पच्चीस, छब्बीस, सत्ताईस, अठ्ठाईस, उन्तीस, तीस
Thai (Expand)
53 Thai Letters , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
54 Thai Numbers ๑, ๒, ๓, ๔, ๕, ๖, ๗, ๘, ๙, ๑๐, ๑๑, ๑๒, ๑๓, ๑๔, ๑๕, ๑๖, ๑๗, ๑๘, ๑๙, ๒๐, ๒๑, ๒๒, ๒๓, ๒๔, ๒๕, ๒๖, ๒๗, ๒๘, ๒๙, ๓๐
55 Thai Counting หนึ่ง, สอง, สาม, สี่, ห้า, หก, เจ็ด, แปด, เก้า, สิบ, สิบเอ็ด, สิบสอง, สิบสาม, สิบสี่, สิบห้า, สิบหก, สิบเจ็ด, สิบแปด, สิบเก้า, ยี่สิบ, ยี่สิบเอ็ด, ยี่สิบสอง, ยี่สิบสาม, ยี่สิบสี่, ยี่สิบห้า, ยี่สิบหก, ยี่สิบเจ็ด, ยี่สิบแปด, ยี่สิบเก้า, สามสิบ
Vietnamese (Expand)
56 Vietnamese Counting một, hai, ba, bốn, năm, sáu, bảy, tám, chín, mười, mười một, mười hai, mười ba, mười bốn, mười lăm, mười sáu, mười bảy, mười tám, mười chín, hai mươi, hai mươi mốt, hai mươi hai, hai mươi ba, hai mươi bốn, hai mươi lăm, hai mươi sáu, hai mươi bảy, hai mươi tám, hai mươi chín, ba mươi
Russian (Expand)
58 Russian Small а, б, в, г, д, е, ж, з, и, к, л, м, н, о, п, р, с, т, у, ф, х, ц, ч, ш, щ, ы, э, ю, я, аа
59 Russian Capital А, Б, В, Г, Д, Е, Ж, З, И, К, Л, М, Н, О, П, Р, С, Т, У, Ф, Х, Ц, Ч, Ш, Щ, Ы, Э, Ю, Я, АА
Greek (Expand)
60 Greek Small α, β, γ, δ, ε, στ, ζ, η, θ, ι, ια, ιβ, ιγ, ιδ, ιε, ιστ, ιζ, ιη, ιθ, κ, κα, κβ, κγ, κδ, κε, κστ, κζ, κη, κθ, λ
61 Greek Capital Α, Β, Γ, Δ, Ε, ΣΤ, Ζ, Η, Θ, Ι, ΙΑ, ΙΒ, ΙΓ, ΙΔ, ΙΕ, ΙΣΤ, ΙΖ, ΙΗ, ΙΘ, Κ, ΚΑ, ΚΒ, ΚΓ, ΚΔ, ΚΕ, ΚΣΤ, ΚΖ, ΚΗ, ΚΘ, Λ

Number Format

In addition to the different number sequences you can get by setting the numberSequence property, you can also customize numbered lists by setting a format through the numberFormat property. This property is a string that contains "##" for the number sequence and any other characters to be displayed in the numbered list. The default value for numberFormat property is "##.". Below are some examples:

##.1., 2., 3.
##)1), 2), 3)
(##)(1), (2), (3)
##:1:, 2:, 3:
Item # ##Item # 1, Item # 2, Item # 3

For a paragraph in a numbered list, the resulting number text from the specified number format can be obtained by checking the read-only property numberText.

Sample Macros

You can find sample Macros in Macroland, specifically created to teach Macro concepts. They are under Samples category. More samples will be added in the future, so don't forget to check it out frequently.

Concepts

Expressions

Macro statements mostly evaluate expression to read or modify data. Expressions can be used to assign variables, access object properties, call functions and do arithmetic, logical or comparison operations. They can also provide literal values.

// Literal values: strings, numeric values and booleans "String Literal" 1234 3.5 true // Variables $name $format // Assignment $i = 0 $i += 1 $x = true $x &&= false $s = "text" $s &= " more text" // Arithmetic 3 - (5 * 2) $x || $y // String concatenation "text" & $str & " more text" // Comparison 7 > 4 "text" != $x // Unary sign and logical not +3 -5 !$a // Ternary operator ?: ($x > 3) ? "yes" : "no" // Function Calls String_Split($str, ";") DialogBox_Create("message") // Property access GetCurrentPage().name $Section.color // Array index $names[0] $multi_dim_arr[0][1][2] $Section.pages[1]

A more complex expression can combine all of these simpler expressions:

"Last page in the section has " & ((String_Length($Section.pages[Array_Length($Section.pages) - 1].name) > 0) ? "a name" : "no name")

Objects

Objects in macros represent OneNote's notebook/section/page hierarchy as well as the contents of a OneNote page.

Querying Objects

Macros can query objects using QueryObjects function and modify their properties:

ExpandForEach ($Text in QueryObjects("Text", GetCurrentPage())) If ($Text.highlightColor == "yellow") $Text.highlightColor = "green"

Macros can also create new pages and insert content on a page:

// Create a page at the end of the first section of the current notebook $Page = InsertObject(GetCurrentNotebook().sections[0], "Page", -1) // Create an Outline and a Paragraph $Page = GetCurrentPage() $Outline = InsertObject($Page, "Outline", -1) $Paragraph = InsertObject($Outline, "Paragraph", 0) $Paragraph.text = "Below is a table" // Now create a table $Table = InsertObject($Outline, "Table", -1) $Row = InsertObject($Table, "Row", -1) $Cell = InsertObject($Row, "Cell", -1) $Paragraph = InsertObject($Cell, "Paragraph", -1) $Text = InsertObject($Paragraph, "Text", -1) $Text.value = "First" $Text.bold = true // Add More text in this paragraph InsertObject($Paragraph, "Text", -1).value = " cell" // Add more cells InsertObject($Row, "Cell", -1).text = "A second cell"

Following is the list of objects macros recognize with the hierarchical structure:

Hierarchy Objects

Notebook
  │
  ├─ Section
  │    │
  │    └─ Page
  │
  └─ SectionGroup
       │
       └─ ·····
            │
            └─ SectionGroup
                 │
                 └─ Section
                      │
                      └─ Page

Page Objects

Page
  │
  ├─ Image
  │    │
  │    └─ Tag
  │
  ├─ EmbeddedFile
  │    │
  │    └─ Tag
  │
  ├─ Title
  │    │
  │    └─ Paragraph
  │            │
  │            ├─ Tag
  │            │
  │            └─ Text
  │
  └─ Outline
       │
       └─ Paragraph
            │
            ├─ Tag
            │
            ├─ Text
            │
            ├─ Image
            │
            ├─ EmbeddedFile
            │
            └─ Table
                 │
                 ├─ Column
                 │
                 └─ Row
                      │
                      └─ Cell
                           │
                           └─ Paragraph
                                │
                                ├─ Tag
                                │
                                ├─ Text
                                │
                                ├─ Image
                                │
                                ├─ EmbeddedFile
                                │
                                └─ Table
                                     │
                                     └─ ·····

Properties

Each object in macros have a set of properties. Some of these properties are read-only while most others are read/write. There are cases where some property may be write-only. For instance formatting properties like bold, italic etc. on Paragraphs are write-only as they can be set but cannot be determined since a paragraph can contain text with mixed formatting.

Properties are accessed with the property access operator (.) and they can be used to filter queries if you are looking for objects with certain property values (e.g. looking for a section with a given color):

ExpandForEach ($Section in GetCurrentNotebook().sections) ExpandIf ($Section.color == "blue") $Section.color = "red"

They can also be used to sort objects (e.g. sorting pages by date):

SortObjects(GetCurrentSection().pages, "dateTime", false)

You can find the list of properties for each object in object documentation.

Variables

Variables in macros are similar to the concept of variables in any other programming language. They can be used to temporarily store data by creating and subsequently initializing them with assignment operators. Their values can then be further manipulated or used in expressions:

$width = 5 $height = 7 $area = $width * $height

Objects themselves and the values of their properties can be stored into variables and after being manipulated they can be stored back into properties:

ExpandForEach ($Cell in QueryObjects("Cell", GetCurrentPage())) $value = $Cell.text_numeric $value += 10 $Cell.text_numeric = $value

Variables are also used to store user input:

// Create a dialog box with some controls $dialog_box = DialogBox_Create("") DialogBox_AddTextBox($dialog_box, "&Find what", $Search, "", false) DialogBox_AddTextBox($dialog_box, "&Replace with", $Replace, "", true) $Options = Array("Current page", "Current section", "Current notebook") DialogBox_AddDropDown($dialog_box, "&Scope", $Scope, "Current section", $Options) DialogBox_AddCheckBox($dialog_box, "Match &case", $MatchCase, false) // Now show the dialog box, the user choices are stored in $Search, // $Replace, $Scope and $MatchCase variables after this call DialogBox_Show($dialog_box)

Data Types

Variables in macros aren't strongly typed. Therefore they can change from one type to the other. For instance a value of "0" can be string type but modifying it by adding "1" will turn it into numeric type. However a variable always have a deterministic data type at any given point of macro execution. See Data Types for all the data types and possible values.

Data Types

Following is the list of data types in macros. Properties can be of one of these data types and variables can be of one of the base types.

Base Types

Name Possible Values
Bool true, false
String Any text
Numeric Any positive or negative integral or floating point value or zero (0)
Date/Time Type of date/time related properties (e.g. createdTime, lastModifiedTime) in several objects. If converted to a string or used in a string context (as a parameter to String functions) it has the following format: YYYY-MM-DDTHH:MM:SS.000Z as specified here. Date/Time functions can be used to easily retrieve parts of this and convert them to user readable strings.
TimeSpan Represents a span of time. TimeSpan values can be created by TimeSpan function and can be used to add or subtract from Date/Time values using DateTime_Add and DateTime_Subtract functions.
Color Type of the color properties (e.g. fontColor, highlightColor) in several objects. Colors are stored in the canonical #rrggbb format or as automatic if no color was set (e.g. no highlightColor or the default fontColor). Color names like: black, blue, red, yellow etc. or the value automatic can be used to set or compare variables or properties of type Color. The function Color can be used to create variables of type Color. See also the possible values for color names at Color
Binary Binary data for an Image or an EmbeddedFile. Binary data can be obtained from binary store to create Image or EmbeddedFile objects. See Using binary data for more information.
Array A set of values of any base type. See Arrays.
Object A OneNote object or a dialog box.

Restricted Types

Restricted types are String types that can only have one of a set of possible values.

Selection

Description
Type of the selection property in several objects. For objects that aren't selected, it will have a value of none, while for selected objects it will have a value of all or partial depending on how much of it is selected. For instance a partially selected paragraph will have a value of partial.
Possible Values
none, partial, all

SuperSub

Description
Type of the supersub property in Text and Paragraph objects. If the text is formatted as a superscript or subscript, then it will have a value of super or sub value, otherwise it will have a value of none.
Possible Values
none, super, sub

ContentType

Description
Type of the contentType property in Paragraph objects.
Possible Values
image, table, text, ink drawing, ink writing, embedded file, embedded media, unknown

ImageFormat

Description
Type of the format property in Image objects.
Possible Values
png, jpg, emf

Alignment

Description
Type of the alignment property in Paragraph objects.
Possible Values
left, center, right

Orientation

Description
Type of the orientation property in Page objects.
Possible Values
portrait, landscape

ObjectType

Description
Type of a OneNote object.
Possible Values
NotebookRoot, Notebook, SectionGroup, Section, Page, Title, Outline, Table, Column, Row, Cell, Paragraph, Text, Image, EmbeddedFile

ParagraphStyle

Description
Type of the style property in Paragraph objects.
Possible Values
p, h1, h2, h3, h4, h5, h6, PageTitle, cite, blockquote, code

DateTimePickerType

Description
Type of a Date/Time picker control in a DialogBox.
Possible Values
date, time, datetime

Arrays

Variables can store a single value or a set of values. Variables that store a set of values are of Array data type. Arrays can store an unbounded amount of <key, value> pairs. The values are always accessed by providing the key (known as index). New elements can be added to arrays by assignment and specifying the a key that doesn't exist in the array:

Creating Arrays

$Names[0] = "Fred" $Names[1] = "Kate" $Names[2] = "Sally"

Arrays can also be created by Array function by simply providing the list of elements:

$Names = Array("Fred", "Kate", "Sally")

Here the indices are autmatically assigned as 0, 1, 2

Iterating over Array Elements

Values in the array can be iterated over using ForEach statements

ForEach ($Name in $Names) InsertObject($Outline, "Paragraph", -1).text = $Name

Array keys are of string or numeric types and they don't have to follow any order.

Array functions

There are a several functions that generate and consume arrays. QueryObjects and QueryText functions return arrays of objects. String_Split function splits a given string into an array of strings, while Array_Join function reverses this. Array_Length function will return the number of elements in an array.

Using an array as a stack or a queue

Array_PopFront and Array_PushBack functions can be used as equivalents of dequeue and enqueue operations on a queue data structure. Similarly Array_PushBack and Array_PopBack functions allow an array to be used as a stack, providing simple push/pop functionality. Finally there is an Array_PushFront function to insert an element at the beginning of an array.

Multi-dimensional Arrays

Arrays can be multi-dimensional if they contain other arrays:

$Names = Array(Array("Fred", "Williams"), Array("Kate", "Smith"), Array("Sally", "Jones")) $SallysLastName = $Names[2][1]

Functions

Functions in macros are similar to the same concept in other programming languages. They take one or more parameters and return a single value (or no value). They can be used to retrieve objects, manipulate strings, dates, arrays, create and display dialog boxes and control the macro execution.

Following is an example usage of String_Length and GetCurrentPage functions to obtain the length of the title of the current page:

$length = String_Length(GetCurrentPage().name)

Below is the list of all available built-in functions:

User Defined Functions

You can also define your own functions with parameters and return value. You can decide whether the paremeters are passed by reference or by value using the byref keyword. For pass-by-value, a copy of the argument is passed as the parameter. For pass-by-reference, a reference to the argument is passed and the function can modify the caller's argument. Objects are always passed by reference regardless of whether the parameter was decorated by byref or not.

// Function takes a page and adds the images in this page in the byref parameters // It returns a Bool indicating whether it found any images or not Function GetImagesInPage($page, byref $imagesInOutline, byref $imagesOnPage) $images = QueryObjects("Image", $page) ExpandForEach ($image in $images) ExpandIf (GetParentOfType($image, "Page", $parentPage)) Array_PushBack($imagesInOutline, $image) ExpandElse Array_PushBack($imagesOnPage, $image) Return Array_Length($images) > 0
// Get images in the current page $imagesInOutline = Array() $imagesOnPage = Array() ExpandIf (GetImagesInPage(GetCurrentPage(), $imagesInOutline, $imagesOnPage)) // We found some images...

Literals

Literals values can be used in the expressions to provide a fixed value. Literals can be of type string, numeric or bool. Following is an example usage of a string literal to modify the title of the current page:

ForEach ($Paragraph in QueryObjects("Paragraph", GetCurrentPage())) $Paragraph.text = "Grocery List" Break 1

The Break statement here is also using the numeric literal "1".

Operators

Macro expressions can contain several different operators. They can be used for assignments, comparisons, arithmetic or logical operations and string concatenations. Following is a list of all the operators. Operators can be operating on one (unary), two (binary) or three (ternary) sub expressions:

Arithmetic Operators

OperatorNameType
+Additionbinary
Subtractionbinary
*Multiplicationbinary
/Divisionbinary
%Modulobinary
Unary Minusunary
+Unary Plusunary
 

Increment/Decrement Operators

OperatorNameType
++$vPre-Incrementunary
––$vPre-Decrementunary
$v++Post-Incrementunary
$v––Post-Decrementunary
 

Assignment Operators

OperatorNameType
=Assignmentbinary
+=Addition Assignmentbinary
–=Subtraction Assignmentbinary
*=Multiplication Assignmentbinary
/=Division Assignmentbinary
%=Modulo Assignmentbinary
&&=Logical And Assignmentbinary
||=Logical Or Assignmentbinary
&=Concatenation Assignmentbinary
 

Comparison Operators

OperatorNameType
==Equalsbinary
!=Not Equalsbinary
<Less Thanbinary
<=Less Than or Equalsbinary
>Greater Thanbinary
>=Greater Than or Equalsbinary
 

Logical Operators

OperatorNameType
&&Logical Andbinary
||Logical Orbinary
!Logical Notunary
 

String Concatenation Operator

OperatorNameType
&Concatenationbinary
 

Ternary Operator

OperatorNameType
?:Ternary Operatorternary

Operator Precedence

In macro expressions, following operator precedence rules apply. The order of operations can be changed by providing parantheses. The Expression Editor automatically fully parenthesizes any expression so that what operator precedence rules were used is obvious. If you type 5 == 2 + 3 * 4 to Expression Editor it will automatically parse and convert it to 5 == (2 + (3 * 4)).

PrecedenceCategoryOperators
1Increment/Decrement++––
2Unary!+
3Product*/%
4Sum & Concatenation+&
5Comparison==!=<<=>>=
6Logical And&&
7Logical Or||
8Ternary?:
9Assignment=+=–=*=/=%=&&=||=&=
Note: Assignments are evaluated right to left

Comments

You can provide comments between macro statements to improve readability of your macros. Comments are inserted using Comment statements :

// Create a new dialog box $dialog_box = DialogBox_Create("") // Now add some controls DialogBox_AddTextBox($dialog_box, "&Find what", $Search, "", false) DialogBox_AddTextBox($dialog_box, "&Replace with", $Replace, "", true) $Options = Array("Current page", "Current section", "Current notebook") DialogBox_AddDropDown($dialog_box, "&Scope", $Scope, "Current section", $Options) DialogBox_AddCheckBox($dialog_box, "Match &case", $MatchCase, false) // Now show the dialog box DialogBox_Show($dialog_box)

This helps with visually separating statements. Comments can also be used to temporarily remove statements from macro execution by moving them under a comment (commenting-out):

// Create a new dialog box $dialog_box = DialogBox_Create("") // Now add some controls DialogBox_AddTextBox($dialog_box, "&Find what", $Search, "", false) DialogBox_AddTextBox($dialog_box, "&Replace with", $Replace, "", true) Expand// For now we don't have following controls: // $Options = Array("Current page", "Current section", "Current notebook") // DialogBox_AddDropDown($dialog_box, "&Scope", $Scope, "Current section", $Options) // DialogBox_AddCheckBox($dialog_box, "Match &case", $MatchCase, false) // Now show the dialog box DialogBox_Show($dialog_box)

Statements

For Statement

Description

Executes an initialization expression followed by a set of statements until the given boolean expression evaluates false. Evaluates the increment expression after each iteration. You can break out of a For loop using a Break statement or skip to the next iteration using a Continue statement.

Syntax

ExpandFor (init-expression, boolean-expression, increment-expression) Statements...

ForEach Statement

Description

Iterates over a given array, stores each element in the array in the given variable and executes a set of statements for each iteration. You can break out of a ForEach loop using a Break statement or skip to the next iteration using a Continue statement.

Syntax

ExpandForEach ($variable in array-expression) Statements...

If Statement

Description

Executes a set of statements if the given boolean expression evaluates true.

Syntax

ExpandIf (boolean-expression) Statements...

Else If Statement

Description

Executes a set of statements if the boolean expression of a preceeding If or Else If statement evaluates false and the given boolean expression evaluates true.

Syntax

ExpandElse If (boolean-expression) Statements...

Else Statement

Description

Executes a set of statements if the boolean expression of an If statement evaluates false.

Syntax

ExpandElse Statements...

Switch Statement

Description

Evaluates an expression and compares it to the value in each of the subsequent Case statements to execute a different set of statements based on which value it equals to..

Syntax

ExpandSwitch (expression) Statements...

Case Statement

Description

Compares the given value to the value of the parent Switch statement and executes a set of statements if they are equal. If a Break statement is not found inside a Case statement, then execution continues into the next Case or Default statement, if any exists..

Syntax

ExpandCase expression: Statements...

Default Statement

Description

Executes a set of statements if values of none of the Case statements are equal to the value of the parent Switch statement. If a Break statement is not found inside a Default statement, then execution continues into the next Case statement, if any exists..

Syntax

ExpandDefault: Statements...

While Statement

Description

Executes a set of statements as long as the given boolean expression evaluates true. You can break out of a While loop using a Break statement or skip to the next iteration using a Continue statement.

Syntax

ExpandWhile (boolean-expression) Statements...

Expression Statement

Description

Evaluates an expression.

Syntax

expression

Comment Statement

Description

Used to provide textual explanations (comments) within the source code or temporarily removing a set of statements from the macro execution (comment-out).

Syntax

Expand// comment // Commented-out Statements...

Break Statement

Description

Breaks out of a ForEach or a While loop. With the given numeric-expression, it can break out of multiple levels of loops.

Syntax

Break numeric-expression

Continue Statement

Description

Skips to the next iteration of a ForEach or a While loop without executing the remaining statements in the loop. With the given numeric-expression, it can skip iterations of multiple levels of loops.

Syntax

Continue numeric-expression

Return Statement

Description

Returns the given expression from the current function. If the current function is Main, exists the macro.

Syntax

Return expression

Hierarchy Objects

NotebookRoot Object

Description

Represents root of all notebooks in OneNote. The current NotebookRoot can be obtained by calling GetNotebookRoot function.

Hierarchical Structure

NotebookRoot objects can contain following objects: Notebook

Creating NotebookRoot Objects

NotebookRoot objects cannot be inserted with Onetastic Macros

Properties

Name Type Access Description
notebooks Array<Notebook> read-only List of open notebooks.
type ObjectType read-only Type of this object. Always has the value of "NotebookRoot".

Notebook Object

Description

Represents a notebook in OneNote. The current Notebook can be obtained by calling GetCurrentNotebook function.

Hierarchical Structure

Notebook objects can contain following objects: SectionGroup Section

Creating Notebook Objects

Notebook objects cannot be inserted with Onetastic Macros

Properties

Name Type Access Description
color Color read-write The color of this Notebook.
hyperlink String read-only A hyperlink that points to this Notebook.
id String read-only The unique identifier of this Notebook.
isCurrentlyViewed Bool read-only Whether this Notebook is currently being viewed by the user in OneNote or not.
isInRecycleBin Bool read-only Whether this Notebook is in the notebook recycle bin or not. Filter by this property if you want to exclude Notebooks in recycle bin.
isUnread Bool read-write Whether this Notebook is unread or not.
lastModifiedTime DateTime read-write The date and time of the last modification to this Notebook.
name String read-write The name of this Notebook.
nickname String read-write The name of this Notebook as displayed in the OneNote client.
path String read-only The physical file path of this Notebook.
sectionCount Numeric read-only The number of sections in this Notebook.
sectionGroupCount Numeric read-only The number of section groups in this Notebook.
sectionGroups Array<SectionGroup> read-only The list of section groups directly in this Notebook.
sections Array<Section> read-only The list of sections directly in this Notebook.
type ObjectType read-only Type of this object. Always has the value of "Notebook".

SectionGroup Object

Description

Represents a section group in OneNote. The current SectionGroup can be obtained by calling GetCurrentSectionGroup function.

Hierarchical Structure

SectionGroup objects can be found under following objects: Notebook SectionGroup

SectionGroup objects can contain following objects: SectionGroup Section

Creating SectionGroup Objects

SectionGroup objects can be inserted directly under following objects: Notebook SectionGroup

Properties

Name Type Access Description
hyperlink String read-only A hyperlink that points to this SectionGroup.
id String read-only The unique identifier of this SectionGroup.
isCurrentlyViewed Bool read-only Whether this SectionGroup is currently being viewed by the user in OneNote or not.
isInRecycleBin Bool read-only Whether this SectionGroup is in the notebook recycle bin or not. Filter by this property if you want to exclude SectionGroups in recycle bin.
isRecycleBin Bool read-only Whether this SectionGroup is the recycle bin for the notebook.
isUnread Bool read-write Whether this SectionGroup is unread or not.
lastModifiedTime DateTime read-write The date and time of the last modification to this SectionGroup.
name String read-write The name of this SectionGroup.
path String read-only The physical file path of this SectionGroup.
sectionCount Numeric read-only The number of sections in this SectionGroup.
sectionGroupCount Numeric read-only The number of section groups in this SectionGroup.
sectionGroups Array<SectionGroup> read-only The list of section groups directly in this SectionGroup.
sections Array<Section> read-only The list of sections directly in this SectionGroup.
type ObjectType read-only Type of this object. Always has the value of "SectionGroup".

Section Object

Description

Represents a section in OneNote. The current Section can be obtained by calling GetCurrentSection function.

Hierarchical Structure

Section objects can be found under following objects: Notebook SectionGroup

Section objects can contain following objects: Page

Creating Section Objects

Section objects can be inserted directly under following objects: Notebook SectionGroup

Properties

Name Type Access Description
areAllPagesAvailable Bool read-only Whether all pages in this Section is available or not. Pages may not be available if they weren't fully uploaded by the client that created it.
color Color read-write The color of this Section.
encrypted Bool read-only Whether this Section is encrypted (password protected) or not.
hyperlink String read-only A hyperlink that points to this Section.
id String read-only The unique identifier of this Section.
isCurrentlyViewed Bool read-only Whether this Section is currently being viewed by the user in OneNote or not.
isDeletedPages Bool read-only Whether this Section is the recycle bin section that contains the deleted pages for the notebook.
isInRecycleBin Bool read-only Whether this Section is in the notebook recycle bin or not. Filter by this property if you want to exclude Sections in recycle bin.
isUnread Bool read-write Whether this Section is unread or not.
lastModifiedTime DateTime read-write The date and time of the last modification to this Section.
locked Bool read-only Whether this Section is encrypted (password protected) and locked or not. Pages in locked Sections cannot be accessed until unlocked by the user.
name String read-write The name of this Section.
pageCount Numeric read-only The number of pages in this Section.
pages Array<Page> read-only The list of pages in this Section.
path String read-only The physical file path of this Section.
readOnly Bool read-only Whether this Section is read-only or not.
type ObjectType read-only Type of this object. Always has the value of "Section".

Page Object

Description

Represents a page in OneNote. The current Page can be obtained by calling GetCurrentPage function.

Hierarchical Structure

Page objects can be found under following objects: Section

Page objects can contain following objects: Image Title Outline EmbeddedFile

Creating Page Objects

Page objects can be inserted directly under following objects: Section

Properties

Name Type Access Description
automaticSize Bool read-write Whether this Page has a fixed printed paper width and height or not.
color Color read-write The background color for this Page.
dateTime DateTime read-write The date and time this Page is originally created.
hasTitle bool read-only Whether this Page has a title or not.
height Numeric read-write The printed paper height of this Page.
hyperlink String read-only A hyperlink that points to this Page.
id String read-only The unique identifier of this Page.
images Array<Image> read-only The list of images directly under in this Page. This array doesn't contain images in outlines.
isCollapsed Bool read-write Whether the subpages of this Page is collapsed or not.
isCurrentlyViewed Bool read-only Whether this Page is currently being viewed by the user in OneNote or not.
isInRecycleBin Bool read-only Whether this Page is in the notebook recycle bin or not. Filter by this property if you want to exclude Pages in recycle bin.
isIndexed Bool read-only Whether this Page is indexed or not.
isUnread Bool read-write Whether this Page is unread or not.
lastModifiedTime DateTime read-write The date and time of the last modification to this Page.
marginBottom Numeric read-write The printed paper bottom margin for this Page.
marginLeft Numeric read-write The printed paper left margin for this Page.
marginRight Numeric read-write The printed paper right margin for this Page.
marginTop Numeric read-write The printed paper top margin for this Page.
name String read-only The name of this Page.
orientation Orientation read-write Whether this Page is portrait or landscape oriented.
outlines Array<Outline> read-only The list of outlines in this Page.
pageLevel Numeric read-write The subpage level of this Page. Subpages will have a level of 2 or 3 where main pages will have a level of 1.
pageObjects Array<PageObject> read-only The list of page object directly under this Page.
rtl Bool read-write Whether this Page is right-to-left aligned or not.
ruleLinesHorizontalColor Color read-write The color for the horizontal rule lines for this Page.
ruleLinesHorizontalSpacing Numeric read-write The amount of space between the horizontal rule lines for this Page in points.
ruleLinesMarginColor Color read-write The color for the vertical margin rule line for this Page.
ruleLinesVerticalColor Color read-write The color for the vertical rule lines for this Page.
ruleLinesVerticalSpacing Numeric read-write The amount of space between the vertical rule lines for this Page in points.
ruleLinesVisible Bool read-write Whether the rule lines for this Page is visible or not.
selection Selection read-write Whether this Page is fully or partially selected or not.
stationeryName String read-only The name of the page template used to create this Page.
title Title read-only The title area of the page that contains the title bar, date and time. Accessing this object will create the page title if it doesn't already exist. Use hasTitle property to check whether a title already exists or not.
type ObjectType read-only Type of this object. Always has the value of "Page".
width Numeric read-write The printed paper width of this Page.

Page Objects

Title Object

Description

Represents the title in a OneNote page.

Hierarchical Structure

Title objects can be found under following objects: Page

Title objects can contain following objects: Paragraph

Creating Title Objects

Accessing the title property of a Page will create a Title object under it if it doesn't already exist.

Remarks

A Page created via Onetastic macro will come with a title if the default template of the Section it is created under has one.

Properties

Name Type Access Description
paragraph Paragraph read-only The single Paragraph in this Title.
selection Selection read-write Whether this Title is fully or partially selected or not.
showDate Bool read-write Whether the page creation date is displayed under this Title or not.
showTime Bool read-write Whether the page creation time is displayed under this Title or not.
type ObjectType read-only Type of this object. Always has the value of "Title".

Outline Object

Description

Represents a note container (outline) in a OneNote page.

Hierarchical Structure

Outline objects can be found under following objects: Page

Outline objects can contain following objects: Paragraph

Creating Outline Objects

Outline objects can be inserted directly under following objects: Page

Properties

Name Type Access Description
author String read-write The original author of this Outline.
authorInitials String read-write The initials of the original author of this Outline.
creationTime DateTime read-write The date and time this Outline is originally created.
height Numeric read-write The height of this Outline in points.
lastModifiedBy String read-write The person who last modified this Outline.
lastModifiedByInitials String read-write The initials of the person who last modified this Outline.
lastModifiedTime DateTime read-write The date and time of last modification on this Outline.
objectId String read-write The unique identifier of this Outline.
paragraphs Array<Paragraph> read-only The list of Paragraphs in this Outline.
selection Selection read-write Whether this Outline is fully or partially selected or not.
sizeSetByUser Bool read-write Whether the dimensions of this Outline is manually set by the user (by dragging a handle on the object). Objects whose dimensions are set by the user will retain that size regardless of the size of their containers.
text String read-write The text of this Outline.
type ObjectType read-only Type of this object. Always has the value of "Outline".
width Numeric read-write The width of this Outline in points.
x Numeric read-write The horizontal position of this Outline on the page in points.
y Numeric read-write The vertical position of this Outline on the page in points.
z Numeric read-write The z-order of this Outline on the page. Objects with higher z-order will show up in front of objects with lower z-orders.

Table Object

Description

Represents a table in a OneNote page.

Hierarchical Structure

Table objects can be found under following objects: Paragraph

Table objects can contain following objects: Row Column

Creating Table Objects

Table objects can be inserted directly under following objects: Outline Cell

Properties

Name Type Access Description
author String read-write The original author of this Table.
authorInitials String read-write The initials of the original author of this Table.
bordersVisible Bool read-write Whether the borders of this Table is visible or not.
colCount Numeric read-only The number of columns in this Table.
columns Array<Column> read-only The list of Columns in this Table.
creationTime DateTime read-write The date and time this Table is originally created.
lastModifiedBy String read-write The person who last modified this Table.
lastModifiedByInitials String read-write The initials of the person who last modified this Table.
lastModifiedTime DateTime read-write The date and time of the last modification to this Table.
objectId String read-write The unique identifier of this Table.
rowCount Numeric read-only The number of Rows in this Table.
rows Array<Row> read-only The list of Rows in this Table.
selection Selection read-write Whether this Table is fully or partially selected or not.
type ObjectType read-only Type of this object. Always has the value of "Table".

Column Object

Description

Represents a column of a Table in a OneNote page.

Hierarchical Structure

Column objects can be found under following objects: Table

Creating Column Objects

Column objects cannot be inserted with Onetastic Macros

Remarks

To insert Columns into a Table, insert one or more Cell object under Row object.

Properties

Name Type Access Description
index Numeric read-only The number of Columns before this Column.
isLocked Bool read-write Whether the width of this Column was set by the user or not.
type ObjectType read-only Type of this object. Always has the value of "Column".
width Numeric read-write The width of this Column in points.

Row Object

Description

Represents a row of a Table in a OneNote page.

Hierarchical Structure

Row objects can be found under following objects: Table

Row objects can contain following objects: Cell

Creating Row Objects

Row objects can be inserted directly under following objects: Table

Properties

Name Type Access Description
author String read-write The original author of this Row.
authorInitials String read-write The initials of the original author of this Row.
cells Array<Cell> read-only The list of cells in this Row.
creationTime DateTime read-write The date and time this Row is originally created.
index Numeric read-only The number of Rows before this Row.
lastModifiedBy String read-write The person who last modified this Row.
lastModifiedByInitials String read-write The initials of the person who last modified this Row.
lastModifiedTime DateTime read-write The date and time of the last modification to this Row.
objectId String read-write The unique identifier of this Row.
selection Selection read-write Whether this Row is fully or partially selected or not.
type ObjectType read-only Type of this object. Always has the value of "Row".

Cell Object

Description

Represents a cell of a table in a OneNote page.

Hierarchical Structure

Cell objects can be found under following objects: Row

Cell objects can contain following objects: Paragraph Table

Creating Cell Objects

Cell objects can be inserted directly under following objects: Row

Remarks

Insert Table object under Cell object to create nested tables. Insert Paragraph object under Cell object to add text into the cell.

Properties

Name Type Access Description
author String read-write The original author of this Cell.
authorInitials String read-write The initials of the original author of this Cell.
backgroundColor Color read-write The background color for this Cell. This property requires OneNote 2013 or above.
colIndex Numeric read-only The number of Columns before the column this Cell is in.
creationTime DateTime read-write The date and time this Cell is originally created.
lastModifiedBy String read-write The person who last modified this Cell.
lastModifiedByInitials String read-write The initials of the person who last modified this Cell.
lastModifiedTime DateTime read-write The date and time of the last modification to this Cell.
objectId String read-write The unique identifier of this Cell.
paragraphs Array<Paragraph> read-only The list of Paragraphs in this Cell.
rowIndex Numeric read-only The number of Rows before the row this Cell is in.
selection Selection read-write Whether this Cell is fully or partially selected or not.
text String read-write The text of this Cell.
text_numeric Numeric read-write The text of this Cell interpreted as a numerical value. Useful to apply arithmetic operations on it.
type ObjectType read-only Type of this object. Always has the value of "Cell".

Paragraph Object

Description

Represents a paragraph of text in a OneNote page.

Hierarchical Structure

Paragraph objects can be found under following objects: Outline Cell Title

Paragraph objects can contain following objects: Text Image Table EmbeddedFile Tag

Creating Paragraph Objects

Paragraph objects can be inserted directly under following objects: Outline Cell

Remarks

Paragraphs can be part of bulleted or numbered list. See Bulleted and numbered lists for more information

Properties

Name Type Access Description
alignment Alignment read-write Text alignment for this Paragraph (e.g. left, right or center).
author String read-write The original author of this Paragraph.
authorInitials String read-write The initials of the original author of this Paragraph.
bold Bool write-only Whether the text in this Paragraph is bold or not. This property is write-only as there may be text with different formatting in the paragraph. Setting this property will apply its value to the whole paragraph.
bulletFontColor Color read-write The color for the bullet for this Paragraph.
bulletFontSize Numeric read-write The font size for the bullet for this Paragraph.
bulletType Numeric read-write The type of the bullet for this Paragraph. See Bulleted and numbered lists for more information.
collapsed Bool read-write Whether this Paragraph is collapsed or not.
content Mixed read-only The content stored in this Paragraph. To find out what type of object is stored in this property, check the contentType property:
contentTypecontent
textArray<Text>
tableTable
imageImage
embedded fileEmbeddedFile
any other value<not-set>
The value is the same as the value of texts property if the contentType property is text.
contentType ContentType read-only The type of content stored in this Paragraph.
creationTime DateTime read-write The date and time this Paragraph is originally created.
fontColor Color write-only The text color for this Paragraph. This property is write-only as there may be text with different formatting in the paragraph. Setting this property will apply its value to the whole paragraph.
fontName String write-only The name of the font for this Paragraph. This property is write-only as there may be text with different formatting in the paragraph. Setting this property will apply its value to the whole paragraph.
fontSize Numeric write-only The font size for this Paragraph. This property is write-only as there may be text with different formatting in the paragraph. Setting this property will apply its value to the whole paragraph.
highlightColor Color write-only The highlight color for this Paragraph. This property is write-only as there may be text with different formatting in the paragraph. Setting this property will apply its value to the whole paragraph.
hyperlink String read-only The hyperlink to this Paragraph.
indent Numeric read-write The indent amount for this Paragraph, relative to its parent Outline or Cell. An unindented Paragraph has an indent of 0.
index Numeric read-only The number of Paragraphs before this Paragraph within its Outline or Cell. The paragraph must be in an Outline or a Cell, otherwise this property has the value of 0.
isPartOfBulletedList Bool read-write Whether this Paragraph is part of a bulleted list or not. See Bulleted and numbered lists for more information.
isPartOfList Bool read-only Whether this Paragraph is part of a bulleted or numbered list or not. See Bulleted and numbered lists for more information.
isPartOfNumberedList Bool read-write Whether this Paragraph is part of a numbered list or not. See Bulleted and numbered lists for more information.
italic Bool write-only Whether the text in this Paragraph is italicized or not. This property is write-only as there may be text with different formatting in the paragraph. Setting this property will apply its value to the whole paragraph.
lang String write-only The language the text in this Paragraph is writte in. This property is write-only as there may be text with different languages in the paragraph. Setting this property will apply its value to the whole paragraph.
lastModifiedBy String read-write The person who last modified this Paragraph.
lastModifiedByInitials String read-write The initials of the person who last modified this Paragraph.
lastModifiedTime DateTime read-write The date and time of the last modification to this Paragraph.
listAlignment Alignment read-write The text alignment for the numbered list for this Paragraph (left vs right). The default alignment value is "right".
listSpacing Numeric read-write The space between the numbered list and the paragraph in points. The default spacing amount is 7.2 points (0.1 inches).
numberBold Bool read-write Whether the numbered list for this Paragraph is bold or not.
numberFont String read-write The name of the font face for the numbered list for this Paragraph.
numberFontColor Color read-write The color for the numbered list for this Paragraph.
numberFontSize Numeric read-write The size of the font for the numbered list for this Paragraph.
numberFormat String read-write The number format for the numbered list for this Paragraph. See Bulleted and numbered lists for more information.
numberItalic Bool read-write Whether the numbered list for this Paragraph is italicized or not.
numberLanguage String read-write The language for the numbered list for this Paragraph.
numberSequence Numeric read-write The number sequence for the numbered list for this Paragraph. See Bulleted and numbered lists for more information.
numberText String read-only The text for the numbered list for this Paragraph.
objectId String read-write The unique identifier of this Paragraph.
rtl Bool read-write Whether this Paragraph is right-to-left aligned or not.
selection Selection read-write Whether this Paragraph is fully or partially selected or not.
spaceAfter Numeric read-write The amount of space after this Paragraph in points. This property requires OneNote 2013 or above.
spaceBefore Numeric read-write The amount of space before this Paragraph in points. This property requires OneNote 2013 or above.
spaceBetween Numeric read-write The amount of space between the lines of this Paragraph in points. This property requires OneNote 2013 or above.
strikethrough Bool write-only Whether the text in this Paragraph is striked through or not. This property is write-only as there may be text with different formatting in the paragraph. Setting this property will apply its value to the whole paragraph.
style ParagraphStyle read-write The style of this Paragraph.
supersub SuperSub write-only Whether the text in this Paragraph is superscript/subscript or not. This property is write-only as there may be text with different formatting in the paragraph. Setting this property will apply its value to the whole paragraph.
tags Array<Tag> read-only List of tags associated with this Paragraph.
text String read-write The text of this Paragraph.
text_numeric Numeric read-write The text of this Paragraph interpreted as a numerical value. Useful to apply arithmetic operations on it.
texts Array<Text> read-only List of Text objects within this Paragraph.
type ObjectType read-only Type of this object. Always has the value of "Paragraph".
underline Bool write-only Whether the text in this Paragraph is underlined or not. This property is write-only as there may be text with different formatting in the paragraph. Setting this property will apply its value to the whole paragraph.

Deprecated Properties

Following properties are deprecated. Do not use these in new macros. See descriptions below on what to use instead.

Name Type Access Description
tagCompleted Bool read-write Whether the first tag associated with this Paragraph is completed (checked) or not. This property is deprecated. Use tags property instead.
tagCompletionDate DateTime read-write The date and time of completion of the first tag associated with this Paragraph. This property is deprecated. Use tags property instead.
tagCreationDate DateTime read-write The date and time of creation of the first tag associated with this Paragraph. This property is deprecated. Use tags property instead.
tagDisabled Bool read-write Whether the first tag associated with this Paragraph is disabled (dimmed) or not. This property is deprecated. Use tags property instead.
tagFontColor Color read-only The font color for the first tag associated with this Paragraph for tags that use formatting instead of a symbol. This property is deprecated. Use tags property instead.
tagHighlightColor Color read-only The highlight color for the first tag associated with this Paragraph for tags that use formatting instead of a symbol. This property is deprecated. Use tags property instead.
tagName String read-only The name of the first tag associated with this Paragraph. This property is deprecated. Use tags property instead.
tagSymbol Numeric read-only The symbol of the first tag associated with this Paragraph. This property is deprecated. Use tags property instead.
tagType Numeric read-only The type of the first tag associated with this Paragraph. This property is deprecated. Use tags property instead.

Text Object

Description

Represents a range of text.

Hierarchical Structure

Text objects can be found under following objects: Paragraph

Creating Text Objects

Text objects can be inserted directly under following objects: Paragraph

Properties

Name Type Access Description
bold Bool read-write Whether this Text is bold or not.
endIndex Numeric read-only The number of characters before the end of this Text in the paragraph.
fontColor Color read-write Color of this Text.
fontName String read-write Name of the font face for this Text.
fontSize Numeric read-write Size of the font for this Text.
highlightColor Color read-write Highlight color of this Text.
hyperlink String read-write The hyperlink of this Text (user would navigate to this hyperlink when clicking on this Text).
italic Bool read-write Whether this Text is italicized or not.
lang String read-write The language in which this Text is written in.
selected Bool read-write Whether this Text is selected or not.
startIndex Numeric read-only The number of characters before this Text in the containing paragraph. The first Text will start with index 0 and each character will be counted as 1.
strikethrough Bool read-write Whether this Text is striked through or not.
supersub SuperSub read-write Whether this Text is subscript/superscript or not.
type ObjectType read-only Type of this object. Always has the value of "Text".
underline Bool read-write Whether this Text is underlined or not.
value String read-write The text itself.

Image Object

Description

Represents an image in a OneNote page.

Hierarchical Structure

Image objects can be found under following objects: Paragraph Page

Creating Image Objects

Image objects can be inserted directly under following objects: Outline Cell Page

Properties

Name Type Access Description
altText String read-write Alternative text for this Image. Used if the page is exported as HTML.
background Bool read-write Whether this Image is a background image or not. Background images aren't selectable and show up behind every other object.
data Binary read-write The binary data for this Image.
format ImageFormat read-write Encoding format of this Image. See data types for possible values.
height Numeric read-write The height of this Image in points.
hyperlink String read-write Hyperlink of this Image user would navigate to this hyperlink when Ctrl+clicking on this Image).
isPrintOut Bool read-write Whether this Image is a printout or not.
lastModifiedTime DateTime read-write The date and time of last modification on this Image.
objectId String read-write The unique identifier of this Image.
printOutDocumentNumber Numeric read-write The document number that points to corresponding the printout file on the page for this Image. Only valid for printouts.
printOutFileNumber Numeric read-write The file number that points to corresponding the printout file on the page for this Image. Only valid for printouts.
printOutPageNumber Numeric read-write The page number that points to corresponding the printout file on the page for this Image. Only valid for printouts.
selection Selection read-write Whether this Image is fully or partially selected or not.
sizeSetByUser Bool read-write Whether the dimensions of this Image is manually set by the user (by dragging a handle on the object). Objects whose dimensions are set by the user will retain that size regardless of the size of their containers.
tags Array<Tag> read-only List of tags associated with this Image.
type ObjectType read-only Type of this object. Always has the value of "Image".
width Numeric read-write The width of this Image in points.
x Numeric read-write The horizontal position of this Image on the page in points.
y Numeric read-write The vertical position of this Image on the page in points.
z Numeric read-write The z-order of this Image on the page. Objects with higher z-order will show up in front of objects with lower z-orders.

Deprecated Properties

Following properties are deprecated. Do not use these in new macros. See descriptions below on what to use instead.

Name Type Access Description
tagCompleted Bool read-write Whether the first tag associated with this Image is completed (checked) or not. This property is deprecated. Use tags property instead.
tagCompletionDate DateTime read-write The date and time of completion of the first tag associated with this Image. This property is deprecated. Use tags property instead.
tagCreationDate DateTime read-write The date and time of creation of the first tag associated with this Image. This property is deprecated. Use tags property instead.
tagDisabled Bool read-write Whether the first tag associated with this Image is disabled (dimmed) or not. This property is deprecated. Use tags property instead.
tagFontColor Color read-only The font color for the first tag associated with this Image for tags that use formatting instead of a symbol. This property is deprecated. Use tags property instead.
tagHighlightColor Color read-only The highlight color for the first tag associated with this Image for tags that use formatting instead of a symbol. This property is deprecated. Use tags property instead.
tagName String read-only The name of the first tag associated with this Image. This property is deprecated. Use tags property instead.
tagSymbol Numeric read-only The symbol used for the first tag associated with this Image. This property is deprecated. Use tags property instead.
tagType Numeric read-only The type of the first tag associated with this Image. This property is deprecated. Use tags property instead.

EmbeddedFile Object

Description

Represents an embedded file attachment in a OneNote page.

Hierarchical Structure

EmbeddedFile objects can be found under following objects: Paragraph Page

Creating EmbeddedFile Objects

EmbeddedFile objects can be inserted directly under following objects: Outline Cell Page

Properties

Name Type Access Description
data Binary read-write The binary data for this EmbeddedFile.
fileName String read-write File name of this EmbeddedFile. This can only be set on newly inserted embedded files.
height Numeric read-only The height of this EmbeddedFile in points.
lastModifiedTime DateTime read-write The date and time of last modification on this EmbeddedFile.
objectId String read-write The unique identifier of this EmbeddedFile.
selection Selection read-write Whether this EmbeddedFile is fully or partially selected or not.
tags Array<Tag> read-only List of tags associated with this EmbeddedFile.
type ObjectType read-only Type of this object. Always has the value of "EmbeddedFile".
width Numeric read-only The width of this EmbeddedFile in points.
x Numeric read-write The horizontal position of this EmbeddedFile on the page in points.
y Numeric read-write The vertical position of this EmbeddedFile on the page in points.
z Numeric read-write The z-order of this EmbeddedFile on the page. Objects with higher z-order will show up in front of objects with lower z-orders.

Deprecated Properties

Following properties are deprecated. Do not use these in new macros. See descriptions below on what to use instead.

Name Type Access Description
tagCompleted Bool read-write Whether the first tag associated with this EmbeddedFile is completed (checked) or not. This property is deprecated. Use tags property instead.
tagCompletionDate DateTime read-write The date and time of completion of the first tag associated with this EmbeddedFile. This property is deprecated. Use tags property instead.
tagCreationDate DateTime read-write The date and time of creation of the first tag associated with this EmbeddedFile. This property is deprecated. Use tags property instead.
tagDisabled Bool read-write Whether the first tag associated with this EmbeddedFile is disabled (dimmed) or not. This property is deprecated. Use tags property instead.
tagFontColor Color read-only The font color for the first tag associated with this EmbeddedFile for tags that use formatting instead of a symbol. This property is deprecated. Use tags property instead.
tagHighlightColor Color read-only The highlight color for the first tag associated with this EmbeddedFile for tags that use formatting instead of a symbol. This property is deprecated. Use tags property instead.
tagName String read-only The name of the first tag associated with this EmbeddedFile. This property is deprecated. Use tags property instead.
tagSymbol Numeric read-only The symbol used for the first tag associated with this EmbeddedFile. This property is deprecated. Use tags property instead.
tagType Numeric read-only The type of the first tag associated with this EmbeddedFile. This property is deprecated. Use tags property instead.

Tag Object

Description

Represents a tag in a OneNote page.

Hierarchical Structure

Tag objects can be found under following objects: Paragraph Image EmbeddedFile

Creating Tag Objects

Tag objects can be inserted directly under following objects: Paragraph Image EmbeddedFile

Remarks

Tags can appear on Images and EmbeddedFiles if they are directly under a Page and on all Paragraphs. For Images and EmbeddedFiles that are under Outlines, check for the parent Paragraph with GetParentOfType function.

Tag Symbols

Following symbols can be used for tags

1
2
3
4
5
6
7
8
9
10
11
12
48
69
28
50
71
30
52
73
32
96
95
94
99
98
97
100
101
102
103
104
105
106
107
108
109
18
110
14
15
17
21
24
111
117
118
119
61
13
40
64
84
43
56
77
36
63
83
39
60
81
42
49
70
29
51
72
31
53
74
33
55
76
35
113
25
26
114
115
116
112
22
23
120
19
20
121
122
123
124
125
126
65
85
44
62
82
41
54
75
34
67
87
46
68
88
47
58
79
38
59
80
16
57
78
37
66
86
45
127
128
27
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143

To change a Tag's symbol, set its symbol property to the number next to the symbol image above.

Properties

Name Type Access Description
completed Bool read-write Whether this Tag is completed (checked) or not.
completionDate DateTime read-write The date and time of completion of this Tag.
creationDate DateTime read-write The date and time of creation of this Tag.
disabled Bool read-write Whether this Tag is disabled (dimmed) or not.
fontColor Color read-write The font color for this Tag for tags that use formatting instead of a symbol.
highlightColor Color read-write The highlight color for this Tag for tags that use formatting instead of a symbol.
name String read-write The name of this Tag.
symbol Numeric read-write The symbol for this Tag. See remarks for the symbols.
type ObjectType read-only Type of this object. Always has the value of "Tag".

Other Objects

DialogBox Object

Description

Represents a dialog box to interact with the user.

Remarks

Represents a dialog box to display a message or request input from user. Dialog boxes can be created with DialogBox_Create and displayed with DialogBox_Show. Controls can be added to dialog boxes with DialogBox_AddTextBox, DialogBox_AddLabel, DialogBox_AddCheckBox, DialogBox_AddDropDown, DialogBox_AddComboBox, and DialogBox_AddColorPicker functions. Dialog box objects have a member named "controls" to access the user input after they are displayed.

Properties

Name Type Access Description
controls Array<Mixed> read-only The values provided by the user for the controls on the dialog box after the dialog is displayed with DialogBox_Show function. The value for checkboxes are Bool while the values for textboxes and drop down list boxes are Strings.
type ObjectType read-only Type of this object. Always has the value of "DialogBox".

MacroMenu Object

Description

Represents the menu of a macro in the ribbon.

Remarks

MacroMenu object represents the menu of the current macro to be displayed in the ribbon. This object is passed as an argument to the Setup function to create a menu. Menu items can be added to a menu using the MacroMenu_AddItem function. See Macro menus for more information on menus.

Properties

Name Type Access Description
type ObjectType read-only Type of this object. Always has the value of "MacroMenu".

Window Object

Description

Represents a OneNote window.

Remarks

OneNote can display notebooks in one or more Windows. The collection of these windows can be accessed through GetWindows function. At most one of the windows is the current window. This can be checked by isCurrent property and the current window can be accessed through Window_GetCurrent. A window can be made current via Window_SetCurrent function. New windows can be created by Window_Create and windows can be closed by Window_Close. The page a window is displaying can be changed by Window_NavigateTo.

Properties

Name Type Access Description
isCurrent Bool read-only Whether this window is the current window or not.
notebook Notebook read-only The notebook this window is currently displaying. This property may be empty if the window is not currently displaying a notebook.
page Page read-only The page this window is currently displaying. This property may be empty if the window is not currently displaying a page.
section Section read-only The section this window is currently displaying. This property may be empty if the window is not currently displaying a section.
sectionGroup SectionGroup read-only The section group this window is currently displaying. This property may be empty if the window is not currently displaying a section group.
type ObjectType read-only Type of this object. Always has the value of "Window".

Functions

Array Functions

Array

Creates an array with given arguments.

Syntax

Array Array(Mixed elements...)

Parameters

Mixed elements (optional)
Elements in the array. No elements or several elements can be provided.

Examples

// Empty Array $array = Array() // Array with three integers $array = Array(1, 2, 3) // Array with mixed type of elements $page = GetCurrentPage() $array = Array(1, "string", false, $page) // 2 dimensional array $array = Array(Array(0, 1, 2), Array(3, 4, 5), Array(5, 6, 7)) // This will be 5: $element = $array[1][2]

Array_FlipKeysAndValues

Exchanges the keys and their associated values in the given array. The values must be numeric or string since they will now become keys.

Syntax

void Array_FlipKeysAndValues(Array array)

Parameters

Array array
Array to flip keys and values.

Examples

$array = Array("red", "green", "blue", 5) // This created the following array // 0 => "red" // 1 => "green" // 2 => "blue" // 3 => 5 Array_FlipKeysAndValues($array) // Now we have the following keys and values: // "red" => 0 // "green" => 1 // "blue" => 2 // 5 => 3 // If the values aren't string or numeric, // flipping keys and values will result in an error $array = Array(GetCurrentPage(), GetCurrentSection()) Array_FlipKeysAndValues($array) // Error: Cannot convert expression of type Object to an expression of type String // If the values aren't unique, latter values will write over former ones $array = Array(3, 5, 8, 5, 2, 3) // This created the following array // 0 => 3, 1 => 5, 2 => 8, 3 => 5, 4 => 2, 5 => 3 Array_FlipKeysAndValues($array) // Now we have the following keys and values: // 3 => 5, 5 => 3, 8 => 2, 2 => 4

Array_FromKeysAndValues

Creates an array by using one array for keys and another for its values. The given arrays must have the same size.

Syntax

Array Array_FromKeysAndValues(
	Array keys, 
	Array values)

Parameters

Array keys
Keys to use for the array. Must contain only numeric or string values.
Array values
Values to use for the array.

Examples

$keys = Array("color", "size", "type") $values = Array("red", "large", "t-shirt") $array = Array_FromKeysAndValues($keys, $values) // This created the following array // "color" => "red" // "size" => "large" // "type" => "t-shirt"

Array_FromRange

Creates an array containing a range of numeric values. This can be used to run a For loop on a sequence of numbers. For instance ForEach ($i in Array_FromRange(1, 10, 1)) will iterate over numbers 1 to 10.

Syntax

void Array_FromRange(
	Numeric start, 
	Numeric end, 
	Numeric step)

Parameters

Numeric start
The first value in the array.
Numeric end
The last value in the array.
Numeric step
The value to use as the increment between elements in the sequence. Can be positive for an increasing sequence or negative for a decreasing sequence. The value of end must be reachable by repeatedly incrementing start with step.

Examples

$array = Array_FromRange(1, 10, 1) // This is the same as $array = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) $array = Array_FromRange(10, 1, -2) // This is the same as $array = Array(10, 8, 6, 4, 2)

Array_Join

Concatenates the elements in the given array using the given glue string and returns the combined string.

Syntax

String Array_Join(
	Array array, 
	String glue)

Parameters

Array array
Array to join together into a string.
String glue
Glue string to add between the array elements.

Examples

$array = Array("apple", "banana", "strawberry") $string = Array_Join($array, ", ") // $string is "apple, banana, strawberry" // You can use an empty glue: $array = Array("b", "a", "n", "a", "n", "a") $string = Array_Join($array, "") // $string is "banana" // Array_Join is the reverse of String_Split: $array = Array("size", "type", "color") $string = Array_Join($array, "/") // $string is "size/type/color" $array = String_Split("size/type/color", "/") // $array is ("size", "type", "color")

Array_KeyExists

Returns whether a given key exists or not in the given array.

Syntax

Array Array_KeyExists(
	Array array, 
	Mixed key)

Parameters

Array array
Array to look for the key in.
Mixed key
Key to look for.

Examples

$array = Array(3, 89, 47, 21, 23) $found3 = Array_KeyExists($array, 3) $found7 = Array_KeyExists($array, 7) // $found3 is true, $found7 is false // You can use this on arrays with string keys as well: $array["color"] = "red" $array["size"] = "large" $foundSize = Array_KeyExists($array, "size") $foundType = Array_KeyExists($array, "type") // $foundSize is true, $foundType is false

Array_Keys

Returns a new array that contains the keys of the given array.

Syntax

Array Array_Keys(Array array)

Parameters

Array array
Array to return the keys of.

Examples

$array = Array(8, 12, 5, 3, 14) $keys = Array_Keys($array) // $keys is (0, 1, 2, 3, 4) $array2["color"] = "red" $array2["size"] = "large" $array2["type"] = "t-shirt" $keys = Array_KeyExists($array2) // $keys is ("color", "size", "type")

Array_Length

Returns the number of elements in the given array.

Syntax

Numeric Array_Length(Array array)

Parameters

Array array
Array return the number of elements.

Examples

$array = Array("apple", "banana", "strawberry") $size = Array_Length($array) // $size is 3

Array_Merge

Returns a new array that contains all the values in the given arrays. The values of each array are appended to the end of the previous one. If the arrays have the same string keys, then the later value for that key will overwrite the previous one. Numeric keys are not overwritten but instead will be appended. Values with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

Syntax

Array Array_Merge(Array arrays...)

Parameters

Array arrays (optional)
Arrays to merge. No arrays or several arrays can be provided.

Examples

$array = Array_Merge() // $array is an empty array $array = Array_Merge(Array(1, 2, 3), Array(7, 8, 9), Array(-2, -4, -5)) // $array is (1, 2, 3, 7, 8, 9, -2, -4, -5) $array1["size"] = "large" $array1["color"] = "red" $array2["size"] = "small" $array2["type"] = "t-shirt" $array3["color"] = "blue" $array3["price"] = 10 $array = Array_Merge($array1, $array2, $array3) // This creates the following array: // "size" => "small" // "color" => "blue" // "type" => "t-shirt" // "price" => 10

Array_PopBack

Removes and returns the last element in the array. To use an array as a stack, use this function along with Array_PushBack.

Syntax

Mixed Array_PopBack(Array array)

Parameters

Array array
Array to remove and return the the last element from.

Examples

$array = Array(6, 4, 8, 10, 12) $lastElement = Array_PopBack($array) $previousElement = Array_PopBack($array) // $array is now (6, 4, 8) // $lastElement is 12 // $previousElement is 10

Array_PopFront

Removes and returns the first element in the array. All numerical keys in the array will be modified to start counting from zero while string keys won't be affected. To use an array as a queue, use this function along with Array_PushBack.

Syntax

Mixed Array_PopFront(Array array)

Parameters

Array array
Array to remove and return the the first element from.

Examples

$array = Array(6, 4, 8, 10, 12) $firstElement = Array_PopFront($array) $secondElement = Array_PopFront($array) // $array is now (8, 10, 12) // $firstElement is 6 // $secondElement is 4 // Numeric keys will reset to start from 0 $array3[5] = 10 $array3[7] = 12 $array3[9] = 14 Array_PopFront($array3) // $array3 is now: // 0 => 12 // 1 => 14 Array_PopFront($array3) // $array3 is now: // 0 => 14 // String keys are not affected: $array4[7] = "a" $array4[-2] = "b" $array4["size"] = "large" $array4["color"] = "red" Array_PopFront($array4) // $array4 is now: // 0 => "b" // "size" => "large" // "color" => "red" Array_PopFront($array4) // $array4 is now: // "size" => "large" // "color" => "red"

Array_PushBack

Inserts the given value to the end of the array. Returns the number of elements in the array after the insertion. To use an array as a stack, use this function along with Array_PopBack. To use an array as a queue, use this function along with Array_PopFront.

Syntax

Numeric Array_PushBack(
	Array array, 
	Mixed value)

Parameters

Array array
Array to insert the value to.
Mixed value
The value to insert.

Examples

$array = Array(6, 4, 8) $sizeAfterFirstPushBack = Array_PushBack($array, 3) $sizeAfterSecondPushBack = Array_PushBack($array, 7) // $array is now (6, 4, 8, 3, 7) // $sizeAfterFirstPushBack is 4 // $sizeAfterSecondPushBack is 5 // You can create an array with Array_PushBack Array_PushBack($array2, 5) // $array2 is now (5) Array_PushBack($array2, 7) // $array2 is now (5, 7) // If the array doesn't have numeric keys, new keys will start from 0 $array3["size"] = "large" $array3["color"] = "red" Array_PushBack($array3, "t-shirt") Array_PushBack($array3, 10) // $array3 is now: // "size" => "large" // "color" => "red" // 0 => "t-shirt" // 1 => 10 // If the array had some numeric keys, new keys will follow the largest one $array4[7] = "a" $array4[-2] = "b" $array4["price"] = 100 Array_PushBack($array4, "first") Array_PushBack($array4, "second") // $array4 is now: // 7 => "a" // -2 => "b" // "price" => 100 // 8 => "first" // 9 => "second"

Array_PushFront

Inserts the given value to the beginning of the array. All numerical keys in the array will be modified to start counting from zero while string keys won't be affected. Returns the number of elements in the array after the insertion.

Syntax

Numeric Array_PushFront(
	Array array, 
	Mixed value)

Parameters

Array array
Array to insert the value to.
Mixed value
The value to insert.

Examples

$array = Array(6, 4, 8) $sizeAfterFirstPushFront = Array_PushFront($array, 3) $sizeAfterSecondPushFront = Array_PushFront($array, 7) // $array is now (7, 3, 6, 4, 8) // $sizeAfterFirstPushFront is 4 // $sizeAfterSecondPushFront is 5 // You can create an array with Array_PushFront Array_PushFront($array2, 5) // $array2 is now (5) Array_PushFront($array2, 7) // $array2 is now (7, 5) // Numeric keys will reset to start from 0 $array3[5] = 10 $array3[7] = 12 Array_PushFront($array3, 8) // $array3 is now: // 0 => 8 // 1 => 10 // 2 => 12 Array_PushFront($array3, 6) // $array3 is now: // 0 => 6 // 1 => 8 // 2 => 10 // 3 => 12 // String keys are not affected: $array4["size"] = "large" $array4[7] = "a" $array4[-2] = "b" $array4["color"] = "red" Array_PushFront($array4, "t-shirt") Array_PushFront($array4, 10) Array_PushFront($array4, 5) // $array4 is now: // 0 => 5 // 1 => 10 // 2 => "t-shirt" // "size" => "large" // 3 => "a" // 4 => "b" // "color" => "red"

Array_RemoveByKey

Removes the element with the given key from the array. Returns true if the key existed in the array and the element is removed, false if the key didn't exist in the array.

Syntax

Bool Array_RemoveByKey(
	Array array, 
	Mixed key)

Parameters

Array array
Array to remove the element from.
Mixed key
Key for the element to remove from the array.

Examples

// Array with numeric keys $array = Array(10, 12, 14, 16, 18) Array_RemoveByKey($array, 0) Array_RemoveByKey($array, 3) // $array is now: // 1 => 12 // 2 => 14 // 4 => 18 // Array with string keys: $array2["size"] = "large" $array2["color"] = "red" $array2["type"] = "t-shirt" Array_RemoveByKey($array2, "type") // $array2 is now: // "size" => "large" // "color" => "red"

Array_Reverse

Reverses the order of elements in the given array.

Syntax

void Array_Reverse(
	Array array, 
	Bool preserveKeys)

Parameters

Array array
Array to reverse.
Bool preserveKeys
If true, the values in the array will have the same keys as before, but just order changed. If false, the values will be assigned to new numeric keys starting from zero.

Examples

$array = Array(2, 4, 6, 8, 10) Array_Reverse($array, false) // $array is now: // 0 => 10 // 1 => 8 // 2 => 6 // 3 => 4 // 4 => 2 // You can choose to preserve keys: $array1 = Array(2, 4, 6, 8, 10) Array_Reverse($array1, true) // $array1 is now: // 4 => 10 // 3 => 8 // 2 => 6 // 1 => 4 // 0 => 2

Array_Shuffle

Randomizes the order of elements in the given array.

Syntax

void Array_Shuffle(
	Array array, 
	Bool preserveKeys)

Parameters

Array array
Array to shuffle.
Bool preserveKeys
If true, the values in the array will have the same keys as before, but just order changed. If false, the values will be assigned to new numeric keys starting from zero.

Examples

// Output would be different each time // Shuffle without preserving keys $array = Array(1, 2, 3, 4, 5, 6) Array_Shuffle($array, false) // $array may be now: // 0 => 5 // 1 => 2 // 2 => 4 // 3 => 3 // 4 => 1 // 5 => 6 // Shuffle, preserving keys $array = Array(1, 2, 3, 4, 5, 6) Array_Shuffle($array, true) // $array may be now: // 2 => 3 // 0 => 1 // 5 => 6 // 1 => 2 // 3 => 4 // 4 => 5

Array_Slice

Returns a new array containing a sequence of elements of the given array.

Syntax

array Array_Slice(
	Array array, 
	Numeric offset, 
	Numeric length, 
	Bool preserveKeys)

Parameters

Array array
Array to get elements from.
Numeric offset
The start offset to get elements. If non-negative, the sequence will start that far away from the beginning of the array. If negative, the sequence will start that far away from the end of the array.
Numeric length
The length of the sequence. If there aren't that many elements in the array, the resulting array can be shorter.
Bool preserveKeys
If true, the values in the resulting array will have the same keys as in the input array. If false, the resulting array will have numeric keys starting from zero.

Examples

$array = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) // 3 elements starting at index 4 $slice = Array_Slice($array, 4, 3, false) // $slice is (5, 6, 7) // First 4 elements $slice = Array_Slice($array, 0, 4, false) // $slice is (1, 2, 3, 4) // 2 elements starting at 4th element from the end (7) $slice = Array_Slice($array, -4, 2, false) // $slice is (7, 8) // Last 3 elements $slice = Array_Slice($array, -3, 3, false) // $slice is (8, 9, 10) // Preserve keys $slice = Array_Slice($array, 4, 3, true) // $slice is: // 4 => 5 // 5 => 6 // 6 => 7

Array_SortByKey

Sorts an array by the keys.

Syntax

void Array_SortByKey(Array array)

Parameters

Array array
Array to sort.

Examples

$array["size"] = "large" $array["type"] = "t-shirt" $array["price"] = 10 $array["color"] = "red" Array_SortByKey($array) // $array is // "color" => "red" // "price" => 10 // "size" => "large" // "type" => "t-shirt"

Array_SortByValue

Sorts an array by the values.

Syntax

void Array_SortByValue(
	Array array, 
	Bool preserveKeys)

Parameters

Array array
Array to sort.
Bool preserveKeys
If true, the values in the array will have the same keys as before, but just order changed. If false, the values will be assigned to new numeric keys starting from zero.

Examples

$array = Array(6, 3, 7, 8, 4, 2, 3) Array_SortByValue($array, false) // $array is // 0 => 2 // 1 => 3 // 2 => 3 // 3 => 4 // 4 => 6 // 5 => 7 // 6 => 8 // Preserve keys $array = Array(6, 3, 7, 8, 4, 2, 3) Array_SortByValue($array, true) // $array is // 5 => 2 // 1 => 3 // 6 => 3 // 4 => 4 // 0 => 6 // 2 => 7 // 3 => 8

Array_Splice

Removes a a sequence of elements of the given array and replaces it with the given array. Numeric keys in the input array is not preseved and re-numbered from 0.

Syntax

void Array_Splice(
	Array array, 
	Numeric offset, 
	Numeric length, 
	Array replacement)

Parameters

Array array
Array to remove and replace elements from.
Numeric offset
The start offset to remove and replace elements. If non-negative, the sequence will start that far away from the beginning of the array. If negative, the sequence will start that far away from the end of the array.
Numeric length
The length of the sequence. If there aren't that many elements in the array, all the elements till the end of the array will be removed and replaced. If given as zero, no elements will be removed but the new elements will be inserted at given offset.
Array replacement
The set of elements to replace with. If this is an empty array, elements are removed only. Keys in the replacement array is ignored.

Examples

$array = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) // Remove 3 elements starting at index 4, and insert (97, 98) Array_Splice($array, 4, 3, Array(97, 98)) // $array is (1, 2, 3, 4, 97, 98, 8, 9, 10) // Remove first 4 elements Array_Splice($array, 0, 4, Array()) // $array is (97, 98, 8, 9, 10) // Remove 2 elements starting at 4th element from the end (98) and insert (0, -1, -2) Array_Splice($array, -4, 2, Array(0, -1, -2)) // $array is (97, 0, -1, -2, 9, 10) // Remove last 3 elements and insert (0) Array_Splice($array, -3, 3, Array(0)) // $array is (97, 0, -1, 0) // Insert (3, 4, 5) at the beginning Array_Splice($array, 0, 0, Array(3, 4, 5)) // $array is (3, 4, 5, 97, 0, -1, 0) // Insert (7, 8, 9) at the end Array_Splice($array, Array_Length($array), 0, Array(7, 8, 9)) // $array is (3, 4, 5, 97, 0, -1, 0, 7, 8, 9)

Array_Unique

Removes duplicate elements from the given array. Keys are preserved but the order of elements may be changed.

Syntax

void Array_Unique(Array array)

Parameters

Array array
Array to remove the duplicates from.

Examples

$array = Array(2, 6, 4, 3, 5, 9, 1, 2, 7, 5, 1, 4, 2, 6) Array_Unique($array) // $array is: // 6 => 1 // 0 => 2 // 3 => 3 // 2 => 4 // 4 => 5 // 1 => 6 // 8 => 7 // 5 => 9

Array_ValueExists

Returns whether a given value exists or not in the given array. A variable is passed to the last parameter to retrieve the key associated with the value if exists.

Syntax

Bool Array_ValueExists(
	Array array, 
	Mixed value, 
	out Mixed key)

Parameters

Array array
Array to look for the value in.
Mixed value
Value to look for.
out Mixed key
If the value is found, the key is stored in this variable. If the value appears more than once in the array first found key is returned.

Examples

$array = Array(2, 4, 6, "apple", "banana", "strawberry", 4, 2) $foundBanana = Array_ValueExists($array, "banana", $key) // $foundBanana is true, $key is 4 $found4 = Array_ValueExists($array, 4, $key) // $found4 is true, $key is 1 $found5 = Array_ValueExists($array, 5, $key) // $found5 is false, $key is not modified

Array_Values

Returns a new array that contains the values of the given array. The new array will have numeric keys starting at zero.

Syntax

Array Array_Values(Array array)

Parameters

Array array
Array return the values of.

Examples

$array["color"] = "red" $array["size"] = "large" $array["type"] = "t-shirt" $array["price"] = 10 $values = Array_Values($array) // $values is ("red", "large", "t-shirt", 10)

IsArray

Returns whether a given expression is an array or not.

Syntax

Bool IsArray(Mixed expression)

Parameters

Mixed expression
Expression to check for.

Examples

IsArray(Array()) // true IsArray(Array(1, 2, 3)) // true IsArray(true) // false IsArray("string") // false IsArray(GetCurrentSection().pages) // true

Color Functions

Color

Creates a variable of type Color.

Syntax

Color Color(String value)

Parameters

String value

The color value. Following string values are accepted:

#rrggbb: Red, green and blue values specified in lowercase hexadecimal (0-9, a-f)

#RRGGBB: Red, green and blue values specified in uppercase hexadecimal (0-9, A-F)

Predefined color names (Expand)

Examples

$color1 = Color("yellow") $color1 == "#ffff00" // True $color2 = Color("#6A5ACD") $color2 == "#6a5acd" // True $color2 == "SlateBlue" // True $color2 == "SpringGreen" // False

Data Store Functions

BinaryStore_Read

Reads file contents from the binary store and returns it. The return value can be assigned to data property of Image or EmbeddedFile objects. See more about this at Using Binary Data.

Syntax

Binary BinaryStore_Read(String name)

Parameters

String name
The name of the file to read from the binary store.

LocalStore_Delete

Deletes the value stored under given key for this macro on the local computer. The value would have been saved by LocalStore_Write function in a previous execution of this macro. See more about this at Storing persistent data.

Syntax

void LocalStore_Delete(String key)

Parameters

String key
The key to delete.

LocalStore_Read

Reads the value stored under the given key for this macro on the local computer. Returns true if the key has been found and the value is stored in the out parameter, false otherwise. The value must have been stored previously using LocalStore_Write function in either the current or a previous execution of this macro. See more about this at Storing Persistent Data.

Syntax

Bool LocalStore_Read(
	String key, 
	out Mixed value)

Parameters

String key
The key the value was stored under previously.
out Mixed value
If the key is found, the value is stored in this parameter. Check the return value of the function to know whether the key was found or not.

LocalStore_Write

Saves given key-value pair for this macro on the local computer. The value can be retrieved later using LocalStore_Read function even in a subsequent execution of this macro. See more about this at Storing persistent data.

Syntax

void LocalStore_Write(
	String key, 
	Mixed value)

Parameters

String key
The key to store the value under.
Mixed value
The value to store. This can be any type other than an Object. If it is an Array, it cannot contain Objects.

Date/Time Functions

Date/Time Manipulation Functions

Date/Time Extraction Functions

DateTime_Now

Returns the current date/time.

Syntax

DateTime DateTime_Now()

Parameters

This function has no parameters

DateTime_FromString

Returns a date/time value by parsing a string representation of it.

Syntax

DateTime DateTime_FromString(String dateStr)

Parameters

String dateStr
String value to parse into a date/time object. It needs to be in the following format: YYYY-MM-DDTHH-MM-SS.000Z as specified at http://www.w3.org/TR/xmlschema-2/#dateTime.

Examples

$date = DateTime_FromString("2022-10-05T22:33:00.000Z") // 2022-10-05 22:33 UTC

DateTime_ToString

Returns a string representation of a date/time value in local or UTC timezone. The format of the string is the following: YYYY-MM-DDTHH-MM-SS.000Z as specified at http://www.w3.org/TR/xmlschema-2/#dateTime.

Syntax

String DateTime_ToString(
	DateTime date, 
	Bool local)

Parameters

DateTime date
Date/time value to convert to string.
Bool local
Whether to output in local timezone or UTC.

Examples

$date = DateTime_ToString(DateTime(2022, 10, 5, 22, 33), false) // outputs: "2022-10-05T22:33:00.000Z"

DateTime_Add

Returns a new date/time value by adding the given time span to the given date/time value.

Syntax

DateTime DateTime_Add(
	DateTime date, 
	TimeSpan timespan)

Parameters

DateTime date
Date/time value to add to.
TimeSpan timespan
Time span amount to add.

Examples

$now = DateTime_Now() // Find 4 days later $fourDaysLater = DateTime_Add($now, TimeSpan(4, "day"))

DateTime_Subtract

Returns a new date/time value by subtracting the given time span from the given date/time value. It can also be used to subtract two date/time values to find the difference between them as a time span value.

Syntax

Mixed DateTime_Subtract(
	DateTime date, 
	Mixed dateOrTimespan)

Parameters

DateTime date
Date/time value to add to.
Mixed dateOrTimespan
Time span amount to subtract, or second date/time value to find the difference.

Examples

$now = DateTime_Now() // Find 3 hours earlier $threeHoursEarlier = DateTime_Subtract($now, TimeSpan(3, "hour")) // Find the difference between them $diff = DateTime_Subtract($now, $threeHoursEarlier) // $diff is 3 hours

DateTime

Returns a date/time value from given year, month, day, hour, minute, and second values. Hour, minute, and second values are optional. The returned date/time value is in the local timezone of the current computer.

Syntax

DateTime DateTime(
	Integer year, 
	Integer month, 
	Integer day, 
	Integer hour, 
	Integer min, 
	Integer sec)

Parameters

Integer year
Year value.
Integer month
Month value.
Integer day
Day value.
Integer hour (optional)
Hour value.
Integer min (optional)
Minute value.
Integer sec (optional)
Second value.

Examples

$date = DateTime(2022, 10, 5, 22, 33) // 2022-10-05 22:33:00 Local time $date = DateTime(2022, 10, 5) // 2022-10-05 00:00:00 Local time

TimeSpan

Returns a time span value that can be added or subtracted from a date/time object using DateTime_Add and DateTime_Subtract functions.

Syntax

TimeSpan TimeSpan(
	Integer amount, 
	String unit)

Parameters

Integer amount
Amount of time, based on the unit.
String unit
Unit for the timespan. Can be one of sec, min, hour, or day.

Examples

$now = DateTime_Now() // Find 4 days later $fourDaysLater = DateTime_Add($now, TimeSpan(4, "day")) // Find 3 hours earlier $threeHoursEarlier = DateTime_Subtract($now, TimeSpan(3, "hour")) // Or you can use negative time span $threeHoursEarlier = DateTime_Add($now, TimeSpan(-3, "hour"))

DateTime_LongDate

Returns the date portion of the given date/time in long date format.

Syntax

String DateTime_LongDate(DateTime dateTime)

Parameters

DateTime dateTime
DateTime value to return the date portion of.

DateTime_ShortDate

Returns the date portion of the given date/time in short date format.

Syntax

String DateTime_ShortDate(DateTime dateTime)

Parameters

DateTime dateTime
DateTime value to return the date portion of.

DateTime_Year

Returns the year of the given date/time.

Syntax

String DateTime_Year(DateTime dateTime)

Parameters

DateTime dateTime
DateTime value to return the month portion of.

DateTime_Month

Returns the month (1-12) of the given date/time.

Syntax

String DateTime_Month(DateTime dateTime)

Parameters

DateTime dateTime
DateTime value to return the month portion of.

DateTime_Day

Returns the day of the month (1-31) of the given date/time.

Syntax

String DateTime_Day(DateTime dateTime)

Parameters

DateTime dateTime
DateTime value to return the day portion of.

DateTime_DayOfTheYear

Returns the day of the year (1-366) of the given date/time.

Syntax

String DateTime_DayOfTheYear(DateTime dateTime)

Parameters

DateTime dateTime
DateTime value to return the day portion of.

DateTime_DayOfTheWeek_Long

Returns the day of the week of the given date/time in long format.

Syntax

String DateTime_DayOfTheWeek_Long(DateTime dateTime)

Parameters

DateTime dateTime
DateTime value to return the day portion of.

DateTime_DayOfTheWeek_Short

Returns the day of the week of the given date/time in short format.

Syntax

String DateTime_DayOfTheWeek_Short(DateTime dateTime)

Parameters

DateTime dateTime
DateTime value to return the day portion of.

DateTime_MonthName_Long

Returns the name of the month of the given date/time in long format.

Syntax

String DateTime_MonthName_Long(DateTime dateTime)

Parameters

DateTime dateTime
DateTime value to return the month portion of.

DateTime_MonthName_Short

Returns the name of the month of the given date/time in short format.

Syntax

String DateTime_MonthName_Short(DateTime dateTime)

Parameters

DateTime dateTime
DateTime value to return the month portion of.

DateTime_DaysSinceSunday

Returns the number of days passed since Sunday for the given date/time.

Syntax

String DateTime_DaysSinceSunday(DateTime dateTime)

Parameters

DateTime dateTime
DateTime value to return the days portion of.

DateTime_LongTime

Returns the time portion of the given date/time in long format.

Syntax

String DateTime_LongTime(DateTime dateTime)

Parameters

DateTime dateTime
DateTime value to return the time portion of.

DateTime_ShortTime

Returns the time portion of the given date/time in short format.

Syntax

String DateTime_ShortTime(DateTime dateTime)

Parameters

DateTime dateTime
DateTime value to return the time portion of.

DateTime_Hour

Returns the hour (0-23) of the given date/time.

Syntax

String DateTime_Hour(DateTime dateTime)

Parameters

DateTime dateTime
DateTime value to return the hour portion of.

DateTime_Min

Returns the minute (0-59) of the given date/time.

Syntax

String DateTime_Min(DateTime dateTime)

Parameters

DateTime dateTime
DateTime value to return the minute portion of.

DateTime_Sec

Returns the second (0-59) of the given date/time.

Syntax

String DateTime_Sec(DateTime dateTime)

Parameters

DateTime dateTime
DateTime value to return the second portion of.

Dialog Box Functions

DialogBox_AddButton

Adds a custom button to a dialog box..

Syntax

void DialogBox_AddButton(
	DialogBox dialogBox, 
	String label, 
	String name)

Parameters

DialogBox dialogBox
The dialogBox to add the button to.
String label
A label for the button. If there is an ampersand (&) sign before a character in the label it becomes the button's accelerator key.
String name
Name of the button. When a dialog box is closed by clicking on this button, DialogBox_Show function will return the name of the button that was clicked..

Remarks

If no custom buttons are added to a dialog box, it will automatically have an "OK" button when it is displayed. Up to 4 buttons can be added to a dialog box. When the user clicks on a button the dialog box closes and DialogBox_Show function will return the name of the button that was clicked

Examples

$dialog = DialogBox_Create("Do you want to delete this page?") DialogBox_AddButton($dialog, "&Yes", "yes") DialogBox_AddButton($dialog, "&No", "no") ExpandIf ("yes" == DialogBox_Show($dialog)) RemoveObject($page)

This will display the following dialog box:

Dialog box with custom button

After user clicks on one of the "Yes" and "No" buttons, DialogBox_Show function returns either "yes" or "no", the name of the button user clicked.

DialogBox_AddCheckBox

Adds a checkbox to a dialog box.

Syntax

void DialogBox_AddCheckBox(
	DialogBox dialogBox, 
	String label, 
	String name, 
	Bool initialValue)

Parameters

DialogBox dialogBox
The dialog box to add the checkbox to.
String label
A label for the checkbox.
String name
Name of the checkbox. The value of the checkbox will be stored dialogBox.controls[name] after the dialog is displayed using DialogBox_Show function.
Bool initialValue
The initial value of the checkbox.

DialogBox_AddColorPicker

Adds a color picker control to a dialog box.

Syntax

void DialogBox_AddColorPicker(
	DialogBox dialogBox, 
	String label, 
	String name, 
	String initialValue)

Parameters

DialogBox dialogBox
The dialog box to add the color picker to.
String label
A label for the color picker.
String name
Name of the color picker. The color picked from the color picker will be stored dialogBox.controls[name] after the dialog is displayed using DialogBox_Show function.
String initialValue
The initial selected value of the color picker.

DialogBox_AddComboBox

Adds a drop down combo box to a dialog box.

Syntax

void DialogBox_AddComboBox(
	DialogBox dialogBox, 
	String label, 
	String name, 
	String initialValue, 
	Array<String> possibleValues, 
	Bool emptyOK)

Parameters

DialogBox dialogBox
The dialog box to add the drop down combo box to.
String label
A label for the drop down combo box.
String name
Name of the drop down combo box. The value of the drop down combo box will be stored dialogBox.controls[name] after the dialog is displayed using DialogBox_Show function.
String initialValue
The initial selected value of the drop down combo box.
Array<String> possibleValues
The values to display in the drop down combo box.
Bool emptyOK
Whether it is OK for user to leave the combo box empty or not. If this is false, then the dialog box cannot be closed without entering some text into the combo box.

DialogBox_AddDateTimePicker

Adds a date/time picker control to a dialog box.

Syntax

void DialogBox_AddDateTimePicker(
	DialogBox dialogBox, 
	String label, 
	String name, 
	DateTime initialValue, 
	DateTimePickerType type)

Parameters

DialogBox dialogBox
The dialog box to add the date/time picker to.
String label
A label for the date/time picker.
String name
Name of the date/time picker. The date/time picked from the date/time picker will be stored dialogBox.controls[name] after the dialog is displayed using DialogBox_Show function.
DateTime initialValue
The initial selected date/time of the date/time picker.
DateTimePickerType type
The type of date/time picker. Can have the values "date", "time", or "datetime".

DialogBox_AddDropDown

Adds a drop down list box to a dialog box.

Syntax

void DialogBox_AddDropDown(
	DialogBox dialogBox, 
	String label, 
	String name, 
	String initialValue, 
	Array<String> possibleValues)

Parameters

DialogBox dialogBox
The dialog box to add the drop down list box to.
String label
A label for the drop down list box.
String name
Name of the drop down list box. The value of the drop down list box will be stored dialogBox.controls[name] after the dialog is displayed using DialogBox_Show function.
String initialValue
The initial selected value of the drop down list box.
Array<String> possibleValues
The values to display in the drop down list box.

DialogBox_AddFontPicker

Adds a font picker control to a dialog box.

Syntax

void DialogBox_AddFontPicker(
	DialogBox dialogBox, 
	String label, 
	String name, 
	String initialValue)

Parameters

DialogBox dialogBox
The dialog box to add the font picker to.
String label
A label for the font picker.
String name
Name of the font picker. The font picked from the font picker will be stored dialogBox.controls[name] after the dialog is displayed using DialogBox_Show function.
String initialValue
The initial selected value of the font picker.

DialogBox_AddLabel

Adds a label to a dialog box.

Syntax

void DialogBox_AddLabel(
	DialogBox dialogBox, 
	String label)

Parameters

DialogBox dialogBox
The dialog box to add the text box to.
String label
A text for the label.

DialogBox_AddRadioGroup

Adds a group of radio buttons to a dialog box. User can choose at most one of the options in the group.

Syntax

void DialogBox_AddRadioGroup(
	DialogBox dialogBox, 
	String label, 
	String name, 
	String initialValue, 
	Array<String> possibleValues)

Parameters

DialogBox dialogBox
The dialog box to add the radio group to.
String label
A label for the whole group.
String name
Name of the radio group. The value of the selected option will be stored dialogBox.controls[name] after the dialog is displayed using DialogBox_Show function.
String initialValue
The initial selected option among the group.
Array<String> possibleValues
The list of options to display.

DialogBox_AddTextBox

Adds a text box to a dialog box.

Syntax

void DialogBox_AddTextBox(
	DialogBox dialogBox, 
	String label, 
	String name, 
	String initialValue, 
	Bool emptyOK)

Parameters

DialogBox dialogBox
The dialog box to add the text box to.
String label
A label for the text box.
String name
Name of the text box. The value of the text box will be stored dialogBox.controls[name] after the dialog is displayed using DialogBox_Show function.
String initialValue
The initial value of the text box.
Bool emptyOK
Whether it is OK for user to leave the text box empty or not. If this is false, then the dialog box cannot be closed without entering some text into the text box.

DialogBox_Create

Creates a dialog box. Use DialogBox_Add* functions to add controls and DialogBox_Show to display it.

Syntax

DialogBox DialogBox_Create(String message)

Parameters

String message
A message to display on the dialog box. Can be empty string if no message is desired.

DialogBox_SetControlEnabled

Enables or disables a control in a dialog box. This function can be called prior to displaying a dialog box via DialogBox_Show or during a dialog box event handler set by DialogBox_SetEventHandler.

Syntax

void DialogBox_SetControlEnabled(
	DialogBox dialogBox, 
	String controlName, 
	Bool enabled)

Parameters

DialogBox dialogBox
The dialog box that contains the control to enable or disable.
String controlName
The name of the control to enable or disable.
Bool enabled
Whether to enable or to disable the control.

DialogBox_SetControlVisible

Hides or shows a control in a dialog box. This function can be called prior to displaying a dialog box via DialogBox_Show or during a dialog box event handler set by DialogBox_SetEventHandler.

Syntax

void DialogBox_SetControlVisible(
	DialogBox dialogBox, 
	String controlName, 
	Bool visible)

Parameters

DialogBox dialogBox
The dialog box that contains the control to hide or show.
String controlName
The name of the control to hide or show.
Bool visible
Whether to hide or to show the control.

DialogBox_SetEventHandler

Sets an event handler for a dialog box.

Syntax

void DialogBox_SetEventHandler(
	DialogBox dialogBox, 
	String functionName)

Parameters

DialogBox dialogBox
The dialog box to set the event handler for.
String functionName
Name of the user defined function to set as an event handler for the dialog.

Remarks

An event handler is a user defined function that gets called when the dialog is first created and then each time when value of one of the controls in the dialog box changes (e.g. user types into a text box, checks a check box, or chooses an option from a dropdown box etc.) or user clicks a custom button. Event handlers are not required to be set for a dialog box but can be used for more control on what controls are visible or enabled under specific conditions. The signature of an event handler is as follows:

Function EventHandler(byref $dialogBox, $controlName)

The first parameter is the dialog box that the event is coming from. The second parameter is the name of the control which the event is originating from. When the event handler is called the first time when the dialog is created, control name will be empty. In the subsequent calls, in case of a value change this will be the name of the corresponding color picker, combo box, date/time picker, drop down, font picker, radio group or text box. In case of a button click, this will be the name of the button.

Handling of button clicks in a dialog

Closing a dialog via X button on the top right ends macro execution and the event handler will not be called.

If there are no custom buttons added to a dialog box, it will display the default "OK" button. In this case, if user clicks on the "OK" button:

If there are custom buttons added to a dialog box (via DialogBox_AddButton), and the user clicks on one of the buttons, the handling of the dialog depends on whether an event handler is set or not:

DialogBox_Show

Displays a dialog box created with DialogBox_Create function. If a dialog box is closed by clicking on one of the action buttons, DialogBox_Show will return the name of the button. If no custom buttons are added by DialogBox_AddButton to the dialog box, then user can click on the default "OK" button and DialogBox_Show will then return "ok".

Syntax

String DialogBox_Show(DialogBox dialogBox)

Parameters

DialogBox dialogBox
The dialog box object to display.

ShowMessage

Shows a message to the user in a message box with OK button. Macro execution continues after user closes the message box.

Syntax

void ShowMessage(String message)

Parameters

String message
A message to display to the user in a message box.

Remarks

A message box contains the macro name as a title and the given message. It may look like this:

Example Message Box

User can click OK or close the dialog using the X button. In either case macro execution will continue.

Examples

ShowMessage("No instances of the search term is found.")

ShowTaskDialog

Shows a task dialog to the user with a number of command buttons to choose from.

Syntax

Integer ShowTaskDialog(
	String title, 
	String message, 
	Array<String> buttons)

Parameters

String title
A title for the task dialog.
String message
A message for the task dialog that will show below the title.
Array<String> buttons
An array of button labels.

Remarks

A task dialog contains a title, a message and a set of command buttons. It may look like this:

Example Task Dialog

User can click one of the command buttons or close the dialog. If user clicks one of the buttons, the dialog will close and this function will return the index of the button in the given button array (0 for the first button, 1 for the second button etc). If user closes the dialog using the X button on the top right corner, then macro execution will stop.

Examples

$message = "You can save the currently selected text as a snippet to be used for later, or you can insert one of the previously saved snippets to the current page." $buttons = Array("Insert previously saved text snippet", "Save selected text as a snippet", "Manage text snippets") $selected = ShowTaskDialog("Choose an option", $message, $buttons) ExpandSwitch ($selected) ExpandCase 0: // User selected first option Break 1 ExpandCase 1: // User selected second option Break 1 ExpandCase 2: // User selected third option Break 1

Macro Execution Functions

ExitMacro

Exits the macro execution while optionally saving any changes made to OneNote. To save changes without exiting macro execution, use the SaveChanges function.

Syntax

void ExitMacro(Bool saveChanges)

Parameters

Bool saveChanges
Saves any changes made by this macro to OneNote if set to true, discards them if set to false.

SaveChanges

Saves any changes made by this macro to OneNote. After changes are saved, all objects within any modified pages are invalidated. That is, if there are variables that are holding objects within such a page (e.g. Outlines, Paragraphs, Text objects etc.) they will be invalid and should not be used again. To get to those objects again, access them through a Page object. Objects within unmodified pages are unaffected.

Macros normally save any changes they made to OneNote at the end of macro execution, except if the execution is terminated by a call to ExitMacro(false). Therefore, it is typically not necessary to use this function. However, there are some cases where you may want to save changes before macro execution ends. For example this function can be useful to obtain certain properties that will only be available after saving changes or to provide incremental updates to the user.

Syntax

void SaveChanges()

Parameters

This function has no parameters

Examples

// Insert a paragraph into the first outline of the current page $page = GetCurrentPage() $outline = $page.outlines[0] $paragraph = InsertObject($outline, "Paragraph", 0) // Add some bold text $text = InsertObject($paragraph, "Text", -1) $text.value = "bold text" $text.bold = true // If we want to get the id or hyperlink for this paragraph, // we can't at this point, since these are only set by OneNote // after the changes are saved // This would return empty string: $id = $paragraph.objectId // Now save the changes we made SaveChanges() // At this point all page objects are invalidated // Do not access $outline, $paragraph, $text anymore as they are invalid // We can get them from the page again: $outline = $page.outlines[0] $paragraph = $outline.paragraphs[0] // Now we can get the id of this paragraph $id = $paragraph.objectId

Macro Menu Functions

MacroMenu_AddItem

Adds a menu item to current macro's menu. Macros can optionally display a menu with multiple items. See Macro menus for more information..

Syntax

void MacroMenu_AddItem(
	MacroMenu menu, 
	String argument, 
	String label, 
	String description)

Parameters

MacroMenu menu
The menu to add menu item to. This object will be passed to the Setup function.
String argument
The argument passed to the Main function if this menu item is clicked.
String label
The label to be displayed in the ribbon for this menu item.
String description
The description to be displayed in the ribbon for this menu item.

Object Functions

GetAncestorOfType

Returns true if the given object has an ancestor of given type and stores that ancestor in the ancestor parameter.

Syntax

Bool GetAncestorOfType(
	Object object, 
	ObjectType type, 
	out Object ancestor)

Parameters

Object object
Object to look for an ancestor of.
ObjectType type
Type of the ancestor to look for.
out Object ancestor
If an ancestor is found, it is stored in this parameter. Check the return value of the function to know whether an ancestor was found or not.

Examples

// Find the first image on the current page $image = QueryObjects("Image", GetCurrentPage()) // Check if this image lives inside a table or not ExpandIf (GetAncestorOfType($image, "Table", $tableAncestor)) // This image is in a table, do something here with $tableAncestor ExpandElse // This image is not in a table

GetCurrentNotebook

Returns the current notebook in OneNote.

Syntax

Notebook GetCurrentNotebook()

Parameters

This function has no parameters

GetCurrentPage

Returns the current page in OneNote.

Syntax

Page GetCurrentPage()

Parameters

This function has no parameters

GetCurrentSection

Returns the current section in OneNote.

Syntax

Section GetCurrentSection()

Parameters

This function has no parameters

GetCurrentSectionGroup

Returns the current section group in OneNote. If the current section is not in a section group, then returns the current Notebook.

Syntax

Mixed GetCurrentSectionGroup()

Parameters

This function has no parameters

GetNotebookRoot

Returns the root of the notebook hierarchy in OneNote.

Syntax

NotebookRoot GetNotebookRoot()

Parameters

This function has no parameters

GetParentOfType

Returns true if the given object has a parent of given type and stores that parent in the parent parameter.

Syntax

Bool GetParentOfType(
	Object object, 
	ObjectType type, 
	out Object parent)

Parameters

Object object
Object to look for a parent of.
ObjectType type
Type of the parent to look for.
out Object parent
If a parent is found, it is stored in this parameter. Check the return value of the function to know whether a parent was found or not.

Examples

// Find the first image on the current page $image = QueryObjects("Image", GetCurrentPage()) // Check if this is an image directly on the page or an image inside an outline // An image in an outline has a direct parent of type Paragraph If (GetParentOfType($image, "Paragraph", $parentParagraph)) // Parent is a Paragraph, do something here with $parentParagraph Else // Parent is not a Paragraph, the image must be directly under the Page

InsertObject

Creates a new object and inserts it into OneNote hierarchy or into a OneNote page. Returns the newly created object.

Syntax

Object InsertObject(
	Object object, 
	ObjectType type, 
	Numeric position)

Parameters

Object object
Parent object to insert the new object into.
ObjectType type
The type of the new object to create and insert. Following types of objects can be inserted: SectionGroup (under a Notebook or a SectionGroup), Section (under a Notebook or a SectionGroup), Page (under a Section), Outline (under a Page), Paragraph (under an Outline or a Cell), Table (under an Outline or a Cell), Row (under a Table), Cell (under a Row), Text (under a Paragraph).
Numeric position
The position of the new object. The value is a 0 based index for the child collection or -1 to insert at the end.

IsObject

Returns whether a given expression is an object or not.

Syntax

Bool IsObject(Mixed expression)

Parameters

Mixed expression
Expression to check for.

Examples

IsObject(GetCurrentPage()) // true IsObject(Array(1, 2, 3)) // false IsObject(true) // false IsObject("string") // false IsObject(Window_GetCurrent()) // true

QueryObjects

Queries requested type of object in OneNote within the given scope. Returns all found object in an array. Search is done in a depth-first manner.

Syntax

Array<Object> QueryObjects(
	ObjectType type, 
	Object scope)

Parameters

ObjectType type
Type of the object to query for.
Object scope
Root object for the search. All objects under this object (including this object) are searched.

QueryText

Queries given text in OneNote within the given scope. Returns all found text object in an array. Search is done in a depth-first manner.

Syntax

Array<Text> QueryText(
	Object scope, 
	String value, 
	Bool ignoreCase)

Parameters

Object scope
Root object for the search. All text under this object (including this object) are searched.
String value
The text value to search for.
Bool ignoreCase
Find text in case-insensitive manner if set to true.

RemoveObject

Removes the given object from its parent object. The object must have a parent object. This can be used to delete content from a Page or whole pages. Certain container objects will only be valid with at least one child, and therefore removing the last child will result in a schema error. For instance Outline and Cell objects require at least one Paragraph inside it..

Syntax

void RemoveObject(Object object)

Parameters

Object object
The object to remove.

SortObjects

Sorts given objects by a given property or a given custom sort order. When sorting object that are not under the same parent object, they are sorted only within their siblings. For instance if you try to sort all pages in current notebook, they will be sorted within each section and they won't move between sections.

Syntax

void SortObjects(
	Array objects, 
	Mixed by, 
	Bool ascending)

Parameters

Array objects
Array of objects to be sorted.
Mixed by
The property to sort by (in which case its type is string) or a custom sort order (in which case its type is an array). A custom sort order array must have indices 0 to number of elements being sorted and its values will be used when comparing corresponding object in the object array.
Bool ascending
Sort in ascending order, if set to true, descending order if set to false.

String Functions

Chr

Creates a string from a given ASCII number or Unicode code point. For instance Chr(10) will return the newline character "\n".

Syntax

String Chr(Mixed number...)

Parameters

Mixed number (optional)
The ASCII number(s) or Unicode code point(s). This can be a single number/code point, multiple numbers/code points separated by commas, or an array of numbers/code points. If given multiple numbers/code points or an array of them, it will return a string that contains each of the characters. Chr(13, 10) or Chr(Array(13, 10)) will return "\r\n".

Examples

Chr(65) // "A" Chr(79, 110, 101, 78, 111, 116, 101) // "OneNote" Chr(Array(77, 97, 99, 114, 111)) // "Macro" Chr(9924, 9917) // "⛄⚽"

String_Contains

Returns true if the first string contains the second string, false otherwise.

Syntax

Bool String_Contains(
	String first, 
	String second, 
	Bool ignoreCase)

Parameters

String first
First string to compare.
String second
Second string to compare.
Bool ignoreCase
Ignores the case of the strings if set to true.

Examples

String_Contains("The quick brown fox", "brown", false) // true // Case Sensitive String_Contains("The quick brown fox", "Quick", false) // false // Case Insensitive String_Contains("The quick brown fox", "Quick", true) // true

String_DoesNotEqual

Returns true if the given two strings are not equal, false otherwise.

Syntax

Bool String_DoesNotEqual(
	String first, 
	String second, 
	Bool ignoreCase)

Parameters

String first
First string to compare.
String second
Second string to compare.
Bool ignoreCase
Ignores the case of the strings if set to true.

Examples

String_DoesNotEqual("banana", "banana", false) // false String_DoesNotEqual("apple", "orange", false) // true // Case Sensitive String_DoesNotEqual("Strawberry", "strawberry", false) // true // Case Insensitive String_DoesNotEqual("Strawberry", "strawberry", true) // false

String_EndsWith

Returns true if the first string ends with the second string, false otherwise.

Syntax

Bool String_EndsWith(
	String first, 
	String second, 
	Bool ignoreCase)

Parameters

String first
First string to compare.
String second
Second string to compare.
Bool ignoreCase
Ignores the case of the strings if set to true.

Examples

// Case Sensitive String_EndsWith("The quick brown fox", "Fox", false) // false // Case Insensitive String_EndsWith("The quick brown fox", "Fox", true) // true

String_Equals

Returns true if the given two strings are equal, false otherwise.

Syntax

Bool String_Equals(
	String first, 
	String second, 
	Bool ignoreCase)

Parameters

String first
First string to compare.
String second
Second string to compare.
Bool ignoreCase
Ignores the case of the strings if set to true.

Examples

String_Equals("banana", "banana", false) // true String_Equals("apple", "orange", false) // false // Case Sensitive String_Equals("Strawberry", "strawberry", false) // false // Case Insensitive String_Equals("Strawberry", "strawberry", true) // true

String_FindFirst

Finds the first occurence of a search string in an input string. Returns true if the string was found and the offset it was found at, false otherwise.

Syntax

Bool String_FindFirst(
	String string, 
	String search, 
	Numeric offset, 
	Bool ignoreCase, 
	out Numeric foundAt)

Parameters

String string
String to search in.
String search
The substring to search for.
Numeric offset
Offset of the input string to start search from. If non-negative, search will start this number of characters counted from the beginning of the string. If negative, the search will start this number of characters counted from the end of the string.
Bool ignoreCase
Ignores the case of the strings if set to true.
out Numeric foundAt
If the search string is found, the offset of the first occurence is stored in this variable.

Examples

// 1 2 3 4 // 01234567890123456789012345678901234567890 $string = "a4 b6 c5 4a b6 d5 f6 d7 e4 b6 c2 56 d4 5a" // ^ ^ ^ // Instances of b6 are marked with ^ // Find first instance String_FindFirst($string, "b6", 0, false, $foundAt) // Returns true, $foundAt is 3 // Find first instance after index 9 String_FindFirst($string, "b6", 9, false, $foundAt) // Returns true, $foundAt is 12 // Find first instance within the last 20 characters String_FindFirst($string, "b6", -20, false, $foundAt) // Returns true, $foundAt is 27 // Not found String_FindFirst($string, "f9", 0, false, $foundAt) // Returns false, $foundAt is not modified // Case Sensitive String_FindFirst("The quick brown fox jumps over the lazy dog", "the", 0, false, $foundAt) // Returns true, $foundAt is 31 // Case Insensitive String_FindFirst("The quick brown fox jumps over the lazy dog", "the", 0, true, $foundAt) // Returns true, $foundAt is 0

String_FindFirstNotOf

Finds the first character that does not match any of given the characters in an input string. Returns true if it was found and the offset it was found at, false otherwise.

Syntax

Bool String_FindFirstNotOf(
	String string, 
	String characters, 
	Numeric offset, 
	out Numeric foundAt)

Parameters

String string
String to search in.
String characters
The set of characters to look for.
Numeric offset
Offset of the input string to start search from. If non-negative, search will start this number of characters counted from the beginning of the string. If negative, the search will start this number of characters counted from the end of the string.
out Numeric foundAt
If a character that does not match any of the given characters is found, the offset of the first occurence is stored in this variable.

Examples

// 1 2 3 4 // 01234567890123456789012345678901234567890 $string = "a4 b6 c5 4a b6 d5 f6 d7 e4 b6 c2 56 d4 5a" // ^ ^ ^ ^ // Instances of c, 7 and f are marked with ^ // Find first instance of anything but a,b,d,e,2,4,5,6 String_FindFirstNotOf($string, "abde2456", 0, $foundAt) // Returns true, $foundAt is 6 // Find first instance after index 9 String_FindFirstNotOf($string, "abde2456", 9, $foundAt) // Returns true, $foundAt is 18 // Find first instance within the last 20 characters String_FindFirstNotOf($string, "abde2456", -20, $foundAt) // Returns true, $foundAt is 22 // Not found String_FindFirstNotOf($string, "abcdef24567", 0, $foundAt) // Returns false, $foundAt is not modified

String_FindFirstOf

Finds the first occurence of any of the given characters in an input string. Returns true if one was found and the offset it was found at, false otherwise.

Syntax

Bool String_FindFirstOf(
	String string, 
	String characters, 
	Numeric offset, 
	out Numeric foundAt)

Parameters

String string
String to search in.
String characters
The set of characters to look for.
Numeric offset
Offset of the input string to start search from. If non-negative, search will start this number of characters counted from the beginning of the string. If negative, the search will start this number of characters counted from the end of the string.
out Numeric foundAt
If any of the characters is found, the offset of the first occurence is stored in this variable.

Examples

// 1 2 3 4 // 01234567890123456789012345678901234567890 $string = "a4 b6 c5 4a b6 d5 f6 d7 e4 b6 c2 56 d4 5a" // ^ ^ ^ ^ // Instances of c, 7 and f are marked with ^ // Find first instance of c, 7, or f String_FindFirstOf($string, "c7f", 0, $foundAt) // Returns true, $foundAt is 6 // Find first instance after index 9 String_FindFirstOf($string, "c7f", 9, $foundAt) // Returns true, $foundAt is 18 // Find first instance within the last 20 characters String_FindFirstOf($string, "c7f", -20, $foundAt) // Returns true, $foundAt is 22 // Not found String_FindFirstOf($string, "abc", 0, $foundAt) // Returns false, $foundAt is not modified

String_FindLast

Finds the last occurence of a search string in an input string. Returns true if the string was found and the offset it was found at, false otherwise.

Syntax

Bool String_FindLast(
	String string, 
	String search, 
	Numeric offset, 
	Bool ignoreCase, 
	out Numeric foundAt)

Parameters

String string
String to search in.
String search
The substring to search for.
Numeric offset
Offset of the input string to start search from. If positive, search will only look at this number of characters at the beginning of the string. If negative, the search will not include this number of characters at the end of the string. If zero, the search will include the whole string.
Bool ignoreCase
Ignores the case of the strings if set to true.
out Numeric foundAt
If the search string is found, the offset of the last occurence is stored in this variable.

Examples

// 1 2 3 4 // 01234567890123456789012345678901234567890 $string = "a4 b6 c5 4a b6 d5 f6 d7 e4 b6 c2 56 d4 5a" // ^ ^ ^ // Instances of b6 are marked with ^ // Find last instance String_FindLast($string, "b6", 0, false, $foundAt) // Returns true, $foundAt is 27 // Find last instance within the first 20 characters String_FindLast($string, "b6", 20, false, $foundAt) // Returns true, $foundAt is 12 // Find last instance skipping the last 30 characters String_FindLast($string, "b6", -30, false, $foundAt) // Returns true, $foundAt is 3 // Not found String_FindLast($string, "f9", 0, false, $foundAt) // Returns false, $foundAt is not modified // Case Sensitive String_FindLast("The quick brown fox jumps over the lazy dog", "The", 0, false, $foundAt) // Returns true, $foundAt is 0 // Case Insensitive String_FindLast("The quick brown fox jumps over the lazy dog", "The", 0, true, $foundAt) // Returns true, $foundAt is 31

String_FindLastNotOf

Finds the last character that does not match any of given the characters in an input string. Returns true if it was found and the offset it was found at, false otherwise.

Syntax

Bool String_FindLastNotOf(
	String string, 
	String characters, 
	Numeric offset, 
	out Numeric foundAt)

Parameters

String string
String to search in.
String characters
The set of characters to look for.
Numeric offset
Offset of the input string to start search from. If non-negative, search will start this number of characters counted from the beginning of the string, going backwards. If negative, the search will start this number of characters counted from the end of the string, going backwards.
out Numeric foundAt
If a character that does not match any of the given characters is found, the offset of the last occurence is stored in this variable.

Examples

// 1 2 3 4 // 01234567890123456789012345678901234567890 $string = "a4 b6 c5 4a b6 d5 f6 d7 e4 b6 c2 56 d4 5a" // ^ ^ ^ ^ // Instances of c, 7 and f are marked with ^ // Find first instance of anything but a,b,d,e,2,4,5,6 String_FindLastNotOf($string, "abde2456", 0, $foundAt) // Returns true, $foundAt is 30 // Find last instance within the first 20 characters String_FindLastNotOf($string, "abde2456", 9, $foundAt) // Returns true, $foundAt is 18 // Find last instance skipping the last 30 characters String_FindLastNotOf($string, "abde2456", -30, $foundAt) // Returns true, $foundAt is 6 // Not found String_FindLastNotOf($string, "abcdef24567", 0, $foundAt) // Returns false, $foundAt is not modified

String_FindLastOf

Finds the last occurence of any of the given characters in an input string. Returns true if one was found and the offset it was found at, false otherwise.

Syntax

Bool String_FindLastOf(
	String string, 
	String characters, 
	Numeric offset, 
	out Numeric foundAt)

Parameters

String string
String to search in.
String characters
The set of characters to look for.
Numeric offset
Offset of the input string to start search from. If positive, search will only look at this number of characters at the beginning of the string. If negative, the search will not include this number of characters at the end of the string. If zero, the search will include the whole string.
out Numeric foundAt
If any of the characters is found, the offset of the last occurence is stored in this variable.

Examples

// 1 2 3 4 // 01234567890123456789012345678901234567890 $string = "a4 b6 c5 4a b6 d5 f6 d7 e4 b6 c2 56 d4 5a" // ^ ^ ^ ^ // Instances of c, 7 and f are marked with ^ // Find last instance of c, 7, or f String_FindLastOf($string, "c7f", 0, $foundAt) // Returns true, $foundAt is 30 // Find last instance within the first 20 characters String_FindLastOf($string, "c7f", 9, $foundAt) // Returns true, $foundAt is 18 // Find last instance skipping the last 30 characters String_FindLastOf($string, "c7f", -30, $foundAt) // Returns true, $foundAt is 6 // Not found String_FindLastOf($string, "abc", 0, $foundAt) // Returns false, $foundAt is not modified

String_GreaterThan

Returns true if the first string is comes after the second string, false otherwise.

Syntax

Bool String_GreaterThan(
	String first, 
	String second, 
	Bool ignoreCase)

Parameters

String first
First string to compare.
String second
Second string to compare.
Bool ignoreCase
Ignores the case of the strings if set to true.

Examples

String_GreaterThan("apple", "banana", false) // false // Case Sensitive String_GreaterThan("strawberry", "Strawberry", false) // true // Case Insensitive String_GreaterThan("strawberry", "Strawberry", true) // false

String_GreaterThanOrEqualTo

Returns true if the first string is comes after the second string or compares equal, false otherwise.

Syntax

Bool String_GreaterThanOrEqualTo(
	String first, 
	String second, 
	Bool ignoreCase)

Parameters

String first
First string to compare.
String second
Second string to compare.
Bool ignoreCase
Ignores the case of the strings if set to true.

Examples

String_GreaterThanOrEqualTo("apple", "banana", false) // false // Case Sensitive String_GreaterThanOrEqualTo("Strawberry", "strawberry", false) // false // Case Insensitive String_GreaterThanOrEqualTo("Strawberry", "strawberry", true) // true

String_Insert

Inserts a string into another string at a specified position and returns the resulting string.

Syntax

String String_Insert(
	String string, 
	String other, 
	Numeric offset)

Parameters

String string
String to insert into.
String other
String to insert.
Numeric offset
Offset to insert at. If non-negative, the string will be inserted at this number of characters counted from the beginning of the string. If negative, the string will be inserted at this number of characters counted from the end of the string.

Examples

$string = "the quick brown fox " $insert = "JUMPED" // Insert at the beginning String_Insert($string, $insert, 0) // "JUMPEDthe quick brown fox " // Insert at the end String_Insert($string, $insert, String_Length($string)) // "the quick brown fox JUMPED" // Insert at index 7 String_Insert($string, $insert, 7) // "the quiJUMPEDck brown fox " // Insert at 5th character from the end String_Insert($string, $insert, -5) // "the quick brownJUMPED fox "

String_Length

Returns the length of the given string.

Syntax

Numeric String_Length(String string)

Parameters

String string
String to return the length of.

Examples

String_Length("") // 0 String_Length("banana") // 6 String_Length("The quick brown fox") // 19

String_LessThan

Returns true if the first string is comes before the second string, false otherwise.

Syntax

Bool String_LessThan(
	String first, 
	String second, 
	Bool ignoreCase)

Parameters

String first
First string to compare.
String second
Second string to compare.
Bool ignoreCase
Ignores the case of the strings if set to true.

Examples

String_LessThan("apple", "banana", false) // true // Case Sensitive String_LessThan("Strawberry", "strawberry", false) // true // Case Insensitive String_LessThan("Strawberry", "strawberry", true) // false

String_LessThanOrEqualTo

Returns true if the first string is comes before the second string or compares equal, false otherwise.

Syntax

Bool String_LessThanOrEqualTo(
	String first, 
	String second, 
	Bool ignoreCase)

Parameters

String first
First string to compare.
String second
Second string to compare.
Bool ignoreCase
Ignores the case of the strings if set to true.

Examples

String_LessThanOrEqualTo("apple", "banana", false) // true // Case Sensitive String_LessThanOrEqualTo("strawberry", "Strawberry", false) // false // Case Insensitive String_LessThanOrEqualTo("strawberry", "Strawberry", true) // true

String_Pad

Pads a string to a certain length with another string and returns the resulting string.

Syntax

String String_Pad(
	String string, 
	String padString, 
	Numeric length, 
	String padDirection)

Parameters

String string
String to be padded with padString.
String padString
String to pad with.
Numeric length
String will be at this length after padding. If this is smaller than the length of the original string, no padding happens.
String padDirection
Direction of the padding. Can be "left", "right" or "both".

Examples

// Pad at the end String_Pad("pqrst", "AB", 10, "right") // "pqrstABABA" // Pad at the beginning String_Pad("pqrst", "AB", 10, "left") // "ABABApqrst" // Pad both sides String_Pad("pqrst", "AB", 10, "both") // "ABpqrstABA"

String_Repeat

Repeats a string given number of times and returns the resulting string.

Syntax

String String_Repeat(
	String string, 
	Numeric multiplier)

Parameters

String string
String to be repeated.
Numeric multiplier
Number of times to repeat the string.

Examples

String_Repeat("Abc", 5) // "AbcAbcAbcAbcAbc"

String_Replace

Finds occurences of a search string in the given string and replaces them with a replacement string and returns the resulting string.

Syntax

String String_Replace(
	String string, 
	Mixed search, 
	Mixed replacement, 
	Bool ignoreCase, 
	out Numeric count)

Parameters

String string
String being searched and replaced on.
Mixed search
The value being searched for. This can be a single string or an array of strings. If it is a single string, replacement should also be a single string and, each occurence of that string is replaced with the replacement string. If it is an array of strings each value is replaced starting from the first element in the array. The replacement can be a single string or an array of strings in this case.
Mixed replacement
The value to replace the search string. This can be a single string or an array of strings. If it is a single string, each occurence of the search string or strings is replaced with the replacement string. If it is an array of strings each value in the array of search strings is replaced with the corresponding entry in the replacement array.
Bool ignoreCase
Ignores the case of the search string(s) if set to true.
out Numeric count
The number of replacements performed will be stored in this variable.

Examples

$string = "abcdefghijABCDEFGHIJ" // Not found String_Replace($string, "345", "{}", true, $count) // Returns "abcdefghijABCDEFGHIJ" // $count is 0 // Case Insensitive String_Replace($string, "def", "{}", true, $count) // Returns "abc{}ghijABC{}GHIJ" // $count is 2 // Case Sensitive String_Replace($string, "def", "{}", false, $count) // Returns "abc{}ghijABCDEFGHIJ" // $count is 1 String_Replace($string, Array("a", "d", "H"), "{}", true, $count) // First replaces "a" with "{}" // Result is "{}bcdefghij{}BCDEFGHIJ // Then replaces "d" with "{}" // Result is "{}bc{}efghij{}BC{}EFGHIJ // Then replaces "H" with "{}" // Result is "{}bc{}efg{}ij{}BC{}EFG{}IJ // $count is 6 String_Replace($string, Array("a", "}b", ")c"), Array("{}", "()", "[]"), true, $count) // First replaces "a" with "{}" // Result is "{}bcdefghij{}BCDEFGHIJ" // Then replaces "}b" with "()" // Result is "{()cdefghij{()CDEFGHIJ" // Then replaces ")c" with "[]" // Result is "{([]defghij{([]DEFGHIJ" // $count is 6 String_Replace($string, Array("ab", "xy", "jA"), Array("XY", "ZW"), false, $count) // First replaces "ab" with "XY" // Result is "XYcdefghijABCDEFGHIJ" // Then replaces "xy" with "ZW" - not found because it is case sensitive // Result is "XYcdefghijABCDEFGHIJ" // Then replaces "jA" with empty string "" // Result is "XYcdefghiBCDEFGHIJ" // $count is 2 String_Replace($string, "ab", Array("XY", "ZW"), true, $count) // Replaces "ab" with "XY". "ZW" is ignored // Returns "XYcdefghijXYCDEFGHIJ" // $count is 2

String_Reverse

Returns the reverse of a given string.

Syntax

String String_Reverse(String string)

Parameters

String string
String to be reversed.

Examples

String_Reverse("abcdefg") // "gfedcba"

String_Split

Splits the current string into an array of strings using the given delimiter.

Syntax

Array<String> String_Split(
	String string, 
	String delimiter)

Parameters

String string
String to split into an array.
String delimiter
Delimiter to split the string using. If empty string, the string is split into its characters.

Examples

$array = String_Split("this is a ball", " ") // $array is ("this", "is", "a", "ball") $array = String_Split("Banana", "") // $array is ("B", "a", "n", "a", "n", "a")

String_StartsWith

Returns true if the first string starts with the second string, false otherwise.

Syntax

Bool String_StartsWith(
	String first, 
	String second, 
	Bool ignoreCase)

Parameters

String first
First string to compare.
String second
Second string to compare.
Bool ignoreCase
Ignores the case of the strings if set to true.

Examples

// Case Sensitive String_StartsWith("The quick brown fox", "the", false) // false // Case Insensitive String_StartsWith("The quick brown fox", "the", true) // true

String_Substring

Returns a part of the given string. The part starts from the 0-based offset and the length of it is count.

Syntax

String String_Substring(
	String string, 
	Numeric offset, 
	Numeric count)

Parameters

String string
String to return the part of.
Numeric offset
0-based start index of the substring. If non-negative, the substring will start this number of characters counted from the beginning of the string. If negative, the substring will start this number of characters counted from the end of the string.
Numeric count
Length of the substring.

Examples

// 7 characters starting at index 5 $substring = String_Substring("The quick brown fox", 5, 7) // $substring is "uick br" // 4 characters starting from the 8th character from the end $substring = String_Substring("The quick brown fox", -8, 4) // $substring is "rown" // First 10 characters $substring = String_Substring("The quick brown fox", 0, 10) // $substring is "The quick " // Last 5 characters $substring = String_Substring("The quick brown fox", -5, 5) // $substring is "n fox"

String_ToLowerCase

Converts the given string to lowercase.

Syntax

String String_ToLowerCase(String string)

Parameters

String string
String to be converted to lowercase.

Examples

String_ToLowerCase("THE Quick BROWN Fox") // "the quick brown fox"

String_ToUpperCase

Converts the given string to uppercase.

Syntax

String String_ToUpperCase(String string)

Parameters

String string
String to be converted to uppercase.

Examples

String_ToLowerCase("The Quick Brown Fox") // "THE QUICK BROWN FOX"

String_Trim

Removes whitespace (or other characters) from the beginning and/or end of a string and returns the resulting string.

Syntax

String String_Trim(
	String string, 
	String characters, 
	String trimDirection)

Parameters

String string
String to be trimmed.
String characters
Set of characters to be trimmed. If left empty, following characters will be removed: Space (ASCII 32), Tab (ASCII 9), New Line (ASCII 10), Carriage Return (ASCII 13), Vertical Tab (ASCII 11).
String trimDirection
Direction of the trim. Can be "left", "right" or "both".

Examples

$string = " The quick brown fox " String_Trim($string, "", "left") // "The quick brown fox\r\n" String_Trim($string, "", "right") // " \tThe quick brown fox" String_Trim($string, "", "both") // "The quick brown fox" String_Trim("The quick brown fox", "Txohef ", "both") // "quick brown"

Window Functions

GetWindows

Returns the set of open OneNote windows.

Syntax

Array<Window> GetWindows()

Parameters

This function has no parameters

Examples

// Close all windows except the current one ExpandForEach ($window in GetWindows()) ExpandIf (!$window.isCurrent) Window_Close($window)

Window_Close

Closes the given OneNote window. If the given window is the current window, one of the other windows will become the current window. Closing last window may cause unexpected results as it will shut down OneNote and the notebooks will no longer be accessible to the currently running macro. Accessing a closed window's members will result in an error.

Syntax

void Window_Close(Window window)

Parameters

Window window
The window to close.

Examples

// Close all windows except the current one ExpandForEach ($window in GetWindows()) ExpandIf (!$window.isCurrent) Window_Close($window)

Window_Create

Creates a new OneNote window. The new window will display the same notebook, section, and page as the previous current window. The newly created window will become the new current window.

Syntax

Window Window_Create()

Parameters

This function has no parameters

Examples

// Create a new OneNote window $window = Window_Create() // Navigate it to the first notebook Window_NavigateTo($window, GetNotebookRoot().notebooks[0])

Window_GetCurrent

Returns the currently open OneNote window.

Syntax

Window Window_GetCurrent()

Parameters

This function has no parameters

Examples

// Navigate the current window to the first page in the current section $window = Window_GetCurrent() Window_NavigateTo($window, GetCurrentSection().pages[0])

Window_NavigateTo

Navigates the given window to the provided location. The location can be a hierarchy object, id of a hierarchy object, or a "onenote:" URL. OneNote may display UI while navigation is under way. This function returns true if the navigation is successful or false if the location is not found or navigation is cancelled by the user.

Syntax

Bool Window_NavigateTo(
	Window window, 
	Mixed location)

Parameters

Window window
The window to navigate to.
Mixed location
The location to navigate to. Expected types are: Notebook, SectionGroup, Section, Page, or a String for id of one of those objects or a URL that starts with "onenote:". Navigating to URLs are slower than navigating with an object or object id.

Examples

// Navigate the current window to the first page in the current section $window = Window_GetCurrent() // Find the first page $page = GetCurrentSection().pages[0] // All three below will do the same thing Window_NavigateTo($window, $page) Window_NavigateTo($window, $page.id) Window_NavigateTo($window, $page.hyperlink)

Window_SetCurrent

Makes the given OneNote window the current window.

Syntax

void Window_SetCurrent(Window window)

Parameters

Window window
The window to make current.