### Full Component Structure Example Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/environment-and-components.md Illustrates the standard structure for a RIME component, including init(), the main component function, and fini() for setup, logic, and cleanup. The env object is optional in the main function. ```lua local function init(env) -- Setup code - runs once when component is loaded -- Initialize env properties for use in the main function env.resource1 = load_resource1() env.resource2 = load_resource2() end local function component_func(arg1, [arg2], [env]) -- Main component logic -- arg1, arg2 depend on component type -- env is optional end local function fini(env) -- Cleanup code - runs when component is unloaded -- Should clean up any resources allocated in init() env.resource1 = nil env.resource2 = nil end -- Export the component return { init = init, func = component_func, fini = fini } ``` -------------------------------- ### Automate librime-lua Plugin Installation Source: https://github.com/hchunhui/librime-lua/wiki/Home Use the provided `install-plugins.sh` script to automatically download and integrate the librime-lua plugin into the librime source directory. This simplifies the setup process. ```bash cd $PATH_TO_RIME_SOURCE bash install-plugins.sh hchunhui/librime-lua ``` -------------------------------- ### Complete RIME Lua Configuration Example Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/module-loading-and-initialization.md This example demonstrates a typical RIME Lua configuration file structure. It shows how to import components, define inline translators, export them, and manage optional global state and utility functions. ```lua -- RIME main Lua configuration -- I. Import components from files local date = require("date") local charset = require("charset") local reverse = require("reverse") local switch = require("switch") local expand = require("expand_translator") -- II. Define inline components local function hello_translator(input, seg) if input == "hello" then yield(Candidate("hello", seg.start, seg._end, "世界", "world")) end end -- III. Export components for use in schemas date_translator = date charset_filter = charset.filter charset_comment_filter = charset.comment_filter reverse_lookup_filter = reverse switch_processor = switch expand_translator = expand hello_translator = hello_translator -- IV. Optional: Global state local feature_enabled = true -- V. Utility functions (not exported as components) local function helper_function() return feature_enabled end ``` -------------------------------- ### CommitHistory push Method Examples Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/commithistory.md Shows practical examples of using the push method with different parameter types. ```lua local history = ctx.commit_history history:push("input", "hello") history:push(ctx.composition, "world") ``` -------------------------------- ### start property Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/segment.md Gets or sets the starting position of the segment within the input text. ```APIDOC ## start or _start (read/write) Start position in the input. ### Properties - **start** or **_start** (integer) - Read/write ### Example ```lua local s = seg.start seg.start = 0 ``` ``` -------------------------------- ### Install Lua Development Files on Debian/Ubuntu Source: https://github.com/hchunhui/librime-lua/wiki/Home Install the necessary development headers and libraries for Lua on Debian-based systems. This command ensures that the build system can find and link against the Lua runtime. ```bash # For Debian/Ubuntu: sudo apt install liblua5.3-dev # or libluajit-5.1-dev ``` -------------------------------- ### Access and Use Dictionary Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/dictionary.md Example of accessing the dictionary through the engine context and performing a lookup. ```lua -- Access dictionary through context local dict = env.engine.dict -- Look up entries local results = dict:lookup("example") ``` -------------------------------- ### Load and Get Configuration Values Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/INDEX.md Explains how to load a configuration file and retrieve specific string values using a given path. ```lua -- Load config local cfg = Config("schema.yaml") local val = cfg:get_string("path/to/value") ``` -------------------------------- ### Full Schema Usage Example Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/schema.md Demonstrates creating a schema, accessing its properties, and applying it to the engine. Includes checking schema name, page size, select keys, and configuration settings. ```lua local schema = Schema("luna_pinyin") -- Check schema properties if schema.name == "朙月拼音" then -- This is the luna_pinyin schema print("Page size: " .. schema.page_size) print("Select keys: " .. schema.select_keys) end -- Access schema config local config = schema.config if config then local enable_tone = config:get_bool("switches/0/states/0") end -- Apply schema to engine env.engine:apply_schema(schema) ``` -------------------------------- ### Load and Get Configuration Values Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/INDEX.md Load a configuration schema and retrieve specific string values from it. ```lua local config = Config("luna_pinyin.schema") local value = config:get_string("schema/name") ``` -------------------------------- ### Module with Init, Function, and Fini Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/module-loading-and-initialization.md This pattern allows modules to perform setup (`init`), core logic (`func`), and cleanup (`fini`) operations, managing internal state via an environment table. ```lua -- reverse.lua local function init(env) env.db = ReverseDb("...") end local function filter(input, env) -- code end local function fini(env) env.db = nil end return { init = init, func = filter, fini = fini } ``` -------------------------------- ### Librime Lua Translator Function Example Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/environment-and-components.md Example of a translator function that yields Candidate objects. Use `yield(candidate)` to produce output. ```lua function translator(input, seg, env) if input == "date" then yield(Candidate("date", seg.start, seg._end, os.date(), "日期")) end end ``` -------------------------------- ### Load, Get, Set, and Save Configuration Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/config.md Demonstrates loading a schema configuration, retrieving string and integer values, modifying a string value, and saving the changes to a custom file. Ensure the schema file exists before loading. ```lua -- Load schema configuration local schema_config = Config("luna_pinyin.schema") -- Get values local schema_name = schema_config:get_string("schema/name") local max_length = schema_config:get_int("speller/max_code_length") -- Modify values schema_config:set_string("schema/name", "Modified Luna Pinyin") -- Save changes schema_config:save_to_file("luna_pinyin.custom.yaml") ``` -------------------------------- ### Access Engine Instance Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/engine.md Get the engine instance from the RIME environment. ```lua local engine = env.engine ``` -------------------------------- ### Enable Examples in Schema Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/sample-implementations.md Configure your schema YAML to include the Lua translators and filters. This sets up the engine to use the provided Lua scripts. ```yaml engine: translators: - lua_translator@date_translator - lua_translator@time_translator - lua_translator@number_translator filters: - lua_filter@charset_filter - lua_filter@single_char_filter - lua_filter@reverse_lookup_filter ``` -------------------------------- ### Get Config Item by Path Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/config.md Retrieves a configuration item at the specified path, which can be of any type. Returns the item or nil if not found. ```lua config:get_item(path) ``` -------------------------------- ### Librime Lua Processor Function Example Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/environment-and-components.md Example of a processor function that handles keyboard events. Returns 0 (kRejected), 1 (kAccepted), or 2 (kNoop). ```lua function processor(key, env) if key.keycode == 0x20 and key:ctrl() then -- handle Ctrl+Space return 1 -- accepted end return 2 -- noop end ``` -------------------------------- ### Librime Lua Filter Function Example Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/environment-and-components.md Example of a filter function that processes a stream of candidates. Use `yield(candidate)` to pass through or modify candidates. ```lua function filter(input, env) for cand in input:iter() do if should_keep(cand) then yield(cand) end end end ``` -------------------------------- ### Get Preedit Information Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/context.md Retrieve the current preedit display information using get_preedit(). ```lua local preedit_info = ctx:get_preedit() ``` -------------------------------- ### Create a Segment Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/segment.md Creates a new segment instance with specified start and end positions. ```lua local seg = Segment(0, 3) ``` -------------------------------- ### Example rime.lua Structure Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/module-loading-and-initialization.md Defines component modules inline, loads modules from files, and exports components for use in RIME schemas. This file serves as the main entry point for Lua customization. ```lua -- Define component modules inline local function my_translator(input, seg) if input == "hello" then yield(Candidate("test", seg.start, seg._end, "世界", "world")) end end -- Load modules from files local date = require("date") local charset = require("charset") local reverse = require("reverse") -- Export components date_translator = date charset_filter = charset.filter charset_comment_filter = charset.comment_filter reverse_lookup_filter = reverse -- Component with initialization local switch = require("switch") switch_processor = switch -- Export with explicit functions my_special_translator = my_translator ``` -------------------------------- ### Translator Memory Usage Example Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/memory.md Demonstrates how to access memory functions within a translator context to check word frequency and track selections. ```lua -- Access memory through translator local function translator(input, seg, env) local memory = env.engine -- Check if word is frequently used if memory:has(input) then local freq = memory:get_frequency(input) if freq > 100 then -- High frequency word end end -- Track word selection memory:push_back(input, selected_value) end ``` -------------------------------- ### prompt property Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/segment.md Gets or sets the prompt text displayed for the segment. ```APIDOC ## prompt (read/write) Prompt text for the segment. ### Properties - **prompt** (string) - Read/write ### Example ```lua local prompt = seg.prompt seg.prompt = "pinyin: " ``` ``` -------------------------------- ### context (property) Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/engine.md Gets the composition context of the engine. This is a read-only property. ```APIDOC ## context (read-only) ### Description The composition context. ### Type `Context` ### Example ```lua local context = engine.context ``` ``` -------------------------------- ### Candidate Constructor Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/INDEX.md Constructs a new Candidate object with the specified type, start position, end position, display text, and comment. ```APIDOC ## Candidate Constructor ### Description Constructs a new Candidate object with the specified type, start position, end position, display text, and comment. ### Method Constructor ### Endpoint N/A (Object Constructor) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **Candidate** (object) - A new Candidate object instance. #### Response Example N/A ``` -------------------------------- ### Get Menu Page Index Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/menu.md Retrieves the current 0-based page index of the menu. ```lua local idx = menu.page_index ``` -------------------------------- ### Get Script Text Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/context.md Retrieve the complete script text of the current composition using get_script_text(). ```lua local script_text = ctx:get_script_text() ``` -------------------------------- ### Complete Lua Component Example Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/environment-and-components.md This Lua code defines a complete component that translates 'date' input into formatted date candidates. It includes initialization to set a date format (with support for custom configuration), a translator function to yield candidates, and a cleanup function. ```lua -- Date translator with configuration local function init(env) local schema = env.engine.schema env.date_format = "%Y-%m-%d" if schema and schema.config then local custom_format = schema.config:get_string("date/format") if custom_format then env.date_format = custom_format end end end local function translator(input, seg, env) if input == "date" then local formatted_date = os.date(env.date_format) yield(Candidate("date", seg.start, seg._end, formatted_date, "日期")) -- Also yield alternative formats yield(Candidate("date", seg.start, seg._end, os.date("%Y/%m/%d"), "日期")) end end local function fini(env) env.date_format = nil end return { init = init, func = translator, fini = fini } ``` -------------------------------- ### Get Candidate Spans Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/candidate.md Retrieves the character span information for a candidate, indicating its start and end positions within the input string. ```lua local spans = cand:spans() ``` -------------------------------- ### Handling Key Combinations and Events Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/keyevent.md Example of a processor function that handles specific key combinations (Ctrl+Shift+V), Alt key events, and key releases. It returns status codes indicating how the event was handled. ```lua local function my_processor(key, env) -- Check for specific key combinations if key.keycode == 0x2B and key:ctrl() and key:shift() then -- Ctrl+Shift+V -- handle paste return 1 -- kAccepted end if key:alt() then -- handle alt key end if key:release() then -- handle key release return 2 -- kNoop end return 2 -- kNoop (unhandled) end ``` -------------------------------- ### Create a Candidate Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/INDEX.md Use this snippet to create a new candidate object. It requires specifying the type, start and end positions, text, and an optional comment. ```lua yield(Candidate(type, start, end, text, comment)) ``` -------------------------------- ### Build RIME with Merged Plugins on Linux Source: https://github.com/hchunhui/librime-lua/wiki/Home Compile librime on Linux, including merged plugins like librime-lua. This command builds the necessary components and prepares them for installation. ```bash # On Linux, merged build make merged-plugins sudo make install ``` -------------------------------- ### Get Menu Page Size Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/menu.md Retrieves the number of candidates displayed per page from the menu object. ```lua local size = menu.page_size ``` -------------------------------- ### Get Context from Engine Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/context.md Obtain the context object from the environment's engine. This is the primary way to access the context. ```lua local context = env.engine.context ``` -------------------------------- ### Access Composition Context Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/engine.md Get the current composition context, which holds information about the ongoing input process. ```lua local context = engine.context ``` -------------------------------- ### Access Segment Start Position Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/segment.md Reads or modifies the starting character index of the segment within the input string. ```lua local s = seg.start seg.start = 0 ``` -------------------------------- ### Example Lua Translator for Date Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/README.md Defines a Lua function that yields a 'date' candidate when the input is 'date'. This is an example of a custom translator. ```lua -- rime.lua local function date_translator(input, seg) if input == "date" then yield(Candidate("date", seg.start, seg._end, os.date("%Y-%m-%d"), "日期")) end end date_translator = date_translator ``` -------------------------------- ### Create and Load Config Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/config.md Instantiate a Config object, optionally loading settings from a specified file during creation or later using load_from_file. ```lua local config = Config() local loaded = config:load_from_file("luna_pinyin.schema") ``` ```lua local config = Config("luna_pinyin.schema") ``` -------------------------------- ### UserDictionary.initialize Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/dictionary.md Initializes the user dictionary with data from a specified file path. Returns true on success. ```APIDOC ## UserDictionary.initialize ### Description Initializes the user dictionary with data from the specified file path. ### Method `initialize(path)` ### Parameters #### Path Parameters - **path** (string) - Required - Path to the dictionary file ### Return Type `bool` — true if successful ``` -------------------------------- ### Librime Lua Segmentor Function Example Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/environment-and-components.md Example of a segmentor function that performs custom segmentation. Returns true if custom segmentation was applied, false otherwise. ```lua function segmentor(seg) if seg.input:match("^%d+$") then -- All digits seg:clear() seg:reset(seg.input) return true end return false end ``` -------------------------------- ### Lua Processor Component Example Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/README.md Defines a processor component that handles keyboard input events. It returns an integer indicating whether the key event was rejected, accepted, or is a no-operation. ```lua function processor(key, env) if key.keycode == 0x20 then -- space return 1 -- accept/consume end return 2 -- no-op end ``` -------------------------------- ### Initialize, Lookup, and Finish Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/sample-implementations.md This pattern involves initializing a resource (like a database), performing lookups during translation, and cleaning up resources afterward. It's useful when translation relies on external data. ```lua function init(env) env.db = load_resource() end function translator(input, seg, env) local result = env.db:lookup(input) if result then yield(Candidate(...)) end end function fini(env) env.db = nil end ``` -------------------------------- ### Configuration Access Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/README.md Provides utilities for accessing and modifying RIME configuration. This includes loading configuration from files, getting and setting boolean, integer, double, and string values, and saving configuration. ```APIDOC ## Configuration Access ### Functions - **Config()** - Signature: `([filename])` - Returns: `Config` - Description: Initializes a configuration object, optionally with a filename. - **config:get_bool/int/double/string()** - Signature: `(path)` - Returns: `value|nil` - Description: Retrieves a configuration value of the specified type by its path. - **config:set_bool/int/double/string()** - Signature: `(path, value)` - Returns: `bool` - Description: Sets a configuration value of the specified type at the given path. - **config:load_from_file()** - Signature: `(path)` - Returns: `bool` - Description: Loads configuration settings from a file. - **config:save_to_file()** - Signature: `(path)` - Returns: `bool` - Description: Saves the current configuration to a file. ``` -------------------------------- ### Create Candidate Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/INDEX.md Demonstrates how to create a new candidate object with specified properties. ```lua -- Create candidate local c = Candidate(type, start, end, text, comment) ``` -------------------------------- ### Get Typed Config Items Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/config.md Retrieve configuration items as specific types (value, list, map) using a path. Returns the item or nil if not found or of the wrong type. ```lua config:get_value(path) ``` ```lua config:get_list(path) ``` ```lua config:get_map(path) ``` -------------------------------- ### ReverseDb Constructor Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/reversedb.md Creates and loads a reverse database from a specified file path. This is the entry point for using the ReverseDb functionality. ```APIDOC ## ReverseDb Constructor ### Description Creates and loads a reverse database from a file. ### Signature ```lua ReverseDb(filename) ``` ### Parameters #### Path Parameters - **filename** (string) - Required - Path to the reverse database file ### Return Type `ReverseDb` - The loaded reverse database ### Example ```lua local pydb = ReverseDb("build/terra_pinyin.reverse.bin") ``` ``` -------------------------------- ### length property Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/segment.md Gets or sets the length of the segment. ```APIDOC ## length (read/write) Length of the segment. ### Properties - **length** (integer) - Read/write ### Example ```lua local len = seg.length seg.length = 5 ``` ``` -------------------------------- ### Initialize User Dictionary Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/dictionary.md Initializes the user dictionary with data from a specified file path. Returns true if successful. ```lua bool initialize(path) ``` -------------------------------- ### tags property Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/segment.md Gets the set of tags associated with the segment. ```APIDOC ## tags (read/write) Tags associated with the segment. ### Properties - **tags** (table) - Read/write - Set of tag strings ### Example ```lua local tags = seg.tags ``` ``` -------------------------------- ### Load Config from File Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/config.md Loads configuration settings from a YAML file. Returns true if the file was loaded successfully. ```lua if config:load_from_file("default.custom") then -- config loaded end ``` -------------------------------- ### menu property Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/segment.md Gets or sets the menu (collection of candidates) for the segment. ```APIDOC ## menu (read/write) The menu (candidates) in the segment. ### Properties - **menu** (Menu) - Read/write ### Example ```lua local menu = seg.menu ``` ``` -------------------------------- ### get_list_size Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/config.md Gets the number of elements in a list located at the specified path. ```APIDOC ## get_list_size(path) Gets the size of a list at the given path. ### Parameters #### Path Parameters - **path** (string) - Required - Path to the list ### Return type `int` — Size of the list ``` -------------------------------- ### Create a Basic Candidate Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/candidate.md Creates a basic candidate using the Candidate constructor. This is useful for simple suggestions like dates. ```lua local cand = Candidate("date", seg.start, seg._end, os.date("%Y-%m-%d"), "今天日期") yield(cand) ``` -------------------------------- ### Instance-Level State Management with init/fini Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/module-loading-and-initialization.md Implement per-instance state management using the `init` and `fini` functions. The `init` function sets up instance-specific data (e.g., `env.instance_data`), and `fini` cleans it up. The main function (`translator` in this case) accesses this instance-specific data via the `env` object. ```lua local function init(env) env.instance_data = {} end local function translator(input, seg, env) -- Each instance has its own env.instance_data end local function fini(env) env.instance_data = nil end return { init = init, func = translator, fini = fini } ``` -------------------------------- ### Initialize and Access Environment Data in Librime Component Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/README.md Demonstrates how to initialize custom data within the environment during component startup and access it in subsequent operations. Ensure data is properly loaded in `init()` and cleaned up in `fini()`. ```lua function init(env) env.my_data = load_data() end function translator(input, seg, env) local data = env.my_data -- use data end function fini(env) env.my_data = nil end ``` -------------------------------- ### Segment Constructor Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/segment.md Creates a new segment with specified start and end positions. ```APIDOC ## Segment Constructor Creates a new segment with specified start and end positions. ### Method ```lua Segment(start_pos, end_pos) ``` ### Parameters #### Path Parameters - **start_pos** (integer) - Required - Start position in input - **end_pos** (integer) - Required - End position in input ### Return type `Segment` — The created segment ### Example ```lua local seg = Segment(0, 3) ``` ``` -------------------------------- ### 引用子目录或嵌套模块 Source: https://github.com/hchunhui/librime-lua/wiki/Scripting 使用 `.` 或 `/` 作为路径分隔符,引用 `lua/` 目录下的子文件夹或嵌套模块。支持多层级路径。 ```yaml engine: translators: - lua_translator@*date.translator # lua/date/translator.lua - lua_translator@*date/translator # lua/date/translator.lua - lua_translator@*date/subdir/translator # lua/date/subdir/translator.lua ``` -------------------------------- ### active_engine (property) Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/engine.md Gets or sets the active or focused engine. This property is read/write. ```APIDOC ## active_engine (read/write) ### Description The active/focused engine. ### Type `Engine` ### Example ```lua local active = engine.active_engine engine.active_engine = another_engine ``` ``` -------------------------------- ### schema (property) Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/engine.md Gets the current schema in use by the engine. This is a read-only property. ```APIDOC ## schema (read-only) ### Description The current schema in use. ### Type `Schema` ### Example ```lua local schema = engine.schema local name = schema.name ``` ``` -------------------------------- ### Create and Load Reverse Database Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/reversedb.md Instantiates a ReverseDb object by loading data from a specified file. Ensure the file path is correct. ```lua local pydb = ReverseDb("build/terra_pinyin.reverse.bin") ``` -------------------------------- ### Get Active Text Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/segment.md Retrieves the portion of the full input string that corresponds to this segment. ```lua local seg_text = seg:active_text("hello") ``` -------------------------------- ### Lookup Phonetics using Reverse Database Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/INDEX.md Demonstrates how to load a reverse phonetic database and perform a lookup for a given text. ```lua -- Lookup phonetics local db = ReverseDb("file.reverse.bin") local result = db:lookup("text") ``` -------------------------------- ### Menu Properties Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/menu.md Access properties of the Menu object to get information about the candidate menu. ```APIDOC ## Menu Object Properties ### `page_size` **Description:** Number of candidates displayed per page. **Type:** `integer` ### `page_index` **Description:** Current page index (0-based). **Type:** `integer` ### `is_empty()` **Description:** Checks if the menu has no candidates. **Type:** `boolean` ### `last_page_size` **Description:** Number of candidates on the last page. **Type:** `integer` ``` -------------------------------- ### 通过 Lua 表导出多个组件 Source: https://github.com/hchunhui/librime-lua/wiki/Scripting 一个 Lua 文件可以通过返回一个表来导出多个组件,并在配置文件中使用 `*` 配合表名和组件名进行引用。 ```yaml engine: translators: - lua_translator@*module_name*subtable1*subtable2*tran@name_space processors: - lua_translator@*module_name*subtable1*subtable2*proc@name_space ``` -------------------------------- ### Initializing ReverseDb for Reverse Lookup Source: https://github.com/hchunhui/librime-lua/wiki/Objects Shows how to initialize a ReverseDb object for reverse lookups using a specified dictionary file. This is typically used for tasks like converting input characters back to their pinyin or other phonetic representations. ```lua local pyrdb = ReverseDb("build/terra_pinyin.reverse.bin") ``` -------------------------------- ### 旧版 librime-lua 模块加载方式 Source: https://github.com/hchunhui/librime-lua/wiki/Scripting 在旧版 librime-lua 中,需要先在 `rime.lua` 中使用 `require` 加载模块,并将返回的组件赋值给全局变量,然后才能在方案配置文件中引用。 ```lua date_translator = require("date_translator") ``` -------------------------------- ### Handle Keyboard Input Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/INDEX.md Shows how to check for specific key combinations, like Ctrl+Space, and return a value to indicate acceptance. ```lua -- Handle keyboard if key:ctrl() and key.keycode == 0x20 then return 1 -- accept end ``` -------------------------------- ### Get Commit Text Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/context.md Retrieve the text that will be committed with the current input state using get_commit_text(). ```lua local committable_text = ctx:get_commit_text() ``` -------------------------------- ### Set Config Item by Path Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/config.md Sets a configuration item at the specified path. Returns true if the operation was successful. ```lua config:set_item(path, item) ``` -------------------------------- ### KeyEvent Properties Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/keyevent.md Access properties of the KeyEvent object to get key code and modifier information. ```APIDOC ## KeyEvent Properties ### `keycode` (read-only) The key code of the pressed key. **Type:** `integer` — ASCII code or special key code **Common values:** - ASCII range: 0x20-0x7E for printable characters - 0xFF00+ for special keys (arrows, function keys, etc.) --- ### `modifier` (read-only) The modifier state (shift, ctrl, alt, etc.). **Type:** `integer` — Bitmask of modifier keys ``` -------------------------------- ### Config Constructor Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/config.md Creates a new Config object, optionally loading configuration from a specified file. ```APIDOC ## Config Constructor Creates a new Config object and optionally loads from a file. ### Parameters #### Path Parameters - **filename** (string) - Optional - Optional path to config file to load ### Return type `Config` — The configuration object ### Example ```lua local config = Config() local loaded = config:load_from_file("luna_pinyin.schema") -- or with constructor argument local config = Config("luna_pinyin.schema") ``` ``` -------------------------------- ### Manage Active Engine Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/engine.md Get or set the currently focused engine. This is useful in multi-engine environments. ```lua local active = engine.active_engine engine.active_engine = another_engine ``` -------------------------------- ### Get Last Page Size Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/menu.md Retrieves the number of candidates present on the last page of the menu. ```lua local size = menu.last_page_size ``` -------------------------------- ### KeySequence Constructor Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/keysequence.md Creates a new key sequence. It can be initialized as empty or parsed directly from a string notation. ```APIDOC ## KeySequence() ### Description Creates a new, empty key sequence. ### Method Constructor ### Parameters None ### Response #### Success Response - **KeySequence** (KeySequence) - A new KeySequence object. ### Request Example ```lua local ks = KeySequence() ``` ## KeySequence(string) ### Description Creates a new key sequence by parsing the provided string notation. ### Method Constructor ### Parameters #### Path Parameters - **string** (string) - Optional key sequence string to parse ### Response #### Success Response - **KeySequence** (KeySequence) - A new KeySequence object parsed from the string. ### Request Example ```lua local ks2 = KeySequence("ctrl+a") ``` ``` -------------------------------- ### Get Input Option State Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/context.md Retrieve the current state of an input option using get_option(option). ```lua local simplification_enabled = ctx:get_option("simplification") ``` -------------------------------- ### 配置多个 Lua 组件实例 Source: https://github.com/hchunhui/librime-lua/wiki/Scripting 通过 `@` 语法为同一个 Lua 模块加载多个实例,以区分不同的命名空间。 ```yaml engine: translators: - lua_translator@*date_translator # name_space "date_translator" - lua_translator@*date_translator@date # namespace "date" ``` -------------------------------- ### 模块化日期翻译器脚本 Source: https://github.com/hchunhui/librime-lua/wiki/Scripting 将翻译器逻辑封装在独立的 Lua 文件中,使用 `local` 限制作用域并 `return` 导出组件。适用于脚本的模块化管理。 ```lua -- lua/date_translator.lua local function translator(input, seg) if (input == "date") then --- Candidate(type, start, end, text, comment) yield(Candidate("date", seg.start, seg._end, os.date("%Y年%m月%d日"), " 日期")) end end return translator ``` -------------------------------- ### Schema Properties Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/schema.md Access read-only properties of a Schema object to get information about the input method configuration. ```APIDOC ## Schema Properties ### `name` (read-only) The display name of the schema. **Type:** `string` ```lua local name = schema.name ``` ### `schema_id` (read-only) The identifier of the schema. **Type:** `string` ```lua local id = schema.schema_id ``` ### `select_keys` (read-only) Keys used for selecting candidates (e.g., "1234567890" or "asdfghjkl"). **Type:** `string` ```lua local keys = schema.select_keys ``` ### `page_size` (read-only) Number of candidates displayed per page. **Type:** `integer` ```lua local size = schema.page_size ``` ### `config` (read-only) The underlying config object for the schema. **Type:** `Config` — The schema configuration, or nil ```lua local config = schema.config if config then local max_length = config:get_int("speller/max_code_length") end ``` ``` -------------------------------- ### Create Shadow Candidate Wrapper Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/candidate.md Wraps an existing candidate as a shadow candidate. This is used for alternative suggestions. ```lua local shadow = cand:to_shadow_candidate("alt", "alternative", "") ``` -------------------------------- ### UserDictionary.load Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/dictionary.md Loads the user dictionary from a specified file path. Returns true on success. ```APIDOC ## UserDictionary.load ### Description Loads the user dictionary from the specified file path. ### Method `load(path)` ### Parameters #### Path Parameters - **path** (string) - Required - Path to the dictionary file ### Return Type `bool` — true if successful ``` -------------------------------- ### Access Segment Length Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/segment.md Reads or modifies the length of the segment. This property is directly tied to start and end positions. ```lua local len = seg.length seg.length = 5 ``` -------------------------------- ### KeySequence Constructor Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/keysequence.md Creates a new KeySequence object. It can be initialized empty or by parsing a string directly. ```lua local ks = KeySequence() ks:parse("ctrl+shift+v") -- or directly local ks2 = KeySequence("ctrl+a") ``` -------------------------------- ### ctx.caret_pos Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/context.md Controls the caret/cursor position within the input. This property allows getting and setting the cursor's position. ```APIDOC ## ctx.caret_pos ### Description Represents the caret/cursor position in the input string. Allows for reading the current position and setting a new position. ### Access read-write ### Type `integer` ### Example ```lua local pos = ctx.caret_pos ctx.caret_pos = 5 ``` ``` -------------------------------- ### Context Constructor Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/context.md Context is obtained from the Engine, not created directly. This shows how to access the current context. ```APIDOC ## Context Constructor Context is obtained from the Engine, not created directly. ```lua local context = env.engine.context ``` ``` -------------------------------- ### Get Selected Candidate Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/context.md Retrieve the currently selected candidate using get_selected_candidate(). Returns nil if no candidate is selected. ```lua local selected_candidate = ctx:get_selected_candidate() ``` -------------------------------- ### Config Methods Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/VERIFICATION.md Methods for loading, saving, and accessing configuration values. ```APIDOC ## Config Methods ### Description Provides methods for managing configuration settings, including loading from files, saving, and accessing various data types. ### Methods - Constructor - load_from_file() - save_to_file() - is_null() - is_value() - is_list() - is_map() - get_bool() - get_int() - get_double() - get_string() - set_bool() - set_int() - set_double() - set_string() - get_item() - set_item() - get_value() - get_list() - get_map() - set_value() - set_list() - set_map() - get_list_size() ``` -------------------------------- ### Load User Dictionary Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/dictionary.md Loads dictionary data from a specified file path. ```lua bool load(path) ``` -------------------------------- ### selected_index property Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/segment.md Gets or sets the index of the selected candidate within the segment. Set to -1 if no candidate is selected. ```APIDOC ## selected_index (read/write) The index of the selected candidate (-1 if none selected). ### Properties - **selected_index** (integer) - Read/write ### Example ```lua local idx = seg.selected_index seg.selected_index = 0 ``` ``` -------------------------------- ### status property Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/segment.md Gets or sets the status of the segment. The status indicates the current state of the segment (e.g., confirmed, selected). ```APIDOC ## status (read/write) The status of the segment. ### Properties - **status** (string) - Read/write - One of: "kVoid", "kGuess", "kSelected", "kConfirmed" ### Example ```lua local status = seg.status seg.status = "kConfirmed" if seg.status == "kConfirmed" then -- segment is confirmed end ``` ``` -------------------------------- ### Get List Size Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/config.md Retrieves the number of elements in a list located at the specified path. Returns the size of the list as an integer. ```lua config:get_list_size(path) ``` -------------------------------- ### Get Frequency of Learned Word Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/memory.md Retrieves the frequency score of a learned word. The score is returned as a double-precision floating-point number. ```lua double get_frequency(text_key) ``` -------------------------------- ### Translator with Environment Initialization and Cleanup Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/translator-filter-patterns.md Implements a translator that utilizes an initialized environment for data lookup, such as a reverse database. Includes functions for initialization and finalization. ```lua local function init(env) -- Initialize environment (called once at startup) env.db = ReverseDb("build/terra_pinyin.reverse.bin") end local function translator(input, seg, env) -- env contains initialized data from init() if input == "py:" then local pinyin = env.db:lookup(input:sub(4)) if pinyin ~= "" then yield(Candidate("py", seg.start, seg._end, pinyin, "拼音")) end end end local function fini(env) -- Cleanup (called at shutdown) env.db = nil end return { init = init, func = translator, fini = fini } ``` -------------------------------- ### Get Dictionary Entry Count Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/memory.md Returns the number of entries present in the dictionary. This count is distinct from learned memory entries. ```lua integer dict_count() ``` -------------------------------- ### Check Switcher Availability Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/types.md Demonstrates how to check if the Switcher type is available in the current Librime version before attempting to use it. ```lua if Switcher == nil then -- Switcher not available in this version end ``` -------------------------------- ### Get the Last Segment of Composition Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/composition.md The `back()` method retrieves the most recently added segment. It returns `nil` if the composition is empty. ```lua Segment back() ``` -------------------------------- ### 配置 Lua 模块作为翻译器 Source: https://github.com/hchunhui/librime-lua/wiki/Scripting 在 Rime 方案配置文件中,使用 `lua_translator@*` 的语法直接引用 Lua 模块作为翻译器。星号 `*` 指示 librime-lua 使用 `require` 加载模块。 ```yaml # luna_pinyin.schema.yaml engine: ... translators: - lua_translator@*date_translator ... ``` -------------------------------- ### Config Methods Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/INDEX.md Methods available for Config objects. ```APIDOC ### Config Methods | Method | Signature | Returns | |--------|-----------|---------| | `load_from_file()` | `(path)` | `bool` | | `save_to_file()` | `(path)` | `bool` | | `get_bool/int/double/string()` | `(path)` | `value|nil` | | `set_bool/int/double/string()` | `(path, value)` | `bool` | | `get_item()` | `(path)` | `ConfigItem|nil` | | `set_item()` | `(path, item)` | `bool` | | `get_list_size()` | `(path)` | `int` | ``` -------------------------------- ### Get Context Property Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/context.md Retrieve the value of a context property using get_property(prop). Returns an empty string if the property is not found. ```lua local user_dict_path = ctx:get_property("user_dict") ``` -------------------------------- ### Check for Menu Availability Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/context.md Use has_menu() to check if there are available candidate selections. ```lua local has_candidates = ctx:has_menu() ``` -------------------------------- ### _end property Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/segment.md Gets or sets the ending position of the segment within the input text. Use `_end` as `end` is a Lua keyword. ```APIDOC ## _end (read/write) End position in the input. Use `_end` instead of `end` since `end` is a Lua keyword. ### Properties - **_end** (integer) - Read/write ### Example ```lua local e = seg._end seg._end = 5 ``` ``` -------------------------------- ### Basic Processor Implementation Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/translator-filter-patterns.md A simple processor that handles keyboard input. It returns kAccepted if Ctrl+Space is pressed, otherwise kNoop. ```lua local kRejected = 0 local kAccepted = 1 local kNoop = 2 local function processor(key, env) -- key: KeyEvent object -- env: environment if key.keycode == 0x20 and key:ctrl() then -- Ctrl+Space -- Handle hotkey return kAccepted -- consumed end return kNoop -- not handled end return processor ``` -------------------------------- ### Context Methods Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/VERIFICATION.md Methods for interacting with the input context, managing composition, and options. ```APIDOC ## Context Methods ### Description Enables interaction with the input context, including text manipulation, state checking, and option management. ### Methods - commit() - get_commit_text() - get_script_text() - get_preedit() - is_composing() - has_menu() - get_selected_candidate() - push_input() - pop_input() - delete_input() - clear() - select() - highlight() - confirm_current_selection() - delete_current_selection() - confirm_previous_selection() - reopen_previous_selection() - clear_previous_segment() - reopen_previous_segment() - clear_non_confirmed_composition() - refresh_non_confirmed_composition() - set_option() - get_option() - set_property() - get_property() - clear_transient_options() ### Properties - input - caret_pos - composition - commit_notifier - select_notifier - update_notifier - delete_notifier - option_update_notifier - property_update_notifier - unhandled_key_notifier - commit_history ``` -------------------------------- ### Get Memory Entry Count Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/memory.md Returns the total number of learned entries in the memory database. This is a simple count of stored items. ```lua integer memory_count() ``` -------------------------------- ### load_from_file Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/config.md Loads configuration from a YAML file specified by the path. ```APIDOC ## load_from_file(path) Loads configuration from a YAML file. ### Parameters #### Path Parameters - **path** (string) - Required - Path to the file (relative to RIME data directory) ### Return type `bool` — true if successful ### Example ```lua if config:load_from_file("default.custom") then -- config loaded end ``` ``` -------------------------------- ### Iterating Through Commit History Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/commithistory.md Shows how to retrieve all commit history entries as a table and iterate through them. ```lua -- Access commit history from context local history = env.engine.context.commit_history -- Check recent commits if not history.empty then local last = history:back() if last.text == "previous" then -- Do something based on what was committed end end -- Iterate through all history local all = history:to_table() for i, record in ipairs(all) do print("Record " .. i .. ": " .. record.type .. " = " .. record.text) end ``` -------------------------------- ### Get Candidate Dynamic Type Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/candidate.md Retrieves the dynamic type of a candidate. Use this to conditionally handle different candidate types like 'Phrase'. ```lua local ctype = cand:get_dynamic_type() if ctype == "Phrase" then -- handle phrase candidates end ``` -------------------------------- ### Candidate Constructor Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/candidate.md Creates a basic candidate object (SimpleCandidate). ```APIDOC ## Constructor ```lua Candidate(type, start, end, text, comment) ``` Creates a basic candidate (SimpleCandidate). | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | type | string | — | Candidate type identifier | | start | integer | — | Start position in input string | | end | integer | — | End position in input string | | text | string | — | Display text for the candidate | | comment | string | — | Comment/annotation shown to user | **Return type:** `an` — The created candidate object **Example:** ```lua local cand = Candidate("date", seg.start, seg._end, os.date("%Y-%m-%d"), "今天日期") yield(cand) ``` ``` -------------------------------- ### Constructing a Set in Lua Source: https://github.com/hchunhui/librime-lua/wiki/Objects Demonstrates the construction of a Set object from a Lua table. Duplicate elements in the input table are automatically handled, resulting in a set with unique elements. ```lua local set_tab = Set({'a','b','c','c'}) # set_tab = {a=true,b=true, c=true} ``` -------------------------------- ### Segmentor for Special Command Syntax Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/translator-filter-patterns.md A segmentor that recognizes input starting with '/' as a special command. It clears existing segmentation and resets it with the command input. ```lua local function segmentor(seg) local input = seg.input if input:sub(1, 1) == "/" then -- Special command syntax seg:clear() seg:reset(input) return true end return false end return segmentor ``` -------------------------------- ### Lua Segmentor Component Example Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/README.md Defines a segmentor component that customizes text segmentation. It returns a boolean indicating whether custom segmentation should be applied. ```lua function segmentor(seg) if seg.input:match("^%d+$") then -- custom segmentation for all-digit input return true end return false end ``` -------------------------------- ### Initializing Custom Environment Properties Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/environment-and-components.md Add custom properties to the environment object during the init() function for use in other component functions. Remember to nil them out in fini() to clean up resources. ```lua function init(env) env.my_database = load_database() env.my_config = {} end function translator(input, seg, env) local db = env.my_database -- use db end function fini(env) env.my_database = nil end ``` -------------------------------- ### get_item Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/api-reference/config.md Retrieves a configuration item of any type at the specified path. ```APIDOC ## get_item(path) Gets a config item at the path (can be any type). ### Parameters #### Path Parameters - **path** (string) - Required - Path to the item ### Return type `ConfigItem` or `nil` ``` -------------------------------- ### Lua Translator Component Example Source: https://github.com/hchunhui/librime-lua/blob/master/_autodocs/README.md Defines a translator component that yields a candidate when the input matches 'trigger'. This component converts input text to candidates. ```lua function translator(input, seg, env) if input == "trigger" then yield(Candidate(...)) end end ```