### Dialog Integration Example Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/widget-system.md Example demonstrating how to create, initialize, run, and clean up a simple dialog with basic button actions. ```c // Create a simple dialog with a button static cb_ret_t my_dialog_callback(Widget *w, Widget *sender, widget_msg_t msg, int parm, void *data) { WDialog *dlg = DIALOG(w); switch (msg) { case MSG_INIT: // Initialize dialog return MSG_HANDLED; case MSG_ACTION: // Handle actions switch (parm) { case B_ENTER: dlg->ret_value = B_ENTER; dlg_close(dlg); return MSG_HANDLED; case B_CANCEL: dlg->ret_value = B_CANCEL; dlg_close(dlg); return MSG_HANDLED; } break; case MSG_DESTROY: // Clean up return MSG_HANDLED; } return MSG_NOT_HANDLED; } // Create and run the dialog WDialog *dlg = dlg_create(TRUE, 5, 10, 15, 50, WPOS_CENTER, FALSE, NULL, my_dialog_callback, NULL, NULL, "My Title"); dlg_init(dlg); int result = dlg_run(dlg); dlg_run_done(dlg); widget_destroy(WIDGET(dlg)); ``` -------------------------------- ### Example mc_search_fn Implementation Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/search-system.md An example implementation of the `mc_search_fn` callback, demonstrating how to provide data from a buffer and handle end-of-data conditions. ```c typedef struct { const char *data; size_t len; } search_data_t; static mc_search_cbret_t my_search_fn(const void *user_data, off_t char_offset, int *current_char) { const search_data_t *sdata = (const search_data_t *)user_data; if (char_offset >= (off_t)sdata->len) { return MC_SEARCH_CB_NOTFOUND; } *current_char = (unsigned char)sdata->data[char_offset]; return MC_SEARCH_CB_OK; } ``` -------------------------------- ### Register a File Watcher Callback Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/event-system.md Example of setting up a file watcher by registering a callback for the 'file_changed' event using mc_event_add(). ```c // Component A - File watcher void setup_file_watcher(void) { GError *error = NULL; if (!mc_event_add("file_manager", "file_changed", on_watched_file_changed, (gpointer)current_file, &error)) { g_error("Failed to register watcher: %s", error->message); } } ``` -------------------------------- ### Example of mc_build_filename() usage Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/utilities.md Demonstrates how to use mc_build_filename to construct a path string. The resulting path is printed and then freed using g_free. ```c char *path = mc_build_filename("/home", "user", "documents", "file.txt", NULL); printf("Path: %s\n", path); g_free(path); ``` -------------------------------- ### Create and Run a Dialog Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/types.md Illustrates the process of creating a dialog window, setting its position, initializing it, running it to get user input, and then cleaning up resources. ```c // Create dialog WDialog *dlg = dlg_create(TRUE, 5, 10, 20, 60, WPOS_CENTER, FALSE, NULL, my_callback, NULL, NULL, "My Dialog"); // Set position dlg->group.widget.rect.y = 5; dlg->group.widget.rect.x = 10; // Run dialog dlg_init(dlg); int ret = dlg_run(dlg); dlg_run_done(dlg); widget_destroy(WIDGET(dlg)); ``` -------------------------------- ### Keymap Configuration File Format Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/keybindings.md Keybindings are stored in ~/.config/mc/mc.keymap using INI format. This example shows how to map keys to commands. ```ini [filemanager] # Key sequence = Command code or name F3 = view F4 = edit Ctrl+x,f = find ``` -------------------------------- ### Complete Configuration API Example Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/configuration.md Demonstrates initializing configuration paths, loading a configuration file, reading string, boolean, and integer values, modifying boolean and integer values, saving the configuration, and cleaning up resources. ```c #include "lib/mcconfig.h" int main(void) { // Initialize paths GError *error = NULL; mc_config_init_config_paths(&error); if (error != NULL) { g_warning("Failed to init paths: %s", error->message); g_error_free(error); } // Load configuration mc_config_t *config = mc_config_init( mc_config_get_full_path("mc.conf"), FALSE); if (config == NULL) { g_warning("Failed to load config"); return 1; } // Read values gchar *editor = mc_config_get_string(config, CONFIG_MISC_SECTION, "editor", "vi"); gboolean use_colors = mc_config_get_bool(config, CONFIG_APP_SECTION, "use_colors", TRUE); int tab_width = mc_config_get_int(config, CONFIG_MISC_SECTION, "tab_width", 8); // Modify values mc_config_set_bool(config, CONFIG_MISC_SECTION, "use_tabs", FALSE); mc_config_set_int(config, CONFIG_MISC_SECTION, "tab_width", 4); // Save if (!mc_config_save_file(config, &error)) { g_warning("Failed to save: %s", error->message); g_error_free(error); } // Cleanup g_free(editor); mc_config_deinit(config); mc_config_deinit_config_paths(); return 0; } ``` -------------------------------- ### Get Full Path to Configuration File Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/configuration.md Constructs and returns the full path to a specified configuration file. The caller is responsible for freeing the returned string. ```c char *mc_config_get_full_path(const char *config_name); ``` -------------------------------- ### Modify File and Notify Event Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/event-system.md Example of modifying a file and then triggering the 'file_changed' event using mc_event_raise() to notify other components. ```c // Component B - File modifier void modify_file(const char *filename) { // Modify the file... // Notify all interested components mc_event_raise("file_manager", "file_changed", (gpointer)filename); } ``` -------------------------------- ### Example: Regex Replace with Backreferences Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/search-system.md Demonstrates replacing text using regex capture groups. Ensure the mc_search object is prepared and a match is found before calling mc_search_replace. ```c // Create search for regex pattern with capture groups mc_search_t *search = mc_search_new("(\w+)\s+(\w+)", "UTF-8"); search->search_type = MC_SEARCH_T_REGEX; mc_search_prepare(search); // Search in text const char *text = "Hello World"; gsize match_len; if (mc_search_run(search, &text, 0, strlen(text), &match_len)) { // Replace first group + space + second group with reversed order gchar *result = mc_search_replace(search, text, "\2 \1"); printf("Result: %s\n", result); // Output: "World Hello" g_free(result); } ``` -------------------------------- ### Open Directory via VFS Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/vfs-core.md Opens a directory for enumeration using the VFS abstraction layer. Returns a DIR handle or NULL on error. The example shows iterating through directory entries. ```c DIR *mc_opendir(const vfs_path_t *vpath); ``` ```c vfs_path_t *path = vfs_path_from_str("/path/to/dir"); DIR *dir = mc_opendir(path); if (dir != NULL) { struct vfs_dirent *entry; while ((entry = mc_readdir(dir)) != NULL) { printf("File: %s\n", entry->d_name); } mc_closedir(dir); } vfs_path_free(path, TRUE); ``` -------------------------------- ### Get Configuration Keys Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/configuration.md Retrieves all parameter names within a specified configuration group. The returned array must be freed using g_strfreev(). ```c gchar **mc_config_get_keys(const mc_config_t *mc_config, const gchar *group, gsize *len); ``` -------------------------------- ### Get User Home Directory Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/configuration.md Retrieves the path to the user's home directory. The returned pointer points to a static buffer and should not be modified or freed. ```c MC_MOCKABLE const char *mc_config_get_home_dir(void); ``` -------------------------------- ### Callback for Watched File Changes Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/event-system.md Example of a callback function that handles the 'file_changed' event, checks if the changed file is the one being watched, and reloads it if necessary. ```c // Component A - Callback static gboolean on_watched_file_changed(const gchar *group, const gchar *event, gpointer user_data, gpointer event_data) { const char *watched_file = (const char *)user_data; const char *changed_file = (const char *)event_data; if (g_strcmp0(watched_file, changed_file) == 0) { printf("Watched file was changed: %s\n", changed_file); reload_file(); } return TRUE; // Continue with other callbacks } ``` -------------------------------- ### Getting Help Context Hotkey Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/keybindings.md Retrieve the key binding for a specific command from a dialog's keymap using get_shortcut_command. Prints the shortcut if found. ```c // Get the key binding for a command from the dialog's keymap char *shortcut = get_shortcut_command(CK_Help, dialog_map); if (shortcut != NULL) { printf("Help key: %s\n", shortcut); } ``` -------------------------------- ### Create and Use a File Entry Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/types.md Demonstrates how to create a file entry, set its properties, retrieve file statistics, and check if it's a directory. Remember to free allocated memory. ```c file_entry_t *entry = g_new0(file_entry_t, 1); entry->fname = g_string_new("myfile.txt"); entry->f.marked = 0; entry->f.link_to_dir = 0; entry->f.stale_link = 0; // Get file stats stat(entry->fname->str, &entry->st); // Check if it's a directory if (S_ISDIR(entry->st.st_mode)) { printf("%s is a directory\n", entry->fname->str); } // Free g_string_free(entry->fname, TRUE); g_free(entry); ``` -------------------------------- ### Get File Metadata (fstat) Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/vfs-core.md Retrieves metadata for an already opened file descriptor. This is useful for getting information about a file after it has been opened using mc_open(). ```c int mc_fstat(int fd, struct stat *buf); ``` -------------------------------- ### Create a Simple Dialog Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/integration-guide.md Demonstrates how to create and display a basic dialog with ENTER and CANCEL buttons. The callback handles user actions. ```c #include "lib/widget.h" #include "lib/tty/tty.h" #include static cb_ret_t dialog_callback(Widget *w, Widget *sender, widget_msg_t msg, int parm, void *data) { WDialog *dlg = DIALOG(w); switch (msg) { case MSG_INIT: return MSG_HANDLED; case MSG_ACTION: if (parm == B_ENTER) { dlg->ret_value = B_ENTER; dlg_close(dlg); } else if (parm == B_CANCEL) { dlg->ret_value = B_CANCEL; dlg_close(dlg); } return MSG_HANDLED; default: return MSG_NOT_HANDLED; } } int main(void) { // Initialize TTY tty_init(TRUE); // Create dialog WDialog *dlg = dlg_create(TRUE, 5, 10, 15, 50, WPOS_CENTER, FALSE, NULL, dialog_callback, NULL, NULL, "Test Dialog"); // Run dialog dlg_init(dlg); int result = dlg_run(dlg); dlg_run_done(dlg); printf("Result: %d\n", result); // Cleanup widget_destroy(WIDGET(dlg)); tty_done(); return 0; } ``` -------------------------------- ### mc_fstat Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/vfs-core.md Retrieves metadata for an already open file descriptor. This is useful for getting information about a file that has been accessed via `mc_open()`. ```APIDOC ## mc_fstat ### Description Get metadata for an open file descriptor. ### Signature ```c int mc_fstat(int fd, struct stat *buf); ``` ### Parameters #### Path Parameters - **fd** (int) - File descriptor from mc_open() - **buf** (struct stat *) - Buffer for stat information ### Returns 0 on success, -1 on error ``` -------------------------------- ### Initialize Configuration Paths Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/configuration.md Initializes the configuration paths for the user. This function may set up default paths or load user-specific configurations. An error parameter is provided for reporting issues. ```c void mc_config_init_config_paths(GError **error); ``` -------------------------------- ### Get MC Cache Directory Path Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/configuration.md Retrieves the path to the Midnight Commander cache directory. This is usually located in ~/.cache/mc/. ```c const char *mc_config_get_cache_path(void); ``` -------------------------------- ### mc_config_init_config_paths() Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/configuration.md Initializes the configuration paths for the user. This is a necessary step before accessing configuration files. ```APIDOC ## mc_config_init_config_paths() ### Description Initialize configuration paths for the user. ### Method void ### Parameters #### Path Parameters - **error** (GError **) - Error return parameter ``` -------------------------------- ### Get MC Configuration Directory Path Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/configuration.md Retrieves the path to the Midnight Commander configuration directory. This is typically located in ~/.config/mc/. ```c const char *mc_config_get_path(void); ``` -------------------------------- ### VFS Path Handling: Correct vs. Incorrect Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/integration-guide.md Illustrates the correct way to create and free vfs_path_t objects to prevent memory leaks, contrasting it with the incorrect approach. ```c // CORRECT: Create and destroy vfs_path_t vfs_path_t *path = vfs_path_from_str("/path"); // ... use path ... vfs_path_free(path, TRUE); // TRUE means free contents // WRONG: Forgetting to free vfs_path_t *path = vfs_path_from_str("/path"); // ... path leak! ... ``` -------------------------------- ### mc_config_init() Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/configuration.md Initializes and loads a configuration file. It takes the full path to the configuration file and a boolean indicating whether to use system-wide defaults. ```APIDOC ## mc_config_init() ### Description Loads a configuration file. ### Parameters #### Path Parameters - **config_file** (const char *) - Required - Full path to the configuration file. - **use_system_defaults** (boolean) - Required - Whether to use system-wide defaults. ### Returns A pointer to the loaded configuration structure (mc_config_t *), or NULL if loading fails. ``` -------------------------------- ### Get Pending VFS Timeouts Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/vfs-core.md Returns the number of pending VFS timeouts in milliseconds. This can be used to monitor the VFS timeout queue. ```c int vfs_timeouts(void); ``` -------------------------------- ### Get Current VFS Directory (vfs_path_t) Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/vfs-core.md Retrieves the current VFS directory as a vfs_path_t object. This provides a structured representation of the path. ```c const vfs_path_t *vfs_get_raw_current_dir(void); ``` -------------------------------- ### Get Basename of a Path Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/utilities.md Extracts the last component of a file path. The returned pointer is part of the input string and does not require deallocation. ```c const char *x_basename(const char *fname); ``` ```c printf("Base: %s\n", x_basename("/home/user/file.txt")); // Output: "file.txt" ``` -------------------------------- ### Initialize Configuration Handle Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/configuration.md Initializes a configuration file handle. Use NULL for ini_path to create an in-memory configuration. Set read_only to TRUE to prevent modifications. ```c mc_config_t *mc_config_init(const gchar *ini_path, gboolean read_only); ``` ```c mc_config_t *config = mc_config_init("/home/user/.config/mc/mc.conf", FALSE); if (config == NULL) { g_warning("Failed to load configuration"); } ``` -------------------------------- ### Normalize, Expand, and Extract Path Components Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/integration-guide.md Demonstrates normalizing, expanding home directory, and extracting basename and extension from a given path. Requires libutil.h. ```c #include "lib/util.h" void process_path(const char *path) { char normalized[PATH_MAX]; g_strlcpy(normalized, path, sizeof(normalized)); // Normalize path canonicalize_pathname_custom(normalized, CANON_PATH_ALL); printf("Normalized: %s\n", normalized); // Expand home directory char *expanded = tilde_expand(normalized); printf("Expanded: %s\n", expanded); g_free(expanded); // Get basename printf("Basename: %s\n", x_basename(path)); // Get extension printf("Extension: %s\n", extension(path)); } ``` -------------------------------- ### Get Current VFS Directory (Static) Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/vfs-core.md Retrieves the current VFS directory path as a pointer to a static, internal buffer. Do not modify this buffer. ```c const char *vfs_get_current_dir(void); ``` -------------------------------- ### Get MC Data Directory Path Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/configuration.md Retrieves the path to the Midnight Commander data directory. This directory is used for storing application data. ```c const char *mc_config_get_data_path(void); ``` -------------------------------- ### Module Initialization Order Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/integration-guide.md Illustrates the correct sequence for initializing multiple Midnight Commander modules in a complete application. Proper order is crucial for dependencies. ```c #include "lib/global.h" #include "lib/vfs/vfs.h" #include "lib/event.h" #include "lib/mcconfig.h" #include "lib/tty/tty.h" #include "lib/widget.h" int main(int argc, char *argv[]) { GError *error = NULL; // 1. TTY/Terminal initialization tty_init(TRUE); // 2. VFS system vfs_init(); vfs_setup_work_dir(); // 3. Event system if (!mc_event_init(&error)) { g_warning("Event init failed: %s", error->message); g_error_free(error); } // 4. Configuration paths mc_config_init_config_paths(&error); // 5. Load configuration // ... load config ... // 6. Shell detection mc_shell_init(); // 7. Application main loop // ... // Shutdown in reverse order mc_shell_deinit(); mc_config_deinit_config_paths(); mc_event_deinit(&error); vfs_shut(); tty_done(); return 0; } ``` -------------------------------- ### Get Username from UID Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/utilities.md Retrieves the username associated with a given User ID (UID). Returns a pointer to a static buffer containing the username. ```c const char *get_owner(uid_t uid); ``` -------------------------------- ### Module Dependency Graph Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/GETTING-STARTED.md Illustrates the hierarchical and system dependencies within the Midnight Commander. Follow this order for initialization. ```text TTY/Terminal ↓ VFS System ─→ Utilities ↓ Event System ─→ Widgets ─→ Dialog System ↓ Configuration ↓ Search System ↓ Keybindings (used by widgets) ``` -------------------------------- ### Create Directory Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/vfs-core.md Creates a new directory at the specified VFS path. The mode parameter defines the directory's permissions. ```c int mc_mkdir(const vfs_path_t *vpath, mode_t mode); ``` -------------------------------- ### Get File Extension Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/utilities.md Retrieves the file extension from a given path, including the leading dot. Returns an empty string if no extension is found. ```c const char *extension(const char *path); ``` ```c printf("Extension: %s\n", extension("document.pdf")); // Output: ".pdf" ``` -------------------------------- ### dlg_init() Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/widget-system.md Initializes a dialog box before it is run. This prepares the dialog for user interaction. ```APIDOC ## dlg_init() ### Description Initialize a dialog before running it. ### Parameters #### Path Parameters - **h** (WDialog *) - Required - Dialog to initialize ``` -------------------------------- ### Initialize Event System with Error Handling Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/event-system.md Initializes the event system and checks for errors. Ensure to free the GError structure upon completion. ```c GError *error = NULL; if (!mc_event_init(&error)) { if (error->code == SOME_ERROR_CODE) { g_warning("Specific error: %s", error->message); } g_error_free(error); } ``` -------------------------------- ### Get VFS File Class Flags Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/vfs-core.md Retrieves the flags associated with the VFS class for a given file path. The flags are defined in the vfs_flags_t enum. ```c vfs_flags_t vfs_file_class_flags(const vfs_path_t *vpath); ``` -------------------------------- ### Compile C Application with MC Library Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/integration-guide.md Link your C application against the Midnight Commander library using pkg-config or manual flags. Ensure GLib development files are also included. ```bash # Link against mc library gcc -o myapp myapp.c `pkg-config --cflags --libs glib-2.0` -lmc # Or manually gcc -o myapp myapp.c -I/usr/include/mc -L/usr/lib -lmc -lglib-2.0 ``` -------------------------------- ### Get File Metadata (lstat) Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/vfs-core.md Retrieves file metadata without following symbolic links. Use this when you need information about the link itself, not the file it points to. ```c MC_MOCKABLE int mc_lstat(const vfs_path_t *vpath, struct stat *buf); ``` -------------------------------- ### Use Events for Component Communication Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/integration-guide.md Shows how to initialize the event system, register a callback for a specific event, and trigger that event. Used for inter-component communication. ```c #include "lib/event.h" #include static gboolean on_file_changed(const gchar *group, const gchar *event, gpointer user_data, gpointer event_data) { const char *filename = (const char *)event_data; printf("File changed: %s\n", filename); return TRUE; } int main(void) { GError *error = NULL; // Initialize event system if (!mc_event_init(&error)) { g_warning("Failed to init events: %s", error->message); return 1; } // Register callback if (!mc_event_add("file_manager", "file_changed", on_file_changed, NULL, &error)) { g_warning("Failed to register: %s", error->message); return 1; } // Trigger event mc_event_raise("file_manager", "file_changed", (gpointer)"myfile.txt"); // Cleanup mc_event_del("file_manager", "file_changed", on_file_changed, NULL); GError *shutdown_error = NULL; mc_event_deinit(&shutdown_error); return 0; } ``` -------------------------------- ### GLib Memory Allocation and Freeing Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/integration-guide.md Illustrates common memory allocation and freeing patterns using GLib functions like g_strdup, g_malloc, g_free, and GString. Requires lib/global.h. ```c #include "lib/global.h" // Includes glib.h // Allocation gchar *str = g_strdup("hello"); // Like strdup gchar *str2 = g_strndup(str, 3); // First N chars void *ptr = g_malloc(size); // Like malloc void *ptr2 = g_malloc0(size); // Like calloc void *ptr3 = g_realloc(ptr, new_size); // Like realloc GString *gstr = g_string_new("hello"); // Dynamic string // Freeing g_free(str); // Free single alloc g_strfreev(array_of_strings); // Free string array g_string_free(gstr, TRUE); // Free GString (TRUE=free content) ``` -------------------------------- ### mc_config_init_config_paths() Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/configuration.md Initializes the configuration paths used by Midnight Commander. This function should be called before attempting to load or access configuration files. ```APIDOC ## mc_config_init_config_paths() ### Description Initializes the configuration paths. ### Returns void ``` -------------------------------- ### VFS Initialization and Shutdown Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/vfs-core.md Functions to initialize and shut down the Virtual File System (VFS) system. `vfs_init()` must be called before any VFS operations, and `vfs_shut()` should be called to free resources. ```APIDOC ## vfs_init() ### Description Initializes the VFS system. Must be called before any VFS operations. ### Function Signature ```c void vfs_init(void); ``` ## vfs_shut() ### Description Shuts down the VFS system and frees all resources. ### Function Signature ```c void vfs_shut(void); ``` ``` -------------------------------- ### Get Current VFS Directory (Allocated) Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/vfs-core.md Retrieves the current VFS directory path as a newly allocated string. The caller is responsible for freeing the returned string. ```c char *vfs_get_current_dir_n(void); ``` -------------------------------- ### mc_util_make_backup_if_possible(), mc_util_restore_from_backup_if_possible(), mc_util_unlink_backup_if_possible() Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/utilities.md Provides functions for managing backup files. `mc_util_make_backup_if_possible` creates a backup, `mc_util_restore_from_backup_if_possible` restores from a backup, and `mc_util_unlink_backup_if_possible` deletes a backup file. ```APIDOC ## Backup Operations ### mc_util_make_backup_if_possible() #### Description Creates a backup copy of a specified file if possible. The backup file will have the original filename appended with a given suffix. #### Parameters - **file_name** (const char *) - The path to the file that needs to be backed up. - **backup_suffix** (const char *) - The suffix to append to the original filename to create the backup file name (e.g., ".bak"). #### Returns - **gboolean** - TRUE if the backup was created successfully, FALSE otherwise. ### mc_util_restore_from_backup_if_possible() #### Description Restores a file from its backup copy if the backup exists. The original file is overwritten with the content of the backup file. #### Parameters - **file_name** (const char *) - The path to the file to restore. - **backup_suffix** (const char *) - The suffix used to identify the backup file. #### Returns - **gboolean** - TRUE if the file was restored successfully, FALSE otherwise. ### mc_util_unlink_backup_if_possible() #### Description Deletes the backup file associated with a given original file name and backup suffix. #### Parameters - **file_name** (const char *) - The original filename. - **backup_suffix** (const char *) - The suffix of the backup file to delete. #### Returns - **gboolean** - TRUE if the backup file was deleted successfully, FALSE otherwise. ``` -------------------------------- ### Initialize Event System Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/event-system.md Initializes the event system. Call this before registering or triggering any events. Handles error reporting via a GError pointer. ```c gboolean mc_event_init(GError **mcerror); ``` ```c GError *error = NULL; if (!mc_event_init(&error)) { g_warning("Failed to initialize events: %s", error->message); g_error_free(error); } ``` -------------------------------- ### Get Group Name from GID Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/utilities.md Retrieves the group name associated with a given Group ID (GID). Returns a pointer to a static buffer containing the group name. ```c const char *get_group(gid_t gid); ``` -------------------------------- ### Execute Search with Callback Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/search-system.md Runs the prepared search operation on a specified range of data, using a callback function to provide the data. Returns TRUE if a match is found. ```c gboolean mc_search_run(mc_search_t *mc_search, const void *user_data, off_t start_search, off_t end_search, gsize *match_len); ``` ```c const char *text = "Hello world"; search_data_t data = { text, strlen(text) }; gsize match_len = 0; if (mc_search_run(search, &data, 0, strlen(text), &match_len)) { printf("Found match of length %zu\n", match_len); } ``` -------------------------------- ### Get File Statistics using MC VFS Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/integration-guide.md Retrieve file metadata such as size and permissions using `mc_stat` with the MC VFS. Handles errors by printing to stderr. ```c #include "lib/vfs/vfs.h" #include #include void show_file_info(const char *path) { vfs_path_t *vpath = vfs_path_from_str(path); struct stat buf; if (mc_stat(vpath, &buf) == 0) { printf("Size: %lld bytes\n", (long long)buf.st_size); printf("Permissions: %o\n", buf.st_mode & 0777); printf("Owner UID: %d\n", buf.st_uid); } else { perror("stat failed"); } vfs_path_free(vpath, TRUE); } // Usage int main(void) { vfs_init(); show_file_info("/etc/passwd"); vfs_shut(); return 0; } ``` -------------------------------- ### Initialize and run a dialog Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/widget-system.md Before running a dialog, initialize it with dlg_init. After dlg_run completes, call dlg_run_done for cleanup. dlg_run returns a status code indicating user action. ```c void dlg_init(WDialog *h); ``` ```c int dlg_run(WDialog *d); ``` ```c void dlg_run_done(WDialog *h); ``` ```c dlg_init(dlg); int result = dlg_run(dlg); if (result == B_ENTER) { // User clicked OK } dlg_run_done(dlg); ``` -------------------------------- ### Get File Extension for Compression Type Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/utilities.md Returns the standard file extension (e.g., ".gz") for a given compression type. The input is an integer representing the compression type. ```c const char *decompress_extension(int type); ``` -------------------------------- ### my_system() Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/utilities.md Executes a shell command with specified flags. It allows for internal execution, execution as a shell command, or hiding output. ```APIDOC ## my_system() ### Description Execute a shell command. ### Parameters #### Path Parameters - **flags** (int) - Required - Flags (EXECUTE_INTERNAL, EXECUTE_AS_SHELL, EXECUTE_HIDE) - **shell** (const char *) - Required - Shell to use (e.g., "/bin/sh") - **command** (const char *) - Required - Command to execute ### Returns Exit status of command ### Flags - `EXECUTE_INTERNAL` — Use internal execution - `EXECUTE_AS_SHELL` — Execute as shell command - `EXECUTE_HIDE` — Hide output ``` -------------------------------- ### my_systemv() Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/utilities.md Executes a command using an argument vector. The argument vector must be NULL-terminated. ```APIDOC ## my_systemv() ### Description Execute a command with argument vector. ### Parameters #### Path Parameters - **command** (const char *) - Required - Command path - **argv** (char *const []) - Required - Arguments (NULL-terminated) ### Returns Exit status ``` -------------------------------- ### Get Full VFS Path to Configuration File Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/configuration.md Retrieves the full Virtual File System (VFS) path for a given configuration file name. The returned path must be freed by the caller. ```c vfs_path_t *mc_config_get_full_vpath(const char *config_name); ``` -------------------------------- ### Get File Metadata Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/vfs-core.md Retrieves file metadata (like size, permissions, timestamps) using the VFS abstraction. This function follows symbolic links. Returns 0 on success, -1 on error. ```c MC_MOCKABLE int mc_stat(const vfs_path_t *vpath, struct stat *buf); ``` -------------------------------- ### my_systeml() Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/utilities.md Executes a command with a variable number of NULL-terminated arguments. It takes execution flags and the shell path as parameters. ```APIDOC ## my_systeml() ### Description Execute a command with variadic arguments (NULL-terminated). ### Parameters #### Path Parameters - **flags** (int) - Required - Execution flags - **shell** (const char *) - Required - Shell path - **...** (char *) - Required - Command and arguments (NULL-terminated) ### Returns Exit status ### Example ```c int status = my_systeml(EXECUTE_AS_SHELL, "/bin/bash", "ls", "-la", "/tmp", NULL); ``` ``` -------------------------------- ### Create File Backup Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/utilities.md Creates a backup copy of a specified file using a given suffix. Returns TRUE if the backup was successful, FALSE otherwise. ```c gboolean mc_util_make_backup_if_possible(const char *file_name, const char *backup_suffix); ``` -------------------------------- ### Get All Group Names Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/configuration.md Retrieves an array of all group (section) names present in the configuration. The number of groups is returned via the 'len' parameter. The returned array must be freed using g_strfreev(). ```c gchar **mc_config_get_groups(const mc_config_t *mc_config, gsize *len); ``` -------------------------------- ### mc_config_init Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/configuration.md Initializes a configuration file handle. It can create an in-memory configuration or open an existing file. The `read_only` flag prevents modifications. ```APIDOC ## mc_config_init ### Description Initialize a configuration file handle. Can create an in-memory configuration or open an existing file. The `read_only` flag prevents modifications. ### Method ```c mc_config_t *mc_config_init(const gchar *ini_path, gboolean read_only); ``` ### Parameters #### Path Parameters - **ini_path** (const gchar *) - Required - Path to INI file (NULL to create in-memory only) - **read_only** (gboolean) - Required - Prevent modifications if TRUE ### Returns New mc_config_t handle on success, NULL on error ### Example ```c mc_config_t *config = mc_config_init("/home/user/.config/mc/mc.conf", FALSE); if (config == NULL) { g_warning("Failed to load configuration"); } ``` ``` -------------------------------- ### List Directory Contents using MC VFS Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/integration-guide.md Use the MC Virtual File System (VFS) to open a directory and iterate through its entries. Remember to initialize and shut down the VFS. ```c #include "lib/vfs/vfs.h" #include void list_directory(const char *path) { vfs_path_t *vpath = vfs_path_from_str(path); DIR *dir = mc_opendir(vpath); if (dir != NULL) { struct vfs_dirent *entry; while ((entry = mc_readdir(dir)) != NULL) { printf("%s\n", entry->d_name); } mc_closedir(dir); } vfs_path_free(vpath, TRUE); } // Usage int main(void) { vfs_init(); list_directory("/home/user"); vfs_shut(); return 0; } ``` -------------------------------- ### Docker Wrapper for Transifex Client Source: https://github.com/midnightcommander/mc/blob/master/maint/sync-transifex/README.md This shell script acts as a wrapper to run the Transifex client (tx) inside a Docker container. It sets up necessary environment variables and mounts volumes for configuration, code, and certificates. Use this to ensure a consistent execution environment for Transifex commands. ```shell #!/bin/sh touch ~/.transifexrc export XUID=$(id -u) export XGID=$(id -g) docker run \ --rm -i \ --user $XUID:$XGID \ --volume="/etc/group:/etc/group:ro" \ --volume="/etc/passwd:/etc/passwd:ro" \ --volume="/etc/shadow:/etc/shadow:ro" \ --volume $(pwd):/app \ --volume ~/.transifexrc:/.transifexrc \ --volume /etc/ssl/certs/ca-certificates.crt:/etc/ssl/certs/ca-certificates.crt \ transifex/txcli \ --root-config /.transifexrc \ "$@" ``` -------------------------------- ### load_mc_home_file() Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/utilities.md Loads a file from the Midnight Commander home directory. It returns the file contents and optionally provides the fully allocated path and file size. Both the path and contents must be freed by the caller. ```APIDOC ## load_mc_home_file() ### Description Load a file from the MC home directory. ### Parameters #### Path Parameters - **from** (const char *) - Required - Base directory - **filename** (const char *) - Required - Filename to load - **allocated_filename** (char **) - Output - full path (must be freed) - **length** (size_t *) - Output - file size ### Returns File contents (must be freed) ``` -------------------------------- ### Enable VFS Debug Logging Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/integration-guide.md Demonstrates how to enable and disable VFS debug logging by setting and closing a log file. ```c // VFS debug logging #include "lib/vfs/vfs.h" vfs_class->logfile = fopen("vfs_debug.log", "w"); // ... VFS operations are logged ... fclose(vfs_class->logfile); ``` -------------------------------- ### VFS Initialization Function Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/vfs-core.md Initializes the Virtual File System (VFS) system. This function must be called before any other VFS operations can be performed. ```c void vfs_init(void); ``` -------------------------------- ### Open File via VFS Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/vfs-core.md Opens a file using the VFS abstraction layer. Supports standard open flags and a variadic argument for file creation mode. Returns a file descriptor or -1 on error. ```c int mc_open(const vfs_path_t *vpath, int flags, ...); ``` ```c vfs_path_t *path = vfs_path_from_str("/path/to/file"); int fd = mc_open(path, O_RDONLY); if (fd != -1) { // File opened mc_close(fd); } vfs_path_free(path, TRUE); ``` -------------------------------- ### Set String List Configuration Parameter Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/configuration.md Use this function to write a list of strings to a configuration parameter. Provide the configuration handle, group, parameter name, an array of strings, and the array's length. ```c void mc_config_set_string_list(mc_config_t *mc_config, const gchar *group, const gchar *param, const gchar *const value[], gsize length); ``` -------------------------------- ### mc_event_init Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/event-system.md Initializes the event system. This must be called before any other event system functions. ```APIDOC ## mc_event_init ### Description Initialize the event system. ### Method gboolean mc_event_init(GError **mcerror); ### Parameters #### Path Parameters * **mcerror** (GError **) - Error return parameter ### Response #### Success Response (TRUE) TRUE on success #### Error Response (FALSE) FALSE on error ### Example ```c GError *error = NULL; if (!mc_event_init(&error)) { g_warning("Failed to initialize events: %s", error->message); g_error_free(error); } ``` ``` -------------------------------- ### Register VFS Filesystem Class Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/vfs-core.md Registers a filesystem plugin with the VFS system. Use this to add custom filesystem support. Returns TRUE on success, FALSE if already registered. ```c gboolean vfs_register_class(struct vfs_class *vfs); ``` ```c if (vfs_register_class(&ftp_class)) { // FTP filesystem registered successfully } ``` -------------------------------- ### Using Static Buffers Safely Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/integration-guide.md Demonstrates the danger of using static buffer return values multiple times and the correct method of copying the data if needed. ```c // WRONG: Using same buffer twice printf("%s %s\n", path_trunc(path1, 30), path_trunc(path2, 30)); // path2 may be corrupted // CORRECT: Copy if needed const char *trunc1 = path_trunc(path1, 30); gchar *copy1 = g_strdup(trunc1); const char *trunc2 = path_trunc(path2, 30); printf("%s %s\n", copy1, trunc2); g_free(copy1); ``` -------------------------------- ### Widget State and Option Macros Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/widget-system.md Convenience macros for setting widget options like cursor visibility and hotkey enablement, as well as widget states such as idle or disabled. ```c #define widget_want_cursor(w, i) widget_set_options(w, WOP_WANT_CURSOR, i) #define widget_want_hotkey(w, i) widget_set_options(w, WOP_WANT_HOTKEY, i) #define widget_want_tab(w, i) widget_set_options(w, WOP_WANT_TAB, i) #define widget_idle(w, i) widget_set_state(w, WST_IDLE, i) #define widget_disable(w, i) widget_set_state(w, WST_DISABLED, i) ``` -------------------------------- ### Specify UTF-8 for Search Objects Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/integration-guide.md Shows the correct way to initialize a search object by specifying UTF-8 encoding for patterns. ```c // Unless you have a specific reason, use UTF-8 mc_search_t *search = mc_search_new(pattern, "UTF-8"); ``` -------------------------------- ### init_uid_gid_cache(), get_owner(), get_group() Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/utilities.md Provides utilities for user and group information. `init_uid_gid_cache` initializes the cache for UID/GID to name conversions, `get_owner` retrieves the username for a given UID, and `get_group` retrieves the group name for a given GID. ```APIDOC ## User and Group Information ### init_uid_gid_cache() #### Description Initializes the cache used for converting User IDs (UID) and Group IDs (GID) to their corresponding names. ### get_owner() #### Description Retrieves the username associated with a given User ID (UID). #### Parameters - **uid** (uid_t) - The User ID for which to get the username. #### Returns - **const char *** - A pointer to the username string. This is a static buffer. ### get_group() #### Description Retrieves the group name associated with a given Group ID (GID). #### Parameters - **gid** (gid_t) - The Group ID for which to get the group name. #### Returns - **const char *** - A pointer to the group name string. This is a static buffer. ``` -------------------------------- ### Expand Tilde to Home Directory Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/utilities.md Expands a tilde character (~) at the beginning of a path to the current user's home directory. The returned string is newly allocated and must be freed. ```c char *tilde_expand(const char *directory); ``` ```c char *expanded = tilde_expand("~/documents"); printf("Expanded: %s\n", expanded); // Output: "/home/user/documents" g_free(expanded); ``` -------------------------------- ### mc_open Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/vfs-core.md Opens a file through the VFS abstraction layer, returning a file descriptor for subsequent operations. ```APIDOC ## mc_open() ### Description Open a file through the VFS abstraction layer. ### Function Signature ```c int mc_open(const vfs_path_t *vpath, int flags, ...) ``` ### Parameters #### Path Parameters - **vpath** (const vfs_path_t *) - VFS path to file - **flags** (int) - Open flags (O_RDONLY, O_WRONLY, O_RDWR, O_CREAT, etc.) - **mode** (mode_t) - File creation mode (variadic argument for O_CREAT) ### Returns - File descriptor on success - -1 on error ### Throws - Sets errno appropriately ### Flags - `O_RDONLY` — Read-only - `O_WRONLY` — Write-only - `O_RDWR` — Read and write - `O_CREAT` — Create file if not exists - `O_EXCL` — Fail if file exists (with O_CREAT) - `O_LINEAR` — Sequential read promise (optimization for remote FS) ### Example ```c vfs_path_t *path = vfs_path_from_str("/path/to/file"); int fd = mc_open(path, O_RDONLY); if (fd != -1) { // File opened mc_close(fd); } vfs_path_free(path, TRUE); ``` ``` -------------------------------- ### Create Hard Link Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/vfs-core.md Creates a hard link to an existing file. Both paths must refer to files within the same filesystem. ```c int mc_link(const vfs_path_t *vpath1, const vfs_path_t *vpath2); ``` -------------------------------- ### mc_search_prepare Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/search-system.md Prepares a search object for execution by compiling the search pattern (e.g., regex) and validating its syntax. This function must be called after configuring the search object and before running the search. ```APIDOC ## mc_search_prepare() ### Description Prepare search pattern for execution (compile regex, validate syntax). ### Method `mc_search_prepare` ### Parameters #### Path Parameters - **mc_search** (mc_search_t *) - Required - Search object ### Returns TRUE if successful, FALSE on error (check mc_search->error) ### Request Example ```c mc_search_t *search = mc_search_new("pattern", "UTF-8"); search->search_type = MC_SEARCH_T_REGEX; search->is_case_sensitive = TRUE; if (!mc_search_prepare(search)) { g_warning("Search error: %s", search->error_str); mc_search_free(search); return; } ``` ``` -------------------------------- ### Configuration File Handle Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/types.md An opaque structure representing a handle to a configuration file, utilizing GLib's GKeyFile for parsing. Used for configuration management. ```c typedef struct mc_config_t { GKeyFile *handle; // GLib key file gchar *ini_path; // File path } mc_config_t; ``` -------------------------------- ### Prepare Search Pattern Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/search-system.md Compiles the search pattern and validates its syntax before execution. Check the 'error' field of the search object if this function returns FALSE. ```c gboolean mc_search_prepare(mc_search_t *mc_search); ``` ```c mc_search_t *search = mc_search_new("pattern", "UTF-8"); search->search_type = MC_SEARCH_T_REGEX; search->is_case_sensitive = TRUE; if (!mc_search_prepare(search)) { g_warning("Search error: %s", search->error_str); mc_search_free(search); return; } ``` -------------------------------- ### Create a hotkey from text Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/widget-system.md hotkey_new generates a hotkey_t structure from a string, parsing for an accelerator character (e.g., '&' prefix). It returns the new hotkey structure. ```c hotkey_t hotkey_new(const char *text); ``` ```c hotkey_t hotkey = hotkey_new("&Save"); // 'S' is the hotkey printf("Hotkey: %c\n", *hotkey.hotkey); hotkey_free(hotkey); ``` -------------------------------- ### mc_build_filename() Source: https://github.com/midnightcommander/mc/blob/master/_autodocs/utilities.md Builds a file path from multiple components using a variadic function. The components are NULL-terminated. ```APIDOC ## mc_build_filename() ### Description Builds a file path from multiple components using a variadic function. The components are NULL-terminated. ### Parameters #### Path Parameters - **first_element** (const char *) - Required - First path component - **...** (const char *) - Required - Additional components (NULL-terminated) ### Returns Newly allocated path (must be freed) ### Example ```c char *path = mc_build_filename("/home", "user", "documents", "file.txt", NULL); printf("Path: %s\n", path); // Output: "/home/user/documents/file.txt" g_free(path); ``` ```