Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a command from cnoremap?

Tags:

vim

I want to map <M-o> to quickly look up buflist from command-mode.

Here's an example normal-mode mapping:

nnoremap <M-o> :ls<CR>

Here's an attempt to do the same for command mode using execute():

cnoremap <M-o> <C-r>=execute(':ls')<CR>

This however simply appends whitespace-separated :ls results to the command line, with no side effect of the :ls table actually showing.

Is there a way to execute a command without leaving command-mode?

Update:

Closest I've come to cracking this using Vimscript is the following:

function! RunCmdFromCmdline(cmd)
    let l:cmd_line = getcmdline()
    echo execute(a:cmd)
    return l:cmd_line
endfunction

cnoremap <M-o> <C-\>eRunCmdFromCmdline(':ls')<CR>

The echo makes it so the results of a:cmd do pop on the screen, however in invisible font. I tried playing with :redraw <bar> in different combinations with no success.

Exiting from the command mode from within a <C-r>= or <C-\>e prompt does not seem possible.

like image 403
mwgkgk Avatar asked Dec 05 '25 17:12

mwgkgk


1 Answers

You can save the contents of the current command line in a register, then run ls and paste the contents of the register:

cnoremap <esc>o <home>let @x="<end>"<cr>:ls<cr>:<c-r>x

So if command line looks like this:

:echo 'some'

type <M-o> to get:

:ls
  1 %a + "filename"          line 1
:echo 'some'
like image 90
builder-7000 Avatar answered Dec 07 '25 17:12

builder-7000



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!