Search code examples
vimeditorvim-pluginneovim

i did mapping with if else condition in init.vim for float term plugin but got an error


for plugin in neovim called float-term actually you don't need to know the plugin at all , it's just error i got from mapping with conditional statements , i want to do conditional mapping like below , if i am do something wrong in function then write right function please.

if you think that my whole method is wrong , that also can be happen then give me right path

for javascript

nnoremap <F5> :FloatermNew node %<CR>

for c

nnoremap <F5> :FloatermNew gcc % && ./a.out<CR>

for c++

nnoremap <F5> :FloatermNew g++ % && ./a.out<CR>

for python

nnoremap <F5> :Floaterm python3 %<CR>

Now i want that these all working with one shortcut F5.

i done like this but get an error

nnoremap <expr> <F5> My_mapping()

function! My_mapping
    if &filetype ==# 'c'
        nnoremap <F5>:FloatermNew gcc % && ./a.out <CR>
    elseif &filetype ==# 'c++'
        nnoremap <F5>:FloatermNew g++ % && ./a.out <CR>
    elseif &filetype ==# 'js'
        nnoremap <F5>:FloatermNew node % <CR>
    elseif &filetype ==# 'py'
        nnoremap <F5>:FloatermNew python3 % <CR>
    else
        nnoremap <F5><CR>
    endif
endfunction

error

Error detected while processing /home/visrut/.config/nvim/init.vim:
line  208:
E123: Undefined function: My_mapping
n  <F5>        * My_mapping()
line  220:
E193: :endfunction not inside a function

can anyone fix error? or if i am totally wrong with this method then can anyone define new way to do this


Solution

  • autocmd FileType javascript nnoremap <buffer> <F5> :w<esc>:FloatermNew node %<CR>
    autocmd FileType c nnoremap <buffer> <F5> :w<esc>:FloatermNew gcc % && ./a.out && rm a.out<CR>
    autocmd FileType cpp nnoremap <buffer> <F5> :w<esc>:FloatermNew g++ % && ./a.out && rm a.out<CR>
    autocmd FileType python nnoremap <buffer> <F5> :w<esc>:FloatermNew python3 %<CR>
    autocmd FileType typescript nnoremap <buffer> <F5> :w<esc>:FloatermNew ts-node %<CR>