syntax highlighting autocmd is not working in neovim - lua

I am new to vim and esp. in lua scripting. I want to create an autocmd such that all the jinja files will get yaml syntax highlighting.
local a = vim.api
a.nvim_create_autocmd( { "BufNewFile", "BufRead" }, {
pattern = { "*.j2" },
command = [[ lua(syntax = "html")]],
})
but this is not working. Could someone point the obvious.
DD.

I give you an Example on how i do Lua Syntaxhighlightning for my own *.luado files.
Before i have copied ( as super Q User: root.root ) /usr/share/nvim/runtime/syntax/lua.vim to /usr/share/nvim/runtime/syntax/luado.vim.
So i can change it independently from original lua.vim.
It is not necessary to change luado.vim for the Example below.
~/.config/nvim/lua/init.lua required by ~/.config/nvim/init.vim
( At First and off course before: syntax on )
--[[ Automatic Execution of Lua Oneliner if file extension *.luado
With Lua Syntaxhighlighting ]]
vim.api.nvim_create_autocmd({"BufEnter"},{
pattern = {"*.luado"},
command = "luado vim.api.nvim_command('setfiletype luado') load(line, 'koys_nvim_auto_luado')()"
})
Triggers at "BufEnter" and shows that "BufNewFile", "BufRead" not really needed.
( Every time before it is shown from Buffer ;-) )
Impression
Now lets change to next Buffer with :bn to test3.luado
And back with :bp to test2.luado (Output of set)
(test2.luado will be shown after ENTER/RETURN)

Related

Using vimscript plugin in lua neovim

I tried to use this simple script (its not from me) for simple reading a file and adding its content to a plugin called projectionist: https://github.com/tpope/vim-projectionist
(The original script: https://github.com/andyl/vim-projectionist-elixir/blob/master/ftdetect/elixir.vim)
I didn't find any api for reading a file in lua nvim. The error in the picture targets the line let l:json = readfile(s:proj_jsn) so I assume that this api is not available by lua?
if vim.g.loaded_vim_projectionist then
return
end
vim.g.loaded_vim_projectionist = 1
vim.api.nvim_exec([[
let s:base_dir = resolve(expand("<sfile>:p:h"))
let s:proj_jsn = s:base_dir . "/projections.json"
function! s:setProjections()
let l:json = readfile(s:proj_jsn)
let l:dict = projectionist#json_parse(l:json)
call projectionist#append(getcwd(), l:dict)
endfunction
call s:setProjections()
]], false)
The error message (picture)
I checked a several times if the file projections.json is in the right place, so this is not the mistake.
Thank you all in advance.

Nesting extra Span in Pandoc filter disappears the image

I am currently working on massaging the HTML output of a Pandoc filter due to some annoying restrictions in the CMS that is the eventual beneficiary of my hard work.
My working filter (now with the obvious declarations) is as follows:
local List = require 'pandoc.List'
local Emph = pandoc.Emph
local Quoted = pandoc.Quoted
local Span = pandoc.Span
local Str = pandoc.Str
local Strong = pandoc.Strong
local image_base = "http://my.website.example/images/"
local image_author = "Someone Not Stigma"
function process_images(el)
el.src = el.src:gsub("^file:images/", image_base)
el.caption = {
Strong( Quoted( "DoubleQuote", el.caption ) ),
Str(" by "),
Emph(image_author)
}
return el
end
return {{Image = process_images}}
In the eventual HTML, this gives me a nice figure with img and figcaption element inside of it. Wonderful. Unfortunately, my CMS destroys the figcaption (like it tends to destroy other stuff), and as such I figured I'd wrap everything in an extra span so I can style that one instead.
function process_images(el)
el.src = el.src:gsub("^file:images/", image_base)
el.caption = {
Span(
{
Strong( Quoted( "DoubleQuote", el.caption ) ),
Str(" by "),
Emph(image_author)
},
{ class="img-caption" }
)
}
return el
end
And yet somehow, this causes Pandoc to completely delete the image from the resulting HTML.
I have tried replacing the table syntaxes with List({}) syntaxes, but that just gives me upvalue complaints. I looked at the manual, but for as far I can tell I am doing everything right.
What am I missing here?
I call pandoc as follows:
pandoc --from=markdown-tex_math_dollars "Content.pure.txt" --lua-filter=".\pandoc-filter.lua" --to=html5 --template=".\pandoc-template.txt" -o "Content.txt"
Extensions are .txt (because these files are not browser ready). The template being used is rather lengthy (there's a fair bit of YAML variables and related markup), but be assured: $body$ can be found in there.
I am not a wise man. Always update to the latest version before posting questions, folks.
I was running an older version of Pandoc (v2.6), and upgrading to v2.9.1.1 suddenly made the output appear again. That's a lot of versions released in the span of about a year!
(In my defense, my Pandoc-filter-fu is not particularly strong, so it makes sense to assume user error rather than program bug. Why is it that every time you assume bug, it is user error, and every time you assume user error, it is an outright bug?)

How do I do "io.read" twice on one variable after inputting the wrong type?

Heyo. I'm pretty new to Lua (although I do code with Java), so I don't really know anything on this. I'm basically trying to get a user's input, and if it's not the right type, then restart. Now, I'm not sure if it's just Lua or my IDE (I'm using ZeroBrane Studio if that helps), but it won't reinput for whatever reason. (it just loops, meaning it skips the io.read line)
::restart::
...
a = io.read("*number")
if unit == nil then
print("Error! Incorrect Input!\nRestarting...")
goto restart
end
Oh, and yes, I'm using goto commands for restart. I thought that might be what's causing the issue, but I also tried this:
a = io.read("*number") --input non-number
print(a) --prints
a = io.read("*number") --skips
print(a) --prints
When you input a number, it doesn't skip.
Any help would be nice. Thanks in advance.
nvm i solved it myself
local a
repeat
a = io.read(); a = tonumber(a)
if not a then
print("Incorrect Input!\n(Try using only numbers)")
end
until a
::restart::
local a = io.read("*n", "*l")
if a == nil then
io.read("*l") -- skip the erroneous input line
print("Error! Incorrect Input!\nRestarting...")
goto restart
end
P.S.
Feel free to use goto whenever it makes your code more understandable.
For example, using while of repeat-until loop in this code wouldn't make it better (you would need either additional local variable or break statement).
Instead of using the built-in filter of io.read() (which I do think is bugged sometimes) you should consider using an own little function to ensure that the correct data will be give by the user.
This is such a function:
function --[[ any ]] GetUserInput(--[[ string ]] expectedType, --[[ string ]] errorText)
local --[[ bool ]] needInput = true
local --[[ any ]] input = nil
while needInput do
input = GetData()
if ( type(input) == expectedType ) then
needInput = false
else
print(errorText)
end
end
return input
end
You can then call it with:
local userInput = GetUserInput("number", "Error: Incorrect Input! Please give a number.")
Oh and on a sidenote: Goto is considered bad practice.

In trepl or luajit, how can I find the source code of a library I'm using?

Let's say I'm working with a lua library I installed using luarocks, and I want to see the definition of a function from that library. In ipython in could use
??function_name
to see the definition in the terminal, in matlab I could use
which function_name
then use my editor to look at the path returned by which. How could I do something similar to find the function definition for a lua library?
In 'plain' Lua/JIT, you can say debug.getinfo( func ) and will get a table containing (among others) the fields short_src, source and linedefined.
For Lua functions, short_src will be the filename or stdin if it was defined in the REPL. (source has a slightly different format, filenames are prefixed with an #, a = prefix is used for C functions or stuff defined interactively, and for loaded functions, it will be the actual string that was loaded.)
You can pack that up in a function like
function sourceof( f )
local info = debug.getinfo( f, "S" )
return info.short_src, info.linedefined
end
or maybe even start an editor and point it there, e.g. (for vim)
function viewsource( f )
-- get info & check it's actually from a file
local info = debug.getinfo( f, "S" )
local src, line = info.source, info.linedefined
if src == "=[C]" then return nil, "Is a C function." end
local path = src:match "^#(.*)$"
if path then
-- start vim (or an other editor if you adapt the format string)
return os.execute( ("vim -fR %q +%d"):format( path, line ) )
end
return nil, "Was defined at run time."
end
And just for fun, here's yet another version that returns the code if it can find it somewhere. (This will also work for functions that have been generated at run time, e.g. by calling load, and where no source file exists. You could also work in the other direction by dumping the loaded snippet into a temp file and opening that…)
-- helper to extract the source block defining the function
local function funclines( str, line1, lineN, filename )
-- if linedefined / lastlinedefined are 0, this is the main chunk's function
if line1 == 0 and lineN == 0 then
filename = filename and filename.." (main chunk)"
or "(chunk defined at runtime)"
return "-- "..filename.."\n"..str
end
-- add line info to file name or use placeholder
filename = filename and filename..":"..line1 or "(defined at runtime)"
-- get the source block
local phase, skip, grab = 1, line1-1, lineN-(line1-1)
local ostart, oend -- these will be the start/end offsets
if skip == 0 then phase, ostart = 2, 0 end -- starts at first line
for pos in str:gmatch "\n()" do
if phase == 1 then -- find offset of linedefined
skip = skip - 1 ; if skip == 0 then ostart, phase = pos, 2 end
else -- phase == 2, find offset of lastlinedefined+1
grab = grab - 1 ; if grab == 0 then oend = pos-2 ; break end
end
end
return "-- "..filename.."\n"..str:sub( ostart, oend )
end
function dumpsource( f )
-- get info & line numbers
local info = debug.getinfo( f, "S" )
local src, line, lastline = info.source, info.linedefined, info.lastlinedefined
-- can't do anything for a C function
if src == "=[C]" then return nil, "Is a C function." end
if src == "=stdin" then return nil, "Was defined interactively." end
-- for files, fetch the definition
local path = src:match "^#(.*)$"
if path then
local f = io.open( path )
local code = f:read '*a'
f:close( )
return funclines( code, line, lastline, path )
end
-- otherwise `load`ed, so `source`/`src` _is_ the source
return funclines( src, line, lastline )
end
A closing remark: If you paste code into a Lua/JIT REPL, locals disappear between definitions, because every line (or minimal complete group of lines) is its own chunk. The common fix (that you probably know) is to wrap everything into a block as do*paste*end, but an alternative is to load[[*paste*]]() (possibly with more =s like [===[ and ]===].) If you paste this way, the above dumpsource (or any other function using debug.getinfo) will then be able to get the source of the function(s). This also means that if you defined a nice function but it's gone from the history and the scroll buffer, you can recover it in this way (if you defined it by loading and not directly feeding the interpreter). Saving the source in a file will then also be possible without copy-pasting and not require editing out the >> prompts.

I cant figure out the why the 2 editors give different syntax errors for the same script

I am getting an error when i compile this lua script. The LUA editor and ptokaX Server seem to think so. I am unable to figure out the error.
The LUA Editor says the error is in dofile( path.."files/mcunsubs.txt" ).
The PtokaX Editor says that the error is in this part of the code :
data = data:gsub( "[\|]", "" )
data = data:gsub( "\&\#124\;", "\|" )
data = data:gsub( "\&\#036\;", "\$" )
Here is the code.
--[[
This file is part of HiT Hi FiT Hai's PtokaX scripts
Copyright: © 2014 HiT Hi FiT Hai group
Licence: GNU General Public Licence v3 https://www.gnu.org/licenses/gpl-3.0.html
--]]
unsubbed={}
subbed={}
dofile( path.."files/mcunsubs.txt" )
tabUsers = Core.GetOnlineUsers()
for k,v in ipairs(tabUsers) do
if not isthere_key(v.sNick,unsubbed) then
table.insert(subbed,v.sNick)
end
end
ircout = function(data)
data = data:gsub( "[\|]", "" ) -- Removing the terminating '|' character only.
data = data:gsub( "\&\#124\;", "\|" )
data = data:gsub( "\&\#036\;", "\$" )
local file= io.open("/root/DCout.txt","a+")
file:write(data.."\n")
file:flush()
file:close()
end
dcmcout = function(data)
for k,v in ipairs(subbed) do
Core.SendToNick(v,data)
end
end
UserConnected= function (tUser)
if not isthere_key(tUser.sNick,unsubbed) then
if not isthere_key(tUser.sNick,subbed) then
table.insert(subbed,tUser.sNick)
end
end
end
RegConnected = UserConnected
OpConnected = UserConnected
UserDisConnected= function (tUser)
key = isthere_key(tUser.sNick,subbed)
while key do
table.remove( subbed, key)
key = isthere_key(user.sNick,subbed)
end
end
RegDisConnected = UserDisConnected
OpDisConnected = UserDisConnected
The Lua editor (which I assume is SciTE) is giving you the error in line #12 because SciTE doesn't recognise the Core table in the next line:
tabUsers = Core.GetOnlineUsers()
When you execute the same script in PtokaX, the Core table is defined and no error is encountered there. Since you are using a newer Lua version than the one in which this file was originally written (written for Lua 5.1, you've Lua 5.2) you are getting the error. Lua 5.1 was more permissive with wrong patterns for string matching, whereas the latter isn't.
For a solution, you can use the following:
data = data:gsub( "|", "" ):gsub( "|", "|" ):gsub( "$", "$" )

Resources