Skip to content
Advertisement

How to concatenate strings to provide as input when calling the term command in neovim

I have the following example:

autocmd FileType python nnoremap <buffer> <leader>c :let python_file=expand('%:p')<CR>:term 'python ' . python_file<CR>

This is an example script for running python code, however whenever I try to use this keybinding in a python file I get the following error:

''python' is not recognized as an internal or external command,

What seems to be happening is that the term command may not be concatenating the strings properly ('python ' . python_file) which I am providing it as a command.

Is there a way I can fix this?

Please note that this is just a simplified example of something which I am trying to do please do not suggest a solution such as :term python expand('%:p') which I know will work for most common cases but it will not work in my case.

Advertisement

Answer

:terminal expects a string, not an expression. You will have to use :help :execute to put your command together:

nnoremap <key> :let python_file=expand('%:p')<CR>:execute 'term python ' .. python_file<CR>

(Please note that this is just a simplified example of something which I am trying to do please do not suggest a solution such as :term python expand('%:p') which I know will work for most common cases but it will not work in my case)

Well, it can be simplified even further:

autocmd FileType python nnoremap <buffer> <leader>c :term python %:p<CR>

Be smart when asking questions. The mapping as you posted it makes no sense so it is pretty legitimate for answerers to focus on the example you gave them and to suggest things based on the examples you submitted: the XY problem is a real problem in these parts.

Case in point, your problem could be stated in much simple terms that wouldn’t attract unwanted attention to your contrived mapping:

I have a file path in variable ... but I can’t make :term use it. I have tried ... and ... but nothing worked. What did I do wrong?

To which there can only be one answer, that doesn’t assume anything about your intent.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement