Vimcraft Docs / vim.cmd - Command Execution

vim.cmd - Command Execution

Execute Ex commands and interact with the command-line interface.

Basic Usage

Execute Ex Commands

// Write current buffer
vim.cmd('write');

// Write and quit
vim.cmd('wq');

// Quit without saving
vim.cmd('q!');

// Open a file
vim.cmd('edit ~/.config/vimcraft/index.ts');

Commands with Arguments

// Substitute
vim.cmd('%s/foo/bar/g');

// Set options via command
vim.cmd('set number');

// Echo message
vim.cmd('echo "Hello, Vimcraft!"');

Common Commands

File Operations

vim.cmd('write');           // Save current buffer
vim.cmd('write %');         // Save current file
vim.cmd('saveas newfile');  // Save as new file
vim.cmd('edit path/file');  // Open file
vim.cmd('enew');            // New empty buffer

Window Management

vim.cmd('split');           // Horizontal split
vim.cmd('vsplit');          // Vertical split
vim.cmd('close');           // Close current window
vim.cmd('only');            // Close all other windows
vim.cmd('wincmd h');        // Move to left window
vim.cmd('wincmd j');        // Move to window below
vim.cmd('wincmd k');        // Move to window above
vim.cmd('wincmd l');        // Move to right window

Buffer Management

vim.cmd('bnext');           // Next buffer
vim.cmd('bprev');           // Previous buffer
vim.cmd('bdelete');         // Delete current buffer
vim.cmd('buffers');         // List buffers

Search and Replace

// Replace in current line
vim.cmd('s/old/new/');

// Replace all in file
vim.cmd('%s/old/new/g');

// Replace with confirmation
vim.cmd('%s/old/new/gc');

// Clear search highlight
vim.cmd('nohlsearch');

Using in Keymaps

// Map to command
vim.keymap.set('n', '<leader>w', () => vim.cmd('write'));
vim.keymap.set('n', '<leader>q', () => vim.cmd('quit'));

// Complex command sequence
vim.keymap.set('n', '<leader>sv', () => {
  vim.cmd('source ~/.config/vimcraft/index.ts');
  console.log('Config reloaded!');
});

Using in Autocommands

vim.api.createAutocmd('BufWritePre', {
  pattern: '*.ts',
  callback: () => {
    // Remove trailing whitespace
    vim.cmd('%s/\\s\\+$//e');
  }
});

Error Handling

Commands that fail will throw an error:

try {
  vim.cmd('edit nonexistent_file');
} catch (e) {
  console.log('Command failed:', e);
}

vim.api.command()

Alternative low-level API:

// Equivalent to vim.cmd()
vim.api.command('write');
vim.api.command('split');

See Also