Skip to content

Scripts API Reference

First, this document covers the basics:

Then, it covers the namespaces. mc is the Scripts API root object.

  • mc.main_window: Open or work with tables other than the current table (e.g. mc.main_window.open_table(path)).
  • mc.table: Current table reads, saves, and table settings (e.g. mc.table.save()).
  • mc.edit: Undoable edits to table data, selection, filters, and sort state (e.g. mc.edit.set_cell(row, col, 'Done')).
  • mc.commands: Built-in Modern CSV commands from menus, shortcuts, and the Command Launcher (e.g. mc.commands.convert_date_time_format()).
  • mc.settings: Global application settings (e.g. mc.settings.theme = 'Dark').
  • mc.analysis: Analysis helpers shared with Formulas (e.g. mc.analysis.zscore(values)). See the Analysis Tools API Reference.

Finally, it covers Examples.

Although there are similarities, the Scripts API is different from the Formulas API since it's much broader in scope.

Basic Types

Scalars are returned as int, float, or str. Multi-cell getters return NumPy arrays:

Getter Returns Notes
mc.cell() scalar One cell value.
Cell.value scalar One value on a Cell object.
mc.row() and mc.col() 1D NumPy array One row or column.
mc.range() and Range.values 2D NumPy array A rectangular block.

Example:

row = mc.main_selected_cell.row
price = mc.cell(row, None, col_title="Price")
quantity = mc.cell(row, None, col_title="Quantity")
mc.edit.set_cell(row, None, price * quantity, col_title="Total")

Blank values in otherwise numeric arrays become nan; non-numeric text makes the array a string array.

If a row, column, or range extends past the end of the data, trailing out-of-bounds cells are returned as blanks. Indexes below the data raise IndexError.

Functions with index_type accept "visual", "display", and "physical". The default is "visual".

String column arguments follow Represent Columns as Letters:

  • Disabled: strings are column titles.
  • Enabled: strings are column letters such as "A" or "AA".

Use col_title or another matching *_title argument for title lookup regardless of that setting.

Tuples

Position

Property Type Description
row int Row index.
col int Column index.

Example:

position = mc.main_selected_cell
print(position.row, position.col)

Dimensions

Property Type Description
rows int Number of data rows.
cols int Number of data columns.
cells int Number of data cells.

Example:

dimensions = mc.dimensions
print(dimensions.rows, dimensions.cols, dimensions.cells)

Data Classes

QueryData.response_map maps either option IDs or text responses to the next query_id.

QueryOption

Variable Type Default Explanation
label str Required Visible option text.
description str "" Secondary option text.
option_id str "" Stable response value; defaults to label when empty.
current_state str "" Current state text for stateful options.
keystroke str "" Keyboard shortcut hint shown on the right.

Example:

option = mc.QueryOption("Open", option_id="open")

QueryData

Variable Type Default Explanation
query_id str "" Key used for this prompt in the response dictionary.
title str "" Launcher prompt title.
description str "" Prompt description shown below the title.
description_is_html bool False Treats description as HTML when True.
editor_text str "" Initial text in the Launcher editor.
editor_selection tuple[int, int] (0, 0) Initial editor selection as (start, length).
editor_select_all bool False Selects the full editor text when True.
options list[QueryOption] [] Static option list.
options_generator Callable[[], list[QueryOption]] or None None Function that builds options when the prompt opens.
use_entry_feedback bool False Enables feedback while the user types.
use_immediate_selection_feedback bool False Enables feedback immediately when an option is selected.
use_delayed_selection_feedback bool False Enables delayed feedback after option selection.
initial_feedback_text str "" Feedback text shown before user input.
highlight_type HighlightType HighlightType.NONE Table highlight mode while the query is active.
input_type InputType InputType.STRING Built-in validation and parsing mode.
validator Callable[[str], bool] or None None Custom validator called after built-in validation.
validator_error_message str "" Message shown when validator returns False.
next_query_id str "" Default next query after this prompt.
response_map dict[str, str] {} Maps option IDs or text responses to the next query_id.
auto_adjust_height bool True Lets the Launcher resize to fit the prompt.
height_adjustment_offset int 0 Adds extra height to the auto-adjusted prompt.

Example:

query = mc.QueryData(
    query_id="status",
    title="Status",
    options=[mc.QueryOption("Open", option_id="open")],
)

FindOptions

Variable Type Default Explanation
case_sensitive bool False Matches letter case when True.
whole_word bool False Matches whole words only when True.
whole_cell bool False Matches whole cell contents only when True.
regex bool False Treats the find phrase as a regular expression.
in_selected_cells bool False Limits searching to the current selection.

Example:

options = mc.FindOptions(whole_cell=True, in_selected_cells=True)

FilterData

Variable Type Default Explanation
type FilterType FilterType.PHRASE_FILTER Filter matching mode.
range Range Range() Row or column range the filter applies to.
filter_str str "" Filter expression.
case_sensitive bool False Matches letter case when True.
whole_word bool False Matches whole words only when True.
whole_cell bool False Matches whole cell contents only when True.
regex bool False Treats filter_str as a regular expression.

Example:

filter_data = mc.FilterData(
    type=mc.FilterType.PHRASE_FILTER,
    range=mc.Range(1, mc.RangeType.COLUMN),
    filter_str="Open",
)

SortData

Variable Type Default Explanation
type SortType SortType.NO_SORT Sort direction.
axis Axis Axis.INVALID_AXIS Axis being sorted.
index int -1 Row or column index used as the sort key.

Example:

sort_data = mc.SortData(
    type=mc.SortType.ASCENDING_SORT,
    axis=mc.Axis.VERTICAL,
    index=1,
)

Enums

Enum Values Notes
RangeType CELL, ROW, COLUMN, BLOCK Shape of a Range.
IndexType PHYSICAL, VISUAL, DISPLAY Row, column, and range index system.
Direction UP, DOWN, LEFT, RIGHT, UNDEFINED Movement or fill direction.
Axis VERTICAL, HORIZONTAL, BOTH_AXES, INVALID_AXIS Sort/filter orientation.
SortType ASCENDING_SORT, DESCENDING_SORT, NO_SORT Sort direction.
FilterType PHRASE_FILTER, EXPLICIT_INDEX_FILTER, INVALID_FILTER Filter matching mode.
EncodingType UTF8, UTF16, UTF16BE, UTF16LE, UTF16FEFF, UTF16FFFE, UTF32, UTF32LE, UTF32BE, UTF32FEFF, UTF32FFFE, ISO8859_1, ISO8859_2, ISO8859_3, ISO8859_4, ISO8859_5, ISO8859_6, ISO8859_7, ISO8859_8, ISO8859_9, ISO8859_10, ISO8859_13, ISO8859_14, ISO8859_15, ISO8859_16, WINDOWS_1250, WINDOWS_1251, WINDOWS_1252, WINDOWS_1253, WINDOWS_1254, WINDOWS_1255, WINDOWS_1256, WINDOWS_1257, WINDOWS_1258, WINDOWS_949, EUC_KR, EUC_JP, ISO_2022_JP, SHIFT_JIS, BIG5_HKSCS, BIG5, GB18030, KOI8_U, KOI8_R File character encoding.
LineEndingType WINDOWS, UNIX, MAC, LINUX Save line endings.
ParsingStandardType RFC_4180, DELIMITER, ALL_QUOTES, SPARSE_QUOTES, ASCII_SEPARATED CSV parsing behavior.
HighlightType NONE, RANGE, ROW, COLUMN, ROW_LINE, COLUMN_LINE, SELECTION Query feedback highlight.
InputType STRING, INT, FLOAT, CELL_LOCATION, RANGE, COLUMN_NAME, ROW_NUMBER, COLUMN_NUMBER Launcher input validation.
DateOrderingType MDY, DMY, YMD Ambiguous date order.
DateTimeFormatType AUTO_DETECTED, CUSTOM, ISO_8601, ISO_8601_DATE_ONLY, UNIX_SECONDS, UNIX_MILLISECONDS, EXCEL Date/time conversion formats.
NumberFormatType DOT_DECIMAL, COMMA_DECIMAL Decimal separator style.
RefreshBehavior AUTO_REFRESH, ASK, IGNORE External file-change behavior.
UuidType V4, V7 UUID generation type.
LanguageType ENGLISH, GERMAN, SPANISH, FRENCH, ITALIAN, JAPANESE, KOREAN, PORTUGUESE, BRAZILIAN_PORTUGUESE, SIMPLIFIED_CHINESE, TRADITIONAL_CHINESE, POLISH, DUTCH, RUSSIAN, UKRAINIAN, ROMANIAN UI language.
FileHandlingModeType EDIT, STREAM_EDIT, PREVIEW, READ_ONLY File opening mode.
PanelPlacementType DOCKED, SEPARATE, UNDEFINED Panel placement. Use DOCKED or SEPARATE for settings.
BomPolicyType PRESERVE, WRITE, NO_WRITE BOM save policy. PRESERVE applies only to existing Unicode files.
PasteOption VALUES_ONLY, FORMULAS_ONLY, FORMATS_ONLY, AUTO_DETECT, DELIMITER, MARKDOWN, HTML, STRAIGHT_TEXT Paste behavior.
FillMode MULTI_CELL_VALUES, SINGLE_VALUE, SERIES Fill command behavior.
SplitMethod BY_DELIMITER, BY_INDEX Split command mode.
InsertLocation ABOVE, BELOW, LEFT, RIGHT Insert location.
UuidFormat STANDARD, STANDARD_UPPER, BRACED, BRACED_UPPER UUID text format.
ParseTableFormat CSV, TAB_SEPARATED, PIPE_SEPARATED, SPACE_SEPARATED, CUSTOM_DELIMITER Import parsing format.
ExportFormat JSON, XML Export output format.
ExportFiles CURRENT_FILE, ALL_OPEN_FILES Files included in export.
ExportLocation TO_ORIGINATING_FOLDERS, TO_SPECIFIC_FOLDER Export destination.

Enum-backed APIs usually accept either the enum value or a lowercase string such as "ascending sort", "utf8", or "simplified chinese".

For paste_cells_special(), use PasteOption.AUTO_DETECT, DELIMITER, MARKDOWN, HTML, or STRAIGHT_TEXT.

Example:

choice = mc.QueryOption("Sort descending", option_id="desc")
query = mc.QueryData(
    query_id="sort",
    title="Sort Order",
    options=[choice],
)

filter_data = mc.FilterData(
    type=mc.FilterType.PHRASE_FILTER,
    range=mc.Range(1, mc.RangeType.COLUMN),
    filter_str="Open",
)

Cell, Range, and RangeList

cell = mc.main_selected_cell
selected_values = mc.values(mc.selection)
print(cell.row, cell.col, selected_values.shape)

Cell

cell = mc.Cell(row=5, col=2, value="Done")

Constructor:

  • Cell(row: int, col: int, value: int | float | str = ""): Creates a table cell object.

Properties:

Property Type Description
index_type str Index system used by row and col: "visual", "display", or "physical".
is_main_cell bool True when this cell is the main selected cell.
row int Cell row; read/write.
col int Cell column; read/write.
value int, float, or str Cell value; read/write on the Python object only.

Changing Cell.value changes only the Python object. Use mc.edit.set_cells() to write edited cells to the table in one undoable command.

Range

Constructors:

  • Range(): Creates an empty range.
  • Range(row: int, col: int, index_type: str = "visual"): Creates a cell range anchored at row, col.
  • Range(index: int, range_type: RangeType, index_type: str = "visual"): Creates a row or column range.
  • Range(range_type: RangeType, index_type: str = "visual"): Creates an empty block range.

Properties:

Property Type Description
type RangeType Shape represented by the range: cell, row, column, or block.
index_type str Index system used by the range: "visual", "display", or "physical".
contains_main_cell bool True when the range contains the main selected cell.
main_cell_position Position Main cell position within the range.
row int Start row; read/write.
col int Start column; read/write.
row_stop int Stop row for block ranges; read/write.
col_stop int Stop column for block ranges; read/write.
values np.ndarray Values in the range as a 2D array.
cells list[Cell] Cells in row-major order.

Range can be iterated to get its Cell objects.

Methods:

  • __contains__(range: Range) -> bool: Returns whether this range contains range.
  • __iter__() -> Iterator[Cell]: Iterates over cells in the range.
block = mc.Range(1, 1)
block.row_stop = 3
block.col_stop = 2

for cell in block:
    print(cell.row, cell.col, cell.value)

RangeList

Constructors:

  • RangeList(): Creates an empty range list.
  • RangeList(range: Range): Creates a range list containing one range.
  • RangeList(ranges: Iterable[Range]): Creates a range list from multiple ranges.

Properties:

Property Type Description
ranges list[Range] Ranges in the list.
cells list[Cell] Deduplicated cells in global row-major order.
num_rows int Number of rows touched by the ranges.
num_cols int Number of columns touched by the ranges.
min_row int Lowest row touched by the ranges.
max_row int Highest row touched by the ranges.
min_col int Lowest column touched by the ranges.
max_col int Highest column touched by the ranges.
lowest_row_start_index int Lowest starting row among the ranges.
lowest_col_start_index int Lowest starting column among the ranges.
ordered_rows list[int] Touched rows in sorted order.
ordered_cols list[int] Touched columns in sorted order.
dimensions Dimensions Bounding dimensions for the range list.

Methods:

  • __len__() -> int: Returns the number of cells in the range list.
  • __contains__(range: Range) -> bool: Returns whether the range list contains range.
  • __iter__() -> Iterator[Range]: Iterates over ranges in the list.
  • __getitem__(index: int) -> Range: Returns the range at index.
  • has_row(row: int) -> bool: Returns whether any range touches row.
  • has_col(col: int) -> bool: Returns whether any range touches col.
  • num_cells_in_row(row: int) -> int: Returns the number of cells touched in row.
  • num_cells_in_col(col: int) -> int: Returns the number of cells touched in col.
  • num_row_ranges_in_row(row: int) -> int: Returns the number of row ranges that touch row.
  • num_col_ranges_in_col(col: int) -> int: Returns the number of column ranges that touch col.
  • rows_in_col(col: int) -> list[int]: Returns touched rows in col.
  • cols_in_row(row: int) -> list[int]: Returns touched columns in row.
  • has_range_type(range_type: RangeType) -> bool: Returns whether the list contains a range of range_type.
  • append(range: Range) -> None: Adds one range to the list.
  • extend(ranges: Iterable[Range]) -> None: Adds multiple ranges to the list.
first_col = mc.Range(1, mc.RangeType.COLUMN)
second_col = mc.Range(2, mc.RangeType.COLUMN)
ranges = mc.RangeList([first_col, second_col])

for cell in ranges.cells:
    print(cell.value)

Type Checking

These work on scalars and NumPy arrays:

  • dtype(val: int | float | str | np.ndarray) -> str: Returns "int", "float", or "string".
  • is_numeric(val: int | float | str | np.ndarray) -> bool: Returns True for numeric scalars or numeric arrays.
  • is_text(val: int | float | str | np.ndarray) -> bool: Returns True for string scalars or string arrays.
  • is_int(val: int | float | str | np.ndarray) -> bool: Returns True for integer scalars or integer arrays.
  • is_float(val: int | float | str | np.ndarray) -> bool: Returns True for float scalars or float arrays.
values = mc.col(None, col_title="Amount")
if mc.is_numeric(values):
    mc.msgbox(f"Total: {mc.sum(values)}")

Error Handling

Invalid API arguments raise standard Python exceptions:

  • IndexError: Invalid row or column indexes.
  • KeyError: Column title strings that do not match a header.
  • TypeError: Wrong argument types.
  • ValueError: Invalid argument combinations, invalid index_type strings, invalid array dimensions, or shape mismatches.
  • mc.LauncherCancelledError: The user cancelled a Launcher prompt from mc.commands.
  • mc.LicenseRequiredError: A command needs a license that is not available.
try:
    mc.commands.go_to_cell()
except mc.LauncherCancelledError:
    return
except (IndexError, KeyError, TypeError, ValueError) as error:
    mc.msgbox(str(error), title="Script Error", kind="error")

Launcher Queries

Use mc.run_queries() to show one or more Launcher prompts.

  • run_queries(queries: list[QueryData]) -> dict[str, str] | None: Runs Launcher prompts in sequence and returns responses by query_id; returns None when the user cancels.
  • msgbox(text: str, title: str = "Script", *, buttons: list[tuple[str, str]] | None = None, default: str | None = None, kind: str = "info") -> str | None: Shows a message box and returns the chosen button response, or None for a default OK box.
queries = [
    mc.QueryData(
        query_id="name",
        title="Name",
        description="Enter a name.",
    ),
    mc.QueryData(
        query_id="column",
        title="Column",
        input_type=mc.InputType.COLUMN_NUMBER,
    ),
]

responses = mc.run_queries(queries)
if responses is None:
    return

print(responses["name"], responses["column"])

QueryData.response_map can route to different next queries based on a response. QueryData.validator can reject a response and reopen the Launcher with an error message.

buttons is a list of (response, label) pairs. kind is "info", "warning", "error", or "question".

mc.msgbox("Done", title="Script")

Main Window

Accessed through mc.main_window.

  • table: Table: Currently active table.
  • open_table(filepath: str) -> Table | None: Opens filepath and returns its Table, or None if it cannot be opened.
table = mc.main_window.open_table("/path/to/data.csv")
if table is not None:
    mc.msgbox(table.filename)

Current Table

mc.table is the current table. For convenience, active-table helpers are also available directly on mc.

Use mc.main_window.open_table() when you need a non-current table. Calls on that returned Table object read or save that table; direct calls like mc.cell() and mc.save() still use the current table.

value = mc.cell(5, None, col_title="Price")
prices = mc.col(None, col_title="Price")
mc.save()

Table Properties

Read-only unless noted:

Property Type Description
filename str File name without the folder path.
filepath str Full file path.
folderpath str Folder that contains the file.
extension str File extension.
is_saved bool True when the table has no unsaved changes.
has_file bool True when the table is backed by a file on disk.
dimensions Dimensions Data dimensions, excluding header rows and header columns.
selection RangeList Current selection; read/write.
main_selected_cell Range Main selected cell; read/write.
if not mc.table.is_saved:
    mc.save()

mc.msgbox(f"{mc.table.filename}: {mc.table.dimensions.rows} rows")

Per-Table Settings

These are read/write on mc.table and affect only the active table:

Setting Type Description
delimiter str Single-character delimiter used when reloading the table.
save_delimiter str Single-character delimiter used when saving the table.
encoding EncodingType or str File encoding used when loading or saving.
save_encoding EncodingType or str File encoding used when saving the table.
parsing_standard ParsingStandardType or str CSV parsing mode.
save_parsing_standard ParsingStandardType or str CSV parsing mode used when saving the table.
line_ending LineEndingType or str Line ending used when saving.
write_bom bool Writes a BOM when saving the table.
first_row_index int First visible row index.
first_col_index int First visible column index.
num_header_rows int Number of header rows.
num_header_cols int Number of header columns.
number_format NumberFormatType or str Decimal-number parsing format.
date_ordering DateOrderingType or str Date component order used for date parsing.
file_handling_mode FileHandlingModeType or str How the table handles the file.
auto_fit_row_height bool Auto-fits row height when enabled.
auto_fit_col_width bool Auto-fits column width when enabled.
minimum_row_height_for_auto_fit float Minimum row height for auto-fit.
minimum_col_width_for_auto_fit float Minimum column width for auto-fit.
maximum_row_height_for_auto_fit float Maximum row height for auto-fit.
maximum_col_width_for_auto_fit float Maximum column width for auto-fit.
highlight_header_rows bool Highlights header rows when enabled.
highlight_header_cols bool Highlights header columns when enabled.
freeze_header_rows bool Freezes header rows when enabled.
freeze_header_cols bool Freezes header columns when enabled.
old_delimiter = mc.table.save_delimiter

try:
    mc.table.save_delimiter = "\t"
    mc.save_as("/path/to/export.tsv")
finally:
    mc.table.save_delimiter = old_delimiter

Table Methods

  • cell(row: int, col: int | str | None, *, col_title: str | None = None, index_type: str = "visual") -> int | float | str: Returns a single cell value.
  • row(row: int, include_headers: bool = False, index_type: str = "visual") -> np.ndarray: Returns row values as a 1D array.
  • col(col: int | str | None, *, col_title: str | None = None, include_headers: bool = False, index_type: str = "visual") -> np.ndarray: Returns column values as a 1D array.
  • col_summary(col: int | str | None = None, *, col_title: str | None = None, include_headers: bool = False, index_type: str = "visual") -> dict[str, Any]: Returns count, sum, mean, min, and max for numeric values in a column.
  • mean_col(col: int | str | None = None, *, col_title: str | None = None, include_headers: bool = False, index_type: str = "visual") -> float: Returns the mean of numeric values in a column.
  • range(corner0: Position, corner1: Position, index_type: str = "visual") -> np.ndarray: Returns rectangular range values as a 2D array.
  • values(range: Range | RangeList) -> np.ndarray: Returns values from a Range or RangeList as a flattened 1D array.
  • save() -> bool: Saves the table and returns whether it succeeded.
  • save_as(path: str) -> bool: Saves the table to path and returns whether it succeeded.
  • reload() -> bool: Reloads the table from disk and returns whether it succeeded.
  • row_count(index_type: str = "visual") -> int: Returns the row count.
  • col_count(index_type: str = "visual") -> int: Returns the column count.
  • last_row_index() -> int: Returns the last data row index.
  • last_col_index() -> int: Returns the last data column index.
  • col_title(col: int | str, index_type: str = "visual") -> str: Returns the title of a column.
  • all_col_titles() -> list[str]: Returns every column title.
  • selected_col_titles() -> list[str]: Returns titles for selected columns.
  • find(phrase: str, find_options: FindOptions) -> Cell: Finds a matching cell, or returns a cell with row and column -1.
  • record(row: int, include_headers: bool = False, index_type: str = "visual") -> dict | list: Returns a row as a dictionary when headers are available, otherwise as a list.

Index conversion helpers convert rows, columns, Range, and RangeList values between "visual", "display", and "physical" index types.

last_col = mc.last_col_index()
mc.msgbox(f"Last column: {mc.col_title(last_col)}")

Undoable Edits

mc.edit functions create undoable table edits. Prefer these when changing data.

cell = mc.main_selected_cell
mc.edit.set_cell(cell.row, cell.col, "Done")

Set Data

  • set_cell(row: int, col: int | str | None, value: int | float | str | list | np.ndarray, *, col_title: str | None = None, index_type: str = "visual", change_selection: bool = True) -> None: Writes a scalar, 1D column, or 2D block starting at one cell.
  • set_cells(cells: list[Cell], *, change_selection: bool = True) -> None: Writes the value of each Cell to its row and column in one undo command.
  • set_row(row: int, values: list | np.ndarray, *, index_type: str = "visual", change_selection: bool = True, start_after_header: bool = True) -> None: Writes values across one row.
  • set_col(col: int | str | None, values: list | np.ndarray, *, col_title: str | None = None, index_type: str = "visual", change_selection: bool = True, start_after_header: bool = True) -> None: Writes values down one column.
  • set_range(range: Range | RangeList, values: int | float | str | list | np.ndarray, *, populate_old_values: bool = True, old_range: Range | RangeList | None = None, set_data_from_old_range: bool = False, change_selection: bool = True) -> None: Writes a scalar, 1D values, or a 2D block to a range.
row = mc.main_selected_cell.row
mc.edit.set_cell(row, None, "Reviewed", col_title="Status")

Insert, Remove, Move, Duplicate

  • insert_rows(row: int | Range | RangeList | None = None, count: int = 1, *, before: bool = True, index_type: str = "visual", change_selection: bool = True) -> None: Inserts rows at row or the current selection.
  • insert_cols(col: int | str | Range | RangeList | None = None, count: int = 1, *, col_title: str | None = None, before: bool = True, index_type: str = "visual", change_selection: bool = True) -> None: Inserts columns at col or the current selection.
  • remove_rows(rows: int | list[int] | Range | RangeList | None = None, count: int = 1, *, index_type: str = "visual", change_selection: bool = True) -> None: Removes rows.
  • remove_cols(cols: int | str | list[int | str] | Range | RangeList | None = None, count: int = 1, *, col_titles: str | list[str] | None = None, index_type: str = "visual", change_selection: bool = True) -> None: Removes columns.
  • remove_empty_rows_cols_at_end(*, change_selection: bool = False) -> None: Removes trailing empty rows and columns.
  • move_cell_contents(from_range: Range | RangeList | None = None, to_range: Range | RangeList | None = None, *, row_delta: int = 0, col_delta: int = 0, change_selection: bool = True) -> None: Moves cell contents to a target range or by row/column deltas.
  • move_rows(from_rows: int | list[int] | Range | RangeList | None = None, *, to_row: int | Range | None = None, delta: int | None = None, index_type: str = "visual", change_selection: bool = True) -> None: Moves rows to an absolute row or relative delta.
  • move_cols(from_cols: int | str | list[int | str] | Range | RangeList | None = None, *, to_col: int | str | Range | None = None, delta: int | None = None, col_titles: str | list[str] | None = None, to_col_title: str | None = None, index_type: str = "visual", change_selection: bool = True) -> None: Moves columns to an absolute column or relative delta.
  • duplicate_rows(from_rows: int | list[int] | Range | RangeList | None = None, count: int = 1, *, to_row: int | Range | None = None, delta: int | None = None, index_type: str = "visual", change_selection: bool = True) -> None: Duplicates rows to an absolute row or relative delta.
  • duplicate_cols(from_cols: int | str | list[int | str] | Range | RangeList | None = None, count: int = 1, *, to_col: int | str | Range | None = None, delta: int | None = None, col_titles: str | list[str] | None = None, to_col_title: str | None = None, index_type: str = "visual", change_selection: bool = True) -> None: Duplicates columns to an absolute column or relative delta.
row = mc.main_selected_cell.row
mc.edit.insert_rows(row, count=1, before=False)
mc.edit.duplicate_cols(col_titles=["Status"], delta=1)

Table Operations

  • paste(paste_ranges: Range | RangeList | None = None, *, copy_ranges: Range | RangeList, change_selection: bool = True) -> None: Pastes copied ranges into paste ranges.
  • transpose(ranges: Range | RangeList | None = None, *, change_selection: bool = True) -> None: Transposes a range or the current selection.
  • filter_row(row: int | Range | None, filter_str: str, *, index_type: str = "visual", case_sensitive: bool = False, whole_word: bool = False, whole_cell: bool = False, regex: bool = False, change_selection: bool = True) -> None: Applies one phrase filter to a row.
  • filter_col(col: int | str | Range | None, filter_str: str, *, col_title: str | None = None, index_type: str = "visual", case_sensitive: bool = False, whole_word: bool = False, whole_cell: bool = False, regex: bool = False, change_selection: bool = True) -> None: Applies one phrase filter to a column.
  • apply_filters(filters: FilterData | list[FilterData], ranges: Range | RangeList | None = None, *, old_filters: FilterData | list[FilterData] | None = None, change_selection: bool = True) -> None: Applies one or more FilterData objects.
  • set_hidden_rows(rows: int | list[int] | Range | RangeList | None = None, *, index_type: str = "visual", change_selection: bool = True) -> None: Hides rows.
  • set_hidden_cols(cols: int | str | list[int | str] | Range | RangeList | None = None, *, col_titles: str | list[str] | None = None, index_type: str = "visual", change_selection: bool = True) -> None: Hides columns.
  • set_hidden_disabled_rows(blocks: tuple[int, int] | list[tuple[int, int]] | Range | RangeList, *, index_type: str = "visual", change_selection: bool = True) -> None: Marks row blocks as hidden-disabled.
  • set_hidden_disabled_cols(blocks: tuple[int, int] | list[tuple[int, int]] | Range | RangeList, *, index_type: str = "visual", change_selection: bool = True) -> None: Marks column blocks as hidden-disabled.
  • sort_by_row(row: int | Range | None = None, *, sort_type: SortType | str = SortType.ASCENDING_SORT, ranges: Range | RangeList | None = None, index_type: str = "visual", change_selection: bool = True) -> None: Sorts columns using a row as the key.
  • sort_by_col(col: int | str | Range | None = None, *, sort_type: SortType | str = SortType.ASCENDING_SORT, ranges: Range | RangeList | None = None, col_title: str | None = None, index_type: str = "visual", change_selection: bool = True) -> None: Sorts rows using a column as the key.
  • duplicate_cell_contents(direction: Direction | str, ranges: Range | RangeList | None = None, *, change_selection: bool = True) -> None: Copies the main cell contents through a range in one direction.
  • set_delimiter(delimiter: str, ranges: Range | RangeList | None = None, *, change_selection: bool = True) -> None: Sets the delimiter for a range or selection.
  • set_line_ending(line_ending: LineEndingType | str, ranges: Range | RangeList | None = None, *, change_selection: bool = True) -> None: Sets the file line ending.
  • set_encoding(encoding: EncodingType | str, ranges: Range | RangeList | None = None, *, change_selection: bool = True) -> None: Sets the file encoding.
  • set_parsing_standard(parsing_standard: ParsingStandardType | str, ranges: Range | RangeList | None = None, *, change_selection: bool = True) -> None: Sets the parsing standard.
  • split_cells_horizontally(ranges: Range | RangeList | None = None, *, delimiter: str | None = None, indexes: list[int] | None = None, insert_cols: bool = True, change_selection: bool = True) -> None: Splits cells horizontally by delimiter or indexes.
  • split_cells_vertically(ranges: Range | RangeList | None = None, *, delimiter: str | None = None, indexes: list[int] | None = None, change_selection: bool = True) -> None: Splits cells vertically by delimiter or indexes.
  • remove_filtered_and_hidden_data(ranges: Range | RangeList | None = None, *, change_selection: bool = True) -> None: Removes filtered-out and hidden data.
  • set_selection(selection: Range | RangeList, *, old_selection: Range | RangeList | None = None) -> None: Changes the table selection.
mc.edit.filter_col(None, "Open", col_title="Status")
mc.edit.sort_by_col(
    col_title="Due Date",
    sort_type=mc.SortType.ASCENDING_SORT,
)

Built-In Commands

mc.commands exposes Modern CSV commands. These are the same commands available from menus, keyboard shortcuts, and the Command Launcher.

If a required argument is left as None, Modern CSV opens the Launcher and asks for it. Supplied arguments are pre-filled and skipped. Command calls block until the command finishes, except commands that open application windows.

If the user cancels a prompt, mc.LauncherCancelledError is raised. If a command needs a license that is not available, mc.LicenseRequiredError is raised.

mc.commands.save_file()
mc.commands.documentation()

Common Command Groups

All commands in this section return None.

  • File
    • new_file(): Opens a new empty table.
    • open_file(): Opens the file dialog.
    • open_folder(): Opens a folder in the side bar.
    • open_recent_file(filepath: str | None = None): Opens a recent file.
    • save_file(): Saves the active table.
    • save_file_as(): Opens the Save As dialog.
    • save_visible_data_as(): Saves only visible data to a new file.
    • save_all_files(): Saves every modified open table.
    • close_file(): Closes the active table.
    • close_all_files(): Closes all open tables.
    • close_all_files_except_current(): Closes every open table except the active one.
    • close_folder(folder_path: str | None = None): Closes a folder in the side bar.
    • reload_file(delimiter: str | None = None, encoding: EncodingType | str | None = None, parsing_standard: ParsingStandardType | str | None = None): Reloads the active table from disk.
    • set_parameters_for_file_save(delimiter: str | None = None, line_ending: LineEndingType | str | None = None, encoding: EncodingType | str | None = None, parsing_standard: ParsingStandardType | str | None = None): Sets save parameters for the active table.
    • import_files(): Opens the Import window.
    • export_to_json_xml_or_excel(): Opens the export window.
    • export_to_pdf(): Opens the export-to-PDF dialog.
    • merge_files(): Opens Merge Files.
    • split_file(): Opens Split File for the active table.
    • print(): Opens the print dialog.
  • Edit / Clipboard
    • undo(): Undoes the last command.
    • redo(): Redoes the last undone command.
    • cut_cells(): Cuts selected cells to the clipboard.
    • copy_cells(): Copies selected cells to the clipboard.
    • copy_cells_to_markdown(include_header: bool | None = None): Copies selected cells as Markdown.
    • copy_cells_to_html(include_header: bool | None = None): Copies selected cells as HTML.
    • paste_cells(): Pastes clipboard content into the table.
    • paste_cells_special(paste_option: PasteOption | str | None = None, delimiter: str | None = None): Pastes with options.
    • edit_selected_cell(): Enters edit mode on the main selected cell.
    • stop_editing(): Exits cell edit mode.
  • Movement
    • move_cell_contents_up(): Moves selected cell contents up one cell.
    • move_cell_contents_down(): Moves selected cell contents down one cell.
    • move_cell_contents_left(): Moves selected cell contents left one cell.
    • move_cell_contents_right(): Moves selected cell contents right one cell.
    • move_cell_contents_to(target_cell: str | None = None): Moves selected cell contents to a cell.
    • move_rows_up(): Moves selected rows up by one.
    • move_rows_down(): Moves selected rows down by one.
    • move_rows_just_above_row(target_row: str | None = None): Moves selected rows above another row.
    • move_cols_left(): Moves selected columns left by one.
    • move_cols_right(): Moves selected columns right by one.
    • move_cols_to_the_left_of_col(target_col: str | None = None): Moves selected columns left of another column.
  • Insertion
    • insert_rows_above(): Inserts a row above the main selected row.
    • insert_rows_below(): Inserts a row below the main selected row.
    • insert_cols_to_the_left(): Inserts a column to the left of the main selected column.
    • insert_cols_to_the_right(): Inserts a column to the right of the main selected column.
    • insert_cells_move_rest_of_row_right(): Inserts blank cells and shifts the rest of the row right.
    • insert_cells_move_rest_of_column_down(): Inserts blank cells and shifts the rest of the column down.
  • Removal
    • remove_rows(): Removes selected rows.
    • remove_cols(): Removes selected columns.
    • remove_duplicate_rows(): Removes duplicate rows.
    • remove_duplicate_cols(): Removes duplicate columns.
    • remove_empty_rows(): Removes empty rows.
    • remove_empty_cols(): Removes empty columns.
    • remove_all_filtered_out_and_hidden_data(): Permanently removes filtered-out and hidden data.
  • Sort
    • sort_selected_col_ascending(): Sorts rows by the selected column ascending.
    • sort_selected_col_descending(): Sorts rows by the selected column descending.
    • sort_selected_row_ascending(): Sorts columns by the selected row ascending.
    • sort_selected_row_descending(): Sorts columns by the selected row descending.
    • sort_selected_cells_horizontally_ascending(): Sorts selected cells horizontally ascending.
    • sort_selected_cells_horizontally_descending(): Sorts selected cells horizontally descending.
    • sort_selected_cells_vertically_ascending(): Sorts selected cells vertically ascending.
    • sort_selected_cells_vertically_descending(): Sorts selected cells vertically descending.
  • Duplicate / Fill
    • duplicate_rows(): Duplicates selected rows once.
    • duplicate_cols(): Duplicates selected columns once.
    • duplicate_cell_contents_to(target_cell: str | None = None): Duplicates selected cell contents to a target cell.
    • duplicate_selected_cell_contents_up(): Duplicates selected cell contents up.
    • duplicate_selected_cell_contents_down(): Duplicates selected cell contents down.
    • duplicate_selected_cell_contents_left(): Duplicates selected cell contents left.
    • duplicate_selected_cell_contents_right(): Duplicates selected cell contents right.
    • copy_main_cell_contents_to_all_selected_cells(): Fills selected cells with the main cell value.
    • fill_selected_cells_with_series(series_pattern: str | None = None): Fills selected cells with a series.
    • fill_selected_cells_with_uuid_guid(uuid_format: UuidFormat | str | None = None): Fills selected cells with UUIDs.
    • add_or_update_id_col(first_id_value: int | None = None): Adds or updates an ID column.
  • Reshape / Split / Join / Trim
    • transpose_table(): Transposes the entire table.
    • transpose_selected_cells(): Transposes selected cells.
    • reshape_selected_cells_row_wise(new_shape: str | None = None): Reshapes selected cells in row-major order.
    • reshape_selected_cells_col_wise(new_shape: str | None = None): Reshapes selected cells in column-major order.
    • join_selected_cells_horizontally(separator: str | None = None): Joins selected cells horizontally.
    • join_selected_cells_vertically(separator: str | None = None): Joins selected cells vertically.
    • join_selected_cells_horizontally_move_rest_of_row_left(separator: str | None = None): Joins cells horizontally and shifts the rest of the row left.
    • split_selected_cells_horizontally(split_method: SplitMethod | str | None = None, delimiter: str | None = None, indexes: str | None = None): Splits selected cells horizontally.
    • split_selected_cells_vertically(split_method: SplitMethod | str | None = None, delimiter: str | None = None, indexes: str | None = None): Splits selected cells vertically.
    • split_selected_cells_horizontally_move_rest_of_row_right(split_method: SplitMethod | str | None = None, delimiter: str | None = None, indexes: str | None = None): Splits cells horizontally and shifts the rest of the row right.
    • parse_selected_cell_contents_as_table(format: ParseTableFormat | str | None = None, delimiter: str | None = None, insert_location: InsertLocation | str | None = None): Parses selected cell text as a table.
    • keep_only_left_part_of_selected_cells(index: int | None = None): Keeps only text left of an index.
    • keep_only_middle_part_of_selected_cells(start_index_and_length: str | None = None): Keeps only a middle slice of text.
    • keep_only_right_part_of_selected_cells(index: int | None = None): Keeps only text right of an index.
    • prepend_cell_contents(prepend_mode: FillMode | str | None = None, prepend_value: str | None = None, prepend_values: str | None = None, series_pattern: str | None = None): Prepends text or a series.
    • append_cell_contents(append_mode: FillMode | str | None = None, append_value: str | None = None, append_values: str | None = None, series_pattern: str | None = None): Appends text or a series.
    • trim_selected_cells(): Trims leading and trailing whitespace.
  • Text
    • upper_case(): Converts selected cells to uppercase.
    • lower_case(): Converts selected cells to lowercase.
    • title_case(): Converts selected cells to title case.
    • upper_camel_case(): Converts selected cells to upper camel case.
    • lower_snake_case(): Converts selected cells to lower snake case.
    • convert_to_acronym(): Converts selected cell text to acronyms.
  • Numbers / Dates / Random
    • zero_fill_whole_numbers(num_digits: int | None = None): Pads whole numbers with leading zeros.
    • remove_leading_zeros(): Removes leading zeros.
    • convert_number_format(to_format: NumberFormatType | str | None = None): Converts selected numeric cells between number formats.
    • fill_selected_cells_with_random_integers(): Fills selected cells with random integers.
    • fill_selected_cells_with_random_decimals_floats(): Fills selected cells with random decimals.
    • set_number_of_decimals(num_decimals: int | None = None): Sets the number of decimal places.
    • convert_date_time_format(from_format: DateTimeFormatType | str | None = None, from_custom_format: str | None = None, to_format: DateTimeFormatType | str | None = None, to_custom_format: str | None = None): Converts selected date/time cells.
    • fill_selected_cells_with_current_date_time_stamp_now(): Inserts the current date/time.
  • Filtering
    • add_filter(column_or_row: str | None = None, filter_string: str | None = None): Adds a phrase filter.
    • add_filter_with_regular_expressions(column_or_row: str | None = None, filter_string: str | None = None): Adds a regex filter.
    • view_edit_filters(filter_selection: str | None = None, filter_string: str | None = None): Opens or updates filter settings.
    • filter_selected_row(filter_string: str | None = None): Filters the selected row.
    • filter_selected_col(filter_string: str | None = None): Filters the selected column.
    • filter_selected_row_with_regular_expressions(filter_string: str | None = None): Regex-filters the selected row.
    • filter_selected_col_with_regular_expressions(filter_string: str | None = None): Regex-filters the selected column.
    • remove_individual_filters(filter_selection: str | None = None): Removes one filter.
    • remove_all_filters(): Removes every filter on the active table.
    • refresh_filters(): Re-evaluates filters against current data.
  • Hiding
    • hide_selected_rows(): Hides selected rows.
    • hide_selected_cols(): Hides selected columns.
    • show_all_hidden_rows(): Shows all hidden rows.
    • show_all_hidden_cols(): Shows all hidden columns.
  • Selection / Navigation
    • select_range(range: str | None = None): Selects a cell range such as "A1:C5".
    • select_from_main_cell_to(target_cell: str | None = None): Extends selection from the main cell to a target cell.
    • select_entire_table(): Selects the entire data region.
    • move_selection_up(): Moves the main cell up one row.
    • go_to_cell(cell_reference: str | None = None): Moves the main cell to a cell reference.
    • go_to_col_by_name(column_name: str | None = None): Moves to a column by title.
    • go_to_file(filepath: str | None = None): Switches to an open file.
  • Find / Replace
    • find_prompt(): Opens the Find toolbar.
    • find_next_match(): Moves to the next find match.
    • replace_prompt(): Opens the Replace toolbar.
    • replace_all_matches(): Replaces all current matches.
  • Headers / Sizing
    • show_file_properties(): Opens File Properties.
    • show_filter_manager(): Opens Filter Manager.
    • set_selected_row_heights(height: float | None = None): Sets selected row heights.
    • set_headers_to_selected_cell(): Marks headers up to the main selected cell.
    • toggle_freeze_header_rows_and_cols(): Toggles freezing all header rows and columns.
  • Analysis Windows
    • statistics_selected_cells(): Opens Statistics for selected cells.
    • statistics_selected_cells_by_cols(): Opens Statistics for selected cells grouped by column.
    • column_analysis_selected_cols(): Opens Column Analysis for selected columns.
    • unique_values_selected_col(): Opens Unique Values for the selected column.
    • pivot_table_selected_cols(): Opens a Pivot Table for selected columns.
    • chart_selected_cols(): Opens a Chart for selected columns.
    • scatter_chart_selected_cols(): Opens a scatter chart for selected columns.
    • line_chart_selected_cols(): Opens a line chart for selected columns.
    • histogram_chart_selected_cols(): Opens a histogram for selected columns.
    • bar_chart_selected_cols(): Opens a bar chart for selected columns.
    • pie_chart_selected_cols(): Opens a pie chart for selected columns.
    • compare_and_reconcile_cols(): Opens Compare and Reconcile Columns.
    • column_lookup(lookup_file: str | None = None, key_col: str | None = None, value_cols: str | None = None, lookup_to_file: str | None = None, lookup_key_col: str | None = None, lookup_result_location: str | None = None): Runs the column lookup flow.
  • Settings
    • toggle_auto_suggest_when_editing(): Toggles auto-suggest while editing.
    • toggle_write_bom(): Toggles mc.table.write_bom.
    • set_bom_policy_for_existing_unicode_files(): Opens the existing-Unicode BOM policy prompt.
    • set_bom_policy_for_new_utf8_files(): Opens the new UTF-8 BOM policy prompt.
    • set_bom_policy_for_new_utf16_and_utf32_files(): Opens the new UTF-16/UTF-32 BOM policy prompt.
    • set_text_editor_panel_placement(): Opens the Text Editor panel placement prompt.
    • set_data_analysis_panel_placement(): Opens the Data Analysis panel placement prompt.
    • set_console_panel_placement(): Opens the Console panel placement prompt.
  • Application Windows
    • preferences(): Opens Preferences.
    • manage_plugins(): Opens Plugin Manager.
    • open_application_data_folder(): Opens the application data folder.
    • documentation(): Opens documentation.
    • open_license_manager(): Opens License Manager.
    • about(): Opens About.
    • check_for_updates(): Opens Check for Updates.
mc.commands.add_filter(column_or_row="Status", filter_string="Open")
mc.commands.convert_date_time_format(to_format="iso 8601 date only")
mc.commands.preferences()

Settings

mc.settings exposes global user settings as read/write properties.

old_theme = mc.settings.theme
mc.settings.theme = "Dark"

Per-table settings live on mc.table, not mc.settings.

Global settings:

Older aliases such as show_editor_panel and let_editor_panel_consume_navigation_keystrokes still work. Use the current names below in new scripts.

Setting Type Description
save_with_trailing_delimiters bool Saves trailing delimiters at the end of each row.
ignore_table_transpose_when_saving bool Saves the current table orientation without applying the table-transpose save option.
bom_policy_for_existing_unicode_files BomPolicyType or str BOM policy for existing Unicode files.
bom_policy_for_new_utf8_files BomPolicyType or str BOM policy for new UTF-8 files.
bom_policy_for_new_utf16_utf32_files BomPolicyType or str BOM policy for new UTF-16 and UTF-32 files.
behavior_when_file_is_changed_externally RefreshBehavior or str Controls whether externally changed files refresh automatically, ask first, or are ignored.
text_editor str Stores the path to the external text editor.
save_after_each_edit bool Saves the active file after each edit.
remove_extraneous_rows_cols_on_file_save bool Removes trailing empty rows and columns when saving.
auto_suggest_when_editing bool Shows auto-suggest while editing cell text.
retain_sort_and_filters_upon_file_refresh bool Keeps sort and filter state when a file refreshes.
let_cell_editor_panel_consume_navigation_keystrokes bool Lets the Cell Editor panel handle navigation keys while editing.
case_sensitive_sorting bool Makes sorting distinguish uppercase and lowercase text.
uuid_type UuidType or str Chooses the UUID version used by UUID fill commands.
show_tab_bar bool Shows or hides the tab bar.
show_side_bar bool Shows or hides the side bar.
show_text_editor_panel bool Shows or hides the Text Editor panel.
show_utilities_panel bool Shows or hides the Utilities panel.
show_data_analysis_panel bool Shows or hides the Data Analysis panel.
show_console_panel bool Shows or hides the Console panel.
show_cell_editor_panel bool Shows or hides the Cell Editor panel.
show_side_bar_open_files bool Shows or hides open files in the side bar.
show_side_bar_folders bool Shows or hides folders in the side bar.
show_row_labels bool Shows or hides row labels.
show_col_labels bool Shows or hides column labels.
text_editor_panel_placement PanelPlacementType or str Docks the Text Editor panel or opens it separately.
data_analysis_panel_placement PanelPlacementType or str Docks the Data Analysis panel or opens it separately.
console_panel_placement PanelPlacementType or str Docks the Console panel or opens it separately.
represent_cols_as_letters bool Displays columns as letters instead of numeric labels.
font str Sets the table font family.
text_size int Sets the table text size in points.
text_font str Sets the text editor font family.
text_font_size int Sets the text editor font size in points.
text_editor_show_side_bar bool Shows or hides the Text Editor panel side bar.
text_editor_show_tab_bar bool Shows or hides the Text Editor panel tab bar.
theme str Sets the UI theme name.
shade_every_other_row bool Shades alternating rows.
shade_every_other_col bool Shades alternating columns.
highlight_main_selected_cells_row bool Highlights the main selected cell's row.
highlight_main_selected_cells_col bool Highlights the main selected cell's column.
fade_outside_of_data_region bool Dims buffer cells outside the data region.
snap_to_row_after_scrolling bool Snaps vertical scrolling to row boundaries.
snap_to_col_after_scrolling bool Snaps horizontal scrolling to column boundaries.
show_white_space bool Shows whitespace characters in text editors.
sync_panes bool Syncs table panes.
language LanguageType or str Sets the UI language.
minimum_number_of_table_rows int Sets the minimum number of rows shown in a table.
minimum_number_of_table_cols int Sets the minimum number of columns shown in a table.
number_of_buffer_rows int Sets how many blank buffer rows are kept beyond the data.
number_of_buffer_cols int Sets how many blank buffer columns are kept beyond the data.
default_row_height float Sets the default row height in pixels.
default_col_width float Sets the default column width in pixels.
search_engine str Sets the search engine URL or domain.
online_map str Sets the online map URL or domain.
enable_check_for_updates bool Enables startup update checks and the Check for Updates command.
detect_imported_file_type_upon_opening_file bool Detects imported file type when opening files.
suppress_auto_fit_warnings bool Suppresses warnings related to auto-fit operations.

Analysis Tools

Scripts and Formulas share the same analysis helpers. In Scripts, helpers are exposed directly on mc and through mc.analysis.

total = mc.sum(mc.col(None, col_title="Amount"))
z = mc.analysis.zscore(mc.col(None, col_title="Score"))

See the Analysis Tools API Reference.

Examples

mc.msgbox(f"Rows: {mc.row_count()}")

Edit Selected Cells

Change Cell.value on Python objects, then commit all changes with one undo command.

cells = []

for cell in mc.selection.cells:
    if isinstance(cell.value, str):
        cell.value = cell.value.strip()
        cells.append(cell)

if cells:
    mc.edit.set_cells(cells, change_selection=False)

Write a 2D Block

set_cell() can write a scalar, a column of values, or a 2D block.

summary = [
    ["Metric", "Value"],
    ["Rows", mc.row_count()],
    ["Columns", mc.col_count()],
]

mc.edit.set_cell(1, 1, summary)

Build a Range

Create a block range and fill it with a single value.

target = mc.Range(1, 1)
target.row_stop = 10
target.col_stop = 3

mc.edit.set_range(target, "")

Read a Record

When header rows exist, record() returns a dictionary for data rows.

record = mc.record(mc.main_selected_cell.row)

if record.get("Status") == "Closed":
    mc.msgbox("This record is already closed.")

Find with Options

Use FindOptions for a scripted find operation.

options = mc.FindOptions(
    case_sensitive=False,
    whole_cell=True,
    in_selected_cells=True,
)

match = mc.find("error", options)
if match.row >= 0 and match.col >= 0:
    mc.edit.set_cell(match.row, match.col, "Needs review")

Apply a Filter

Build FilterData directly when you do not want to use a built-in command prompt.

status_col = mc.Range(2, mc.RangeType.COLUMN)
filter_data = mc.FilterData(
    type=mc.FilterType.PHRASE_FILTER,
    range=status_col,
    filter_str="Open",
)

mc.edit.apply_filters(filter_data)

Sort with an Undo Wrapper

Sort rows by a column title.

mc.edit.sort_by_col(
    col_title="Revenue",
    sort_type=mc.SortType.DESCENDING_SORT,
)

Launcher Options

Use QueryOption for a discrete list.

query = mc.QueryData(
    query_id="action",
    title="Choose Action",
    options=[
        mc.QueryOption("Trim whitespace", option_id="trim"),
        mc.QueryOption("Uppercase", option_id="upper"),
    ],
)

responses = mc.run_queries([query])
if responses is None:
    return

if responses["action"] == "trim":
    mc.commands.trim_selected_cells()
elif responses["action"] == "upper":
    mc.commands.upper_case()

Launcher Validation

Use a validator when built-in input_type validation is not enough.

def is_positive(value):
    return value.isdigit() and int(value) > 0

query = mc.QueryData(
    query_id="count",
    title="Number of Rows",
    input_type=mc.InputType.INT,
    validator=is_positive,
    validator_error_message="Enter a positive whole number.",
)

responses = mc.run_queries([query])
if responses:
    mc.edit.insert_rows(count=int(responses["count"]))

Command Cancellation

Built-in commands raise LauncherCancelledError when the user cancels a required prompt.

try:
    mc.commands.go_to_cell()
except mc.LauncherCancelledError:
    return

Temporarily Change a Setting

Global settings are properties on mc.settings.

old_value = mc.settings.show_console_panel

try:
    mc.settings.show_console_panel = True
    mc.msgbox("Console Panel is visible.")
finally:
    mc.settings.show_console_panel = old_value

Work with Another Table

Use mc.main_window.open_table() when a script needs data from another file.

lookup_table = mc.main_window.open_table("/path/to/lookup.csv")
if lookup_table is None:
    return

keys = lookup_table.col(None, col_title="Key")
values = lookup_table.col(None, col_title="Value")
lookup = dict(zip(keys, values))

current_key = mc.cell(mc.main_selected_cell.row, None, col_title="Key")
mc.msgbox(str(lookup.get(current_key, "No match")))