Migrating Filetype autocmd setting from vimscript to lua - neovim

I'm migrating my vimscript settings to lua, but hit a snag.
I got several of these type of autocmd settings which I don't have a clue how to migrate them
augroup py_fold_custom
autocmd!
autocmd FileType python setlocal foldmethod=indent
augroup END
augroup html_syntax_disable
autocmd!
autocmd Filetype html if getfsize(expand("%")) > 500000 | setlocal syntax=off | endif
augroup END
Can somebody help?

Good choice switching to neovim. I know how it feels overwhelming to translate these sort of commands. While most of my config has been converted, I have one huge monster vim script command that I've yet to be able to translate.
As with everything in neovim you have several options of how to convert these to lua.
First, using autocommands
local generalSettingsGroup = vim.api.nvim_create_augroup('General settings', { clear = true })
vim.api.nvim_create_autocmd('FileType', {
pattern = { '*.py' },
callback = function()
vim.opt.foldmethod = 'indent'
end,
group = generalSettingsGroup,
})
vim.api.nvim_create_autocmd('FileType', {
pattern = { '*.html' },
callback = function()
if vim.api.nvim_buf_line_count(0) > 500000 then
vim.bo.syntax = 'off'
end
end,
group = generalSettingsGroup,
})
But you could also use the ftplugin directory for things like this.
You can still use lua, and upon detection of these file types this code will be run by neovim just by being in this directory.
In a file in your config directory create ftplugin/python.lua with this in the file
vim.opt.foldmethod = 'indent'
And for the html one ftplugin/html.lua
if vim.api.nvim_buf_line_count(0) > 500000 then
vim.bo.syntax = 'off'
end
Those are the main ways that come to mind for me. I hope this helps!

Related

After updating neovim to 0.81 and all plugins to latest release, autocmd to highlight words on cursor hold is not working on certain languages

I have an auto command highlight words on cursor hold and this autocmd gets attached to buffer when the LSP server has the capability of documentFormattingProvider.
After updating neovim to 0.81 and all the plugins and language servers. The behaviour of this autocmd is buggy.
on svelte files, it does not work and actually outputs error: method textDocument/documentHighlight is not supported by any of the servers registered for the current buffer (lsp:svelte)
on python, no highlighting, no errors, but running lua vim.lsp.buf.document_highlight() on cmd line while cursor on repetitive word, it does highlight (lsp:pyright,black)
on go, it is working! (lsp:gopls)
on typescript files, it is working (lsp:tsserver)
on dart it is working (lsp:dartls)
Here is my dotfiles
local function lsp_highlight_document(client)
-- Set autocommands conditional on server_capabilities
if client.server_capabilities.documentFormattingProvider then
vim.api.nvim_exec(
[[
augroup lsp_document_highlight
autocmd! * <buffer>
autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight()
autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references()
augroup END
]],
false
)
end
end
I also tried (also not working):
local function lsp_highlight_document(client)
-- Set autocommands conditional on server_capabilities
if client.server_capabilities.documentFormattingProvider then
vim.api.nvim_create_augroup("lsp_document_highlight", { clear = true })
vim.api.nvim_clear_autocmds({ buffer = bufnr, group = "lsp_document_highlight" })
vim.api.nvim_create_autocmd("CursorHold", {
callback = vim.lsp.buf.document_highlight,
buffer = bufnr,
group = "lsp_document_highlight",
desc = "Document Highlight",
})
vim.api.nvim_create_autocmd("CursorMoved", {
callback = vim.lsp.buf.clear_references,
buffer = bufnr,
group = "lsp_document_highlight",
desc = "Clear All the References",
})
end
end
Both of these functions gets called here
options.on_attach = function(client, bufnr)
if client.name == "tsserver" then
client.server_capabilities.documentFormattingProvider = true
end
if client.name == "sumneko_lua" then
client.server_capabilities.documentFormattingProvider = false
end
lsp_highlight_document(client)
lsp_keymaps(bufnr)
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
options.capabilities = cmp_nvim_lsp.default_capabilities(capabilities)
return options
Prior to this update, it was working fine in every language. Not sure what is missing.
Here is my config, which works for pyright, pylsp, lua-language-server etc.:
local api = vim.api
local lsp = vim.lsp
if client.server_capabilities.documentHighlightProvider then
vim.cmd([[
hi! link LspReferenceRead Visual
hi! link LspReferenceText Visual
hi! link LspReferenceWrite Visual
]])
local gid = api.nvim_create_augroup("lsp_document_highlight", { clear = true })
api.nvim_create_autocmd("CursorHold" , {
group = gid,
buffer = bufnr,
callback = function ()
lsp.buf.document_highlight()
end
})
api.nvim_create_autocmd("CursorMoved" , {
group = gid,
buffer = bufnr,
callback = function ()
lsp.buf.clear_references()
end
})
end
Works well on nvim 0.8.1. Try it to see if it works. If it does not work, I think there is something wrong with your config, you need to dig deeper to find why.

How to select symbols onWorkspaceSymbol

I am developing an extension for visual studio code using language server protocol, and I am including the support for "Go to symbol in workspace". My problem is that I don't know how to select the matches...
Actually I use this function I wrote:
function IsInside(word1, word2)
{
var ret = "";
var i1 = 0;
var lenMatch =0, maxLenMatch = 0, minLenMatch = word1.length;
for(var i2=0;i2<word2.length;i2++)
{
if(word1[i1]==word2[i2])
{
lenMatch++;
if(lenMatch>maxLenMatch) maxLenMatch = lenMatch;
ret+=word1[i1];
i1++;
if(i1==word1.length)
{
if(lenMatch<minLenMatch) minLenMatch = lenMatch;
// Trying to filter like VSCode does.
return maxLenMatch>=word1.length/2 && minLenMatch>=2? ret : undefined;
}
} else
{
ret+="Z";
if(lenMatch>0 && lenMatch<minLenMatch)
minLenMatch = lenMatch;
lenMatch=0;
}
}
return undefined;
}
That return the sortText if the word1 is inside the word2, undefined otherwise. My problem are cases like this:
My algorithm see that 'aller' is inside CallServer, but the interface does not mark it like expected.
There is a library or something that I must use for this? the code of VSCode is big and complex and I don't know where start looking for this information...
VSCode's API docs for provideWorkspaceSymbols() provide the following guidance (which I don't think your example violates):
The query-parameter should be interpreted in a relaxed way as the editor will apply its own highlighting and scoring on the results. A good rule of thumb is to match case-insensitive and to simply check that the characters of query appear in their order in a candidate symbol. Don't use prefix, substring, or similar strict matching.
These docs were added in response to this discussion, where somebody had very much the same issue as you.
Having a brief look at VSCode sources, internally it seems to use filters.matchFuzzy2() for the highlighting (see here and here). I don't think it's exposed in the API, so you would probably have to copy it if you wanted the behavior to match exactly.

How can I run a VBScript file silently in the background?

I want to run a VBScript file silently, because it is just a part of a hidden script.
I'm using the VBScript to export automatically documents out of SAP, that is working perfectly, unless showing each step in the SAP-GUI.
The VBScript file is started in a PowerShell, where I already tried to hide the process like:
$vbsPDPPath = "$env:userprofile\AppData\Roaming\KPIReport"
$vbsPDPName = "SAP-ExportPDP.vbs"
$processNamePDP = $vbsPDPPath + "\" + $vbsPDPName
Start-Process $processNamePDP -WindowStyle Hidden
Didn't work out though.
I'm looking for a solution like in VBA, where you can just add:
Application.ScreenUpdating = False
Still have no idea how to solve it. I thought it would be helpful to let you see the vbs-code, there must be the fault.
I noticed that I haven't mentioned to hide the SAP GUI as well as the Excel Application.
Dim Number_PDP
Dim testNode
Dim WshShell
Dim profile
Set WshShell = WScript.CreateObject("WScript.Shell")
profile = WshShell.ExpandEnvironmentStrings("%USERPROFILE%")
'read XML file
Set xmlDoc = CreateObject("MSXML.DomDocument")
xmlDoc.Load profile & "\AppData\Roaming\KPIReport\DIS.xml"
For Each testNode In xmlDoc.selectNodes("/Reports/Report")
Number_PDP = testNode.SelectSingleNode("DIS_PDP").Text
'connect to SAP GUI
If Not IsObject(application) Then
Set SapGuiAuto = GetObject("SAPGUI")
Set application = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(connection) Then
Set connection = application.Children(0)
End If
If Not IsObject(session) Then
Set session = connection.Children(0)
End If
If IsObject(WScript) Then
WScript.ConnectObject session, "on"
WScript.ConnectObject application, "on"
End If
SapGuiAuto.Visible = false
'not working, thought it is possible to hide SAP
session.findById("wnd[0]").resizeWorkingPane 132,31,false
session.findById("wnd[0]/tbar[0]/okcd").text = "/n cv04n"
session.findById("wnd[0]").sendVKey 0
...
'cutted a couple of rows, just opens a document in Excel with SAP
'after SAP opens Excel I used this code to save the documents
set objExcel = getobject(,"Excel.Application")
if err.number<>0 then
err.clear
end if
'this part should be hidden as well, not working
objExcel.Visible = false
objExcel.ActiveWorkbook.SaveAs profile & "\AppData\Roaming\KPIReport\" & Number_PDP
objExcel.ActiveWorkbook.Close
objExcel.Quit
Next
I would use a workaround in both cases.
For example:
. . .
'session.findById("wnd[0]").resizeWorkingPane 132,31,false
session.findById("wnd[0]").iconify
. . .
and
. . .
'objExcel.Visible = false
objExcel.WindowState = 2
. . .
Regards,
ScriptMan

Breaking Matlab code long lines in Latex listings environment

I need to include Matlab code in my Latex file. I'm using the listings package with matlab-prettifier and the settings are:
\usepackage{listings}
\usepackage[numbered, framed]{matlab-prettifier}
...
\lstset{
style = Matlab-editor,
basicstyle = \mlttfamily\scriptsize,
escapechar = ",
mlshowsectionrules = true,
}
\lstinputlisting[breaklines = true, breakatwhitespace=false]{test.m}
The long lines do not break, however. Any idea why this happens and how to solve it?
Edit: I discovered that if I change the class of the document from mwbk (current) to article, the lines break as desired. There should be a conflict with the class mwbk defined in
http://web.mit.edu/ghudson/dev/nokrb/third/tetex/texmf/tex/latex/mwcls/mwbk.cls, but I cannot figure out what is the problem.

Sed and awk application

I've read a little about sed and awk, and understand that both are text manipulators.
I plan to use one of these to edit groups of files (code in some programming language, js, python etc.) to make similar changes to large sets of files.
Primarily editing function definitions (parameters passed) and variable names for now, but the more I can do the better.
I'd like to know if someone's attempted something similar, and those who have, are there any obvious pitfalls that one should look out for? And which of sed and awk would be preferable/more suitable for such an application. (Or maybe something entirely else? )
Input
function(paramOne){
//Some code here
var variableOne = new ObjectType;
array[1] = "Some String";
instanceObj = new Something.something;
}
Output
function(ParamterOne){
//Some code here
var PartOfSomething.variableOne = new ObjectType;
sArray[1] = "Some String";
var instanceObj = new Something.something
}
Here's a GNU awk (for "gensub()" function) script that will transform your sample input file into your desired output file:
$ cat tst.awk
BEGIN{ sym = "[[:alnum:]_]+" }
{
$0 = gensub("^(" sym ")[(](" sym ")[)](.*)","\\1(ParameterOne)\\3","")
$0 = gensub("^(var )(" sym ")(.*)","\\1PartOfSomething.\\2\\3","")
$0 = gensub("^a(rray.*)","sA\\1","")
$0 = gensub("^(" sym " =.*)","var \\1","")
print
}
$ cat file
function(paramOne){
//Some code here
var variableOne = new ObjectType;
array[1] = "Some String";
instanceObj = new Something.something;
}
$ gawk -f tst.awk file
function(ParameterOne){
//Some code here
var PartOfSomething.variableOne = new ObjectType;
sArray[1] = "Some String";
var instanceObj = new Something.something;
}
BUT think about how your real input could vary from that - you could have more/less/different spacing between symbols. You could have assignments starting on one line and finishing on the next. You could have comments that contain similar-looking lines to the code that you don't want changed. You could have multiple statements on one line. etc., etc.
You can address every issue one at a time but it could take you a lot longer than just updating your files and chances are you still will not be able to get it completely right.
If your code is EXCEEDINGLY well structured and RIGOROUSLY follows a specific, highly restrictive coding format then you might be able to do what you want with a scripting language but your best bets are either:
change the files by hand if there's less than, say, 10,000 of them or
get a hold of a parser (e.g. the compiler) for the language your files are written in and modify that to spit out your updated code.
As soon as it starts to get slightly more complicated you will switch to a script language anyway. So why not start with python in the first place?
Walking directories:
walking along and processing files in directory in python
Replacing text in a file:
replacing text in a file with Python
Python regex howto:
http://docs.python.org/dev/howto/regex.html
I also recommend to install Eclipse + PyDev as this will make debugging a lot easier.
Here is an example of a simple automatic replacer
import os;
import sys;
import re;
import itertools;
folder = r"C:\Workspaces\Test\";
skip_extensions = ['.gif', '.png', '.jpg', '.mp4', ''];
substitutions = [("Test.Alpha.", "test.alpha."),
("Test.Beta.", "test.beta."),
("Test.Gamma.", "test.gamma.")];
for root, dirs, files in os.walk(folder):
for name in files:
(base, ext) = os.path.splitext(name);
file_path = os.path.join(root, name);
if ext in skip_extensions:
print "skipping", file_path;
else:
print "processing", file_path;
with open(file_path) as f:
s = f.read();
before = [[s[found.start()-5:found.end()+5] for found in re.finditer(old, s)] for old, new in substitutions];
for old, new in substitutions:
s = s.replace(old, new);
after = [[s[found.start()-5:found.end()+5] for found in re.finditer(new, s)] for old, new in substitutions];
for b, a in zip(itertools.chain(*before), itertools.chain(*after)):
print b, "-->", a;
with open(file_path, "w") as f:
f.write(s);