Problem:
There's a pasted text of multiple short text rows separated by the new line, such as
aaa
bbb
ccc
…
etc
Expectations: I tried to use the nvim macro to make it looks like so
'aaa',
'bbb',
'ccc',
…
etc
My nvim conf:
set mouse=a " enable mouse
set encoding=utf-8
set number
set noswapfile
set scrolloff=7
"set autoindent
set fileformat=unix
filetype indent on " load filetype-specific indent files
" for tabulation
set smartindent
set softtabstop=4
set expandtab
set tabstop=4
set expandtab
set shiftwidth=4
inoremap jk <esc>
inoremap " ""<left>
inoremap ' ''<left>
inoremap ( ()<left>
inoremap [ []<left>
inoremap { {}<left>
inoremap {<CR> {<CR>}<ESC>O
inoremap {;<CR> {<CR>};<ESC>O
call plug#begin('~/.vim/plugged')
Plug 'neovim/nvim-lspconfig'
Plug 'hrsh7th/nvim-cmp'
Plug 'hrsh7th/cmp-nvim-lsp'
Plug 'saadparwaiz1/cmp_luasnip'
Plug 'L3MON4D3/LuaSnip'
" color schemas
Plug 'morhetz/gruvbox' " colorscheme gruvbox
Plug 'mhartington/oceanic-next' " colorscheme OceanicNext
Plug 'kaicataldo/material.vim', { 'branch': 'main' }
Plug 'ayu-theme/ayu-vim'
Plug 'xiyaowong/nvim-transparent'
Plug 'Pocco81/AutoSave.nvim'
Plug 'justinmk/vim-sneak'
" JS/JSX/TS
Plug 'pangloss/vim-javascript'
Plug 'leafgarland/typescript-vim'
Plug 'peitalin/vim-jsx-typescript'
Plug 'maxmellon/vim-jsx-pretty'
" TS from here https://jose-elias-alvarez.medium.com/configuring-neovims-lsp-client-for-typescript-development-5789d58ea9c
Plug 'jose-elias-alvarez/null-ls.nvim'
Plug 'jose-elias-alvarez/nvim-lsp-ts-utils'
Plug 'nvim-lua/plenary.nvim'
" BY ISLAM
" Plug 'mhartington/nvim-typescript', {'do': './install.sh'}
Plug 'dense-analysis/ale'
Plug 'neoclide/coc.nvim', {'branch': 'release'}
Plug 'lewis6991/gitsigns.nvim'
"Plug 'prettier/vim-prettier', {
" \ 'do': 'npm install --frozen-lockfile --production',
" \ 'for': ['javascript', 'typescript', 'typescriptreact', 'javascriptreact', 'css', 'less', 'scss', 'json', 'graphql', 'markdown', 'vue', 'svelte', 'yaml', 'html'] }"
Plug 'bmatcuk/stylelint-lsp'
Plug 'nvim-telescope/telescope.nvim', { 'tag': '0.1.0' }
Plug 'nvim-telescope/telescope-fzf-native.nvim', { 'do': 'make' }
" Convenient floating terminal window
"Plug 'voldikss/vim-floaterm'
call plug#end()
let g:loaded_python3_provider = 0
let g:ale_disable_lsp = 1
" let g:ale_completion_enabled = 1
" Leader bind to space
let mapleader = ","
" Netrw file explorer settings
let g:netrw_banner = 0 " hide banner above files
let g:netrw_liststyle = 3 " tree instead of plain view
let g:netrw_browse_split = 3 " vertical split window when Enter pressed on file
" Disable quickfix window for prettier
let g:prettier#quickfix_enabled = 0
" Turn on vim-sneak
let g:sneak#label = 1
colorscheme gruvbox
"colorscheme OceanicNext
" colorscheme material
let g:material_terminal_italics = 1
"variants: default, palenight, ocean, lighter, darker, default-community,
" palenight-community, ocean-community, lighter-community,
" darker-community
"let g:material_theme_style = 'darker'
if (has('termguicolors'))
set termguicolors
endif
" variants: mirage, dark, dark
"let ayucolor="mirage"
"colorscheme ayu
" turn off search highlight
nnoremap ,<space> :nohlsearch<CR>
lua << EOF
-- Set completeopt to have a better completion experience
vim.o.completeopt = 'menuone,noselect'
-- luasnip setup
local luasnip = require 'luasnip'
local async = require "plenary.async"
-- nvim-cmp setup
local cmp = require 'cmp'
cmp.setup {
completion = {
autocomplete = true
},
snippet = {
expand = function(args)
require('luasnip').lsp_expand(args.body)
end,
},
mapping = {
['<C-p>'] = cmp.mapping.select_prev_item(),
['<C-n>'] = cmp.mapping.select_next_item(),
['<C-d>'] = cmp.mapping.scroll_docs(-4),
['<C-f>'] = cmp.mapping.scroll_docs(4),
['<C-Space>'] = cmp.mapping.complete(),
['<C-e>'] = cmp.mapping.close(),
['<CR>'] = cmp.mapping.confirm {
behavior = cmp.ConfirmBehavior.Replace,
select = true,
},
['<Tab>'] = function(fallback)
if vim.fn.pumvisible() == 1 then
vim.fn.feedkeys(vim.api.nvim_replace_termcodes('<C-n>', true, true, true), 'n')
elseif luasnip.expand_or_jumpable() then
vim.fn.feedkeys(vim.api.nvim_replace_termcodes('<Plug>luasnip-expand-or-jump', true, true, true), '')
else
fallback()
end
end,
['<S-Tab>'] = function(fallback)
if vim.fn.pumvisible() == 1 then
vim.fn.feedkeys(vim.api.nvim_replace_termcodes('<C-p>', true, true, true), 'n')
elseif luasnip.jumpable(-1) then
vim.fn.feedkeys(vim.api.nvim_replace_termcodes('<Plug>luasnip-jump-prev', true, true, true), '')
else
fallback()
end
end,
},
sources = {
{ name = 'nvim_lsp' },
{ name = 'luasnip' },
},
}
local nvim_lsp = require('lspconfig')
-- Use an on_attach function to only map the following keys
-- after the language server attaches to the current buffer
local on_attach = function(client, bufnr)
local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end
local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end
-- Enable completion triggered by <c-x><c-o>
buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc')
-- Mappings.
local opts = { noremap=true, silent=true }
-- See `:help vim.lsp.*` for documentation on any of the below functions
buf_set_keymap('n', 'gD', '<cmd>lua vim.lsp.buf.declaration()<CR>', opts)
buf_set_keymap('n', 'gd', '<cmd>lua vim.lsp.buf.definition()<CR>', opts)
buf_set_keymap('n', 'K', '<cmd>lua vim.lsp.buf.hover()<CR>', opts)
buf_set_keymap('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts)
buf_set_keymap('n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts)
buf_set_keymap('n', '<space>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', opts)
buf_set_keymap('n', '<space>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', opts)
buf_set_keymap('n', '<space>wl', '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>', opts)
buf_set_keymap('n', '<space>D', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts)
buf_set_keymap('n', '<space>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts)
buf_set_keymap('n', '<space>ca', '<cmd>lua vim.lsp.buf.code_action()<CR>', opts)
buf_set_keymap('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts)
buf_set_keymap('n', '<space>e', '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>', opts)
buf_set_keymap('n', '[d', '<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>', opts)
buf_set_keymap('n', ']d', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', opts)
buf_set_keymap('n', '<space>q', '<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>', opts)
buf_set_keymap('n', '<space>f', '<cmd>lua vim.lsp.buf.formatting()<CR>', opts)
end
-- TS setup
local buf_map = function(bufnr, mode, lhs, rhs, opts)
vim.api.nvim_buf_set_keymap(bufnr, mode, lhs, rhs, opts or {
silent = true,
})
end
nvim_lsp.tsserver.setup({
on_attach = function(client, bufnr)
client.resolved_capabilities.document_formatting = false
client.resolved_capabilities.document_range_formatting = false
local ts_utils = require("nvim-lsp-ts-utils")
ts_utils.setup({})
ts_utils.setup_client(client)
buf_map(bufnr, "n", "gs", ":TSLspOrganize<CR>")
buf_map(bufnr, "n", "gi", ":TSLspRenameFile<CR>")
buf_map(bufnr, "n", "go", ":TSLspImportAll<CR>")
on_attach(client, bufnr)
end,
})
require('gitsigns').setup()
local null_ls = require("null-ls")
null_ls.setup({
sources = {
null_ls.builtins.diagnostics.eslint,
null_ls.builtins.code_actions.eslint,
null_ls.builtins.formatting.prettier
},
on_attach = on_attach
})
-- Use a loop to conveniently call 'setup' on multiple servers and
-- map buffer local keybindings when the language server attaches
local servers = { 'typescript-language-server', 'pyright', 'rust_analyzer' }
for _, lsp in ipairs(servers) do
nvim_lsp[lsp].setup {
on_attach = on_attach,
flags = {
debounce_text_changes = 150,
}
}
end
EOF
lua << EOF
require'lspconfig'.tsserver.setup{
filetypes = { "typescript", "typescriptreact", "typescript.tsx" },
root_dir = function() return vim.loop.cwd() end -- run lsp for javascript in any directory
}
EOF
" Delete buffer while keeping window layout (don't close buffer's windows).
" Version 2008-11-18 from http://vim.wikia.com/wiki/VimTip165
if v:version < 700 || exists('loaded_bclose') || &cp
finish
endif
let loaded_bclose = 1
if !exists('bclose_multiple')
let bclose_multiple = 1
endif
" Display an error message.
function! s:Warn(msg)
echohl ErrorMsg
echomsg a:msg
echohl NONE
endfunction
" Command ':Bclose' executes ':bd' to delete buffer in current window.
" The window will show the alternate buffer (Ctrl-^) if it exists,
" or the previous buffer (:bp), or a blank buffer if no previous.
" Command ':Bclose!' is the same, but executes ':bd!' (discard changes).
" An optional argument can specify which buffer to close (name or number).
function! s:Bclose(bang, buffer)
if empty(a:buffer)
let btarget = bufnr('%')
elseif a:buffer =~ '^\d\+$'
let btarget = bufnr(str2nr(a:buffer))
else
let btarget = bufnr(a:buffer)
endif
if btarget < 0
call s:Warn('No matching buffer for '.a:buffer)
return
endif
if empty(a:bang) && getbufvar(btarget, '&modified')
call s:Warn('No write since last change for buffer '.btarget.' (use :Bclose!)')
return
endif
" Numbers of windows that view target buffer which we will delete.
let wnums = filter(range(1, winnr('$')), 'winbufnr(v:val) == btarget')
if !g:bclose_multiple && len(wnums) > 1
call s:Warn('Buffer is in multiple windows (use ":let bclose_multiple=1")')
return
endif
let wcurrent = winnr()
for w in wnums
execute w.'wincmd w'
let prevbuf = bufnr('#')
if prevbuf > 0 && buflisted(prevbuf) && prevbuf != btarget
buffer #
else
bprevious
endif
if btarget == bufnr('%')
" Numbers of listed buffers which are not the target to be deleted.
let blisted = filter(range(1, bufnr('$')), 'buflisted(v:val) && v:val != btarget')
" Listed, not target, and not displayed.
let bhidden = filter(copy(blisted), 'bufwinnr(v:val) < 0')
" Take the first buffer, if any (could be more intelligent).
let bjump = (bhidden + blisted + [-1])[0]
if bjump > 0
execute 'buffer '.bjump
else
execute 'enew'.a:bang
endif
endif
endfor
execute 'bdelete'.a:bang.' '.btarget
execute wcurrent.'wincmd w'
endfunction
command! -bang -complete=buffer -nargs=? Bclose call <SID>Bclose(<q-bang>, <q-args>)
nnoremap <silent> <Leader>bd :Bclose<CR>
map gn :bn<cr>
map gp :bp<cr>
map gw :Bclose<cr>
set relativenumber
set rnu
let g:transparent_enabled = v:true
tnoremap <Esc> <C-\><C-n>
" Telescope bindings
nnoremap ,f <cmd>Telescope find_files<cr>
nnoremap ,g <cmd>Telescope live_grep<cr>
" Go to next or prev tab by H and L accordingly
nnoremap H gT
nnoremap L gt
" Telescope fzf plugin
lua << EOF
require('telescope').load_extension('fzf')
EOF
" White colors for LSP messages in code
set termguicolors
hi DiagnosticError guifg=White
hi DiagnosticWarn guifg=Yellow
hi DiagnosticInfo guifg=White
hi DiagnosticHint guifg=White
So i started recording macro, applied it to the first, second rows and it was ok until i reached the lines where something gone wrong and line refined as unexpected, one or two quotes in wrong places and the comma too.
In my nvim config i have autocompletion for double quotes when write one, and for other symbols too, but i disabled that lines, entered in nvim :source $MYVIMRC and it didn't applied.
I guess $MYVIMRC was exactly for vim, but not the NVIM, so how can i apply that conf. changes properly ?
And the main point, even though the macro should have done right job instead of a real wrong fact i faced… so what may caused it ?
Related
I am new to Neovim and lua as programming language. I am trying to setup a Neovim as a full complete IDE.
My issue deals with Mason and LSP capabilities. It seems that my LSP server is executing but my configuration is not correctly setup properly. My point is that the keymapping from my attach table are not applied
My file setup is the following:
~/.config/nvim/init.lua
~/.config/nvim/lua/jpv/ {init.lua, ...., mason.lua, lsp}
~/.config/nvim/lua/jpv/lsp/ {init.lua, handlers.lua}
I have a file mason.lua
require("mason").setup({
ui = {
icons = {
package_installed = "✓",
package_pending = "➜",
package_uninstalled = "✗"
}
}
})
require("mason-lspconfig").setup_handlers({
function(server)
local opts = {
on_attach = require("jpv.lsp.handlers").on_attach,
capabilities = require("jpv.lsp.handlers").capabilities,
}
if server == "sumneko_lua" then
print("Inside" .. server)
local sumneko_opts = require("jpv.lsp.settings.sumneko_lua")
opts = vim.tbl_deep_extend("force", sumneko_opts, opts)
end
if server == "kotlin_language_server" then
print("Inside" .. server)
local kotlin_ls = require("jpv.lsp.settings.kotlin_ls")
opts = vim.tbl_deep_extend("force", kotlin_ls, opts)
end
-- print("For server " .. server)
-- for key, value in pairs(opts) do
-- print("Has key ".. key)
-- end
require("lspconfig")[server].setup{opts}
end
})
On the other side I have a lsp folder with an init.lua
local status_ok, nvm_lsp = pcall(require, "lspconfig")
if not status_ok then
return
end
require("jpv.lsp.handlers").setup()
require("jpv.mason")
Last, my handlers.lua is
local M = {}
-- TODO: backfill this to template
M.setup = function()
local signs = {
{ name = "DiagnosticSignError", text = "" },
{ name = "DiagnosticSignWarn", text = "" },
{ name = "DiagnosticSignHint", text = "" },
{ name = "DiagnosticSignInfo", text = "" },
}
for _, sign in ipairs(signs) do
vim.fn.sign_define(sign.name, { texthl = sign.name, text = sign.text, numhl = "" })
end
local config = {
-- disable virtual text
virtual_text = false,
-- show signs
signs = {
active = signs,
},
update_in_insert = true,
underline = true,
severity_sort = true,
float = {
focusable = false,
style = "minimal",
border = "rounded",
source = "always",
header = "",
prefix = "",
},
}
vim.diagnostic.config(config)
vim.lsp.handlers["textDocument/hover"] = vim.lsp.with(vim.lsp.handlers.hover, {
border = "rounded",
width = 60,
})
vim.lsp.handlers["textDocument/signatureHelp"] = vim.lsp.with(vim.lsp.handlers.signature_help, {
border = "rounded",
width = 60,
})
end
local function lsp_highlight_document(client)
-- Set autocommands conditional on server_capabilities
local status_ok, illuminate = pcall(require, "illuminate")
if not status_ok then
print("RETURNING")
return
end
print("NOT returning")
illuminate.on_attach(client)
-- end
end
local function lsp_keymaps(bufnr)
local opts = { noremap = true, silent = true }
vim.api.nvim_buf_set_keymap(bufnr, "n", "gD", "<cmd>lua vim.lsp.buf.declaration()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "gd", "<cmd>lua vim.lsp.buf.definition()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "K", "<cmd>lua vim.lsp.buf.hover()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "gi", "<cmd>lua vim.lsp.buf.implementation()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "<C-k>", "<cmd>lua vim.lsp.buf.signature_help()<CR>", opts)
-- vim.api.nvim_buf_set_keymap(bufnr, "n", "<leader>rn", "<cmd>lua vim.lsp.buf.rename()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "gr", "<cmd>lua vim.lsp.buf.references()<CR>", opts)
-- vim.api.nvim_buf_set_keymap(bufnr, "n", "<leader>ca", "<cmd>lua vim.lsp.buf.code_action()<CR>", opts)
-- vim.api.nvim_buf_set_keymap(bufnr, "n", "<leader>f", "<cmd>lua vim.diagnostic.open_float()<CR>", opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "[d", '<cmd>lua vim.diagnostic.goto_prev({ border = "rounded" })<CR>', opts)
vim.api.nvim_buf_set_keymap(
bufnr,
"n",
"gl",
'<cmd>lua vim.diagnostic.open_float({ border = "rounded" })<CR>',
opts
)
vim.api.nvim_buf_set_keymap(bufnr, "n", "]d", '<cmd>lua vim.diagnostic.goto_next({ border = "rounded" })<CR>', opts)
vim.api.nvim_buf_set_keymap(bufnr, "n", "<leader>q", "<cmd>lua vim.diagnostic.setloclist()<CR>", opts)
vim.cmd([[ command! Format execute 'lua vim.lsp.buf.format{async=true}' ]])
print("Inside keymaps iiiiiiiiiiiiiiiiiiiiiii")
end
M.on_attach = function(client, bufnr)
-- vim.notify(client.name .. " starting...")
-- TODO: refactor this into a method that checks if string in list
print("Client is " .. client)
if client.name == "tsserver" then
client.resolved_capabilities.document_formatting = false
end
print("Assigning keymaps")
lsp_keymaps(bufnr)
print("Illuminating document")
lsp_highlight_document(client)
end
local capabilities = vim.lsp.protocol.make_client_capabilities()
local status_ok, cmp_nvim_lsp = pcall(require, "cmp_nvim_lsp")
if not status_ok then
return
end
print("LOOOAADIN")
M.capabilities = cmp_nvim_lsp.update_capabilities(capabilities)
return M
Replace setup_handlers with this on your mason.lua file:
require("mason-lspconfig").setup_handlers({
function(server)
local opts = {
on_attach = require("jpv.lsp.handlers").on_attach,
capabilities = require("jpv.lsp.handlers").capabilities,
}
require("lspconfig")[server].setup(opts)
if server == "sumneko_lua" then
local sumneko_opts = require("jpv.lsp.settings.sumneko_lua")
-- assuming sumneko_opts return a table
sumneko_opts["on_attach"] = opts.on_attach
sumneko_opts["capabilities"] = opts.capabilities
require("lspconfig")[server].setup(sumneko_opts)
end
end})
I have updated neovim to the latest version in the stable ppa (0.7.2)
However, I get some
Packer.nvim: error running config for toggleterm.nvim: attempt to call a nil value
Packer.nvim: error running config for nvim-cmp: attempt to call a nil value
...
I am not sure what could cause an error like this and how to debug it.
My plugins.lua (removing some unrelated plugins looks as follows)
local fn = vim.fn
-- Automatically install packer
local install_path = fn.stdpath "data" .. "/site/pack/packer/start/packer.nvim"
if fn.empty(fn.glob(install_path)) > 0 then
PACKER_BOOTSTRAP = fn.system {
"git",
"clone",
"--depth",
"1",
"https://github.com/wbthomason/packer.nvim",
install_path,
}
print "Installing packer close and reopen Neovim..."
vim.cmd [[packadd packer.nvim]]
end
-- Autocommand that reloads neovim whenever you save the plugins.lua file
vim.cmd [[
augroup packer_user_config
autocmd!
autocmd BufWritePost plugins.lua source <afile> | PackerSync
augroup end
]]
-- Use a protected call so we don't error out on first use
local status_ok, packer = pcall(require, "packer")
if not status_ok then
return
end
-- Have packer use a popup window
packer.init {
display = {
open_fn = function()
return require("packer.util").float { border = "rounded" }
end,
},
}
-- Install your plugins here
return packer.startup(function(use)
-- My plugins here
use "wbthomason/packer.nvim" -- Have packer manage itself
use "nvim-lua/popup.nvim" -- An implementation of the Popup API from vim in Neovim
use "nvim-lua/plenary.nvim" -- Useful lua functions used by lots of plugins
use {"akinsho/toggleterm.nvim", tag = 'v2.*', config = function()
require("toggleterm").setup()
end}
-- complete plugins
use {'hrsh7th/nvim-cmp', config = function() require('cmp')
end,
}
-- The completion plugin
use "hrsh7th/cmp-buffer" -- buffer completions
use "hrsh7th/cmp-path" -- path completions
use "hrsh7th/cmp-cmdline" -- cmdline completions
use "hrsh7th/cmp-nvim-lsp" -- lsp completions
-- snippets
use {"L3MON4D3/LuaSnip", --snippet engine
after = 'nvim-cmp',
config = function() require('luasnip.snippets') end,
}
use "saadparwaiz1/cmp_luasnip" -- snippet completions
use "rafamadriz/friendly-snippets" -- a bunch of snippets to use
-- Telescope
use "nvim-telescope/telescope.nvim"
-- Treesitter
use {
"nvim-treesitter/nvim-treesitter",
run = ":TSUpdate"
}
-- Automatically set up your configuration after cloning packer.nvim
-- Put this at the end after all plugins
if PACKER_BOOTSTRAP then
require("packer").sync()
end
end)
and for toggleterm.lua as follows
local status_ok, toggleterm = pcall(require, "toggleterm")
if not status_ok then
print("Toggleterm status not OK")
return
end
toggleterm.setup({
size = 20,
open_mapping = [[<c-\>]],
hide_numbers = true,
shade_filetypes = {},
shade_terminals = true,
shading_factor = 2,
start_in_insert = true,
insert_mappings = true,
persist_size = true,
direction = "float",
close_on_exit = true,
shell = vim.o.shell,
float_opts = {
border = "curved",
winblend = 0,
highlights = {
border = "Normal",
background = "Normal",
},
},
})
function _G.set_terminal_keymaps()
local opts = {noremap = true}
vim.api.nvim_buf_set_keymap(0, 't', '<esc>', [[<C-\><C-n>]], opts)
vim.api.nvim_buf_set_keymap(0, 't', 'jk', [[<C-\><C-n>]], opts)
vim.api.nvim_buf_set_keymap(0, 't', '<C-h>', [[<C-\><C-n><C-W>h]], opts)
vim.api.nvim_buf_set_keymap(0, 't', '<C-j>', [[<C-\><C-n><C-W>j]], opts)
vim.api.nvim_buf_set_keymap(0, 't', '<C-k>', [[<C-\><C-n><C-W>k]], opts)
vim.api.nvim_buf_set_keymap(0, 't', '<C-l>', [[<C-\><C-n><C-W>l]], opts)
end
vim.cmd('autocmd! TermOpen term://* lua set_terminal_keymaps()')
local Terminal = require("toggleterm.terminal").Terminal
local node = Terminal:new({ cmd = "node", hidden = true })
function _NODE_TOGGLE()
node:toggle()
end
local ncdu = Terminal:new({ cmd = "ncdu", hidden = true })
function _NCDU_TOGGLE()
ncdu:toggle()
end
local htop = Terminal:new({ cmd = "htop", hidden = true })
function _HTOP_TOGGLE()
htop:toggle()
end
local python = Terminal:new({ cmd = "python", hidden = true })
function _PYTHON_TOGGLE()
python:toggle()
end
:PackerUpdate (from inside nvim) fixed the issue for me.
Ok, so I am trying to create a text-based adventure game. I am currently creating the attack system. Here is the code
start = io.read()
if start == "start" then
ma1 = "jab your opponent"
ma2 = "hook your oppenent"
fa1 = "kick your oppenent"
ha1 = "headbutt your oppenent"
--Melee weapon
mw1 = "fist1"
mw2 = "fist2"
foot = "Kick"
head = "headbutt"
--Magic attacks
ms1 = "none"
ms2 = "none"
ms3 = "none"
ms4 = "none"
--Gadgets
bow = "none"
gun = "none"
sg = "none"
function atk()
io.write("Do you use melee(1), magic(2), or tech(3)?", "\n")
ac = io.read()
if ac == "1" then
io.write("Do you", ma1,",", ma2, ",",fa1,",or",ha1"?", "\n")
end
end
end
print(atk())
Every time I run this it outputs this:
lua: jdoodle.lua:25: global 'ha1' is not callable (a string value)
stack traceback:
jdoodle.lua:25: in function 'atk'
jdoodle.lua:29: in main chunk
[C]: in ?
So if you have any solutions thank you.
You missed a comma:
start = io.read()
if start == "start" then
--body
if ac == "1" then
io.write("Do you", ma1, ", ", ma2, ", ", fa1, ", or", ha1, "?", "\n")
end
end
print(atk())
I use elixirls lsp-client and efm-server (mainly for credo) for working with elixir-files in Neovim.
I want to use lsp-config for formatting elixir files and want to make it default lsp-client for vim.lsp.buf.formatting() command.
Currently, everytime I try to save a file, it asks me to choose a language server as shown in the image below.
How to make elixirls the default language server for vim.lsp.buf.formatting() and vim.lsp.buf.formatting_sync(nil, 100) commands ?
My relevant init.lua file is as follows:
-----------------------------------------------------------------------------------------------
--- LSP
-----------------------------------------------------------------------------------------------
local nvim_lsp = require("lspconfig")
-- Use an on_attach function to only map the following keys
-- after the language server attaches to the current buffer
local custom_attach = function(client, bufnr)
local function buf_set_keymap(...)
vim.api.nvim_buf_set_keymap(bufnr, ...)
end
local function buf_set_option(...)
vim.api.nvim_buf_set_option(bufnr, ...)
end
-- Enable completion triggered by <c-x><c-o>
buf_set_option("omnifunc", "v:lua.vim.lsp.omnifunc")
-- Mappings.
local opts = {noremap = true, silent = true}
-- See `:help vim.lsp.*` for documentation on any of the below functions
buf_set_keymap("n", "gD", "<Cmd>lua vim.lsp.buf.declaration()<CR>", opts)
buf_set_keymap("n", "gd", "<Cmd>lua vim.lsp.buf.definition()<CR>", opts)
buf_set_keymap("n", "K", "<Cmd>lua vim.lsp.buf.hover()<CR>", opts)
buf_set_keymap("n", "gi", "<cmd>lua vim.lsp.buf.implementation()<CR>", opts)
buf_set_keymap("n", "<C-k>", "<cmd>lua vim.lsp.buf.signature_help()<CR>", opts)
buf_set_keymap("n", "<space>wa", "<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>", opts)
buf_set_keymap("n", "<space>wr", "<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>", opts)
buf_set_keymap("n", "<space>wl", "<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>", opts)
buf_set_keymap("n", "<space>D", "<cmd>lua vim.lsp.buf.type_definition()<CR>", opts)
buf_set_keymap("n", "<space>rn", "<cmd>lua vim.lsp.buf.rename()<CR>", opts)
buf_set_keymap("n", "<space>ca", "<cmd>lua vim.lsp.buf.code_action()<CR>", opts)
buf_set_keymap("n", "gr", "<cmd>lua vim.lsp.buf.references()<CR>", opts)
buf_set_keymap("n", "<space>e", "<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>", opts)
buf_set_keymap("n", "[d", "<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>", opts)
buf_set_keymap("n", "]d", "<cmd>lua vim.lsp.diagnostic.goto_next()<CR>", opts)
buf_set_keymap("n", "<space>q", "<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>", opts)
buf_set_keymap("n", "<space>f", "<cmd>lua vim.lsp.buf.formatting_sync(nil, 100)<CR>", opts)
-- vim.api.nvim_command("au BufWritePost <buffer> lua vim.lsp.buf.formatting()")
-- vim.api.nvim_command("au BufWritePost <buffer> lua vim.lsp.buf.formatting_sync(nil, 100)")
-- autocmd BufWritePre *.lua lua vim.lsp.buf.formatting_sync(nil, 100)
end
USER = vim.fn.expand("$USER")
local sumneko_binary = "/Users/" .. USER .. "/language-servers/lua-language-server/bin/macOS/lua-language-server"
local sumneko_root_path = "/Users/" .. USER .. "/language-servers/lua-language-server"
nvim_lsp.sumneko_lua.setup {
cmd = {sumneko_binary, "-E", sumneko_root_path .. "/main.lua"},
on_attach = custom_attach,
settings = {
Lua = {
runtime = {
-- Tell the language server which version of Lua you're using (most likely LuaJIT in the case of Neovim)
version = "LuaJIT",
-- Setup your lua path
path = vim.split(package.path, ";")
},
diagnostics = {
-- Get the language server to recognize the `vim` global
globals = {"vim"}
},
workspace = {
-- Make the server aware of Neovim runtime files
library = {[vim.fn.expand("$VIMRUNTIME/lua")] = true, [vim.fn.expand("$VIMRUNTIME/lua/vim/lsp")] = true}
}
}
}
}
vim.api.nvim_command("au BufWritePost *.lua lua vim.lsp.buf.formatting()")
vim.api.nvim_command("au BufWritePost *.ex lua vim.lsp.buf.formatting()")
-- vim.api.nvim_command("au BufWritePost *.exs lua vim.lsp.buf.formatting()")
require"lspconfig".efm.setup {
init_options = {documentFormatting = true},
filetypes = {"lua", "elixir"},
settings = {
rootMarkers = {".git/"},
languages = {
lua = {
{
formatCommand = "lua-format -i --no-keep-simple-function-one-line --no-break-after-operator --column-limit=150 --break-after-table-lb",
formatStdin = true
}
}
}
}
}
local path_to_elixirls = vim.fn.expand("/Users/" .. USER .. "/language-servers/elixir-ls/rel/language_server.sh")
nvim_lsp.elixirls.setup({
cmd = {path_to_elixirls},
on_attach = custom_attach,
settings = {
elixirLS = {
-- I choose to disable dialyzer for personal reasons, but
-- I would suggest you also disable it unless you are well
-- aquainted with dialzyer and know how to use it.
dialyzerEnabled = false,
-- I also choose to turn off the auto dep fetching feature.
-- It often get's into a weird state that requires deleting
-- the .elixir_ls directory and restarting your editor.
fetchDeps = false
}
}
})
Using vim.lsp.buf.formatting_seq_sync() instead of vim.lsp.buf.formatting() fixes the issue.
I have a motorized roller blind project.
I am following this instructable: https://www.instructables.com/id/Motorized-WiFi-IKEA-Roller-Blind/ .
I am using the code in the instructable, but I suspect tha fault is in one of these codes:
config.lua
-- file : config.lua
local module = {}
module.SSID = {}
module.SSID["ssid"] = "password"
-- example for local MQTT
--module.MQHOST = "ohab.local"
--module.MQPORT = 1883
--module.MQID = node.chipid()
--module.MQUSR = ""
--module.MQPW = ""
-- example for cloud MQTT
module.MQHOST = "192.***.*.*"
module.MQPORT = 1883
module.MQID = node.chipid()
module.MQUSR = "username"
module.MQPW = "password"
module.MQTLS = 1 -- 0 = unsecured, 1 = TLS/SSL
module.ENDPOINT = "/house/masterbedroom/rollerblind/"
module.ID = "0"
--module.SUB = "set"
module.SUB = {[module.ENDPOINT .. module.ID .. "/set"]=0,[module.ENDPOINT .. "all"]=0}
module.POST = module.ENDPOINT .. module.ID .. "/status"
return module
wifi_setup
-- file: setup.lua
local module = {}
local function wifi_wait_ip()
if wifi.sta.getip()== nil then
print("IP unavailable, Waiting...")
else
tmr.stop(1)
gpio.write(pin_led,1) --off
print("\n================== ==================")
print("ESP8266 mode is: " .. wifi.getmode())
print("MAC address is: " .. wifi.ap.getmac())
print("IP is "..wifi.sta.getip())
print("====================================")
mq.start()
end
end
local function wifi_start(list_aps)
if list_aps then
gpio.write(pin_led,0) --on
for key,value in pairs(list_aps) do
if config.SSID and config.SSID[key] then
wifi.setmode(wifi.STATION);
wifi.sta.config(key,config.SSID[key])
wifi.sta.connect()
print("Connecting to " .. key .. " ...")
--config.SSID = nil -- can save memory
tmr.alarm(1, 2500, 1, wifi_wait_ip)
end
end
else
print("Error getting AP list")
end
end
function module.start()
print("Configuring Wifi ...")
wifi.setmode(wifi.STATION);
wifi.sta.getap(wifi_start)
end
return module
Sadly I cant manage to go beyond step 4. After I have tried to download the code to the ESP8266 I only get this error:
PANIC: unprotected error in call to Lua API (wifi_setup.lua:25: bad argument #1 to 'config' (config table not found!))
I have only changed the stuff the instructable told me to change, and I have tried to look for faults myself but I cant find any... It's the first time I am using Lua, so this is totally new for me.
Hope somebody here can offer some help. Been stuck on this for days...
THIS PART OF THE PROBLEM IS SOLVED. CHECK COMMENTS FOR SOLUTION
Sadly when one problem is solved, a new one rises...
The chip is now successfully connecting to the wifi and mqtt service, but when I try to do the dry run by putting in the command 'step_move(1000,FWD,2)' nothing happens. The motor should rotate...
Also when I press the button I get a new panic error as follows:
PANIC: unprotected error in call to Lua API (button.lua:23: attempt to perform arithmetic on upvalue '?' (a nil value))
button.lua
--file button4.lua
do
-- use pin 1 as the input pulse width counter
local pin=5
local debounce = 150 --ms
local longpress = 2000 --ms
local pulse1, pulse2, du, now, trig = 1, 0, 0, tmr.now, gpio.trig
local prev_int_time, int_time, up_time = 0
local cal_steps = 100000
local cal_steps_dn = 0
local cal_steps_up = 0
local cal_state = 0 -- 0 = not calibration, 1 = calibrating down, 2 = calibrating up
state = 0 -- state: 0 = up, 1 = transition, 2 = down
gpio.mode(pin,gpio.INT)
local function pin4cb(level)
int_time = now() / 1000
if ((int_time - prev_int_time) > debounce) then
if (level == 0) then
up_time = int_time
else
if((int_time - up_time) > longpress) then
print("calibrating")
cal_state = 1
--cur_step = 100000
step_move(cal_steps,FWD,2)
else -- short press
print("short", cal_state)
if (cal_state == 2) then -- calibrated up (done)
print("calibration done")
state = 0 -- up
cur_step = 0
tot_steps = cal_steps - step_stepsleft
print("cal_steps: " .. cal_steps)
print("step_stepsleft: " .. step_stepsleft)
print("tot_steps: " .. tot_steps)
step_stop()
pins_disable()
cal_state = 0
if file.open("cfg_tot_steps.lua", "w+") then
file.write("tot_steps=" .. tot_steps .. '\n')
file.close()
end
elseif (cal_state == 1) then -- calibrated dn (switch direction)
print("calibration low point")
print(cal_steps - step_stepsleft)
step_stop()
step_move(cal_steps,REV,2)
cal_state = 2
elseif (cal_state == 0) then
if (state == 0 and step_stepsleft == 0) then -- i am up, go dowm
rollerblind.down()
-- state = 2
elseif (state == 1) then -- i am moving, do nothing
-- do nothing
elseif (state == 2 and step_stepsleft == 0) then -- i am down, go up
rollerblind.up()
-- state = 0
end
end
end
end
--print (level)
prev_int_time = int_time
end
end
gpio.trig(pin, "both", pin4cb)
end
Here is the code for the stepper.lua:
-- stepper.lua
-- code from: http://www.esp8266.com/viewtopic.php?f=19&t=2326
-- simple stepper driver for controlling a stepper motor with a
-- l293d driver
-- nodemcu pins: 0 5 6 7
stepper_pins = {1,3,2,4} -- (A-)blue, (A+)pink, (B-)yellow, (B+)orange
--stepper_pins = {1,2,3,4}
-- half or full stepping
step_states4 = {
{1,0,0,1},
{1,1,0,0},
{0,1,1,0},
{0,0,1,1}
}
step_states8 = {
{1,0,0,0},
{1,1,0,0},
{0,1,0,0},
{0,1,1,0},
{0,0,1,0},
{0,0,1,1},
{0,0,0,1},
{1,0,0,1},
}
step_states = step_states4 -- choose stepping mode
step_numstates = 4 -- change to match number of rows in step_states
step_delay = 10 -- choose speed
step_state = 0 -- updated by step_take-function
step_direction = 1 -- choose step direction -1, 1
step_stepsleft = 0 -- number of steps to move, will de decremented
step_timerid = 4 -- which timer to use for the steps
status_timerid = 2 -- timer id for posing of status messages
-- setup pins
function pins_enable()
for i = 1, 4, 1 do
gpio.mode(stepper_pins[i],gpio.OUTPUT)
end
end
function pins_disable()
-- for i = 1, 4, 1 do -- no power, all pins
for i = 2, 4, 1 do -- no power, all pins except one (to keep it in place)
gpio.mode(stepper_pins[i],gpio.INPUT)
end
end
-- turn off all pins to let motor rest
function step_stopstate()
for i = 1, 4, 1 do
gpio.write(stepper_pins[i], 0)
end
end
-- make stepper take one step
function step_take()
-- jump to the next state in the direction, wrap
step_state = step_state + step_direction
cur_step = cur_step + step_direction * FWD
if step_state > step_numstates then
step_state = 1;
elseif step_state < 1 then
step_state = step_numstates
end
-- write the current state to the pins
pins_enable()
for i = 1, 4, 1 do
gpio.write(stepper_pins[i], step_states[step_state][i])
end
-- might take another step after step_delay
step_stepsleft = step_stepsleft-1
if step_stepsleft > 0 then
-- if cur_step > 0 and cur_step < tot_steps and step_stepsleft > 0 then
tmr.alarm(step_timerid, 10, 0, step_take )
--tmr.alarm(step_timerid, 10, 0, step_take )
else
step_stopstate()
step_stop()
pins_disable()
mq.post_status()
if file.open("cfg_cur_step.lua", "w+") then
file.write("cur_step=" .. cur_step .. '\n')
file.close()
end
end
end
-- public method to start moving number of 'int steps' in 'int direction'
function step_move(steps, direction, delay)
tmr.stop(step_timerid)
step_stepsleft = steps
step_direction = direction
step_delay = delay
step_take()
end
function step_go_to(step, delay)
if step >= cur_step then
steps = step - cur_step
step_move(steps, FWD, delay)
end
if step <= cur_step then
steps = cur_step - step
step_move(steps, REV, delay)
end
end
function percent_go_to(percent, delay)
if(percent >= 0 and percent <= 100) then
step_stop()
tmr.register(status_timerid, 1000, tmr.ALARM_AUTO, function () mq.post_status() end)
tmr.start(status_timerid)
step = percent * tot_steps / 100
step_go_to(step, delay)
end
end
-- public method to cancel moving
function step_stop()
tmr.stop(step_timerid)
tmr.stop(status_timerid)
step_stepsleft = 0
step_stopstate()
end
Let's parse the error message one by one:
unprotected error in call to Lua API (wifi_setup.lua:25: bad argument #1 to 'config' (config table not found!))
Unprotected error means that you did a normal function call, as opposed to a protected call (aka pcall), which is a function call where you expect errors to occur and want to provide means to handle them. Since you did not do a protected call, Lua does not know how to handle the error and terminates right away (which is not a bad thing).
wifi_setup.lua:25 tells you the file and line at which the error occured.
bad argument #1 to 'config' means that the problem is due to the first argument passed to a function named config.
config table not found! is the error message provided by the implementer of that function.
So in summary, there is a problem with the function call wifi.sta.config(key,config.SSID[key]) as it expects a table as first argument, while you provided something different (ie. a string with the BSSID). Indeed checking with the NodeMCU docs shows that you need to pass a table to this function:
wifi.sta.config()
Sets the WiFi station configuration. [...]
Syntax
wifi.sta.config(station_config)
Parameters
station_config table containing configuration data for
station
The expected layout of the table is documented in detail on that page as well.
ComicSansMS provided a great answer the essence of which is that you need to replace
wifi.sta.config(key,config.SSID[key])
with
wifi.sta.config{ssid=key,pwd=config.SSID[key]}
Thus a standalone example could be like this:
--wifi.setmode(wifi.NULLMODE)
config = {}
config.SSID = {}
config.SSID["ssid"] = "password"
function wifi_wait_ip()
if wifi.sta.getip() == nil then
print("IP unavailable, Waiting...")
else
tmr.stop(1)
print("\n====================================")
print("ESP8266 mode is: " .. wifi.getmode())
print("MAC address is: " .. wifi.ap.getmac())
print("IP is " .. wifi.sta.getip())
print("====================================")
end
end
function wifi_start(list_aps)
if list_aps then
for key, value in pairs(list_aps) do
if config.SSID and config.SSID[key] then
wifi.setmode(wifi.STATION);
wifi.sta.config{ssid=key, pwd=config.SSID[key]}
-- wifi.sta.connect() not needed as config() uses auto-connect=true by default
print("Connecting to " .. key .. " ...")
tmr.alarm(1, 2500, 1, wifi_wait_ip)
end
end
else
print("Error getting AP list")
end
end
function start()
print("Configuring Wifi ...")
wifi.setmode(wifi.STATION)
wifi.sta.getap(wifi_start)
end
start()