### Define Installation Function Source: https://github.com/orbitalquark/textadept/blob/default/CMakeLists.txt Defines a reusable function to install core Textadept files and directories to a specified destination. ```cmake function(install_data dir) install(FILES init.lua LICENSE DESTINATION ${dir}) install(DIRECTORY core docs ${scintillua_SOURCE_DIR}/lexers test themes DESTINATION ${dir}) install(DIRECTORY modules DESTINATION ${dir} PATTERN ".git" EXCLUDE PATTERN "build" EXCLUDE) endfunction() ``` -------------------------------- ### Example Session File Content Source: https://github.com/orbitalquark/textadept/wiki/RelativePaths This is an example of a Textadept session file, illustrating the format used to store buffer information, split view configurations, current view, and window size. ```text buffer: 3907 3907 109 [TEXTADEPTHOME]//../data/modules/textadept/session.lua buffer: 306 306 0 [TEXTADEPTHOME]//../data/session buffer: 395 395 0 [TEXTADEPTHOME]//../data/init.lua buffer: 2288 2288 48 [TEXTADEPTHOME]//core/args.lua buffer: 0 0 0 [TEXTADEPTHOME]//../app_3.7_beta_2_org/core/args.lua buffer: 4789 4789 65 [TEXTADEPTHOME]//../app_3.7_beta_2_org/modules/textadept/session.lua buffer: 2781 2781 78 [TEXTADEPTHOME]//../data/modules/pathutils.lua buffer: 2013 2013 5 [TEXTADEPTHOME]//../data/modules/pathutils-test.lua split0: true 705 view1: 1 split2: false 451 view1: 8 view2: 9 current_view: 1 size: 1280 949 ``` -------------------------------- ### Textadept Key Modes Example Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Demonstrates how to define and manage key modes in Textadept, allowing for context-specific key bindings. Includes an example of a 'vi mode' with bindings for navigation and entering insert mode. ```APIDOC ## Modes Modes are groups of key bindings such that when a key [mode](#keys.mode) is active, Textadept ignores all key bindings defined outside the mode until the mode is unset. Here is a simple vi mode example: ```lua keys.command_mode = { ['h'] = buffer.char_left, ['j'] = buffer.line_up, ['k'] = buffer.line_down, ['l'] = buffer.char_right, ['i'] = function() keys.mode = nil ui.statusbar_text = 'INSERT MODE' end } keys['esc'] = function() keys.mode = 'command_mode' end events.connect(events.UPDATE_UI, function() if keys.mode == 'command_mode' then return end ui.statusbar_text = 'INSERT MODE' end) keys.mode = 'command_mode' -- default mode ``` **Warning**: When creating a mode, be sure to define a way to exit the mode, otherwise you will probably have to restart Textadept. ``` -------------------------------- ### FetchContent Setup Source: https://github.com/orbitalquark/textadept/blob/default/CMakeLists.txt Initializes FetchContent module for downloading and managing external dependencies. Sets options for quiet fetching and nightly builds. ```cmake include(FetchContent) set(FETCHCONTENT_QUIET OFF) set(nightlies scinterm scintillua regex) # fetch latest version if NIGHTLY is true set(deps_dir ${CMAKE_BINARY_DIR}/_deps) ``` -------------------------------- ### Configure Linux Installation Source: https://github.com/orbitalquark/textadept/blob/default/CMakeLists.txt Handles directory creation, symlink management for binaries and desktop files, and archive creation for Linux systems. ```cmake if(NOT (WIN32 OR APPLE)) include(GNUInstallDirs) set(ta_bin_dir ${CMAKE_INSTALL_FULL_BINDIR}) install(CODE "file(MAKE_DIRECTORY ${ta_bin_dir})") set(ta_data_dir ${CMAKE_INSTALL_FULL_DATADIR}/textadept) file(RELATIVE_PATH ta_bin_to_data_dir ${CMAKE_INSTALL_FULL_BINDIR} ${ta_data_dir}) install(CODE "file(MAKE_DIRECTORY ${CMAKE_INSTALL_FULL_DATADIR}/applications)") file(RELATIVE_PATH ta_app_to_data_dir ${CMAKE_INSTALL_FULL_DATADIR}/applications ${ta_data_dir}) function(install_links target) if(DEFINED TEXTADEPT_HOME) install(TARGETS ${target} DESTINATION ${ta_bin_dir}) else() install(TARGETS ${target} DESTINATION ${ta_data_dir}) install(CODE "file(CREATE_LINK ${ta_bin_to_data_dir}/${target} ${ta_bin_dir}/${target} SYMBOLIC)") endif() install(FILES src/${target}.desktop DESTINATION ${ta_data_dir}) install(CODE "file(CREATE_LINK ${ta_app_to_data_dir}/${target}.desktop ${CMAKE_INSTALL_FULL_DATADIR}/applications/${target}.desktop SYMBOLIC)") endfunction() if(QT) install_links(textadept) endif() if(GTK3 OR GTK2) install_links(textadept-gtk) endif() if(CURSES) install_links(textadept-curses) endif() install_data(${ta_data_dir}) install(FILES core/images/textadept.svg DESTINATION ${CMAKE_INSTALL_DATADIR}/icons/hicolor/scalable/apps) set(textadept_tgz textadept_${version}.tgz) if(CMAKE_SYSTEM_PROCESSOR MATCHES "^aarch") set(textadept_tgz textadept_${version}.arm.tgz) endif() # Note: can use file(ARCHIVE_CREATE ... WORKING_DIRECTORY) in CMake 3.31. add_custom_target(archive COMMAND ${CMAKE_COMMAND} -E tar czf ${CMAKE_BINARY_DIR}/${textadept_tgz} textadept WORKING_DIRECTORY ${CMAKE_INSTALL_FULL_DATADIR}) endif() ``` -------------------------------- ### Launch Textadept in View Mode Source: https://github.com/orbitalquark/textadept/wiki/TextadeptViewer Example command to launch Textadept with the view-mode argument, opening specific files and navigating to a line. ```bash textadept --view-mode foo.lua bar.lua -e 'buffer:goto_line(9)' ``` -------------------------------- ### Configure Windows Installation Source: https://github.com/orbitalquark/textadept/blob/default/CMakeLists.txt Handles Windows-specific deployment, including system runtime libraries and deployment of Qt dependencies using windeployqt. ```cmake elseif(WIN32) set(ta_dir ${CMAKE_INSTALL_PREFIX}/textadept) if(QT) install(TARGETS textadept DESTINATION ${ta_dir}) endif() if(CURSES) install(TARGETS textadept-curses DESTINATION ${ta_dir}) endif() install_data(${ta_dir}) install(TARGETS iconv DESTINATION ${ta_dir}) if(NOT (EXISTS ${ta_dir}/${qt_major}Core.dll OR EXISTS ${ta_dir}/${qt_major}Cored.dll)) install(CODE "execute_process(COMMAND ${WINDEPLOYQT_EXECUTABLE} --no-compiler-runtime ${ta_dir}/textadept.exe)") install(CODE "file(REMOVE ${ta_dir}/d3dcompiler_47.dll ${ta_dir}/opengl32sw.dll)") set(CMAKE_INSTALL_SYSTEM_RUNTIME_DESTINATION ${ta_dir}) # put system libs here, not in bin/ include(InstallRequiredSystemLibraries) endif() add_custom_target(archive COMMAND 7z a ${CMAKE_BINARY_DIR}/textadept_${version}.zip textadept WORKING_DIRECTORY ${CMAKE_INSTALL_PREFIX}) ``` -------------------------------- ### View: Indentation Guides Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Configure the display of indentation guides. ```APIDOC ## `view.indentation_guides` ### Description Draw indentation guides. Indentation guides are dotted vertical lines that appear within indentation whitespace at each level of indentation. ### Method N/A (Property) ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response - **guide_mode** (string) - The mode for drawing indentation guides. - `view.IV_NONE`: Do not draw any guides. - `view.IV_REAL`: Draw guides only within indentation whitespace. - `view.IV_LOOKFORWARD`: Draw guides beyond the current line up to the next non-empty line's indentation level, but with an additional level if the previous non-empty line is a fold point. - `view.IV_LOOKBOTH`: Draw guides beyond the current line up to either the indentation level of the previous or next non-empty line, whichever is greater. ### Default Value `view.IV_LOOKBOTH` in the GUI version, and `view.IV_NONE` in the terminal version. ``` -------------------------------- ### Configure macOS Installation Source: https://github.com/orbitalquark/textadept/blob/default/CMakeLists.txt Handles macOS application bundle structure, macdeployqt integration, and code signing for Homebrew-installed Qt. ```cmake elseif(APPLE) set(ta_bin_dir ${CMAKE_INSTALL_PREFIX}/Textadept.app/Contents/MacOS) set(ta_data_dir ${CMAKE_INSTALL_PREFIX}/Textadept.app/Contents/Resources) if(QT) install(TARGETS textadept DESTINATION ${ta_bin_dir}) endif() if(CURSES) install(TARGETS textadept-curses DESTINATION ${ta_bin_dir}) endif() install(PROGRAMS scripts/osx/textadept_osx DESTINATION ${ta_bin_dir}) install_data(${ta_data_dir}) install(CODE "file(RENAME ${ta_data_dir}/core/images/textadept.icns ${ta_data_dir}/textadept.icns)") if(POLICY CMP0177) # CMake 3.31 auto-normalizes .. in install() paths. cmake_policy(SET CMP0177 NEW) endif() install(FILES src/Info.plist DESTINATION ${ta_data_dir}/../) if(NOT EXISTS ${ta_data_dir}/qt.conf) install(CODE "execute_process(COMMAND ${MACDEPLOYQT_EXECUTABLE} ${CMAKE_INSTALL_PREFIX}/Textadept.app -executable=${ta_bin_dir}/textadept)") # Homebrew Qt's macdeployqt cannot resolve rpaths to Homebrew's lib prefix. # Work around this issue by adding Homebrew's lib to the executable's rpaths. find_program(BREW brew) if(BREW) execute_process(COMMAND ${BREW} --prefix OUTPUT_VARIABLE BREW_PREFIX OUTPUT_STRIP_TRAILING_WHITESPACE) if(QT_DIR MATCHES "^${BREW_PREFIX}") install(CODE "execute_process(COMMAND ${CMAKE_INSTALL_NAME_TOOL} -add_rpath ${BREW_PREFIX}/lib ${ta_bin_dir}/textadept)") install(CODE "execute_process(COMMAND codesign --sign - --force --deep ${CMAKE_INSTALL_PREFIX}/Textadept.app)") endif() endif() endif() install(PROGRAMS scripts/osx/ta DESTINATION ${CMAKE_INSTALL_PREFIX}) add_custom_target(archive COMMAND ${CMAKE_COMMAND} -E tar cf ${CMAKE_BINARY_DIR}/textadept_${version}.zip --format=zip Textadept.app ta WORKING_DIRECTORY ${CMAKE_INSTALL_PREFIX}) endif() ``` -------------------------------- ### Compile Textadept using CMake Source: https://github.com/orbitalquark/textadept/blob/default/docs/README.md Use these commands to configure, build, and install Textadept from the source directory. ```bash cmake -S . -B build_dir -D CMAKE_BUILD_TYPE=RelWithDebInfo \ -D CMAKE_INSTALL_PREFIX=build_dir/install cmake --build build_dir -j # compiled binaries are in build_dir/ cmake --install build_dir # self-contained installation is in build_dir/install/ ``` -------------------------------- ### Example of Registering a Command-Line Option Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Illustrates the usage of `args.register` to define a command-line option with its short and long forms, number of arguments, callback function, and description. ```lua args.register('-r', '--read-only', 0, function() ... end, 'Read-only mode') ``` -------------------------------- ### Example lfile structure Source: https://github.com/orbitalquark/textadept/wiki/Fold A sample structure of an lfile used for language translations. ```text lgcode colSectionIdentity: N: «Identiteit» E: «Identity» F: «Identité» lgcode colSectionIdentityInfo: N: «Dit onderdeel van het formulier toont een beknopt overzicht van de collecties» E: «This part of the form shows a concise overview of the collections» F: «Cet élément du formulaire affiche un bref aperçu des collections» lgcode colSectionStatus: N: «Status» E: «Status» F: «Statut» lgcode colSectionStatusInfo: N: «Dit onderdeel van het formulier toont diverse elementen in verband met het bewerken van de collectiedata» E: «This part of the form shows different elements related to editing the collection data» F: «Cet élément du formulaire affiche divers éléments en rapport avec l'édition des données de la collection» ``` -------------------------------- ### Run Command Entry Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Opens the command entry with a specified label and callback function. The second example demonstrates spawning a process. ```lua ui.command_entry.run('echo:', ui.print) ui.command_entry.run('$', os.spawn, 'bash', 'env', ui.print) -- spawn a process ``` -------------------------------- ### Textadept Key Chains Example Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Illustrates the use of key chains, which allow multiple key bindings to be assigned to a single key sequence. Shows how to define a key chain and mentions the default behavior of 'Esc' to clear a chain. ```APIDOC ## Key Chains Key chains are a powerful concept. They allow you to assign multiple key bindings to one key sequence. By default, the `Esc` key cancels a key chain, but you can redefine it via [`keys.CLEAR`](#keys.CLEAR). An example key chain looks like: ```lua keys['alt+a'] = { a = function1, b = function2, c = {...} } ``` Pressing `Alt+A` activates the chain, and pressing `A` after that invokes function1. `Alt+A` followed by `B` invokes function2, and so on. ``` -------------------------------- ### Define CSS start rule with tagging Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Combines the CSS tag pattern with an HTML tag rule. ```lua local css_start_rule = #css_tag * tag ``` -------------------------------- ### Embed child lexer into parent (PHP example) Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Demonstrates a child lexer embedding itself into a parent lexer. ```lua local html = lexer.load('html') local php_start_rule = lex:tag('php_tag', '') html:embed(lex, php_start_rule, php_end_rule) ``` -------------------------------- ### Match Patterns at Line Start Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Use `lexer.starts_line` to ensure a pattern only matches at the beginning of a line. Optionally allows matching after indentation. ```lua local preproc = lex:tag(lexer.PREPROCESSOR, lexer.starts_line(lexer.to_eol('#'))) ``` -------------------------------- ### Configure Language-Specific Test Commands in Textadept Source: https://context7.com/orbitalquark/textadept/llms.txt Set up commands for running tests for different programming languages. Examples include 'busted' for Lua, 'pytest' for Python, and 'npm test' for JavaScript. ```lua textadept.run.test_commands.lua = 'busted' textadept.run.test_commands.python = 'pytest' textadept.run.test_commands.javascript = 'npm test' ``` -------------------------------- ### Configure Project Build Commands in Textadept Source: https://context7.com/orbitalquark/textadept/llms.txt Specify build commands for projects, either by absolute path or by detecting the project root. Uses 'make' or 'cmake --build build' as examples. ```lua textadept.run.build_commands['/path/to/project'] = 'make' textadept.run.build_commands[io.get_project_root()] = 'cmake --build build' ``` -------------------------------- ### Line Information Retrieval Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Functions and properties to get information about lines, including their start positions, lengths, and indentation. ```APIDOC ## buffer:position_from_line ### Description Returns a line's start position. ### Method `buffer:position_from_line(line)` ### Parameters #### Path Parameters - **line** (integer) - Line number to get the start position for. If *line* exceeds `buffer.line_count + 1`, `-1` will be returned. ## buffer.line_indent_position ### Description Map of line numbers to their end-of-line-indentation positions. ### Method `buffer.line_indent_position` ### Parameters (Read-only) ## buffer.line_end_position ### Description Map of line numbers to their end-of-line positions before any end-of-line characters. ### Method `buffer.line_end_position` ### Parameters (Read-only) ## buffer.line_count ### Description The number of lines in the buffer. ### Method `buffer.line_count` ### Parameters (Read-only) There is always at least one. ## buffer.line_indentation ### Description Map of line numbers to their column indentation amounts. ### Method `buffer.line_indentation` ### Parameters (Read-only) ## buffer:line_length ### Description Returns the number of bytes on a line, including end of line characters. ### Method `buffer:line_length(line)` ### Parameters #### Path Parameters - **line** (integer) - Line number to get the length of. To get line length excluding end of line characters, use `buffer.line_end_position[line] - buffer.position_from_line(line)`. ``` -------------------------------- ### Text Range and Deletion Operations in Textadept Source: https://context7.com/orbitalquark/textadept/llms.txt Extract specific text segments or remove content. `buffer:text_range(start, end)` gets text between specified positions. For deletion, `buffer:clear()` removes the character at the caret, and `buffer:delete_range(pos, len)` removes a specified number of characters starting from a position. ```lua -- Get text range local range = buffer:text_range(1, 50) ``` ```lua -- Delete character at caret buffer:clear() ``` ```lua -- Delete range of text buffer:delete_range(10, 5) -- delete 5 chars starting at pos 10 ``` -------------------------------- ### Initialize and Configure Enhanced Show Style Source: https://github.com/orbitalquark/textadept/wiki/enhanced-show-style Load the module in the init.lua file and enable the desired tooltip features. ```lua enhanced_show_style = require 'common.enhanced-show-style' enhanced_show_style.show_saved_bytes = true enhanced_show_style.show_codepoint_names = true ``` -------------------------------- ### List Lua and C Project Files with io.quick_open Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Utilize io.quick_open to prompt the user with a selection of Lua and C files within the current project's root directory. This uses glob patterns to filter the files. ```lua io.quick_open(io.get_project_root(), '**/*.{lua,c}') -- list Lua and C project files ``` -------------------------------- ### Define start rule for CSS embedding Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Creates an LPeg pattern to identify the start of a CSS block within HTML. ```lua local css_tag = P(']+type="text/css"', index) then return true end end) ``` -------------------------------- ### Find Word Start Position in Lua Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Calculates the start position of a word based on the provided position and character set constraints. ```lua -- Consider the buffer text "word....word" buffer:word_start_position(3, true) --> 1 buffer:word_start_position(7, true) --> 7 buffer:word_start_position(7, false) --> 5 buffer:word_start_position(9, false) --> 5 buffer:word_start_position(9, true) --> 9 ``` -------------------------------- ### Textadept Run and Build Commands Overview Source: https://context7.com/orbitalquark/textadept/llms.txt Provides a comprehensive list of commands for running, compiling, building, and testing code in Textadept. Includes configuration for language-specific commands and placeholders for file paths. ```lua -- Run current file textadept.run.run() -- Compile current file textadept.run.compile() -- Build project textadept.run.build() -- Run tests textadept.run.test() -- Stop running process textadept.run.stop() -- Configure run commands per language textadept.run.run_commands.lua = 'lua "%f"' textadept.run.run_commands.python = 'python3 "%f"' textadept.run.run_commands.javascript = 'node "%f"' textadept.run.run_commands.c = './"%e"' -- run compiled executable textadept.run.run_commands.go = 'go run "%f"' textadept.run.run_commands.rust = 'cargo run' -- Configure compile commands textadept.run.compile_commands.c = 'gcc -o "%e" "%f"' textadept.run.compile_commands.cpp = 'g++ -o "%e" "%f"' textadept.run.compile_commands.java = 'javac "%f"' textadept.run.compile_commands.typescript = 'tsc "%f"' -- Configure build commands (for projects) textadept.run.build_commands['/path/to/project'] = 'make' textadept.run.build_commands[io.get_project_root()] = 'cmake --build build' -- Configure test commands textadept.run.test_commands.lua = 'busted' textadept.run.test_commands.python = 'pytest' textadept.run.test_commands.javascript = 'npm test' -- Run command placeholders: -- %f = full path to current file -- %e = path without extension -- %d = directory of current file -- %p = project root directory -- Navigate to error/warning in output textadept.run.goto_error(true) -- next error textadept.run.goto_error(false) -- previous error -- Error patterns for parsing output textadept.run.error_patterns.mylang = { '^([^:]+):(%d+):(.+)$' -- filename:line:message } ``` -------------------------------- ### Configure CTAGS Path for Textadept Source: https://github.com/orbitalquark/textadept/wiki/GotoSymbol Sets the CTAGS variable based on the operating system (Windows or other). Requires ctags to be installed and the CTAGS variable to point to its installation. ```lua -- Author: mitchell local CTAGS if WIN32 then CTAGS = '"c:\\bin\\ctags.exe" --sort=yes --fields=+K-f' else CTAGS = 'ctags --sort=yes --fields=+K-f' end ``` -------------------------------- ### io.quick_open Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Prompts the user to select a file to open from a list of files read from a directory. ```APIDOC ## io.quick_open ### Description Prompts the user to select a file to open from a list of files read from a directory. ### Parameters - **paths** (string/table) - Optional - Directory path or table of paths to search. - **filter** (string/table) - Optional - Filter specifying files and directories to yield. ``` -------------------------------- ### GET /buffer/get_text Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Retrieves the entire text content of the current buffer. ```APIDOC ## GET buffer:get_text ### Description Returns the buffer's text. ### Method GET ### Endpoint buffer:get_text() ### Response #### Success Response (200) - **text** (string) - The full text content of the buffer. ``` -------------------------------- ### List Non-Build Project Files with io.quick_open Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Employ io.quick_open to present a file selection dialog, excluding files within any 'build' directories in the project. This is achieved using a negation pattern in the filter. ```lua io.quick_open(io.get_project_root(), '!build') -- list non-build project files ``` -------------------------------- ### List Files in Buffer's Directory with io.quick_open Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Use io.quick_open to display a file selection dialog for files located in the same directory as the current buffer. This is useful for quickly accessing related files. ```lua io.quick_open(buffer.filename:match('^(.+)[/\\]')) -- list files in the buffer's directory ``` -------------------------------- ### lexer.embed Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Embeds a child lexer into a parent lexer using specific start and end rules. ```APIDOC ## lexer.embed(lexer, child, start_rule, end_rule) ### Description Embeds a child lexer into a parent lexer. ### Parameters - **lexer** (table) - Required - Parent lexer. - **child** (table) - Required - Child lexer. - **start_rule** (pattern) - Required - LPeg pattern matching the beginning of the child lexer. - **end_rule** (pattern) - Required - LPeg pattern matching the end of the child lexer. ``` -------------------------------- ### Get View Number from View Object Source: https://github.com/orbitalquark/textadept/wiki/CloseUnsplitView Retrieves the numerical identifier for a given view object. ```lua function get_view_num(v) return _G._VIEWS[v] end ``` -------------------------------- ### Configure Qt Libraries Source: https://github.com/orbitalquark/textadept/blob/default/CMakeLists.txt Sets up Qt library targets based on the detected Qt major version. Requires Widgets, Core5Compat, and Network components. ```cmake if(QT) set(qt_major Qt${QT_VERSION_MAJOR}) if(QT_VERSION_MAJOR GREATER 5) find_package(${qt_major} COMPONENTS Widgets Core5Compat Network REQUIRED) set(qt_libraries ${qt_major}::Widgets ${qt_major}::Core5Compat ${qt_major}::Network) else() find_package(${qt_major} COMPONENTS Widgets Network REQUIRED) set(qt_libraries ${qt_major}::Widgets ${qt_major}::Network) endif() endif() ``` -------------------------------- ### Embed Child Lexers Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Embeds a child lexer into a parent lexer using start and end rules. ```lua html:embed(css, css_start_rule, css_end_rule) html:embed(lex, php_start_rule, php_end_rule) -- from php lexer ``` -------------------------------- ### Embed child lexer into parent Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Registers the child lexer with the parent using start and end rules. ```lua lex:embed(css, css_start_rule, css_end_rule) ``` -------------------------------- ### Switching Buffers Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Demonstrates how to switch to a specific buffer or a relative buffer index. ```lua view:goto_buffer(_BUFFERS[1]) -- switch to first buffer view:goto_buffer(-1) -- switch to the buffer before the current one ``` -------------------------------- ### Initialize Lua Pattern Find Module Source: https://github.com/orbitalquark/textadept/wiki/lua-pattern-find Add this line to your init.lua file to load the module. ```lua require('lua-pattern-find') ``` -------------------------------- ### Define lfs.walk filters Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Examples of shell-style glob patterns used to filter files and directories during traversal. ```lua '*.lua' -- match all Lua files in the top-level directory '**/*.lua' -- match all Lua files in any directory {'**/*.{c,h}', '!build'} -- match all C source files except in the top-level build/ directory {'include/*', 'src/*'} -- match all immediate children of the 'include/' and 'src/' dirs {'include/**', 'src/**'} -- match everything in 'include/' and 'src/', including subdirectories ``` -------------------------------- ### Create and Manage Buffers in Textadept Source: https://context7.com/orbitalquark/textadept/llms.txt Learn how to create new buffers, open files, save changes, and close buffers. Use `buffer.new()` for a blank buffer and `io.open_file()` to load from disk. Saving can be done with `buffer:save()` or `buffer:save_as()`. Buffers can be closed with `buffer:close()`, optionally forcing without saving. ```lua -- Create a new buffer buffer.new() ``` ```lua -- Open a file into a new buffer io.open_file('/path/to/file.lua') ``` ```lua -- Save current buffer buffer:save() ``` ```lua -- Save buffer to a new file buffer:save_as('/path/to/newfile.lua') ``` ```lua -- Close current buffer (prompts if unsaved) buffer:close() ``` ```lua -- Close buffer without saving buffer:close(true) ``` -------------------------------- ### Find Indicator Boundary Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Retrieves the previous boundary position for a given indicator number starting from a specific position. ```lua buffer:indicator_start(indicator, pos) ``` -------------------------------- ### Initiate Textadept on Linux Source: https://github.com/orbitalquark/textadept/wiki/RelativePaths Command to launch Textadept on Linux using a relative path for the user directory. ```bash cd [somepath]/textadept ./app_3.7_beta_2/textadept -u ../data/ ``` -------------------------------- ### Connect Session Auto-load Event Source: https://github.com/orbitalquark/textadept/wiki/RelativePaths Registers an event handler to automatically load the session when Textadept starts, if enabled. ```lua events.connect('arg_none', function() if SAVE_ON_QUIT then load() end end) ``` -------------------------------- ### Initiate Textadept on Linux via Wine Source: https://github.com/orbitalquark/textadept/wiki/RelativePaths Command to launch the Windows binary of Textadept on Linux using Wine with a relative user directory path. ```bash wine ~/my-apps/textadept/app_3.7_beta_2/textadept.exe -u ../data/ ``` -------------------------------- ### Initialize common modules directory Source: https://github.com/orbitalquark/textadept/wiki/modules-common Place this code in ~/.textadept/modules/common/init.lua to iterate through and require all Lua files in the directory. ```lua local lfs = require 'lfs' for filename in lfs.dir(_USERHOME..'/modules/common/') do if filename:find('%.lua$') and filename ~= 'init.lua' then require('common.'..filename:match('^(.+)%.lua$')) end end ``` -------------------------------- ### Open Files and Projects via Command Line Source: https://github.com/orbitalquark/textadept/blob/default/docs/manual.md Launch Textadept and open specific files or project directories directly from the terminal. ```bash textadept /path/to/file1 ../relative/path/to/file2 textadept /path/to/project/ relative/path/to/file1 relative/file2 ``` -------------------------------- ### Map Buffer Positions to Styles Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Access `lexer.style_at` to get a read-only map of buffer positions to their string style names. ```lua lexer.style_at ``` -------------------------------- ### ui.dialogs.open Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Prompts the user to select a file from the filesystem. ```APIDOC ## ui.dialogs.open ### Description Prompts the user to select a file from the filesystem. ### Parameters #### Options Table - **title** (string) - Title of the dialog. - **dir** (string) - Directory to initially show. - **file** (string) - File to initially select. Requires `dir` to be set. - **multiple** (boolean) - Allow multiple file selection. Not supported in terminal version. - **only_dirs** (boolean) - Only allow selection of directories. ### Returns - filename or table of filenames (string or table) - The selected filename(s). - `nil` - If the user canceled the dialog. ### Usage Example ```lua ui.dialogs.open{title = 'Open File', dir = _HOME, multiple = true} ``` ``` -------------------------------- ### Initialize File Browser via Command Entry Source: https://github.com/orbitalquark/textadept/wiki/ta-filebrowser Use this command in the Textadept command entry to initialize the file browser for a specific directory. ```lua require('file_browser').init('/path/to/project') ``` -------------------------------- ### Define Line Comments Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Define line-style comments using lexer.to_eol. The second example shows how to handle line continuation characters. ```lua local shell_comment = lex:tag(lexer.COMMENT, lexer.to_eol('#')) ``` ```lua local c_line_comment = lex:tag(lexer.COMMENT, lexer.to_eol('//', true)) ``` -------------------------------- ### Open a file selection dialog Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Use ui.dialogs.open to prompt the user to select a file or directory. Options include setting the initial directory, pre-selecting a file, and allowing multiple selections or directory-only selection. ```lua ui.dialogs.open{title = 'Open File', dir = _HOME, multiple = true} ``` -------------------------------- ### Get Text Range from Buffer Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Use `lexer.text_range` to retrieve a specific portion of text from the buffer using its absolute position and length. ```lua lexer.text_range ``` -------------------------------- ### Configure Quick Open Limits and Filters in Textadept Source: https://github.com/orbitalquark/textadept/blob/default/docs/manual.md Customize the maximum number of files shown in the quick open dialog and define project-specific filters to include only certain directories. This is done by modifying `io.quick_open_max` and `io.quick_open_filters` in your `~/.textadept/init.lua`. ```lua io.quick_open_max = 10000 -- support huge projects io.quick_open_filters['/path/to/project'] = {'include/**', 'src/**'} -- only show these directories ``` -------------------------------- ### Manage Views and Buffers Source: https://context7.com/orbitalquark/textadept/llms.txt Methods for splitting views, switching buffers, and configuring display properties like wrapping and whitespace. ```lua -- Split view horizontally (top and bottom) view:split() -- Split view vertically (left and right) view:split(true) -- Unsplit current view view:unsplit() -- Get current view's buffer local buf = view.buffer -- Switch to another buffer in current view view:goto_buffer(_BUFFERS[1]) -- go to first buffer view:goto_buffer(-1) -- go to previous buffer view:goto_buffer(1) -- go to next buffer -- Access all views for i, v in ipairs(_VIEWS) do print('View', i, 'shows buffer:', v.buffer.filename) end -- Scroll view view:scroll_caret() -- scroll caret into view view:vertical_center_caret() -- center caret vertically view:line_scroll(0, 10) -- scroll 10 lines down view:scroll_to_start() -- scroll to start view:scroll_to_end() -- scroll to end -- First visible line print(view.first_visible_line) -- Lines visible on screen print(view.lines_on_screen) -- Zoom (GUI only) view:zoom_in() -- increase font size view:zoom_out() -- decrease font size view.zoom = 0 -- reset zoom -- Line wrapping view.wrap_mode = view.WRAP_WORD -- wrap at word boundaries view.wrap_mode = view.WRAP_CHAR -- wrap at character boundaries view.wrap_mode = view.WRAP_NONE -- no wrapping (default) -- View whitespace view.view_ws = view.WS_VISIBLEALWAYS -- show spaces and tabs view.view_ws = view.WS_INVISIBLE -- hide whitespace (default) -- Show line numbers view.margin_width_n[1] = 40 -- set margin 1 width (line numbers) -- Indentation guides (GUI only) view.indentation_guides = view.IV_LOOKBOTH ``` -------------------------------- ### Configure Project Run Commands with Custom Environment Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Map project root paths to run shell commands. Functions can return custom working directories and process environments, useful for setting up specific execution contexts. ```lua textadept.run.run_project_commands[_HOME] = function() local env = {TEXTADEPT_HOME = _HOME} for setting in os.spawn('env'):read('a'):gmatch('[^ ]+') do env[#env + 1] = setting end return _HOME .. '/build/textadept -f -n', '/tmp', env -- run test instance of Textadept end ``` -------------------------------- ### Word Boundary Detection Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Functions to find the start and end positions of words within the buffer, with options to control word character definition. ```APIDOC ## buffer:word_start_position ### Description Returns a word's start position. ### Method `buffer:word_start_position(pos, only_word_chars)` ### Parameters #### Path Parameters - **pos** (integer) - Position of the word. - **only_word_chars** (boolean) - If `true`, stops searching at the first non-word character to the left of *pos*. Otherwise, the first character to the left of *pos* sets the type of the search as word or non-word and the search stops at the first non-matching character. ### Request Example ```lua -- Consider the buffer text "word....word" buffer:word_start_position(3, true) --> 1 buffer:word_start_position(7, true) --> 7 buffer:word_start_position(7, false) --> 5 buffer:word_start_position(9, false) --> 5 buffer:word_start_position(9, true) --> 9 ``` ## buffer:word_end_position ### Description Returns a word's end position. ### Method `buffer:word_end_position(pos, only_word_chars)` ### Parameters #### Path Parameters - **pos** (integer) - Position of the word. - **only_word_chars** (boolean) - If `true`, stops searching at the first non-word character to the right of *pos*. Otherwise, the first character to the right of *pos* sets the type of the search as word or non-word and the search stops at the first non-matching character. ### Request Example ```lua -- Consider the buffer text "word....word" buffer:word_end_position(3, true) --> 5 buffer:word_end_position(5, true) --> 5 buffer:word_end_position(5, false) --> 9 buffer:word_end_position(7, true) --> 7 buffer:word_end_position(7, false) --> 9 ``` ``` -------------------------------- ### Initiate Textadept on Windows Source: https://github.com/orbitalquark/textadept/wiki/RelativePaths Command to launch Textadept on Windows using a relative path for the user directory. ```batch c:\my-apps\textadept\app_3.7_beta_2\textadept.exe -u ../data/ ``` -------------------------------- ### Replace Entry Text Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Gets or sets the text in the 'Replace' entry field. When searching in files, this represents the current file and directory filter. ```APIDOC ## `ui.find.replace_entry_text` ### Description The text in the "Replace" entry. When searching for text in a directory of files, this is the current file and directory filter. ``` -------------------------------- ### Configure themes and styles Source: https://github.com/orbitalquark/textadept/blob/default/docs/manual.md Set the editor theme and customize specific style attributes for languages like Java. ```lua if not CURSES then view:set_theme('light', {font = 'Monospace', size = 12}) -- You can alternatively use the following to keep the default theme: -- view:set_theme{font = 'Monospace', size = 12} end -- Color Java class names black instead of the default yellow. events.connect(events.LEXER_LOADED, function(name) if name ~= 'java' then return end local default_fore = view.style_fore[view.STYLE_DEFAULT] view.style_fore[buffer:style_of_name(lexer.CLASS)] = default_fore end) ``` -------------------------------- ### Match Typical Words Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Use `lexer.word` to match a standard word pattern, typically starting with a letter or underscore and followed by alphanumeric characters or underscores. ```lua lexer.word ``` -------------------------------- ### Create a Menu Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md The `ui.menu` function creates menus. It takes a table defining menu items, their IDs, and optional keycodes/modifiers. Use '&' for mnemonics in Qt. ```lua ui.menu{ {'_New', 1}, {'_Open', 2}, {''}, {'&Quit', 4} } ``` ```lua ui.menu{ {'_New', 1, string.byte('n'), view.MOD_CTRL} } -- 'Ctrl+N' ``` -------------------------------- ### Create Snippet with Default Placeholder Source: https://context7.com/orbitalquark/textadept/llms.txt Define a code snippet for a for loop with default values for the loop counter, start, and end, and a placeholder for the loop body. ```lua -- Snippet with default placeholder snippets['for'] = 'for ${1:i} = ${2:1}, ${3:10} do\n\t$0\nend' ``` -------------------------------- ### Navigate bookmarks with textadept.bookmarks.goto_mark Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Jumps to the next or previous bookmarked line in the current buffer. ```lua textadept.bookmarks.goto_mark(true) -- jump to the next bookmark textadept.bookmarks.goto_mark(false) -- jump to the previous bookmark ``` -------------------------------- ### Convert CamelCase to snake_case Source: https://github.com/orbitalquark/textadept/wiki/FunctionList Example of adding a custom function to convert selected text from CamelCase to snake_case. This requires the `addEntry` function from the `functionlist` module. ```lua local m_functionlist = _m.common.functionlist m_functionlist.addEntry("under", "Convets CamelCase to under_scores", function() buffer:replace_sel(buffer:get_sel_text():gsub("(%u)", function(s) return "_"..string.lower(s) end)) end ) ``` -------------------------------- ### Fetch Windows-Specific Dependencies Source: https://github.com/orbitalquark/textadept/blob/default/CMakeLists.txt Downloads and makes available pdcurses and libiconv for Windows builds. ```cmake if(WIN32) fetch(pdcurses https://prdownloads.sourceforge.net/pdcurses/PDCurses-3.9.zip) fetch(iconv https://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.17.tar.gz) FetchContent_MakeAvailable(pdcurses iconv) endif() ``` -------------------------------- ### lexer.add_fold_point API Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Adds a fold point to a lexer, defining how code blocks can be folded for better readability. Supports string-based or function-based definitions for start and end symbols. ```APIDOC ## lexer.add_fold_point ### Description Adds a fold point to a lexer. ### Method `lexer.add_fold_point(lexer, tag_name, start_symbol, end_symbol)` ### Parameters #### Path Parameters - **lexer** (Lexer) - The lexer to add a fold point to. - **tag_name** (string) - String tag name of fold point text. - **start_symbol** (string) - String fold point start text. - **end_symbol** (string or function) - Either string fold point end text, or a function that returns whether or not `start_symbol` is a beginning fold point (1), an ending fold point (-1), or not a fold point at all (0). If it is a function, it is passed the following arguments: - `text`: The text being processed for fold points. - `pos`: The position in `text` of the beginning of the line currently being processed. - `line`: The text of the line currently being processed. - `s`: The position of `start_symbol` in `line`. - `symbol`: `start_symbol` itself. ### Usage Examples ```lua lex:add_fold_point(lexer.OPERATOR, '{', '}') lex:add_fold_point(lexer.KEYWORD, 'if', 'end') lex:add_fold_point('custom', function(text, pos, line, s, symbol) ... end) ``` ``` -------------------------------- ### Accessing Textadept Views Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Get a specific view by its index or find the index of a view using the `_VIEWS` table. This allows programmatic access to different editor views. ```lua local view = _VIEWS[n] -- view at index n local i = _VIEWS[view] -- index of view in _VIEWS ``` -------------------------------- ### Open Files and Import Previous Session Source: https://github.com/orbitalquark/textadept/wiki/import-default-session Use the -s switch to open specified files in addition to files from the previous session. ```bash textadept -s session file1 file2 ... fileN ``` -------------------------------- ### Set Indicator Hover Foreground Color Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Customize the foreground color of an indicator when the mouse hovers over it or the caret is within it. This example sets the hover color for link indicators to red. ```lua view.indic_hover_fore[indic_link] = 0xFF0000 -- hovering over links colors them blue ``` -------------------------------- ### Load a module in init.lua Source: https://github.com/orbitalquark/textadept/blob/default/docs/manual.md Explicitly load a module and configure its settings within the user initialization file. ```lua local lsp = require('lsp') lsp.server_commands.cpp = 'clangd' ``` -------------------------------- ### Create Custom Text Ranges Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Use `lexer.range` to define patterns that match text between specified start and end markers. Supports single-line restriction, escape characters, and balanced delimiters. ```lua local dq_str_escapes = lexer.range('"') local dq_str_noescapes = lexer.range('"', false, false) local unbalanced_parens = lexer.range('(', ')') local balanced_parens = lexer.range('(', ')', false, false, true) ``` -------------------------------- ### Import Default Session in init.lua Source: https://github.com/orbitalquark/textadept/wiki/import-default-session Configure Textadept to import the previous session's files via the 'File > Import default session' menu item by adding this Lua code to your init.lua. ```lua local function import_default_session() io.close_all_buffers() textadept.session.load(_USERHOME..'/session') for i = 1, #arg do local filename = lfs.abspath(arg[i], arg[-1]) if lfs.attributes(filename) then -- not a switch io.open_file(filename) end end end local file_menu = textadept.menu.menubar[_L['File']] table.insert(file_menu, #file_menu - 2, {'Import Default Session', import_default_session}) ``` -------------------------------- ### Customize LEXER_LOADED Event Handling Source: https://github.com/orbitalquark/textadept/blob/default/docs/api.md Connect to the `events.LEXER_LOADED` event to perform actions after a language lexer is loaded. This example shows how to set Lua 5.1 keywords if the 'lua' lexer is loaded. ```lua events.connect(events.LEXER_LOADED, function(name) if name ~= 'lua' then return end -- Use Lua 5.1 keywords instead of Lua 5.2+ keywords. buffer.lexer:set_word_list(lexer.KEYWORD, { 'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'if', 'in', 'local', 'or', 'nil', 'not', 'repeat', 'return', 'then', 'true', 'until', 'while' }) end) ``` -------------------------------- ### Generate HTML Documentation Source: https://github.com/orbitalquark/textadept/blob/default/CMakeLists.txt Optional target to generate HTML documentation using Lua and bundle. ```cmake option(GENERATE_HTML "Generate HTML documentation in docs/" OFF) if(GENERATE_HTML) find_program(LUA lua REQUIRED) find_program(BUNDLE bundle REQUIRED) add_custom_target(html COMMAND ./gen_docs.sh WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/scripts) endif() ``` -------------------------------- ### Fatal Error if No Platform Found Source: https://github.com/orbitalquark/textadept/blob/default/CMakeLists.txt Checks if any UI platform (Qt, GTK3, GTK2, Curses) was successfully configured. Exits with an error if none are available. ```cmake if(NOT (QT OR GTK3 OR GTK2 OR CURSES)) message(FATAL_ERROR "No suitable platform found.") endif() ```