I cannot activate NVIM's built-in LSPs for javascript and html - language-server-protocol

I am trying to utilize NVIM's built-in LSPs. While I've been able to implement the LSP for css and python, I haven't been successful with javascript and html.
I installed the LSPs with
:LspInstall <LSP>
Here's how I'm loading the LSPs:
packadd nvim-lspconfig
packadd completion-nvim
:lua << EOF
local nvim_lsp = require('nvim_lsp')
local on_attach = function(_, bufnr)
require('completion').on_attach()
local opts = { noremap=true, silent=true }
end
local servers = {'tsserver', 'cssls', 'html', 'pyls'}
for _, lsp in ipairs(servers) do
nvim_lsp[lsp].setup {
on_attach = on_attach
}
print("lsp istalled -", lsp)
end
EOF
:LspInstallInfo shows:
{
cssls = {
bin_dir = "~/.cache/nvim/nvim_lsp/cssls/node_modules/.bin",
binaries = {
["css-languageserver"] = "~/.cache/nvim/nvim_lsp/cssls/node_modules/.bin/css-languageserver"
},
install_dir = "~/.cache/nvim/nvim_lsp/cssls",
is_installed = true
},
html = {
bin_dir = "~/.cache/nvim/nvim_lsp/html/node_modules/.bin",
binaries = {
["html-languageserver"] = "~/.cache/nvim/nvim_lsp/html/node_modules/.bin/html-languageserver"
},
install_dir = "~/.cache/nvim/nvim_lsp/html",
is_installed = true
},
tsserver = {
bin_dir = "~/.cache/nvim/nvim_lsp/tsserver/node_modules/.bin",
binaries = {
["typescript-language-server"] = "~/.cache/nvim/nvim_lsp/tsserver/node_modules/.bin/typescript
-language-server"
},
install_dir = "~/.cache/nvim/nvim_lsp/tsserver",
is_installed = true
}
}
They seem to be installed and the LSPs for *.css and *.py work fine.
When I open a *.js, *.ts, or *.html file I get the same response with the :LspInstallInfo command. However, I don't think the LSP is active because I do not receive any warning or error messages regarless of what I type.
I've tried loading the LSP different ways, including:
require'nvim_lsp'.tsserver.setup{}
require'nvim_lsp'.html.setup{}
I came across a post about installing typescript and I did, but it didn't seem to have any effect.
I've deactivated all of the other plugins and had the same results.

After installation, you should take consider root_dir. So if you don't have a matching root directory LSP doesn't launch.
In order to automatically launch a language server, lspconfig
searches up the directory tree from your current buffer to find a file
matching the root_dir pattern defined in each server's configuration.
For pyright, this is any directory containing ".git", "setup.py",
"setup.cfg", "pyproject.toml", or "requirements.txt").
Language servers require each project to have a root in order to
provide completion and search across symbols that may not be defined
in your current file, and to avoid having to index your entire
filesystem on each startup.
But if you want to launch LSP in any directory, you can use something like this for Javscript:
require'lspconfig'.tsserver.setup{
filetypes = { "typescript", "typescriptreact", "typescript.tsx" },
root_dir = function() return vim.loop.cwd() end -- run lsp for javascript in any directory
}

I was working on setting up neovim 0.5 today and landed up here looking for something else related to LSP. Anyho, I do have a working setup; here's a brief:
Install neovim nightly (>= 0.5 version)
Install nvim-lspconfig package (I used vim-plug)
Install tsserver: npm i -g typescript-language-server
Add setup in init.vim (remove EOF lines if init.lua):
lua << EOF
require'lspconfig'.tsserver.setup{}
EOF
Restart neovim
I noticed you're using commands like LspInstall & LspInstallInfo, but they are not present in my setup. I'm afraid I cannot comment of why they it work as expected.
LSP by itself doesn't show autocompletion. Have to use another plugin. I am getting good results with completion-nvim
This is a good reference : neovim-and-its-built-in-language-server-protocol
Oh, do give :help lsp a read if you haven't already. Cheers!

Related

VS Code Extension. How to get the directory of the current open file?

I ran into a problem while writing an extension for Visual Studio Code!
I keep getting messages like this "Cannot read properties of undefined (reading 'uri')", etc.
const defaultCompiler = 'g++';
// define the command for compiling C++ code with each compiler
const compilerCommands = {
'g++': 'g++ -S -o "{oFile}" "{cFile}"',
'clang++': 'clang++ -S -o "{oFile}" "{cFile}"'
};
let currentlyOpenFilePath = vscode.window.activeTextEditor;
// let curDir = vscode.workspace.workspaceFolders[0].uri.path
let cFile = currentlyOpenFilePath.document.uri.path;
let dirPath = path.dirname(cFile);
let oFile = path.join(dirPath, 'output.s');
let command = compilerCommands[this.currentCompiler].replace('{cFile}', currentlyOpenFilePath).replace('{oFile}', oFile);
I surfed all over Google in search of a solution to the problem, but everything I found did not help me. I tried various combinations in variables currentlyOpenFilePath, curDir, cFile (currently open file), dirPath, oFile.
My system is MacOS and also needs to work on Windows.
And also the extension is local (the previous version of the code took the path not of the current open file, but the path to the extension)
I need this plugin, when called, to successfully process the command "g++ -S -o {oFile} {cFile}" or "clang++ -S -o {oFile} {cFile}" by changing {cFile} to the current path to the open .cpp file in editor a in {oFile}, same path as {cFile} but saved as output.s
let workspacePath = '';
if (vscode.workspace.workspaceFolders?.length) {
workspacePath = workspace.workspaceFolders[0].uri.fsPath;
workspacePath = path.normalize(workspacePath);
}
Try to see if it's what you want

Cleanest way to fix Windows 'filename too long' CI tests failure in this code?

I'm trying to solve this Windows filename issue
Basically our CI job fails, with the 'filename too long' error for Windows.
warning: Could not stat path 'node_modules/data-validator/tests/data/data-examples/ds000247/sub-emptyroom/ses-18910512/meg/sub-emptyroom_ses-18910512_task-noise_run-01_meg.ds/sub-emptyroom_ses-18910512_task-noise_run-01_meg.acq': Filename too long
I've read the docs for Node's path module, which seems like a possible solution. I also read about a Windows prefix (\\?\) to bypass the MAX_PATH...but have no idea how to implement these in a clean way.
This part of the codebase with the tests that are failing. The hardcoded path (testDatasetPath) is likely part of the problem.
function getDirectories(srcpath) {
return fs.readdirSync(srcpath).filter(function(file) {
return (
file !== '.git' && fs.statSync(path.join(srcpath, file)).isDirectory()
)
})
}
var missing_session_files = //array of strings here
const dataDirectory = 'data-validator/tests/data/'
function createDatasetFileList(path) {
const testDatasetPath = `${dataDirectory}${path}`
if (!isNode) {
return createFileList(testDatasetPath)
} else {
return testDatasetPath
}
}
createFileList function
function createFileList(dir) {
const str = dir.substr(dir.lastIndexOf('/') + 1) + '$'
const rootpath = dir.replace(new RegExp(str), '')
const paths = getFilepaths(dir, [], rootpath)
return paths.map(path => {
return createFile(path, path.replace(rootpath, ''))
})
}
tl;dr A GitLab CI Job fails on Windows because the node module filenames become too long. How can I make this nodejs code OS agnostic?
This is a known error in the Windows Environment, however, there is a fix..
If you're using an NTFS based filesystem, you should be able to enable long paths in
Local Computer Policy > Computer Configuration > Administrative Templates > System > Filesystem > NTFS
This is also specified in the document you just linked, and theoretically, should work. However, the path shouldn't really be longer than 32 bits,
This will come with some performance hits, but should get the job done.
Also, you should preferably switch to a better package or search for alternatives. If this is your own package, maybe restructure it?
Finally, if none of these work, move your project folder directly to your data drive, (C:\) this will cut down on the other nested and parent folders.
This is inherently bad, and you may run into issues during deployment, if you choose to do it.

Open a directory in File Explorer

On ms Windows from node.js code, how can I open a specific directory (ex: c:\documents) in Windows file explorer?
I guess in c#, it would be:
process.Start(#"c:\test")
Try the following, which opens a File Explorer window on the computer running Node.js:
require('child_process').exec('start "" "c:\\test"');
If your path doesn't contain whitespace, you can also get away with 'start c:\\test', but the above - which requires "" as the 2nd argument[1] is the most robust approach.
Note:
The File Explorer window will launch asynchronously, and will receive focus when it does.
This related question asks for a solution that prevents the window from "stealing" focus.
[1] cmd.exe's internal start command by default interprets a "..."-enclosed 1st argument as the window title for the new console window to create (which doesn't apply here). By supplying a (dummy) window title - "" - explicitly, the 2nd argument is reliably interpreted as the target executable / document path.
Would be good to use this package so it would open on diffrent platform
https://www.npmjs.com/package/open-file-explorer
Or just use this part of it
function openExplorerin(path, callback) {
var cmd = ``;
switch (require(`os`).platform().toLowerCase().replace(/[0-9]/g, ``).replace(`darwin`, `macos`)) {
case `win`:
path = path || '=';
cmd = `explorer`;
break;
case `linux`:
path = path || '/';
cmd = `xdg-open`;
break;
case `macos`:
path = path || '/';
cmd = `open`;
break;
}
let p = require(`child_process`).spawn(cmd, [path]);
p.on('error', (err) => {
p.kill();
return callback(err);
});
}
I found another way on the WSL and potentially windows itself.
Note that you have to make sure you're formatting the path for Windows not Linux (WSL).
I wanted to save something on Windows, so in order to do that you use /mnt directory on WSL.
// format the path, so Windows isn't mad at us
// first we specify that we want the path to be compatible with windows style
// then we replace the /mnt/c/ with the format that windows explorer accepts
// the path would look like `c:\\Users\some\folder` after this line
const winPath = path.win32.resolve(dir).replace('\\mnt\\c\\', 'c:\\\\');
// then we use the same logic as the previous answer but change it up a bit
// do remember about the "" if you have spaces in your name
require('child_process').exec(`explorer.exe "${winPath}"`);
This should open the file explorer for you.
A slightly simpler, and more cross-platform solution, would be to use this.
var explorer;
switch (platform()) {
case "win32": explorer = "explorer"; break;
case "linux": explorer = "xdg-open"; break;
case "darwin": explorer = "open"; break;
}
spawn(explorer, [path], { detached: true }).unref();
platform() is from the os module, and spawn is from the child_process module.

NixOS beginner: xmonad and haskellmode in NixOS 14.04

I'm trying so set up a NixOS VM for code development in haskell, and got into troubles with the basic installation of both xmonad and emacs. The relevant part of my /etc/nixos/configuration.nix is
environment.systemPackages = with pkgs; [
emacs
emacs24Packages.haskellMode
xlibs.xmessage
haskellPackages.haskellPlatform.ghc
haskellPackages.xmobar
haskellPackages.xmonad
haskellPackages.xmonadContrib
haskellPackages.xmonadExtras
];
xmonad: when I try to compile the code, xmonad complains that it couldn't find the module XMonad.Util.EZConfig.
Compiling xmonad.hs with ghc is ok, and I'm also able to load the module into ghci.
On the #nixos channel, I was told to use the function ghcWithPackages, but I wasn't able to correct the problem. Moreover, I'd like to understand why there is this problem in the first place, as it seems to me that this is a very simple use case. A minimal xmonad.hs with which I have the problem is:
import XMonad
import XMonad.Util.EZConfig
main = xmonad $ defaultConfig
{ modMask = mod4Mask
, terminal = "konsole"
}
`additionalKeysP`
[ ("M-e", spawn "emacs")
, ("M-f", spawn "firefox")
]
emacs: after the installation of the package haskellmode (look at the configuration.nix above), I'm not able to enter haskell-mode in emacs.
I put together these problems as I suspect they're both caused by a fundamental incomprehension of something on my behalf, so the cause may be common.
just add
windowManager.xmonad.enableContribAndExtras = true;
to
/etc/nixos/configuration.nix
Then start xmonad the usual way through your .xsession file
I can't add comment for now... But I think it's a problem with cabal local and global repositories.
As I see, "Nix allows users to install packages without requiring root privileges, and provides each user with its own view of the set of installed packages. Multiple versions of a program or library can be installed at the same time. Package upgrades are atomic and can be rolled back."
Maybe you can use ghc-pkg list to see if, in root and normal user, the packages are well installed.
I am unsure why you're unable to compile that... I can't offer a solution, but personally, I am able to compile my XMonad config which includes
import XMonad.Util.EZConfig
This is the relevant lines in my configuration.
environment.systemPackages = with pkgs; [
haskellPackages.xmobar
haskellPackages.xmonad
haskellPackages.xmonad-contrib
haskellPackages.xmonad-extras
];
programs.dconf.enable = true;
services = {
dbus = {
enable = true;
packages = [ pkgs.dconf ];
};
xserver = {
enable = true;
libinput = {
enable = true;
touchpad.disableWhileTyping = true;
};
serverLayoutSection = ''
Option "StandbyTime" "0"
Option "SuspendTime" "0"
Option "OffTime" "0"
'';
displayManager = {
defaultSession = "none+xmonad";
lightdm.enable = true;
lightdm.greeters.mini.enable = true;
};
windowManager.xmonad = {
enable = true;
enableContribAndExtras = true;
};
xkbOptions = "caps:ctrl_modifier";
};
};
env = {
XMONAD_CONFIG_DIR = "$XDG_CONFIG_HOME/xmonad";
XMONAD_CACHE_DIR = "$XDG_CONFIG_HOME/xmonad";
XMONAD_DATA_DIR = "$XDG_CONFIG_HOME/xmonad";
};
As someone pointed out, it might be because you don't have the line:
enableContribAndExtras = true;
I posted my configuration also so you could see how this would tie into a more extensive configuration, in this case for lightdm.

intel XDK directory browsing

I'm trying to get a way to reach and parse all JSON file from a directory, witch inside an Intel Xdk project. All files in my case stored in '/cards' folder of the project.
I have tried to reach theme with fs.readdirSync('/cards') method, but that wasn't pointed to the location what I expected, and I haven't got luck with 'intel.xdk.webRoot' path.
With the simulator I've managed to get files, with a trick:
fs.readdirSync(intel.xdk.webRoot.replace('localhost:53862/http-services/emulator-webserver/ripple/userapp/', '')+'cards');
(intel.xdk.webRoot contains absolute path to my '/cards' folder)
and its work like a charm, but it isn't working in any real device what I'd like to build it.
I have tried it with iOS7 and Android 4.2 phones.
Please help me to use in a great way the fs.readdirSync() method, or give me some alternate solution.
Thanks and regards,
satire
You can't use nodejs api's on mobile apps. It is a bug that the XDK emulator lets you do it. The bug is fixed in the next release of XDK.
You could write a node program that scans the directory and then writes out a js file with the contents of the directory. You would run the node script on your laptop before packaging the app in the build tab. The output would look like this:
files.js:
dir = {files: ['file1.txt', 'file2.txt']}
Then use a script tag to load it:
And your js can read the dir variable. This assumes that the contents does not change while the app is running.
The location of your application's root directory will vary depending on the target platform and can also vary with the emulator and the debug containers (e.g., App Preview versus App Analyzer). Here's what I've done to locate files within the project:
// getWebPath() returns the location of index.html
// getWebRoot() returns URI pointing to index.html
function getWebPath() {
"use strict" ;
var path = window.location.pathname ;
path = path.substring( 0, path.lastIndexOf('/') ) ;
return 'file://' + path ;
}
function getWebRoot() {
"use strict" ;
var path = window.location.href ;
path = path.substring( 0, path.lastIndexOf('/') ) ;
return path ;
}
I have not been able to test this exhaustively, but it appears to be working so far. Here's an example where I'm using a Cordova media object and want it to play a file stored locally in the project. Note that I have to "special case" the iOS container:
var x = window.device && window.device.platform ;
console.log("platform = ", x) ;
if(x.match(/(ios)|(iphone)|(ipod)|(ipad)/ig)) {
var media = new Media("audio/bark.wav", mediaSuccess, mediaError, mediaStatus) ;
}
else {
var media = new Media(getWebRoot() + "/audio/bark.wav", mediaSuccess, mediaError, mediaStatus) ;
}
console.log("media.src = ", media.src) ;
media.play() ;
Not quite sure if this is what you are looking for...
You will need to use the Cordova build in the Intel XDK, here is information on building with Cordova:
https://software.intel.com/en-us/html5/articles/using-the-cordova-for-android-ios-etc-build-option
And a DirectoryReader example:
function success(entries) {
var i;
for (i=0; i<entries.length; i++) {
console.log(entries[i].name);
}
}
function fail(error) {
alert("Failed to list directory contents: " + error.code);
}
// Get a directory reader
var directoryReader = dirEntry.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(success,fail);

Resources