Compare commits

..

No commits in common. "main" and "0.0.7" have entirely different histories.
main ... 0.0.7

19 changed files with 218 additions and 717 deletions

View File

@ -2,56 +2,6 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
## [0.0.10] - 2024-06-09
### Features
- Runtime is now optional
- [**breaking**] `init.lua` configuration is now a `mkNeovimPkg`'s option
- Add option init config object to generate `init.lua`
### Miscellaneous Tasks
- Add alejandra to nix shell
## [0.0.9] - 2024-06-09
### Features
- Sloth command has now completion
- Add describe subcommand
- Introduce mkPluginsFromInputs function
### Bug Fixes
- Init/config are loaded to on-the-fly build plugins
- Plugins with init are now loaded as they should be
### Refactor
- Filters are now fully dynamic
### Miscellaneous Tasks
- Remove sourcesWith fn, using lib.fileset
- Move back to flake-utils
## [0.0.8] - 2024-06-04
### Features
- Can load lazy plugins on events
- Can load lazy plugins on keymaps
### Bug Fixes
- Move files instead of copying them
- Sloth list was broken since refactoring
### Miscellaneous Tasks
- Switch from nixpkgs `23.11` to `unstable`
## [0.0.7] - 2024-06-03 ## [0.0.7] - 2024-06-03
### Features ### Features

157
README.md
View File

@ -8,20 +8,19 @@ A [neovim] plugin and configuration management plugin, highly inspired by [lazy]
- [Features](#features) - [Features](#features)
- [SemVer](#semver) - [SemVer](#semver)
- [Installation](#installation) - [Installation](#installation)
- [Flake installation](#flake-installation) - [Flake installation](#flake-installation)
- [Usage](#usage) - [Usage](#usage)
- [Documentation](#documentation) - [Documentation](#documentation)
- [nix](#nix) - [nix](#nix)
- [`mkPluginsFromInputs`](#mkpluginsfrominputs) - [`mkNeovimPkg`](#mkneovimpkg)
- [`mkNeovimPkg`](#mkneovimpkg) - [neovim (lua)](#neovim-lua)
- [neovim (lua)](#neovim-lua) - [Using default `init.lua`](#using-default-initlua)
- [Using default `init.lua`](#using-default-initlua) - [Using your own `init.lua`](#using-your-own-initlua)
- [Using your own `init.lua`](#using-your-own-initlua) - [`:Sloth` command](#sloth-command)
- [`:Sloth` command](#sloth-command) - [`list` subcommand](#list-subcommand)
- [`list` subcommand](#list-subcommand) - [`load` subcommand](#load-subcommand)
- [`load` subcommand](#load-subcommand) - [`version` subcommand](#version-subcommand)
- [`version` subcommand](#version-subcommand) - [API](#api)
- [API](#api)
<!-- TOC --> <!-- TOC -->
@ -45,8 +44,8 @@ A [neovim] plugin and configuration management plugin, highly inspired by [lazy]
- [X] Lazy load your plugins - [X] Lazy load your plugins
- [X] on command - [X] on command
- [X] on filetype - [X] on filetype
- [X] on event - [ ] on event
- [X] on keybinding - [ ] on keybinding
- [X] load plugins in order (via plugin `dependencies` property) - [X] load plugins in order (via plugin `dependencies` property)
- [X] Have a `:Sloth` command to load or query your plugins - [X] Have a `:Sloth` command to load or query your plugins
- [ ] Generate spell files on build (maybe) - [ ] Generate spell files on build (maybe)
@ -123,95 +122,34 @@ sloth-flake.lib.mkNeovimPkg {
### nix ### nix
#### `mkPluginsFromInputs`
`mkPluginsFromInputs` is a helper function that converts flake inputs (starting by `"plugin-"` by default) into vimPlugins.
Example:
```nix
{
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
sloth-flake.url = "github:lemarsu/sloth-flake.nvim";
utils.url = "github:numtide/flake-utils";
plugin-base64 = {
url = "github:moevis/base64.nvim";
flake = false;
};
plugin-cellular-automaton = {
url = "github:eandrju/cellular-automaton.nvim";
flake = false;
};
};
outputs = {utils, sloth-flake, ...}@inputs: let
fu = utils.lib;
in fu.eachDefaultSystem (system: let
plugins = sloth-flake.lib.mkPluginsFromInputs {
inherit pkgs inputs;
};
in {
packages = rec {
default = neovim;
neovim = pkgs.callPackage ./package.nix {
# By adding `plugins` here, we can use `with plugins; base64 cellular-automaton`,
inherit plugins sloth-flake;
};
};
};
}
```
The function accepts the following attributes:
- `pkgs` **REQUIRED** the nixpkgs set.
- `inputs` **REQUIRED** the inputs from a flake.
- `predicate` **optional** predicate to filter input by name. By default, it's
filter inputs with `hasPrefix "plugin-"`.
- `nameMap` **optional** function to change the key of the input in the resulting
set. By default, the 7 first letters are removed, so to remove the "plugin-"
prefix.
- `buildVimPlugin` **optional** function used to build the plugin. Defaults to
`pkgs.vimUtils.buildVimPlugin`.
#### `mkNeovimPkg` #### `mkNeovimPkg`
`mkNeovimPkg` requires only the `pkgs` argument. `mkNeovimPkg` requires only the `pkgs` argument.
Here's a list of all accepted arguments Here's a list of all accepted arguments
| name | default | description | | name | default | description |
|-------------------------|-------------------------|---------------------------------------------------------------------| |-------------------------|-------------------------|----------------------------------------------------------------|
| `pkgs` | N/A | The nixpkgs set. **REQUIRED** | | `pkgs` | N/A | The nixpkgs set. **REQUIRED** |
| `package` | `pkgs.neovim-unwrapped` | The unwrapped neovim package to use | | `package` | `pkgs.neovim-unwrapped` | The unwrapped neovim package to use |
| `init` | `null` | The `init.lua` of your config (string, path or init config object)¹ | | `runtime` | `{}` | Your Runtime configuration (see below) |
| `runtime` | `{}` | Your Runtime configuration (see below) | | `dependencies` | `[]` | A list of your dependencies (see below) |
| `dependencies` | `[]` | A list of your dependencies (see below) | | `dependenciesExtraArgs` | `{}` | Extra arguments to load your dependencies in other files |
| `dependenciesExtraArgs` | `{}` | Extra arguments to load your dependencies in other files | | `viAlias` | `false` | Wether to create a `vi` alias to run neovim |
| `extraLuaPackages` | `null` | Extra lua packages needed for the plugin | | `vimAlias` | `false` | Wether to create a `vim` alias to run neovim |
| `viAlias` | `false` | Wether to create a `vi` alias to run neovim | | `vimdiffAlias` | `false` | Wether to create a `vimdiff` alias to run neovim in diff mode |
| `vimAlias` | `false` | Wether to create a `vim` alias to run neovim | | `nvimdiffAlias` | `false` | Wether to create a `nvimdiff` alias to run neovim in diff mode |
| `vimdiffAlias` | `false` | Wether to create a `vimdiff` alias to run neovim in diff mode |
| `nvimdiffAlias` | `false` | Wether to create a `nvimdiff` alias to run neovim in diff mode |
> ¹ If you give your own `init.lua` as string or path, you'll have to call `sloth-flake` lua plugin yourself. See more below.
The init configuration object accepts the following properties:
| name | default | description |
|------------|---------|----------------------------------------------------------------------------|
| `init` | `null` | Lua code call before plugins init. String or path. |
| `postInit` | `null` | Lua code call after plugins init and before plugin config. String or path. |
| `config` | `null` | Luas cod call after plugins config. String or path. |
The Runtime configuration object accepts the following properties: The Runtime configuration object accepts the following properties:
| name | default | description | | name | default | description |
|-----------|---------|--------------------------------| |-----------|---------|--------------------------------|
| `version` | `null` | The version of your runtime | | `version` | `null` | The version of your runtime |
| `init` | `null` | The `init.lua` of your config¹ |
| `src` | `null` | The content of your runtime | | `src` | `null` | The content of your runtime |
> ¹ If you give your own `init.lua`, you'll have to call `sloth-flake` lua plugin yourself. See more below.
The dependencies is a list of element of either: The dependencies is a list of element of either:
- path: the path of the file to load other dependencies - path: the path of the file to load other dependencies
- package: a nix package of a neovim/vim plugin - package: a nix package of a neovim/vim plugin
@ -219,18 +157,15 @@ The dependencies is a list of element of either:
The Plugin configuration object accepts the following properties: The Plugin configuration object accepts the following properties:
| name | default | description | | name | default | description |
|--------------------|---------|----------------------------------------------------------------| |----------------|---------|----------------------------------------------------------------|
| `plugin` | N/A | The plugin to load² **REQUIRED** | | `plugin` | N/A | The plugin to load² **REQUIRED** |
| `init` | `null` | Lua code (as string of path) to call before loading the plugin | | `init` | `null` | Lua code (as string of path) to call before loading the plugin |
| `config` | `null` | Lua code (as string of path) to call after loading the plugin | | `config` | `null` | Lua code (as string of path) to call after loading the plugin |
| `dependencies` | `[]` | The plugin dependencies³ | | `dependencies` | `[]` | The plugin dependencies³ |
| `extraLuaPackages` | `null` | Extra lua packages needed for the plugin | | `lazy` | `false` | Should the plugin be loaded lazily |
| `lazy` | `false` | Should the plugin be loaded lazily | | `cmd` | `[]` | Command to put as place_holder to lazy load the plugin⁴ |
| `cmd` | `[]` | Command to put as place_holder to load the lazy plugin⁴ | | `ft` | `[]` | Filetype to watch to lazy load the plugin⁴ |
| `ft` | `[]` | Filetype to watch to load the lazy plugin⁴ |
| `events` | `[]` | Events to watch to load the lazy plugin⁴⁵ |
| `keymaps` | `[]` | Keymaps that when press will load the lazy plugin⁴⁶ |
> ² The plugin can be either a nix package or an object with only `name` and > ² The plugin can be either a nix package or an object with only `name` and
> `src` as properties. The latter will be used to create a nix package of your > `src` as properties. The latter will be used to create a nix package of your
@ -243,26 +178,6 @@ The Plugin configuration object accepts the following properties:
> ⁴ Setting this property implicitly set `lazy` to `true`. > ⁴ Setting this property implicitly set `lazy` to `true`.
> ⁵ Events can be a string, an Event object or a list of either. You can
> represent a simple event name and pattern with the following string format :
> "BufRead *.md".
> ⁶ Keymaps can be a string, an Keymap object or a list of either.
The Event configuration object accepts the following properties:
| name | default | description |
|-----------|---------|----------------------------------------------------------------|
| `name` | N/A | The name of the event as string or list of string **REQUIRED** |
| `pattern` | `null` | Pattern (as string or list of string) associated to the event |
The Keymap configuration object accepts the following properties:
| name | default | description |
|-----------|---------|----------------------------------------------------|
| `mode` | `"n"` | The mode of the keymap as string or list of string |
| `mapping` | N/A | The actual mapping **REQUIRED** |
### neovim (lua) ### neovim (lua)
#### Using default `init.lua` #### Using default `init.lua`

View File

@ -1 +1 @@
0.0.10 0.0.7

View File

@ -63,6 +63,24 @@
"type": "github" "type": "github"
} }
}, },
"flake-utils_2": {
"inputs": {
"systems": "systems_2"
},
"locked": {
"lastModified": 1694529238,
"narHash": "sha256-zsNZZGTGnMOf9YpHKJqMSsa0dXbfmxeoJ7xHlrt+xmY=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "ff7b65b44d01cf9ba6a71320833626af21126384",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"flakeCompat": { "flakeCompat": {
"flake": false, "flake": false,
"locked": { "locked": {
@ -117,16 +135,16 @@
}, },
"nixpkgs_2": { "nixpkgs_2": {
"locked": { "locked": {
"lastModified": 1717196966, "lastModified": 1716991068,
"narHash": "sha256-yZKhxVIKd2lsbOqYd5iDoUIwsRZFqE87smE2Vzf6Ck0=", "narHash": "sha256-Av0UWCCiIGJxsZ6TFc+OiKCJNqwoxMNVYDBChmhjNpo=",
"owner": "nixos", "owner": "nixos",
"repo": "nixpkgs", "repo": "nixpkgs",
"rev": "57610d2f8f0937f39dbd72251e9614b1561942d8", "rev": "25cf937a30bf0801447f6bf544fc7486c6309234",
"type": "github" "type": "github"
}, },
"original": { "original": {
"owner": "nixos", "owner": "nixos",
"ref": "nixos-unstable", "ref": "nixos-23.11",
"repo": "nixpkgs", "repo": "nixpkgs",
"type": "github" "type": "github"
} }
@ -229,19 +247,20 @@
}, },
"utils": { "utils": {
"inputs": { "inputs": {
"systems": "systems_2" "flake-utils": "flake-utils_2"
}, },
"locked": { "locked": {
"lastModified": 1710146030, "lastModified": 1696281284,
"narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=", "narHash": "sha256-xcmtTmoiiAOSk4abifbtqVZk0iwBcqJfg47iUbkwhcE=",
"owner": "numtide", "owner": "gytis-ivaskevicius",
"repo": "flake-utils", "repo": "flake-utils-plus",
"rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a", "rev": "6cf1e312fb259693c4930d07ca3cbe1d07ef4a48",
"type": "github" "type": "github"
}, },
"original": { "original": {
"owner": "numtide", "owner": "gytis-ivaskevicius",
"repo": "flake-utils", "ref": "v1.4.0",
"repo": "flake-utils-plus",
"type": "github" "type": "github"
} }
}, },

View File

@ -2,8 +2,8 @@
description = "My neovim configuration"; description = "My neovim configuration";
inputs = { inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable"; nixpkgs.url = "github:nixos/nixpkgs/nixos-23.11";
utils.url = "github:numtide/flake-utils"; utils.url = "github:gytis-ivaskevicius/flake-utils-plus/v1.4.0";
nil.url = "github:oxalica/nil"; nil.url = "github:oxalica/nil";
yants.url = "github:divnix/yants"; yants.url = "github:divnix/yants";
alejandra = { alejandra = {
@ -20,25 +20,24 @@
yants, yants,
... ...
} @ inputs: let } @ inputs: let
inherit (builtins) readFile replaceStrings; versionFile = builtins.replaceStrings ["\n"] [""] (builtins.readFile ./VERSION);
fu = utils.lib;
versionFile = replaceStrings ["\n"] [""] (readFile ./VERSION);
version =
if self.sourceInfo ? dirtyShortRev
then "${versionFile}-${self.sourceInfo.dirtyShortRev}"
else versionFile;
forSystem = system: let version = if self.sourceInfo ? dirtyShortRev
pkgs = nixpkgs.legacyPackages.${system}; then "${versionFile}-${self.sourceInfo.dirtyShortRev}"
formatter = alejandra.defaultPackage.${system}; else versionFile;
inherit (inputs.nil.packages.${system}) nil;
in {
inherit formatter;
devShells.default = import ./shell.nix {
inherit pkgs nil formatter;
};
};
in in
(fu.eachDefaultSystem forSystem) utils.lib.mkFlake {
// {lib = import ./lib {inherit version yants;};}; inherit self inputs;
outputsBuilder = channel: let
system = channel.nixpkgs.system;
in {
formatter = alejandra.defaultPackage.${channel.nixpkgs.system};
devShells.default = import ./shell.nix {
pkgs = channel.nixpkgs;
inherit (inputs.nil.packages.${system}) nil;
};
};
lib = import ./lib {inherit version yants;};
};
} }

View File

@ -1,9 +1,18 @@
{ {version, yants}: let
version,
yants,
}: let
types = import ./types.nix {inherit yants;}; types = import ./types.nix {inherit yants;};
in { in {
mkNeovimPkg = import ./mkNeovimPkg.nix {inherit version types;}; mkNeovimPkg = import ./mkNeovimPkg.nix {inherit version types;};
mkPluginsFromInputs = import ./mkPluginsFromInputs.nix;
sourcesWith = path: paths: let
samePath = a: let a' = builtins.toString a; in b: a' == builtins.toString b;
isRoot = samePath "/";
isInPath = path: subPath:
if isRoot subPath
then false
else (samePath path subPath) || (isInPath path (builtins.dirOf subPath));
filter = src: _type: builtins.any (includePath: isInPath includePath src) paths;
in
builtins.path {
inherit path filter;
};
} }

View File

@ -6,18 +6,13 @@
types, types,
... ...
}: let }: let
inherit (builtins) foldl' isPath isList isString mapAttrs match elemAt; inherit (builtins) isPath foldl';
inherit (lib.attrsets) attrNames optionalAttrs; inherit (lib.attrsets) attrNames optionalAttrs;
inherit (lib.lists) concatMap; inherit (lib.lists) concatMap;
inherit (lib.strings) fileContents splitString; inherit (lib.strings) fileContents;
lua = callPackage ./lua.nix {}; lua = callPackage ./lua.nix {};
callPackage = lib.callPackageWith (pkgs // dependenciesExtraArgs);
hasMatch = pattern: str: isList (match pattern str); callPackage = lib.callPackageWith (pkgs // dependenciesExtraArgs);
wrapArray = value:
if isList value
then value
else [value];
defaultPlugin = { defaultPlugin = {
enabled = true; enabled = true;
@ -27,8 +22,6 @@
lazy = false; lazy = false;
cmd = []; cmd = [];
ft = []; ft = [];
events = [];
keymaps = [];
}; };
remotePluginToNeovimPlugin = p: remotePluginToNeovimPlugin = p:
@ -37,39 +30,6 @@
pname = name; pname = name;
}; };
defaultKeymap = {mode = "n";};
normalizeKeymap = keymap: let
value = (
if isString keymap
then {mapping = keymap;}
else keymap
);
in
mapAttrs (_: wrapArray) (defaultKeymap // value);
normalizeKeymaps = keymaps:
if isList keymaps
then map normalizeKeymap keymaps
else [(normalizeKeymap keymaps)];
normalizeEvent = event: let
value =
if ! isString event
then event
else if ! hasMatch ".* .*" event
then {name = event;}
else let
part = elemAt (splitString " " event);
in {
name = part 0;
pattern = part 1;
};
in
mapAttrs (_: wrapArray) value;
normalizeEvents = events:
if isList events
then map normalizeEvent events
else [(normalizeEvent events)];
withPluginDefaults = dep: defaultPlugin // dep; withPluginDefaults = dep: defaultPlugin // dep;
normalizePlugin = d: let normalizePlugin = d: let
dep = types.dependency d; dep = types.dependency d;
@ -80,7 +40,7 @@
inherit (dep) plugin; inherit (dep) plugin;
in in
if attrNames plugin == ["name" "src"] if attrNames plugin == ["name" "src"]
then dep // {plugin = remotePluginToNeovimPlugin plugin;} then {plugin = remotePluginToNeovimPlugin plugin;}
else dep; else dep;
p = withPluginDefaults plugin; p = withPluginDefaults plugin;
in in
@ -88,11 +48,7 @@
// rec { // rec {
hasCommands = p.cmd != []; hasCommands = p.cmd != [];
hasFileTypes = p.ft != []; hasFileTypes = p.ft != [];
keymaps = normalizeKeymaps p.keymaps; lazy = p.lazy || hasCommands || hasFileTypes;
hasKeymaps = p.keymaps != [];
events = normalizeEvents p.events;
hasEvents = p.events != [];
lazy = p.lazy || hasCommands || hasFileTypes || hasEvents || hasKeymaps;
optional = lazy || p.init != null; optional = lazy || p.init != null;
}; };
@ -122,13 +78,16 @@
vimUtils.buildVimPlugin { vimUtils.buildVimPlugin {
inherit version; inherit version;
pname = "sloth-flake"; pname = "sloth-flake";
src = with lib.fileset; src = ../lua/sloth-flake;
toSource {
root = ../.;
fileset = ../lua/sloth-flake;
};
buildPhase = '' buildPhase = ''
dir=lua/sloth-flake dir=lua/sloth-flake
mkdir -p $dir
cp *.lua $dir
for d in *; do
if [[ -d "$d" ]] && [[ "$d" != 'lua' ]]; then
cp -r "$d" $dir
fi
done
cat <<'LUA' > $dir/dependencies.lua cat <<'LUA' > $dir/dependencies.lua
${pluginsLuaDef plugins} ${pluginsLuaDef plugins}
@ -148,6 +107,7 @@
else content; else content;
pluginLuaDef = memo: plugin: let pluginLuaDef = memo: plugin: let
# plugin = builtins.removeAttrs plugin ["dependencies" "plugin"];
mkTypeFn = type: let mkTypeFn = type: let
content = textOrContent plugin.${type}; content = textOrContent plugin.${type};
in in
@ -177,12 +137,6 @@
}) })
// (optionalAttrs plugin.hasFileTypes { // (optionalAttrs plugin.hasFileTypes {
inherit (plugin) ft; inherit (plugin) ft;
})
// (optionalAttrs plugin.hasEvents {
inherit (plugin) events;
})
// (optionalAttrs plugin.hasKeymaps {
inherit (plugin) keymaps;
}); });
}; };
pluginsLuaDef = plugins: pluginsLuaDef = plugins:

View File

@ -6,21 +6,21 @@
package ? pkgs.neovim-unwrapped, package ? pkgs.neovim-unwrapped,
dependencies ? [], dependencies ? [],
dependenciesExtraArgs ? {}, dependenciesExtraArgs ? {},
extraLuaPackages ? (_: []), runtime ? {},
runtime ? null,
init ? null,
viAlias ? false, viAlias ? false,
vimAlias ? false, vimAlias ? false,
vimdiffAlias ? false, vimdiffAlias ? false,
nvimdiffAlias ? false, nvimdiffAlias ? false,
... ...
} @ config: let } @ config: let
inherit (builtins) isString isPath map; inherit (builtins) map;
inherit (pkgs) callPackage bash lib; inherit (pkgs) callPackage bash lib;
inherit (lib.strings) optionalString; inherit (lib.strings) optionalString;
inherit (lib.lists) concatMap optional;
inherit (lib.trivial) flip; inherit (lib.trivial) flip;
inherit (lib.attrsets) optionalAttrs; # inherit (lib.lists) concatMap filter foldl' map optional reverseList;
# inherit (lib.attrsets) attrNames optionalAttrs;
# inherit (lib.strings) concatStringsSep fileContents hasSuffix removePrefix removeSuffix replaceStrings;
# inherit (lib.debug) traceIf traceSeq traceVal traceValSeq traceValFn;
deps = callPackage ./deps.nix {inherit dependenciesExtraArgs types;}; deps = callPackage ./deps.nix {inherit dependenciesExtraArgs types;};
@ -29,69 +29,20 @@
runtimePlugin = deps.mkRuntimePlugin runtime; runtimePlugin = deps.mkRuntimePlugin runtime;
plugins = plugins =
normalizedPlugins normalizedPlugins
++ ( ++ (deps.normalizePlugins [runtimePlugin sloth-flake]);
deps.normalizePlugins
([sloth-flake] ++ (optional (runtime != null) runtimePlugin))
);
extractPlugin = p: {inherit (p) optional plugin;}; extractPlugin = p: {inherit (p) optional plugin;};
extractPlugins = map extractPlugin; extractPlugins = map extractPlugin;
extractLuaPackageFn = plugin: customRC = let
optional (plugin ? extraLuaPackages) plugin.extraLuaPackages; rc = ({init ? ../lua/default_init.lua, ...}: init) runtime;
extractLuaPackagesFn = plugins: let
fnList = concatMap extractLuaPackageFn plugins;
concatPackages = ps: fn: fn ps;
in in
ps: concatMap (concatPackages ps) fnList; deps.textOrContent rc;
buildInit = {
init ? null,
postInit ? null,
config ? null,
}: let
initStr = optionalString (! isNull init) ''
(function()
${deps.textOrContent init}
end)();
'';
slothCall =
if isNull postInit
then "require('sloth-flake').setup {}"
else ''
require('sloth-flake').setup {
post_init = function()
${deps.textOrContent postInit}
end,
};
'';
configStr = optionalString (! isNull config) ''
(function()
${deps.textOrContent config}
end)()
'';
in ''
-- Generated by sloth-flake
${initStr}
${slothCall}
${configStr}
'';
customRC =
if isString init || isPath init
then deps.textOrContent init
else buildInit (optionalAttrs (! isNull init) init);
neovimConfig = neovimConfig =
pkgs.neovimUtils.makeNeovimConfig { pkgs.neovimUtils.makeNeovimConfig {
inherit customRC; inherit customRC;
plugins = extractPlugins plugins; plugins = extractPlugins plugins;
extraLuaPackages = ps:
(extractLuaPackagesFn plugins ps) ++ (extraLuaPackages ps);
} }
// {luaRcContent = customRC;}; // {luaRcContent = customRC;};
params = params =

View File

@ -1,20 +0,0 @@
{
pkgs,
inputs,
predicate ? pkgs.lib.strings.hasPrefix "plugin-",
nameMap ? builtins.substring 7 (-1),
buildVimPlugin ? pkgs.vimUtils.buildVimPlugin,
}: let
inherit (builtins) attrNames filter foldl' mapAttrs;
names = filter predicate (attrNames inputs);
mkPlugin = m: k: let
name = nameMap k;
pluginDef = {
inherit name;
src = inputs.${k};
};
in
m // {${name} = pluginDef;};
plugins = foldl' mkPlugin {} names;
in
mapAttrs (_: buildVimPlugin) plugins

View File

@ -1,30 +1,17 @@
{yants, ...}: let {yants, ...}: rec {
stringList = with yants; list string;
stringOrStringList = with yants; either string stringList;
stringOrStringListOr = type:
with yants;
option (eitherN [string type (list (either string type))]);
in rec {
# The runtime object # The runtime object
runtimeType = with yants; runtimeType = with yants;
struct "runtime" { struct "runtime" {
# The version of the runtime # The version of the runtime
version = option string; version = option string;
# The init configuration file
init = option (either path string);
# The content of the runtime directory # The content of the runtime directory
src = any; src = any;
}; };
neovimInitType = with yants;
struct "neovimInit" {
# Lua code to call before plugins loaded
init = option (either string path);
# Lua code called after init but before import
postInit = option (either string path);
# Lua code called after all plugins are loaded
config = option (either string path);
};
# As simple remote plugin definition # As simple remote plugin definition
basicPluginType = with yants; basicPluginType = with yants;
struct "basicPlugin" { struct "basicPlugin" {
@ -35,24 +22,10 @@ in rec {
src = any; src = any;
}; };
eventType = with yants;
struct "event" {
# The name of the event
name = stringOrStringList;
# The pattern of the event
pattern = stringOrStringList;
};
keymapType = with yants;
struct "keymap" {
# The mode of the keymap
mode = option stringOrStringList;
# The mapping of the keymap
mapping = stringOrStringList;
};
# The plugin type of dependencies # The plugin type of dependencies
pluginType = with yants; pluginType = with yants; let
stringList = list string;
in
struct "plugin" { struct "plugin" {
# Whether this plugin should be enabled. This option allows specific # Whether this plugin should be enabled. This option allows specific
# plugins to be disabled. # plugins to be disabled.
@ -72,14 +45,11 @@ in rec {
# Ensure thoses plugins are loaded before the current one # Ensure thoses plugins are loaded before the current one
dependencies = option (list drv); dependencies = option (list drv);
# Ensure those packages are available
extraLuaPackages = option function;
# Should this plugin be load lazily ? # Should this plugin be load lazily ?
lazy = option bool; lazy = option bool;
# List of events on which the plugin should be loaded # List of events on which the plugin should be loaded
events = option (stringOrStringListOr eventType); # events = option stringList;
# List of commands on which the plugin should be loaded # List of commands on which the plugin should be loaded
cmd = option stringList; cmd = option stringList;
@ -88,7 +58,7 @@ in rec {
ft = option stringList; ft = option stringList;
# List of keystrokes on which the plugin should be loaded # List of keystrokes on which the plugin should be loaded
keymaps = option (stringOrStringListOr keymapType); # keys = option stringList;
# Priority of the module. Influence the order of loading plugins. # Priority of the module. Influence the order of loading plugins.
# Highest values get loaded before. # Highest values get loaded before.
@ -108,20 +78,14 @@ in rec {
# Default is pkgs.neovim-unwrapped # Default is pkgs.neovim-unwrapped
package = option drv; package = option drv;
# init.lua configuration
init = option (eitherN [string path neovimInitType]);
# An array of dependencies. # An array of dependencies.
dependencies = option (list dependency); dependencies = list dependency;
# Extra argument to pass to dependencies files # Extra argument to pass to dependencies files
dependenciesExtraArgs = option (attrs any); dependenciesExtraArgs = attrs any;
# Ensure those packages are available
extraLuaPackages = option function;
# Runtime configuration # Runtime configuration
runtime = option runtimeType; runtime = runtimeType;
# Create a vi alias # Create a vi alias
viAlias = option bool; viAlias = option bool;

View File

@ -1,74 +0,0 @@
local Dep = require 'sloth-flake.dep'
local utils = require 'sloth-flake.utils'
local function yesno(value)
return value and "Yes" or "No"
end
local function list(items)
if items == nil or #items == 0 then
return "None"
end
return vim.iter(items):join(', ')
end
local function describe(dep)
utils.info('Name: %s', dep.name)
utils.info('Is loaded: %s', yesno(dep.is_loaded))
utils.info('Is lazy: %s', yesno(dep.is_lazy))
utils.info('Has init: %s', yesno(dep.init))
utils.info('Has config: %s', yesno(dep.config))
utils.info('Dependencies: %s', list(dep.dependency_names))
utils.info('Filetypes: %s', list(dep.ft))
utils.info('Commands: %s', list(dep.cmd))
if dep.events == nil then
utils.info('Events: None')
else
utils.info('Events:')
for _, event in ipairs(dep.events) do
for _, name in ipairs(event.name) do
for _, pattern in ipairs(event.pattern) do
utils.info(' - %s %s', name, pattern)
end
end
end
end
if dep.keymaps == nil then
utils.info('Keymaps: None')
else
utils.info('Keymaps:')
for _, keymap in ipairs(dep.keymaps) do
for _, mode in ipairs(keymap.mode) do
for _, mapping in ipairs(keymap.mapping) do
utils.info(' - %s %s', mode, mapping)
end
end
end
end
end
return {
complete = function(line)
if line.arg_idx == 3 then
local prefix = line.args[line.arg_idx].arg
return vim.iter(Dep.all()):map(function(name)
return name
end):filter(function(name)
return vim.startswith(name, prefix)
end):totable()
end
end,
cmd = function(plugins)
if #plugins == 0 then
utils.error("You should at least give a plugin to describe!")
return
end
local plugin = plugins[1]
local dep = Dep.get(plugin)
if dep == nil then
return utils.error([[Unknown plugin "%s"]], plugin)
end
describe(dep)
end,
}

View File

@ -6,72 +6,15 @@ local commands = {
list = require 'sloth-flake.command.list', list = require 'sloth-flake.command.list',
load = require 'sloth-flake.command.load', load = require 'sloth-flake.command.load',
version = require 'sloth-flake.command.version', version = require 'sloth-flake.command.version',
describe = require 'sloth-flake.command.describe',
} }
local function parse_line(line, cursor_pos) function sloth_cmd(param)
local raw_args = vim.split(line, ' +', { trimempty = true })
local parse_pos = 1
local args = vim.iter(raw_args):map(function(arg)
local start, stop = string.find(line, arg, parse_pos, { plain = true })
parse_pos = stop
return {
arg = arg,
start = start,
stop = stop,
}
end):totable()
parse_pos = 1
local arg_idx = 1
vim.iter(args):find(function(arg)
if cursor_pos < arg.start then
arg_idx = arg_idx - 1
return true
elseif cursor_pos <= arg.stop then
return true
end
arg_idx = arg_idx + 1
return false
end)
arg_idx = arg_idx < 1 and 1 or arg_idx
if arg_idx > #args then
args[#args + 1] = {
arg = "",
start = line:len(),
stop = line:len(),
}
end
return {
line = line,
args = args,
arg_idx = arg_idx,
pos = cursor_pos,
in_arg_pos = args[arg_idx] and cursor_pos - args[arg_idx].start + 1,
}
end
-- print(vim.inspect(parse_line('Sloth ', 6)))
local function sloth_cmd_complete(arg_lead, cmd_line, cursor_pos)
local parsed_line = parse_line(cmd_line, cursor_pos)
local arg = parsed_line.args[parsed_line.arg_idx]
if parsed_line.arg_idx == 2 then
return vim.iter(commands):map(function(name, command)
return vim.startswith(name, arg.arg) and name or nil
end):totable()
elseif parsed_line.arg_idx > 2 then
local cmd = parsed_line.args[2].arg
local command = commands[cmd]
return command and command.complete(parsed_line)
end
end
local function sloth_cmd(param)
local args = param.fargs local args = param.fargs
local cmd = args[1] or "list"; local cmd = args[1] or "list";
table.remove(args, 1) table.remove(args, 1)
local command = commands[cmd] local fn = commands[cmd]
if command then if fn then
command.cmd(args) fn(args)
else else
vim.api.nvim_err_writeln(string.format([[No Sloth subcommand "%s"]], cmd)) vim.api.nvim_err_writeln(string.format([[No Sloth subcommand "%s"]], cmd))
end end
@ -80,7 +23,6 @@ end
function M.register() function M.register()
vim.api.nvim_create_user_command('Sloth', sloth_cmd, { vim.api.nvim_create_user_command('Sloth', sloth_cmd, {
nargs = '*', nargs = '*',
complete = sloth_cmd_complete
}) })
end end

View File

@ -1,55 +1,29 @@
local Dep = require 'sloth-flake.dep' local Dep = require 'sloth-flake.dep'
local utils = require 'sloth-flake.utils' local utils = require 'sloth-flake.utils'
local filters = { return function(args)
all = { local filter = args[1] or "all"
filter = function(iter) local deps = vim.iter(Dep.all()):map(function(_, dep)
-- Nothing to do return dep:name()
return iter end)
end if filter == "all" then
}, -- Nothing to do
loaded = { elseif filter == "loaded" then
filter = function(iter) deps = deps:filter(function(dep)
return iter:filter(function(dep) return Dep.get(dep):is_loaded()
return Dep.get(dep).is_loaded
end)
end
},
notloaded = {
filter = function(iter)
return iter:filter(function(dep)
return not Dep.get(dep).is_loaded
end)
end
},
}
return {
complete = function(line)
if line.arg_idx == 3 then
local prefix = line.args[3].arg
return vim.iter(vim.tbl_keys(filters)):filter(function(name)
return vim.startswith(name, prefix)
end):totable()
end
end,
cmd = function(args)
local filter_name = args[1] or "all"
local filter = filters[filter_name]
if not filter then
utils.error([[No Sloth list filter "%s".]], cmd)
utils.error("Filters are: %s", vim.iter(vim.tbl_keys(filters)):join(', '))
return
end
local deps = vim.iter(Dep.all()):map(function(_, dep)
return dep.name
end) end)
deps = filter.filter(deps):totable() elseif filter == "notloaded" then
table.sort(deps) deps = deps:filter(function(dep)
for _, dep in ipairs(deps) do return not Dep.get(dep):is_loaded()
print(string.format("- %s", dep)) end)
end else
end, utils.error([[No Sloth list filter "%s".]], cmd)
} utils.error("Filters are: all, loaded, notloaded")
return
end
deps = deps:totable()
table.sort(deps)
for _, dep in ipairs(deps) do
print(string.format("- %s", dep))
end
end

View File

@ -1,32 +1,15 @@
local Dep = require 'sloth-flake.dep' local Dep = require 'sloth-flake.dep'
local utils = require 'sloth-flake.utils' local utils = require 'sloth-flake.utils'
return { return function(plugins)
complete = function(line) if #plugins == 0 then
local previous_deps = vim.iter(line.args):enumerate():map(function(i, arg) utils.error("You should at least give a plugin to load!")
if i < 3 or i > line.arg_idx then return end return
return arg.arg end
end):totable() for _, plugin in ipairs(plugins) do
local dep = Dep.get(plugin)
local prefix = line.args[line.arg_idx].arg if dep ~= nil then
return vim.iter(Dep.all()):filter(function(name, dep) dep:load()
return vim.startswith(name, prefix) and not dep.is_loaded
and not vim.list_contains(previous_deps, name)
end):map(function(name)
return name
end):totable()
end,
cmd = function(plugins)
if #plugins == 0 then
utils.error("You should at least give a plugin to load!")
return
end end
for _, plugin in ipairs(plugins) do end
local dep = Dep.get(plugin) end
if dep ~= nil then
dep:load()
end
end
end,
}

View File

@ -1,7 +1,4 @@
return { return function()
complete = function() end, local version = require('sloth-flake.version')
cmd = function() print(string.format('Sloth v%s', version()))
local version = require('sloth-flake.version') end
print(string.format('Sloth v%s', version()))
end,
}

View File

@ -18,7 +18,26 @@ function M.new(values)
self.sm = state_machine.build(State, { self.sm = state_machine.build(State, {
enter = { enter = {
[State.Shimed] = function() [State.Shimed] = function()
return self:_shim() if self.cmd then
for _, cmd in ipairs(self.cmd) do
vim.api.nvim_create_user_command(cmd, self:lazy_load_cmd(cmd), {
desc = "Sloth-flake placeholder for plugin " .. self.name,
nargs = '*',
bang = true,
})
end
end
if self.ft then
local group_id = vim.api.nvim_create_augroup(self.augroup_name, {
clear = true,
})
vim.api.nvim_create_autocmd('FileType', {
group = group_id,
pattern = self.ft,
callback = self:lazy_load_ft()
})
end
end, end,
[State.Inited] = function() [State.Inited] = function()
for _, dep in ipairs(self.dependencies) do for _, dep in ipairs(self.dependencies) do
@ -33,7 +52,7 @@ function M.new(values)
dep:import() dep:import()
end end
if self.is_lazy or self.values.init then if self.is_lazy then
vim.cmd("packadd " .. self.name) vim.cmd("packadd " .. self.name)
end end
end, end,
@ -48,7 +67,15 @@ function M.new(values)
}, },
exit = { exit = {
[State.Shimed] = function() [State.Shimed] = function()
self:_unshim() if self.cmd then
for _, cmd in ipairs(self.cmd) do
vim.api.nvim_del_user_command(cmd)
end
end
if self.ft then
vim.api.nvim_del_augroup_by_name(self.augroup_name)
end
end, end,
}, },
events = { events = {
@ -107,14 +134,6 @@ function M:get_ft()
return self.values.ft return self.values.ft
end end
function M:get_events()
return self.values.events
end
function M:get_keymaps()
return self.values.keymaps
end
function M:get_is_lazy() function M:get_is_lazy()
return self.values.lazy or false return self.values.lazy or false
end end
@ -131,10 +150,6 @@ function M:get_is_loaded()
return self.state >= State.Loaded return self.state >= State.Loaded
end end
function M:get_has_events()
return self.ft or self.events
end
function M:get_augroup_name() function M:get_augroup_name()
return "Sloth-plugin-" .. self.name return "Sloth-plugin-" .. self.name
end end
@ -143,70 +158,6 @@ function M:shim()
return self.sm:shim() return self.sm:shim()
end end
function M:_shim()
if self.cmd then
for _, cmd in ipairs(self.cmd) do
vim.api.nvim_create_user_command(cmd, self:lazy_load_cmd(cmd), {
desc = "Sloth-flake placeholder for plugin " .. self.name,
nargs = '*',
bang = true,
})
end
end
if self.has_events then
local group_id = vim.api.nvim_create_augroup(self.augroup_name, {
clear = true,
})
if self.ft then
vim.api.nvim_create_autocmd('FileType', {
group = group_id,
pattern = self.ft,
callback = self:lazy_load_event('FileType')
})
end
if self.events then
for _, event in ipairs(self.events) do
vim.api.nvim_create_autocmd(event.name, {
group = group_id,
pattern = event.pattern,
callback = self:lazy_load_event(event.name)
})
end
end
end
if self.keymaps then
for _, keymap in ipairs(self.keymaps) do
for _, mapping in ipairs(keymap.mapping) do
vim.keymap.set(keymap.mode, mapping, self:lazy_load_mapping(mapping))
end
end
end
end
function M:_unshim()
if self.cmd then
for _, cmd in ipairs(self.cmd) do
vim.api.nvim_del_user_command(cmd)
end
end
if self.has_events then
vim.api.nvim_del_augroup_by_name(self.augroup_name)
end
if self.keymaps then
for _, keymap in ipairs(self.keymaps) do
for _, mapping in ipairs(keymap.mapping) do
vim.keymap.del(keymap.mode, mapping)
end
end
end
end
function M:init() function M:init()
return self.sm:init() return self.sm:init()
end end
@ -236,22 +187,15 @@ function M:lazy_load_cmd(cmd)
end end
end end
function M:lazy_load_event(name) function M:lazy_load_ft()
return function(param) return function(param)
self:load() self:load()
vim.api.nvim_exec_autocmds(name, { vim.api.nvim_exec_autocmds('FileType', {
pattern = param.match, pattern = param.match,
}) })
end end
end end
function M:lazy_load_mapping(mapping)
return function(param)
self:load()
vim.cmd.normal(mapping)
end
end
local deps = {} local deps = {}
for k, v in pairs(raw_deps) do for k, v in pairs(raw_deps) do
deps[k] = M.new(v) deps[k] = M.new(v)

View File

@ -50,8 +50,8 @@ function SM:run_enter_state(state)
end end
function SM:run_exit_state(state) function SM:run_exit_state(state)
local exit_fn = self.defs.exit and self.defs.exit[state] or empty_fn local enter_fn = self.defs.exit and self.defs.exit[state] or empty_fn
exit_fn(self.state) enter_fn(self.state)
end end
local function wrap_state_array(val) local function wrap_state_array(val)

View File

@ -1,9 +1,5 @@
local M = {} local M = {}
function M.info(...)
print(string.format(...))
end
function M.error(...) function M.error(...)
vim.api.nvim_err_writeln(string.format(...)) vim.api.nvim_err_writeln(string.format(...))
end end

View File

@ -1,15 +1,13 @@
{ {
formatter,
nil,
pkgs, pkgs,
nil,
... ...
}: }:
with pkgs; with pkgs;
mkShell { mkShell {
buildInputs = [ buildInputs = [
formatter
git-cliff
nil nil
sumneko-lua-language-server sumneko-lua-language-server
git-cliff
]; ];
} }