### Generate Windows Installers Source: https://github.com/typesettingtools/aegisub/blob/master/README.md Commands to generate the installer or portable zip after a successful build. ```bash ninja win-installer ``` ```bash ninja win-portable ``` -------------------------------- ### Install Linux Build Dependencies Source: https://github.com/typesettingtools/aegisub/blob/master/README.md Command to install all necessary development packages on Ubuntu 24.04. ```bash sudo apt install build-essential pkg-config meson ninja-build gettext intltool libfontconfig1-dev libass-dev libboost-chrono-dev libboost-locale-dev libboost-regex-dev libboost-system-dev libboost-thread-dev zlib1g-dev wx3.2-headers libwxgtk3.2-dev icu-devtools libicu-dev libpulse-dev libasound2-dev libopenal-dev libffms2-dev libfftw3-dev libhunspell-dev libuchardet-dev libcurl4-gnutls-dev libgl1-mesa-dev libgtest-dev libgmock-dev libportal-gtk3-dev ``` -------------------------------- ### Install macOS Dependencies Source: https://github.com/typesettingtools/aegisub/blob/master/README.md Commands to install required build dependencies and configure environment variables for macOS. ```bash pip3 install meson # or brew install meson if you installed Python via brew brew install cmake ninja pkg-config libass boost zlib ffms2 fftw hunspell uchardet export LDFLAGS="-L/usr/local/opt/icu4c/lib" export CPPFLAGS="-I/usr/local/opt/icu4c/include" export PKG_CONFIG_PATH="/usr/local/opt/icu4c/lib/pkgconfig" ``` -------------------------------- ### Build Aegisub on Linux Source: https://github.com/typesettingtools/aegisub/blob/master/README.md Commands to configure, compile, and install Aegisub on Linux systems. ```bash meson setup build --prefix=/usr/local --buildtype=release --strip -Dsystem_luajit=false -Ddefault_library=static meson compile -C build meson install -C build --skip-subprojects luajit ``` -------------------------------- ### Implement Progress Reporting and Logging Source: https://context7.com/typesettingtools/aegisub/llms.txt Updates the Aegisub progress bar and task description during loops. Includes examples of various logging verbosity levels and setting an undo point. ```lua function process_with_progress(subtitles, selected_lines, active_line) local total = #subtitles -- Set the progress dialog title aegisub.progress.title("Processing %d lines", total) for i = 1, total do -- Update progress bar (0-100%) aegisub.progress.set(i / total * 100) -- Update task description aegisub.progress.task("Processing line %d of %d", i, total) -- Check if user clicked Cancel if aegisub.progress.is_cancelled() then aegisub.log(2, "Operation cancelled by user\n") return end -- Process the line... local line = subtitles[i] if line.class == "dialogue" then -- Do something with the line end end -- Logging with verbosity levels: -- 0: Fatal error -- 1: Error (recoverable) -- 2: Warning -- 3: Hint -- 4: Debug -- 5: Trace aegisub.log(0, "Fatal: Something went very wrong!\n") aegisub.log(1, "Error: Could not process line %d\n", 42) aegisub.log(2, "Warning: Unexpected value encountered\n") aegisub.log(3, "Hint: Consider using a different approach\n") aegisub.log(4, "Debug: Variable x = %s\n", tostring(x)) aegisub.log(5, "Trace: Entering function process_line\n") -- Log without level (always shown) aegisub.log("Processing complete!\n") aegisub.set_undo_point("Process with progress") end ``` -------------------------------- ### Clipboard Access Functions Source: https://context7.com/typesettingtools/aegisub/llms.txt Provides functions to get text from and set text to the system clipboard. Requires the 'aegisub.clipboard' module. ```lua local clipboard = require 'aegisub.clipboard' function clipboard_example(subtitles, selected_lines, active_line) -- Get clipboard contents local text = clipboard.get() if text and text ~= "" then aegisub.log("Clipboard contains: %s\n", text) -- Use clipboard text in subtitles local line = subtitles[active_line] line.text = line.text .. text subtitles[active_line] = line end -- Set clipboard contents local line = subtitles[active_line] clipboard.set(line.text) aegisub.log("Copied line text to clipboard\n") aegisub.set_undo_point("Clipboard operation") end ``` -------------------------------- ### Retrieve audio selection with aegisub.get_audio_selection Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/misc.txt Returns the start and end timestamps of the current audio selection in milliseconds. ```Lua function aegisub.get_audio_selection() ``` -------------------------------- ### aegisub.get_audio_selection Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/misc.txt Retrieves the start position and duration of the current audio selection in milliseconds. ```APIDOC ## aegisub.get_audio_selection ### Description Retrieves the start position and duration of the current audio selection in milliseconds. ### Method Function ### Endpoint N/A (Lua function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Returns 2 values, all numbers: 1. Position of the selection, in milliseconds. 2. End of the selection, in milliseconds. ``` -------------------------------- ### Load Lua Values with luabins.load Source: https://github.com/typesettingtools/aegisub/blob/master/subprojects/luabins/README.md Deserializes binary data into Lua values, with examples for handling unknown or known data structures. ```lua local values = { luabins.load(data) } assert(values[1], values[2]) ``` ```lua function eat_true(t, ...) assert(t, ...) return ... end my_value_handler(eat_true(luabins.load(data))) ``` -------------------------------- ### filter_options_dialog Function Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/basic-function-interface.txt This function is called by Aegisub to get a Dialog Window definition to prompt the user for input before an export operation. ```APIDOC ## Filter Options Window Provider function This function is called by Aegisub to get a Dialog Window definition to prompt the user for input before an export operation. The data input into the dialog returned by this function are automatically stored into the original subtitle file when an export operation is started. function filter_options_dialog( subtitles, stored_options) The name of the function is script-defined. (It doesn't have to be filter_options_dialog.) @subtitles (user data) A Subtitles Object, that can be used to retrieve information about the subtitle file the filter is to be applied on. @stored_options (table) The currently stored options for this export filter. The keys in this table are the option names, and the values are the values stored for those options. Returns: A Dialog Window table. ``` -------------------------------- ### Retrieve Subtitle Line Count Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/subtitle-data.txt Use the length operator or the .n property to get the total number of lines in the subtitle file. ```lua n = #subs n = subs.n ``` -------------------------------- ### Clone and Build Aegisub on Windows Source: https://github.com/typesettingtools/aegisub/blob/master/README.md Commands to clone the repository and initiate the build process from the Visual Studio command prompt. ```bash git clone https://github.com/TypesettingTools/Aegisub.git ``` ```bash meson build -Ddefault_library=static ``` ```bash cd build ninja ``` -------------------------------- ### File Stream Encoding Management Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/file-streams.txt Functions for getting and setting the text encoding of a file stream. ```APIDOC ## Getting text encoding ### Description This function returns a string describing the current text encoding used for a file stream. ### Method function ### Endpoint aegisub.fstream.get_encoding(stream) ### Parameters #### Path Parameters - **stream** (user data) - Required - The Input File Stream or Output File Stream to get the encoding for. ### Response #### Success Response (200) - **encoding** (String) - Describes the encoding. This string can be used for setting the encoding later. ## Setting text encoding ### Description This function changes the current text encoding used for a file stream. ### Method function ### Endpoint aegisub.fstream.set_encoding(stream, encoding) ### Parameters #### Path Parameters - **stream** (user data) - Required - The Input File Stream or Output File Stream to change the encoding for. - **encoding** (string) - Required - The new encoding to use. ### Response #### Success Response (200) - **old_encoding** (String) - Describes the old encoding. ``` -------------------------------- ### Build Aegisub with Meson for Distribution Source: https://github.com/typesettingtools/aegisub/blob/master/README.md Use these commands to build Aegisub for a distribution package, ensuring LuaJIT is handled and tests are disabled. ```bash meson subprojects download luajit # Or use the tarball meson subprojects packagefiles --apply luajit meson setup builddir --wrap-mode=nodownload --prefix=/usr --buildtype=release -Dsystem_luajit=false -Ddefault_library=static -Dtests=false Meson compile -C builddir Meson install -C builddir --skip-subprojects luajit ``` -------------------------------- ### Build macOS Bundle Source: https://github.com/typesettingtools/aegisub/blob/master/README.md Commands to configure, compile, and package Aegisub for macOS. ```bash meson build_static -Ddefault_library=static -Dbuildtype=debugoptimized -Dbuild_osx_bundle=true -Dlocal_boost=true meson compile -C build_static meson test -C build_static --verbose meson compile osx-bundle -C build_static meson compile osx-build-dmg -C build_static ``` -------------------------------- ### Create Configuration Dialogs in Lua Source: https://context7.com/typesettingtools/aegisub/llms.txt Defines a layout table for various input controls and uses aegisub.dialog.display to capture user input. Results are accessed via the control names defined in the configuration table. ```lua function show_dialog_example(subtitles, selected_lines, active_line) -- Define the dialog layout local dialog_config = { -- Label (display only) { class = "label", x = 0, y = 0, width = 4, height = 1, label = "Configure your settings:" }, -- Text input { class = "edit", name = "prefix_text", x = 0, y = 1, width = 4, height = 1, text = "Default text", hint = "Enter prefix text" }, -- Multi-line text input { class = "textbox", name = "notes", x = 0, y = 2, width = 4, height = 3, text = "Line 1\nLine 2" }, -- Integer input with spinner { class = "intedit", name = "repeat_count", x = 0, y = 5, width = 2, height = 1, value = 1, min = 1, max = 100 }, -- Float input with spinner { class = "floatedit", name = "scale_factor", x = 2, y = 5, width = 2, height = 1, value = 1.0, min = 0.1, max = 10.0, step = 0.1 }, -- Dropdown selection { class = "dropdown", name = "position", x = 0, y = 6, width = 2, height = 1, items = {"Top", "Middle", "Bottom"}, value = "Bottom" }, -- Checkbox { class = "checkbox", name = "apply_to_all", x = 2, y = 6, width = 2, height = 1, label = "Apply to all lines", value = false }, -- Color picker { class = "color", name = "text_color", x = 0, y = 7, width = 2, height = 1, value = "#FFFFFF" }, -- Color with alpha { class = "coloralpha", name = "shadow_color", x = 2, y = 7, width = 2, height = 1, value = "#000000AA" } } -- Custom buttons (optional) local buttons = {"Apply", "Preview", "Cancel"} -- Display the dialog local pressed, results = aegisub.dialog.display(dialog_config, buttons) -- Handle results if pressed == "Apply" then -- Access values by control name local prefix = results.prefix_text local count = results.repeat_count local color = results.text_color local apply_all = results.apply_to_all -- Process with the settings... aegisub.log("Prefix: %s, Count: %d\n", prefix, count) elseif pressed == "Cancel" or pressed == false then aegisub.cancel() -- Abort the macro end end aegisub.register_macro("Dialog Example", "Shows dialog usage", show_dialog_example) ``` -------------------------------- ### Get File Stream Encoding Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/file-streams.txt Retrieves the current text encoding string for a given file stream. ```lua function aegisub.fstream.get_encoding(stream) ``` -------------------------------- ### Utility Functions for Color and String Operations Source: https://context7.com/typesettingtools/aegisub/llms.txt Includes functions for table copying, color conversion (ASS format, RGB, HSV, HSL), interpolation, clamping, and string manipulation. Requires 'utils.lua' to be included. ```lua include("utils.lua") function utility_examples() -- Table operations local original = {a = 1, b = {c = 2}} local shallow = table.copy(original) -- Shallow copy local deep = table.copy_deep(original) -- Deep copy -- Color functions (ASS format: &HAABBGGRR&) local ass_col = ass_color(255, 128, 0) -- Returns "&H0080FF&" (RGB to ASS) local ass_a = ass_alpha(128) -- Returns "&H80&" local style_col = ass_style_color(255, 128, 0, 64) -- With alpha for styles -- Extract color components local r, g, b, a = extract_color("&H400080FF&") -- Returns 255, 128, 0, 64 -- Color from style string local r, g, b = color_from_style("&H0080FF&") local alpha = alpha_from_style("&H80&") -- Color space conversion local r, g, b = HSV_to_RGB(0.5, 1.0, 1.0) -- Hue, Saturation, Value local r, g, b = HSL_to_RGB(0.5, 1.0, 0.5) -- Hue, Saturation, Lightness -- Interpolation local val = interpolate(0.5, 0, 100) -- Returns 50 local col = interpolate_color(0.5, "&H0000FF&", "&HFF0000&") -- Blend colors local alp = interpolate_alpha(0.5, "&H00&", "&HFF&") -- Blend alpha -- Clamp value to range local clamped = clamp(150, 0, 100) -- Returns 100 -- String operations (added to string table) local head, tail = string.headtail("first second third") -- "first", "second third" local trimmed = string.trim(" hello ") -- "hello" -- Word iterator for word in string.words("one two three") do aegisub.log("Word: %s\n", word) end end ``` -------------------------------- ### Implement a Format Reader Function Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/basic-function-interface.txt Use this function to import subtitle files from foreign formats. It takes an input file stream and an empty subtitle object to populate. ```lua function read_format( input_file, output_subs ) -- Format reading logic here return true end ``` -------------------------------- ### Define Script Information Globals Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/basic-function-interface.txt Set these global variables to provide metadata about your script, such as its name, description, author, and version. ```lua script_name = "My Script Name" script_description = "A detailed description of what the script does." script_author = "Author Name" script_version = "1.0.0" ``` -------------------------------- ### Lua API - Save and Load Source: https://github.com/typesettingtools/aegisub/blob/master/subprojects/luabins/README.md Functions for saving Lua values into a binary string and loading them back. ```APIDOC ## Lua API ### `luabins.save(...)` Saves arguments into a binary string. #### Parameters * `...` (any) - The Lua values to save. #### Returns * `string` - The binary string representation of the saved data on success. * `nil, string` - An error message if saving fails. #### Example ```lua local str = assert(luabins.save(1, "two", { "three", 4 })) ``` ### `luabins.load(string)` Loads a list of values from a binary string. #### Parameters * `string` (string) - The binary string to load data from. #### Returns * `true, ...` - `true` followed by the loaded values on success. * `nil, string` - An error message if loading fails. #### Example ```lua -- If the data structure is unknown: local values = { luabins.load(data) } assert(values[1], values[2]) -- If the data structure is known: function eat_true(t, ...) assert(t, ...) return ... end my_value_handler(eat_true(luabins.load(data))) ``` ``` -------------------------------- ### C API - Save and Load Source: https://github.com/typesettingtools/aegisub/blob/master/subprojects/luabins/README.md C functions for saving Lua values from the stack into a binary string and loading binary data back onto the stack. ```APIDOC ## C API ### `int luabins_save(lua_State * L, int index_from, int index_to)` Save Lua values from the given state within the specified stack index range. #### Parameters * `L` (lua_State *) - The Lua state. * `index_from` (int) - The starting index of the stack range (inclusive). * `index_to` (int) - The ending index of the stack range (inclusive). #### Returns * `0` - On success. The saved data is pushed as a string onto the top of the stack. * `non-zero` - On failure. An error message is pushed onto the top of the stack. #### Notes * The Lua value stack remains untouched. * An empty range is not considered an error. * You can save from 0 to `LUABINS_MAXTUPLE` values. * Only real non-negative indices are valid. ### `int luabins_load(lua_State * L, const unsigned char * data, size_t len, int *count)` Load Lua values from the given byte chunk onto the Lua stack. #### Parameters * `L` (lua_State *) - The Lua state. * `data` (const unsigned char *) - Pointer to the binary data. * `len` (size_t) - The length of the binary data. * `count` (int *) - Pointer to an integer that will store the number of values pushed onto the stack. #### Returns * `0` - On success. Loaded values are pushed onto the stack, and `count` is set to the number of values pushed. * `non-zero` - On failure. An error message is pushed onto the top of the stack. #### Notes * Having zero loaded items is a valid scenario. ``` -------------------------------- ### Regular Expression Pattern Matching Source: https://context7.com/typesettingtools/aegisub/llms.txt The 're' module provides Boost.Regex-based pattern matching. Use 're.compile' for patterns intended for reuse. ```lua local re = require 'aegisub.re' function regex_examples() local text = "Hello World, hello universe" -- Compile a regex (recommended for reuse) local pattern = re.compile("hello", re.ICASE) -- Case-insensitive -- Find all matches local matches = pattern:find(text) if matches then for _, m in ipairs(matches) do aegisub.log("Found '%s' at %d-%d\n", m.str, m.first, m.last) end end -- Iterator version for match_str, first, last in pattern:gfind(text) do aegisub.log("Match: %s\n", match_str) end -- Match with capturing groups local groups = pattern:match(text) if groups then for i, g in ipairs(groups) do aegisub.log("Group %d: %s\n", i, g.str) end end -- Substitution local result = pattern:sub(text, "hi") -- Replace first match local result_all = pattern:sub(text, "hi", 0) -- Replace all (0 = unlimited) -- Split string local parts = re.split(text, ",\\s*") -- Split on comma+space -- Static functions (compile pattern each time) local found = re.find(text, "\\w+") local replaced = re.sub(text, "World", "Universe") -- Available flags: -- re.ICASE: Case-insensitive matching -- re.NOSUB: Don't store subexpression matches -- re.NEWLINE_ALT: \\n as line separator -- re.NO_MOD_M: ^ and $ don't match at newlines -- re.NO_MOD_S: . doesn't match newline end ``` -------------------------------- ### Table Reference Behavior in Luabins Source: https://github.com/typesettingtools/aegisub/blob/master/subprojects/luabins/README.md Demonstrates how Luabins treats table references as independent objects upon loading. ```lua local t = { 42 } { t, t } ``` ```lua { { 42 }, { 42 } } ``` -------------------------------- ### Implement a Format Writer Function Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/basic-function-interface.txt This function is used to export subtitles to a foreign file format. It receives the subtitle data and an output file stream. ```lua function write_format( input_subs, output_file ) -- Format writing logic here return true end ``` -------------------------------- ### Set progress dialog title Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/progress-reporting.txt Sets the title of the progress dialog using a format string. ```Lua function aegisub.progress.title(title, ...) ``` -------------------------------- ### Provide a Filter Options Dialog Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/basic-function-interface.txt Implement this function to define a dialog window for user input before an export operation. It receives subtitle data and previously stored options. ```lua function filter_options_dialog( subtitles, stored_options ) -- Return a Dialog Window table here end ``` -------------------------------- ### Including Other Scripts Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/basic-function-interface.txt Provides a custom `include()` function to load other Lua scripts, with specific search rules for finding the files. ```APIDOC ## Including Other Scripts For implementation reasons (and partially compatibility reasons), the Lua built-in dofile() and loadfile() functions are removed, and a custom include() function is provided instead. This function behaves almost the same as dofile(), except that it doesn't support reading from stdin (no such thing exists/is supposed to exist for Aegisub) and it follows some special search rules along a path. ### function include(filename) @filename (string) The relative path to the script to include. Returns: Any return-values of the included script. File search rules: 1. If there are no path-components in the filename (ie. just a filename), the directory of the original script is searched first. Afterwards, the search path specified in the Aegisub configuration file is searched. 2. If the filename contains path components, it is only searched relative to the location of the original script file. 3. Absolute paths are not mangled in any way. Using absolute paths is discouraged. (Absolute paths were disallowed in Automation 3.) ``` -------------------------------- ### Append or Insert Subtitle Lines Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/subtitle-data.txt Add new lines to the end of the file or before a specific index. ```lua subs[0] = line subs.append(line[, line2, ...]) subs[-i] = line subs.insert(i, line[, line2, ...]) ``` -------------------------------- ### aegisub.dialog.display Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/configuration-dialogs.txt Displays a dialog box with custom controls and buttons, and returns the user's input and selection. ```APIDOC ## aegisub.dialog.display ### Description Displays a dialog box defined by a `dialog` table and optionally custom `buttons`. It returns the user's selection and the data entered into the dialog fields. ### Method `aegisub.dialog.display(dialog, buttons)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **dialog** (table) - Required - A table defining the dialog's controls. - **buttons** (table) - Optional - An array table of strings defining the labels for custom buttons. If omitted or invalid, standard 'Ok' and 'Cancel' buttons are used. ### Request Example ```lua local myDialog = { -- dialog definition fields here } local myButtons = {"Save", "Discard"} aegisub.dialog.display(myDialog, myButtons) ``` ### Response #### Success Response (200) - **button_clicked** (boolean or string) - If custom buttons are used, this is the text on the clicked button. If standard buttons are used, this is a boolean: `true` for 'Ok', `false` for 'Cancel'. Returns `false` if the dialog is closed without clicking a button. - **dialog_results** (table) - A table containing the values entered by the user in the dialog fields. #### Response Example ```lua local button, results = aegisub.dialog.display(myDialog, myButtons) if button == "Save" then -- process saved data elseif button == false then -- dialog was closed without selection else -- handle other button clicks or cancel end -- Accessing dialog results: local userInput = results["fieldName"] ``` ``` -------------------------------- ### Include Other Scripts Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/basic-function-interface.txt Use the custom `include` function to load and execute other Lua scripts. It supports specific search rules for finding files. ```lua include("my_other_script.lua") ``` -------------------------------- ### Text Measurement with Style Source: https://context7.com/typesettingtools/aegisub/llms.txt Calculates the rendered dimensions (width, height, descent, external leading) of text using a given style. Requires a style object to be found. ```lua function text_measurement_example(subtitles, selected_lines, active_line) -- Get style reference local line = subtitles[active_line] local style = nil for i = 1, #subtitles do local l = subtitles[i] if l.class == "style" and l.name == line.style then style = l break end end if not style then return end -- Measure text dimensions local text = "Sample Text" local width, height, descent, ext_lead = aegisub.text_extents(style, text) aegisub.log("Text: %s\n", text) aegisub.log("Width: %d pixels\n", width) aegisub.log("Height: %d pixels\n", height) aegisub.log("Descent: %d pixels\n", descent) -- Below baseline aegisub.log("External leading: %d pixels\n", ext_lead) -- Use for positioning calculations local script_width = 1920 local centered_x = (script_width - width) / 2 end ``` -------------------------------- ### Regular Expression Module (re) Source: https://context7.com/typesettingtools/aegisub/llms.txt Provides Boost.Regex-based pattern matching with full Unicode support for string manipulation. ```APIDOC ## re Module ### Description Provides regex pattern matching. Can be used via compiled objects or static functions. ### Methods - **re.compile(pattern, flags)** - Compiles a regex pattern - **pattern:find(text)** - Finds all matches - **pattern:gfind(text)** - Iterator for matches - **pattern:match(text)** - Match with capturing groups - **pattern:sub(text, replacement, [count])** - Substitution - **re.split(text, pattern)** - Split string by pattern ### Flags - **re.ICASE** - Case-insensitive - **re.NOSUB** - Don't store subexpressions - **re.NEWLINE_ALT** - \n as line separator ``` -------------------------------- ### Karaoke Templater ASS Comment Syntax Source: https://context7.com/typesettingtools/aegisub/llms.txt Use these comment lines in your subtitle file to define syllable effects, code execution, and inline Lua expressions. ```lua -- Example karaoke template lines in ASS format: -- (These go in your subtitle file as Comment lines) -- Template for per-syllable effect: -- Comment: 0,0:00:00.00,0:00:00.00,Default,,0,0,0,template syl,{\an5\pos($scenter,$smiddle)\t($start,$end,\fscx120\fscy120)\t($end,$end+200,\fscx100\fscy100)} -- Template with code execution: -- Comment: 0,0:00:00.00,0:00:00.00,Default,,0,0,0,code once,fxgroup.main = true -- Template variables available: -- $start, $end, $dur, $mid: Timing values -- $x, $y: Position -- $left, $center, $right: Horizontal positions -- $top, $middle, $bottom: Vertical positions -- $width, $height: Dimensions -- $sstart, $send, $sdur, $smid: Syllable timing -- $sleft, $scenter, $sright: Syllable positions -- $si: Syllable index -- Inline Lua expressions use !expr! syntax: -- Comment: 0,0:00:00.00,0:00:00.00,Default,,0,0,0,template syl,{\pos($x,!line.y + math.sin(syl.i)*10!)} -- Template modifiers: -- "template syl" - Per-syllable template -- "template line" - Per-line template -- "template char" - Per-character template -- "template furi" - Per-furigana template -- "code once" - Run code once at start -- "code line" - Run code per line -- "code syl" - Run code per syllable -- Built-in template functions: -- retime(mode, start_offset, end_offset) - Adjust timing -- Modes: "syl", "presyl", "postsyl", "line", "preline", "postline", -- "start2syl", "syl2end", "set", "sylpct" -- relayer(layer) - Change layer number -- restyle(style) - Change style -- maxloop(n) - Set maximum loop iterations -- remember(name, value) - Store value for later recall -- recall(name, default) - Retrieve stored value ``` -------------------------------- ### Video and Script Information Retrieval Source: https://context7.com/typesettingtools/aegisub/llms.txt Fetches video properties like dimensions and aspect ratio, converts between milliseconds and frames, retrieves keyframes, and accesses script resolution and info lines. ```lua function get_video_info() -- Get video dimensions (nil if no video loaded) local video_width, video_height, video_ar, video_artype = aegisub.video_size() if video_width then aegisub.log("Video: %dx%d\n", video_width, video_height) aegisub.log("Aspect ratio: %f (type: %d)\n", video_ar, video_artype) else aegisub.log("No video loaded\n") end -- Get current frame number (nil if no video) local frame = aegisub.frame_from_ms(5000) -- Frame at 5 seconds local ms = aegisub.ms_from_frame(100) -- Time of frame 100 -- Get keyframes (empty table if none) local keyframes = aegisub.keyframes() for _, frame_num in ipairs(keyframes) do aegisub.log("Keyframe: %d\n", frame_num) end end ``` ```lua function get_script_info(subtitles) -- Get script resolution local res_x, res_y = subtitles.script_resolution() aegisub.log("Script resolution: %dx%d\n", res_x, res_y) -- Get script properties from info lines for i = 1, #subtitles do local line = subtitles[i] if line.class == "info" then aegisub.log("%s: %s\n", line.key, line.value) end end end ``` -------------------------------- ### Save Lua Values with luabins.save Source: https://github.com/typesettingtools/aegisub/blob/master/subprojects/luabins/README.md Serializes a tuple of Lua values into a binary string. ```lua local str = assert(luabins.save(1, "two", { "three", 4 })) ``` -------------------------------- ### Karaoke Templater API Source: https://context7.com/typesettingtools/aegisub/llms.txt The Karaoke Templater allows for dynamic subtitle effect generation using commented dialogue lines in ASS format. ```APIDOC ## Karaoke Templater ### Description Uses commented dialogue lines to generate complex karaoke effects. Supports per-syllable, per-line, and per-character templates. ### Template Modifiers - **template syl** - Per-syllable template - **template line** - Per-line template - **template char** - Per-character template - **template furi** - Per-furigana template - **code once** - Run code once at start - **code line** - Run code per line - **code syl** - Run code per syllable ### Built-in Functions - **retime(mode, start_offset, end_offset)** - Adjust timing - **relayer(layer)** - Change layer number - **restyle(style)** - Change style - **maxloop(n)** - Set maximum loop iterations - **remember(name, value)** - Store value for later recall - **recall(name, default)** - Retrieve stored value ``` -------------------------------- ### Access Subtitle Lines Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/subtitle-data.txt Retrieve or replace a specific line using index-based access. ```lua line = subs[i] subs[i] = line ``` -------------------------------- ### Unicode Utility Module Source: https://context7.com/typesettingtools/aegisub/llms.txt Provides functions for UTF-8 aware string manipulation and character analysis. ```APIDOC ## unicode Module ### Description Utility functions for handling UTF-8 encoded strings correctly. ### Methods - **unicode.charwidth(text, pos)** - Get character width in bytes - **unicode.chars(text)** - Iterator over characters - **unicode.len(text)** - Get string length in characters - **unicode.codepoint(char)** - Get Unicode codepoint - **unicode.to_upper_case(text)** - Convert to uppercase - **unicode.to_lower_case(text)** - Convert to lowercase - **unicode.to_fold_case(text)** - Convert for case-insensitive comparison ``` -------------------------------- ### Registering an Export Filter in Lua Source: https://context7.com/typesettingtools/aegisub/llms.txt Creates an export filter that processes all dialogue lines during the export operation. Supports custom configuration dialogs and execution priority. ```lua script_name = "Add Border Effect" script_description = "Adds border styling to all dialogue lines during export" script_author = "Your Name" script_version = "1.0" -- Processing function for the export filter -- @param subtitles: Subtitle file object -- @param config: Table with user configuration from options dialog function process_filter(subtitles, config) aegisub.progress.task("Processing lines...") for i = 1, #subtitles do aegisub.progress.set(i / #subtitles * 100) local line = subtitles[i] if line.class == "dialogue" and not line.comment then -- Add border override tag at the start local border_size = config.border_size or 2 line.text = "{\\bord" .. border_size .. "}" .. line.text subtitles[i] = line end end end -- Optional function to provide a configuration dialog -- @param subtitles: Subtitle file object for customization -- @param stored_options: Previously stored options function filter_options_dialog(subtitles, stored_options) return { { class = "label", x = 0, y = 0, width = 2, height = 1, label = "Border size:" }, { class = "floatedit", name = "border_size", x = 2, y = 0, width = 2, height = 1, value = stored_options.border_size or 2, min = 0, max = 10, step = 0.5 } } end -- Register with priority (higher = runs earlier) aegisub.register_filter( script_name, script_description, 1000, -- Priority process_filter, filter_options_dialog -- Optional config dialog ) ``` -------------------------------- ### read_format Function Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/basic-function-interface.txt This function is called by Aegisub to import a file from a foreign file format. ```APIDOC ## Format Reader Function This function is called by Aegisub to import a file from a foreign file format. function read_format( input_file, output_subs) The name of the function is script-defined. (It doesn't have to be read_format.) @input_file (user data) An Input File Stream, representing the file selected for import. @output_subs (user data) An empty Subtitles Object the imported data should be added to. Returns: Boolean. True if the import succeeded, false if it failed. ``` -------------------------------- ### Set progress bar percentage Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/progress-reporting.txt Updates the progress bar to the specified percentage. ```Lua function aegisub.progress.set(percent) ``` -------------------------------- ### Update Moonscript for Aegisub Source: https://github.com/typesettingtools/aegisub/blob/master/README.md Instructions for updating the Moonscript file to be compatible with Aegisub, involving modifications to package loading and loader functions. ```moonscript bin/moon bin/splat.moon -l moonscript moonscript/ > bin/moonscript.lua ``` -------------------------------- ### File Pointer Operations Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/file-streams.txt Functions for managing the file pointer position within a stream. ```lua function aegisub.fstream.tell(stream) ``` ```lua function aegisub.fstream.seek(stream, length) ``` ```lua function aegisub.fstream.reset(stream) ``` -------------------------------- ### aegisub.register_writer Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/basic-function-interface.txt Registers a new File Format Writer Feature. ```APIDOC ## aegisub.register_writer ### Description Registers a new File Format Writer for exporting subtitles. ### Parameters - **name** (string) - Required - The name of the file format. - **extension** (string) - Required - The default file extension for export. - **processing_function** (function) - Required - The function called to perform the file export. ``` -------------------------------- ### Progress Dialog Functions Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/progress-reporting.txt Functions to control the progress dialog, including setting its position, title, and checking for cancellation. ```APIDOC ## Setting the progress bar position ### Description Sets the position of the progress bar in the progress dialog. ### Method `aegisub.progress.set(percent)` ### Parameters #### Path Parameters - **percent** (number) - Required - The percentage completed (0-100). ### Response #### Success Response (200) Returns: nothing. ## Showing the current task ### Description Sets a message describing the current task being performed. ### Method `aegisub.progress.task(msg, ...)` ### Parameters #### Path Parameters - **msg** (string) - Required - A format string for the message. - **...** - Optional - Parameters to be formatted into the message string. ### Response #### Success Response (200) Returns: nothing. ## Setting the progress dialog title ### Description Sets the title of the progress dialog. ### Method `aegisub.progress.title(title, ...)` ### Parameters #### Path Parameters - **title** (string) - Required - A format string for the title. - **...** - Optional - Parameters to be formatted into the title string. ### Response #### Success Response (200) Returns: nothing. ## Getting the "cancelled" status ### Description Checks if the user has clicked the Cancel button in the progress dialog. ### Method `aegisub.progress.is_cancelled()` ### Response #### Success Response (200) Returns: Boolean. True if the user has clicked Cancel, false otherwise. ``` -------------------------------- ### Calculate text dimensions with aegisub.text_extents Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/misc.txt Calculates the rendered width, height, descent, and external leading of a string based on a provided style table. Does not support line breaks or formatting tags. ```Lua function aegisub.text_extents(style, text) ``` -------------------------------- ### Set current task message Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/progress-reporting.txt Updates the message displayed in the progress dialog using a format string. ```Lua function aegisub.progress.task(msg, ...) ``` -------------------------------- ### Apply Karaoke Effect with Karaskel Library Source: https://context7.com/typesettingtools/aegisub/llms.txt Applies karaoke effects to selected subtitle lines using the Karaskel library. This preprocesses lines, extracts syllables, and generates effect lines for each syllable. ```lua include("karaskel.lua") script_name = "Karaoke Effect Example" script_description = "Demonstrates karaskel library usage" function apply_effect(subtitles, selected_lines, active_line) -- Collect metadata and styles local meta, styles = karaskel.collect_head(subtitles, true) -- true = generate furigana styles -- meta contains: -- meta.res_x, meta.res_y: Script resolution -- meta.video_x_correct_factor: Aspect ratio correction for _, i in ipairs(selected_lines) do local line = subtitles[i] if line.class == "dialogue" and not line.comment then -- Preprocess the line (adds positioning, sizing, karaoke data) karaskel.preproc_line(subtitles, meta, styles, line) -- Now line has additional properties: -- line.text_stripped: Text without override tags -- line.duration: Line duration in ms -- line.styleref: Reference to the style object -- line.width, line.height: Text dimensions -- line.left, line.center, line.right: Horizontal positions -- line.top, line.middle, line.bottom: Vertical positions -- line.x, line.y: Default position based on alignment -- line.kara: Table of karaoke syllables -- line.furi: Table of furigana (if applicable) -- Process each syllable for si = 0, line.kara.n do local syl = line.kara[si] -- Syllable properties: -- syl.text, syl.text_stripped, syl.text_spacestripped -- syl.duration, syl.start_time, syl.end_time -- syl.width, syl.height -- syl.left, syl.center, syl.right -- syl.style: Style reference -- syl.inline_fx: Inline effect name from \-fx tag -- Create effect line for this syllable local fx_line = table.copy(line) fx_line.start_time = line.start_time + syl.start_time fx_line.end_time = line.start_time + syl.end_time fx_line.text = string.format( "{\\an5\\pos(%d,%d)\\t(\\fscx120\\fscy120)\\t(0.5,1,\\fscx100\\fscy100)}%s", line.left + syl.center, line.y, syl.text_stripped ) fx_line.effect = "fx" subtitles.append(fx_line) end -- Mark original line as karaoke source line.comment = true line.effect = "karaoke" subtitles[i] = line end end aegisub.set_undo_point("Apply karaoke effect") end aegisub.register_macro(script_name, script_description, apply_effect) ``` -------------------------------- ### Script Information Globals Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/basic-function-interface.txt Global variables that can be set by the script author to provide metadata about the script. These are informational and do not affect script execution. ```APIDOC ## Script Information Globals These are a series of global variables, the script author can set. They are purely informational, and won't have any actual influence on how the script is treated. None of these are required, but it is recommended to provide them. These should never be present in include files. ### script_name (string) A short, descriptive name for the script, used for presenting it to the user in the UI. ### script_description (string) A longer description of the purpose of the script, presented to the user in the UI. ### script_author (string) Name(s) of the author(s) of the script. ### script_version (string) Version number of the script. ``` -------------------------------- ### write_format Function Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/basic-function-interface.txt This function is called by Aegisub to export a file to a foreign file format. ```APIDOC ## Format Writer Function This function is called by Aegisub to export a file to a foreign file format. function write_format( input_subs, output_file) The name of the function is script-defined. (It doesn't have to be write_format.) @input_subs (user data) A Subtitles Object representing the subtitles to be exported. @output_file (user data) An Output File Stream, representing the file the exported data should be written to. Returns: Boolean. True if the export succeeded, false if it failed. If this function returns false, the output file is deleted from disk. ``` -------------------------------- ### aegisub.register_macro Source: https://github.com/typesettingtools/aegisub/blob/master/automation/v4-docs/basic-function-interface.txt Registers a new Macro Feature in the Aegisub interface. ```APIDOC ## aegisub.register_macro ### Description Registers a new Macro Feature to be displayed in the Aegisub menu. ### Parameters - **name** (string) - Required - The displayed name of the menu item. - **description** (string) - Required - A longer description shown on the status bar. - **processing_function** (function) - Required - The function called for macro execution. - **validation_function** (function) - Optional - A function to determine if the macro can act on current subtitles. ```