Init lazyvim

This commit is contained in:
2023-09-14 21:03:17 +03:00
parent 0030230429
commit 78d13aca61
29 changed files with 138 additions and 3600 deletions

View File

@@ -1,64 +0,0 @@
# pwnvim - my portable nvim setup
This repo is for [nix](https://nixos.org/) users. If that doesn't mean anything to you, you're probably in the wrong place. Although I rather enjoy the name of this being "pwn vim", it is really my initials, "pw" and "nvim" that drove the name choice. If you're worried that running this will pwn your machine, then you should just use it as inspiration for building your own. I doubt my config will work exactly how you'd like it to anyway.
## Background
One of the awesome thing about nix is that you can track your vim/neovim config and change it along with changes to the versions of plugins and neovim itself. This makes me very happy. I used to use different dot-file configs so I could get my settings onto new machines quickly, but these days I'm all in on nix and [home-manager](https://github.com/nix-community/home-manager). Prior to this project, my neovim configs were embedded in my system configs.
But one of the reasons I started using Nix in the first place was one of [Burke Libbey's videos](https://www.youtube.com/channel/UCSW5DqTyfOI9sUvnFoCjBlQ/videos) on the topic (I forget which one) showing how he could develop on someone else's machine using his familiar editor and settings without modifying or messing up anything on anyone else's machine. It was a sweet demo and it made an impression even though I almost never find myself trying to write code on someone else's machine.
But Burke's approach to nix is quite different from mine. Perhaps his has evolved since he made his videos. Regardless, my preferred approach is to drive everything installed on my machine off of [declarative config files](https://github.com/zmre/nix-config). I'm also a huge fan of [flakes](https://nixos.wiki/wiki/Flakes). If I want to install something permanently (as opposed to in a temporary shell), I edit my config files and run a command to make my system match the files. It's great.
But recently I was helping someone else with their config. And I really missed having my neovim setup -- not just my favorite shortcuts, but also my nix code formatter and LSP helper and such. So I was motivated to make a version of my config that didn't read the configs out of the usual `~/.config/neovim` folder, but instead was sandboxed so it could be ephemeral.
The only examples I could find of doing this in a flake was in [Jordan Isaacs](https://github.com/jordanisaacs/neovim-flake) flake, which showed me this would be possible. But it worked a bit differently than I wanted. It was important to me that all of my dependencies, like LSP servers, ripgrep, fzy, and others be encapsulated within (without messing with the global environment at all). His is nicely modular with various switches, which mine is not at this point, but this works great for my needs at the moment.
## What's Included
As of the writing of this README, it will give nice syntax highlighting to almost anything, but full nice environments for rust, typescript, svelte, nix, lua, and markdown. I will probably add to these as I dust off old projects or pick up new things. But this is sort of a warning that it might not work ideally for you if you're programming in perl, php, java, or something else outside of my wheelhouse.
It includes git symbols, fugitive, nice status lines and tab bars for buffers, file choosers via telescope, autocomplete, and much more. Take a look at the [flake.nix](./flake.nix) file to get a full picture.
## Using It
Most of the key bindings use which-key so you can self discover them. The leader key is comma so hitting comma and waiting a second will help guide you. Or you can look at my [cheatsheet](./cheatsheet.md) which has keys I want to remember, some of which are built-in and others of which are specific to this config.
From a system with nix installed, you can simply do this:
`nix run github:zmre/pwnvim`
to try it out.
There are a few ways to install a flake in your own config if you want it to be more permanent. I add it as an overlay in my config so it's available as a package. So in `flake.nix` you'd have something like this (note, this won't work as-is, but is meant to be a general guide):
```nix
{
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixpkgs-unstable";
# ...
pwnvim.url = "github:zmre/pwnvim";
pwneovide.url = "github:zmre/pwneovide";
}
outputs = inputs@{ pwnvim, pwneovide, ... }: {
pkgs = import nixpkgs {
inherit system;
overlays = [
(final: prev: {
pwnvim = inputs.pwnvim.packages.${final.system}.pwnvim;
pwneovide = inputs.pwneovide.packages.${final.system}.pwneovide;
})
];
};
}
}
```
And later in your config you'd specify `pkgs.pwnvim` as something to install.
When you want to run it, just use `nvim` and not `pwnvim` though I may make both work later.
## TODO
* [ ] Setup some testing so a build fails if there are errors on load or if LSP breaks for some programming language
* [ ] Make some alternate flake targets that produce other outputs such as a lightweight one (no programming stuff), and one that works in terminals without fancy fonts and with only 16 colors

View File

@@ -1,272 +0,0 @@
# Cheatsheet pwnvim Hotkeys Reference
_This is a combination of built-in universal keys and things that are specific to my config._
## Misc
* `gx` or enter to open a URL (but need gx if the URL is in a task)
* `gf` to open the file path under the cursor
* `gv` to **reselect** last selection
* `gi` to go back to last insertion point and insert
* `gp` paste markdown url (auto lookup the title)
* `:PasteImg` will save image to subdir if it is on clipboard
* On mac, use `ctrl` modifier on screenshot like `cmd-ctrl-shift-4` to put screenshot on clipboard
* `g ctrl-g` show cursor col, line, word, byte offsets
* `g~`_m_ switch case of _movement_
* `'"` go to position before last edit
* `';` go to last edited line
* ` g;`, ` g,` go forward/backward in change list
* ` di(`, ` di"` delete within parents/quotes. Do ` a` instead of ` i` for taking out the delimiters
* `"_c`_m_ change _movement_ but blackhole the deletion so you can use the `"` register or paste
* Alt: use `v`_m_`p` to select that which you want to change and paste over it (or use `cmd-v` instead of `p`)
* `,b` reduce multiple blank lines to one (or add bold in markdown files)
* `,cd` change dir to current file's path
* `,lcd` change dir for cur buffer only to current file's path
* `,q` open quicklist with any errors
* `q:` opens command mode but in editor
* `<C-f>` is equivalent but launches from command mode
* `F2`, `,e` Show/hide file explorer
* `F3` Fast grep
* `F4` Toggle showing invisible characters
* `F7` Show tags or file outline drawer
* `F8` Insert current date
* `F9` Focus mode for writing
* `F10` Quicklook preview file
* `F12` Reset syntax parsing
## Windowing
* `,x` close current buffer
* `^Ws` `:split` horiz window split
* `^Wv` `:vsplit` vert window split
* `^Wn` `:new` horz split with new
* `^Wo` `:only` make current window only one
* `^Wr` rotate windows
* `^Wc` close current window pane
* `:sb `_n_ Split the buffer window and populate new split with buffer _n_
* `H`, `L` goto prev/next buffer
* `[1`, `]1` jump to first buffer/tab (or second with 2, etc.)
## Folds
* `zf`_m_ create fold of movement _m_
* `zf/`_string_ create fold to match
* `:`_r_`fo` create fold for range _r_
* `zo`, `zc` open, close one fold
* `zO`, `zC` open, close folds recursively
* `zr`, `zm` open, close one fold level entire doc
* `zR`, `zM` open, close all folds
* `[z`, `]z` navigate between folds
* `za`, `<space>` toggle fold under cursor
## Completion
* `^N`, `^P` word completion _(INSERT)_
* `^X^L` line completion _(INSERT)_
* `^X^O` word completion _(INSERT)_
* `^X^U` to complete :emoji: symbols (then use `,e` to turn it into a symbol if desired)
* `^e` to cancel autocomplete (my config)
## Digraphs
* `^k<char1><char2>` to insert digraph with two char code
* ✓ = OK
* ✗ = XX
* ™ = TM
* © = Co
* → = ->
* `ga` view code of char under cursor (note the digraph code at the end)
* `:help digraph-table` to view all
## Spelling
* `[s`, `]s` prev/next misspelled word
* `[S`, `]S` prev/next "bad" word (skips rare words)
* `zg` add to word list
* `zw` add to the bad word list
* `z=` suggest words
* `1z=` auto take first suggested word
* `^X^K` Autocomplete from dictionary
* Thesaurus
* https://raw.githubusercontent.com/moshahmed/vim/master/thesaurus/thesaurii.txt or http://www.gutenberg.org/files/3202/files/mthesaur.txt
* set thesaurus+=/Users/yanis/thesaurus/words.txt
* `^X^T` show synonyms
## Programming (many require lsp server)
* `,c ` (c space) comment, uncomment current line or selection
* `,ls` show symbols outline
* `,ld` goto definition
* `,lD` goto implementation
* `,li` info hover
* `,lI` implementations popup menu
* `,lr` show references
* `,lf` fixit code actions menu
* `,lt` signature
* `,le` show line errors
* `,lR` rename symbol
* `,l=` format current line or selection
* `,fsd` find symbols in document
* `,fsw` find symbols in workspace
* `,rt` run test under cursor
* `,rT` run all tests
* `,i1` use tab for indent
* `,i2` use two spaces for indent
* `,i4` use four spaces for indent
* `,ir` retab to current setting
## Git
* `,gs` browse git status and jump to selected file
* `,gb` browse git branches and switch to selected
* `,gc` browse git commits
* `,gh` show current line blame
* `,tb` show current line blame
* `,g-` reset (unstage) current hunk
* `,g+` stage current hunk
* `,hs` stage hunk
* `,hr` reset hunk
* `,hS` stage buffer
* `,hR` reset buffer
* `,hp` preview hunk
* `,hb` hunk blame
* `,hd` diff this file
* `,hD` diff this to index
* `]c`, `[c` next/prev change
* `]n`, `[n` next/prev conflict
* `:G`, `:GStatus`
* Use `ctrl + n` / `ctrl + p` to jump between files
* Press `-` on a file to toggle whether it is added (`git add` or `git reset` depending)
* Press `p` on a file to walk through hunks of changes and selectively add parts of a file
* Press `<enter>` to view it and then `:Gdiff` to see changes
* Press `cc` to commit
* Press `ca` to amend last commit
* `gq` to close status buffer
* `=` toggle inline diff of file under cursor (preferred)
* Or `dp` to invoke git diff on the file under the cursor
* `:Gdiff`
* index on left (git added or last committed), working copy on right
* `:diffget` will pull changes from opposite window in allowing to undo changes
* Press `s` to stage a hunk
* Press `u` to unstage a hunk
* Press `-` to toggle staging of hunk
* Use `]c` and `[c` to jump between hunks
* `:Gcommit`
* `:GBrowse` to launch current file in github in browser
* "In commit messages, GitHub issues, issue URLs, and collaborators can be omni-completed (`<C-X><C-O>`, see :help compl-omni). This makes inserting those `Closes #123` remarks slightly easier than copying and pasting from the browser.
* `:Gedit :0`
* Open index version of current file in a tmp buffer. index file is the git added version.
* `:Gedit`
* Explore git objects to navigate commits and old versions of the tree without changing anything
* Can hit enter on parent (prev commit) or tree (state of all files at this point) and then select other files
* Get into this better with `:Gclog`
* When looking at a commit, hit enter on a diff line to see how things changed
* Capital `C` will jump you from a tmp file or whatever up to related commit
* `:Git mergetool` load current conflicts into quickfix list (TODO: try `ri` on the git status screen to initiate rebase)
* Navigate through the conflicted files (use the unimpaired `[q` and `]q`)
* Launch the 3-way merge tool with `:Gvdiffsplit!` (the `!` is for 3-way and `v` for vertical split)
* Now put cursor in the middle window.
* Left pane, "2", is local, right pane is remote, "3". For rebase though, left seems to be master and right the local branch.
* Use `d2o` or `d3o` to pull changes from left or right for current chunk.
* Navigate between chunks with `]c` and `[c`
* When a file is good, use `:Gw` and move on
* When finished you get to the end of the quickfix list, use `:G` to check status then `cc` to commit.
* After commit, use `rr` in the status screen or `:G rebase --contine` and hope you don't get a fresh set of conflicts, but if you do, repeat from the top.
## Notes
* `,ng` spawn grammar checker
* `,nn` use zk to add new note under $ZK_NOTEBOOK_DIR/Notes (prompt for dir)
* `,no` use zk to open note by heading or filename
* `,nt` use zk to find notes by tag
* `,nf` use zk to find notes
* `,nm` use zk to make new meeting note in $ZK_NOTEBOOK_DIR/Notes/meetings
* `,nd` use zk to make new diary note in $ZK_NOTEBOOK_DIR/Calendar
* `,nh` open hotsheet note
* `gt` turn url under cursor into titled link
* in open markdown note only
* `,np` new peer note in same folder as this one
* `,nl` show outbound links
* `,nr` show reference (inbound) links
* `,ni` show info preview
* `K` over link to preview linked note
## Plugin: Telescope
Fuzzy finder via Telescope
* `,ff` fuzzy search files
* `,fg` fuzzy grep files
* `,fb` fuzzy find buffer
* `,fh` fuzzy search history of open files
* `,fq` fuzzy browse quickfix
* `,fl` fuzzy browse location list
* `,fz` fuzzy browse zoxide
* `,fp` fuzzy browse projects
* `,fk` fuzzy browse keymaps
* `,fd` fuzzy browse document symbols
* Inside the popup window:
* `ctrl + p` on selection to paste selection at cursor
* `ctrl + y` on selection to copy selection
* `ctrl + o` on selection call `open` on it
* ctrl + q to put results in quick fix list
* `ctrl + e` create new file in current dir or creates dir if name contains trailing slash or subdirs like `dir/subdir/file`
## Plugin: NvimTree file explorer
* `<CR>`, `o` open a file or folder
* `<C-e>` edit the file in place, effectively replacing the tree explorer
* `<F10>` quicklook file under cursor
* `y` copy just filename to clipboard
* `Y` copy the relative path (to cwd) to clipboard
* `O` same as (edit) with no window picker
* `<C-]>` cd in the directory under the cursor
* `<C-v>` open the file in a vertical split
* `<C-x>` open the file in a horizontal split
* `<C-t>` open the file in a new tab
* `<`, `>` navigate to the prev/next sibling of current file/directory
* `P` move cursor to the parent directory
* `<BS>` close current opened directory or parent
* `<Tab>` open the file as a preview (keeps the cursor in the tree)
* `I` toggle visibility of files/folders hidden via git ignore
* `H` toggle visibility of dotfiles
* `a` add a file; leaving a trailing `/` will add a directory
* `d` delete a file (will prompt for confirmation)
* `r` rename a file
* `x` add/remove file/directory to cut clipboard
* `c` add/remove file/directory to copy clipboard
* `p` paste from clipboard; cut clipboard has precedence over copy; will prompt for confirmation
* `]e`, `[e` go to next/prev diagnostic item
* `]c`, `[c` go to next/prev git item
* `s` open a file with default system application or a folder with default file manager, using |system_open| option
* `f` live filter nodes dynamically based on regex matching.
* `F` clear live filter
* `q` close tree window
* `W` collapse the whole tree
* `E` expand the whole tree, stopping after expanding |actions.expand_all.max_folder_discovery| folders; this might hang neovim for a while if running on a big folder
* `S` prompt the user to enter a path and then expands the tree to match the path
### Plugin: Unimpaired
* `[a`, `]a` prev/next file if multiple specified on cli
* `[A`, `]A` first/last file if multiple specified on cli
* `[b`, `]b` prev/next buffer
* `[B`, `]B` first/last buffer
* `[l`, `]l` prev/next location list
* `[L`, `]L` first/last location list
* `[q`, `]q` prev/next quickfix errors list
* `[Q`, `]Q` first/last quickfix errors list
* `[o`, `]o` prev/next file in dir by alpha
* `[<space>`, `]<space>` add line above/below
* `[e`, `]e` exchange line with above/below
* `[x`_m_ xml encode (&lt;) movement _m_ or _VISUAL_
* `]x`_m_ xml decode (&lt;) movement _m_ or _VISUAL_
* `[u`_m_ url encode (%20) movement _m_ or _VISUAL_
* `]u`_m_ url decode (%20) movement _m_ or _VISUAL_
* `[y`_m_ c encode (\") movement _m_ or _VISUAL_
* `]y`_m_ c decode (\") movement _m_ or _VISUAL_
### Plugin: Grammarous
* `,ng` will kick off the grammar checker
* `]g` and `[g` to navigate grammar issues
* `,gf` to auto fix an issue
* `,gx` to ignore an issue
### Plugin: DiffView
* `:DiffviewOpen`
* `[x` and `]x` to navigate conflicts
* `,co` choose ours
* `,ct` choose theirs
* `,cb` choose base
* `,ca` choose all
* `dx` delete entire conflict region
* `,b` toggle list of files
* `<tab>` and `<shift>-<tab>` next/prev file with conflicts

112
flake.lock generated
View File

@@ -18,63 +18,6 @@
"type": "github"
}
},
"flake-utils_2": {
"inputs": {
"systems": "systems_2"
},
"locked": {
"lastModified": 1685518550,
"narHash": "sha256-o2d0KcvaXzTrPRIo0kOLV0/QXHhDQ5DTi+OxcjO8xqY=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "a1720a10a6cfe8234c0e93907ffe81be440f4cef",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"flake-utils_3": {
"inputs": {
"systems": "systems_3"
},
"locked": {
"lastModified": 1685518550,
"narHash": "sha256-o2d0KcvaXzTrPRIo0kOLV0/QXHhDQ5DTi+OxcjO8xqY=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "a1720a10a6cfe8234c0e93907ffe81be440f4cef",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"groovyls": {
"inputs": {
"flake-utils": "flake-utils_2",
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1686055585,
"narHash": "sha256-e+hjiIvQZ6Dmow7cJlGTS0LmJh8vNRhyU/HDHPOIqi0=",
"owner": "miknikif",
"repo": "groovyls",
"rev": "cb877e243f5b3c2e725ac2d50a6f70c184161d4a",
"type": "github"
},
"original": {
"owner": "miknikif",
"repo": "groovyls",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1692986144,
@@ -91,33 +34,10 @@
"type": "github"
}
},
"npm-groovy-lint": {
"inputs": {
"flake-utils": "flake-utils_3",
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1686068056,
"narHash": "sha256-vekjA/8b6lxDtxlsj/IUO81EMy0Z0k9xKcUlaipRwLU=",
"owner": "miknikif",
"repo": "npm-groovy-lint",
"rev": "445cf4137a92d56716bfdc1a803cbb54a496a308",
"type": "github"
},
"original": {
"owner": "miknikif",
"repo": "npm-groovy-lint",
"type": "github"
}
},
"root": {
"inputs": {
"flake-utils": "flake-utils",
"groovyls": "groovyls",
"nixpkgs": "nixpkgs",
"npm-groovy-lint": "npm-groovy-lint"
"nixpkgs": "nixpkgs"
}
},
"systems": {
@@ -134,36 +54,6 @@
"repo": "default",
"type": "github"
}
},
"systems_2": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
},
"systems_3": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
}
},
"root": "root",

138
flake.nix
View File

@@ -3,28 +3,16 @@
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-23.05";
flake-utils.url = "github:numtide/flake-utils";
groovyls.url = "github:miknikif/groovyls";
groovyls.inputs.nixpkgs.follows = "nixpkgs";
npm-groovy-lint.url = "github:miknikif/npm-groovy-lint";
npm-groovy-lint.inputs.nixpkgs.follows = "nixpkgs";
};
outputs = inputs @ {
self,
nixpkgs,
flake-utils,
groovyls,
npm-groovy-lint,
...
}:
flake-utils.lib.eachDefaultSystem (system: let
pkgs = import nixpkgs {
inherit system;
inherit
(import ./overlays.nix {
inherit inputs;
})
overlays
;
};
recursiveMerge = attrList: let
@@ -41,35 +29,24 @@
f [] attrList;
in rec {
dependencies = with pkgs; [
nil # nix lsp
ripgrep
zsh # terminal requires it
fd
git
curl # needed to fetch titles from urls
zk # lsp for markdown notes
terraform-ls # terraform lsp
tflint # terraform linter
shellcheck # sh scripts check
proselint # ditto
luaformatter # ditto for lua
lua-language-server
prisma-engines # ditto for schema.prisma files
nodePackages.prettier # ditto
nodePackages.bash-language-server # bash lsp
nodePackages.vscode-json-languageserver # json lsp
pkgs.npm-groovy-lint # groovy lsp
python310Packages.python-lsp-server # todo: is specifying 310 an issue?
alejandra # nix formatter alternative
statix # linter for nix
vale # linter for prose
jdk11 # for groovy
groovy
pkgs.groovyls # groovy lsp
go # go itself
golangci-lint # go lint
golangci-lint-langserver # go lint
gopls # google go lsp
packer # hcl formatter
lazygit
wget
cargo
python310
python310Packages.pip
php82
php82Packages.composer
go
ruby
luarocks
nodejs
zulu #java11
fish
fzf
];
neovim-augmented = recursiveMerge [
pkgs.neovim-unwrapped
@@ -88,91 +65,16 @@
customRC =
''
lua << EOF
package.path = "${self}/?.lua;" .. package.path
groovyls_cmd = { "${pkgs.jdk11}/bin/java", "-jar", "${pkgs.groovyls}/groovyls-all.jar" }
groovy_lsp_settings = { groovy = { classpath = { "${pkgs.groovy}/lib" } } }
package.path = "${self}/lua/?.lua;" .. package.path
''
+ pkgs.lib.readFile ./init.lua
+ ''
EOF
'';
packages.myPlugins = with pkgs.vimPlugins; {
start = with pkgs.vimPlugins; [
# Common dependencies of other plugins
popup-nvim # dependency
plenary-nvim # dependency of some other plugins
nvim-treesitter # syntax highlight
crates-nvim # inline intelligence for Cargo.toml
nvim-lspconfig # LSP for intilligent coding
null-ls-nvim # formatting and linting via lsp system
lspsaga-nvim
trouble-nvim # navigate all warnings and errors in quickfix-like window
fidget-nvim # show lsp status in bottom right but not status line
neodev-nvim # help for neovim lua api
lsp-format-nvim
SchemaStore-nvim # json schemas
# vim-fugitive # git control
# UI
onedarkpro-nvim # colorscheme
todo-comments-nvim # highlight TODO comments
ir_black # colorscheme for basic terminals
telescope-nvim # da best popup fuzzy finder
telescope-fzy-native-nvim # with fzy gives better results
telescope-frecency-nvim # and frecency comes in handy too
nvim-colorizer-lua # color over CSS like #00ff00
nvim-web-devicons # makes things pretty; used by many plugins below
nvim-tree-lua # file navigator
gitsigns-nvim # git status in gutter
symbols-outline-nvim # navigate the current file better
lualine-nvim # nice status bar at bottom
# vim-tpipeline # combine tmux and vim statusbars into a single one
vim-bbye # fix bdelete buffer stuff needed with bufferline
bufferline-nvim
indent-blankline-nvim # visual indent
toggleterm-nvim # better terminal management
nvim-treesitter.withAllGrammars # better code coloring
# playground # treesitter playground
nvim-treesitter-textobjects # jump around and select based on syntax (class, function, etc.)
nvim-treesitter-context # keep current block header (func defn or whatever) on first line
lf-vim
# Autocompletion
nvim-cmp # generic autocompleter
cmp-nvim-lsp # use lsp as source for completions
cmp-nvim-lua # makes vim config editing better with completions
cmp-buffer # any text in open buffers
cmp-path # complete paths
cmp-cmdline # completing in :commands
cmp-emoji # complete :emojis:
cmp-nvim-lsp-signature-help # help complete function call by showing args
cmp-npm # complete node packages in package.json
nvim-autopairs # balances parens as you type
nvim-ts-autotag # balance or rename html
vim-emoji # TODO: redundant now?
luasnip # snippets driver
cmp_luasnip # snippets completion
friendly-snippets # actual library of snippets used by luasnip
zk-nvim # lsp for a folder of notes for searching/linking/etc
true-zen-nvim # distraction free, width constrained writing mode
undotree # better vim file edit history
comment-nvim # code commenter
nvim-surround # .... updated lua-based alternative to tpope's surround
nui-nvim # UI Component Library for Neovim
gitsigns-nvim # git file changes
project-nvim
vim-tmux-navigator # navigate vim and tmux panes together
impatient-nvim # speeds startup times by caching lua bytecode
which-key-nvim # WhichKey is a lua plugin for Neovim 0.5 that displays a popup with possible key bindings of the command you started typing
diffview-nvim # git diff viewer
];
opt = with pkgs.vimPlugins; [
# grammar check
vim-grammarous
];
};
# packages.myPlugins = with pkgs.vimPlugins; {
# start = with pkgs.vimPlugins; [];
# opt = with pkgs.vimPlugins; [];
# };
};
};
apps.pwnvim = flake-utils.lib.mkApp {

View File

@@ -1,19 +1 @@
-- Neovide needs this defined very early
-- if vim.fn.has('mac') == 1 then
-- vim.opt.guifont = "Hasklug Nerd Font:h18"
-- else
-- vim.opt.guifont = "Hasklug Nerd Font:h9"
-- end
require('impatient')
require('impatient').enable_profile()
require('pwnvim.filetypes').config()
require('pwnvim.options').defaults()
require('pwnvim.options').gui()
require('pwnvim.mappings')
require('pwnvim.abbreviations')
require('pwnvim.plugins').ui()
require('pwnvim.plugins').diagnostics(groovyls_cmd, groovy_lsp_settings) -- groovyls_cmd is dynamically created by nix
require('pwnvim.plugins').telescope()
require('pwnvim.plugins').completions()
require('pwnvim.plugins').notes()
require('pwnvim.plugins').misc()
require("config.lazy")

3
lua/config/autocmds.lua Normal file
View File

@@ -0,0 +1,3 @@
-- Autocmds are automatically loaded on the VeryLazy event
-- Default autocmds that are always set: https://github.com/LazyVim/LazyVim/blob/main/lua/lazyvim/config/autocmds.lua
-- Add any additional autocmds here

3
lua/config/keymaps.lua Normal file
View File

@@ -0,0 +1,3 @@
-- Keymaps are automatically loaded on the VeryLazy event
-- Default keymaps that are always set: https://github.com/LazyVim/LazyVim/blob/main/lua/lazyvim/config/keymaps.lua
-- Add any additional keymaps here

65
lua/config/lazy.lua Normal file
View File

@@ -0,0 +1,65 @@
local lazypath = vim.fn.stdpath("data") .. "/lazy/lazy.nvim"
if not vim.loop.fs_stat(lazypath) then
-- bootstrap lazy.nvim
-- stylua: ignore
vim.fn.system({ "git", "clone", "--filter=blob:none", "https://github.com/folke/lazy.nvim.git", "--branch=stable",
lazypath })
end
vim.opt.rtp:prepend(vim.env.LAZY or lazypath)
require("lazy").setup({
spec = {
-- add LazyVim and import its plugins
{ "LazyVim/LazyVim", import = "lazyvim.plugins" },
{
"folke/tokyonight.nvim",
opts = {
transparent = true,
styles = {
sidebars = "transparent",
floats = "transparent",
},
},
},
{
"telescope.nvim",
dependencies = {
"nvim-telescope/telescope-fzf-native.nvim",
build = "make",
config = function()
require("telescope").load_extension("fzf")
end,
},
},
{ import = "lazyvim.plugins.extras.lang.json" },
{ import = "lazyvim.plugins.extras.ui.mini-animate" },
{ import = "lazyvim.plugins.extras.lang.terraform" },
{ import = "plugins" },
},
defaults = {
-- By default, only LazyVim plugins will be lazy-loaded. Your custom plugins will load during startup.
-- If you know what you're doing, you can set this to `true` to have all your custom plugins lazy-loaded by default.
lazy = false,
-- It's recommended to leave version=false for now, since a lot the plugin that support versioning,
-- have outdated releases, which may break your Neovim install.
version = false, -- always use the latest git commit
-- version = "*", -- try installing the latest stable version for plugins that support semver
},
install = { colorscheme = { "tokyonight", "habamax" } },
checker = { enabled = true }, -- automatically check for plugin updates
performance = {
rtp = {
-- disable some rtp plugins
disabled_plugins = {
"gzip",
-- "matchit",
-- "matchparen",
-- "netrwPlugin",
"tarPlugin",
"tohtml",
"tutor",
"zipPlugin",
},
},
},
})

7
lua/config/options.lua Normal file
View File

@@ -0,0 +1,7 @@
-- Options are automatically loaded before lazy.nvim startup
-- Default options that are always set: https://github.com/LazyVim/LazyVim/blob/main/lua/lazyvim/config/options.lua
-- Add any additional options here
vim.g.mapleader = ","
vim.opt.number = true
vim.opt.relativenumber = false

6
lua/plugins/mason.lua Normal file
View File

@@ -0,0 +1,6 @@
return {
"williamboman/mason.nvim",
opts = function(_, opts)
table.insert(opts.ensure_installed, "prettierd")
end,
}

13
lua/plugins/null-ls.lua Normal file
View File

@@ -0,0 +1,13 @@
return {
"jose-elias-alvarez/null-ls.nvim",
opts = function(_, opts)
if type(opts.sources) == "table" then
local null_ls = require("null-ls")
vim.list_extend(opts.sources, {
null_ls.builtins.formatting.prettierd,
null_ls.builtins.formatting.terraform_fmt,
null_ls.builtins.diagnostics.terraform_validate,
})
end
end,
}

View File

@@ -0,0 +1,8 @@
return {
"neovim/nvim-lspconfig",
opts = {
servers = {
terraformls = {},
},
},
}

View File

@@ -0,0 +1,11 @@
return {
"nvim-treesitter/nvim-treesitter",
opts = function(_, opts)
if type(opts.ensure_installed) == "table" then
vim.list_extend(opts.ensure_installed, {
"terraform",
"hcl",
})
end
end,
}

View File

@@ -1,8 +0,0 @@
{inputs, ...}: {
overlays = [
(final: prev: {
inherit (inputs.groovyls.packages.${final.system}) groovyls;
inherit (inputs.npm-groovy-lint.packages.${final.system}) npm-groovy-lint;
})
];
}

View File

@@ -1,63 +0,0 @@
vim.cmd("ab jjcheck ✓")
vim.cmd("ab Ironcore IronCore")
vim.cmd("ab Hubspot HubSpot")
vim.cmd("ab jjheart ♥")
vim.cmd("ab jjcomm ⌘")
vim.cmd("ab accidant accident")
vim.cmd("ab accomodate accommodate")
vim.cmd("ab accross across")
vim.cmd("ab acheive achieve")
vim.cmd("ab accomodate accommodate")
vim.cmd("ab acomodate accommodate")
vim.cmd("ab andthe and the")
vim.cmd("ab apparant apparent")
vim.cmd("ab aquisition acquisition")
vim.cmd("ab assistent assistant")
vim.cmd("ab asthe as the")
vim.cmd("ab atthe at the")
vim.cmd("ab beutiful beautiful")
vim.cmd("ab cemetary cemetery")
vim.cmd("ab changeing changing")
vim.cmd("ab convertable convertible")
vim.cmd("ab defendent defendant")
vim.cmd("ab embarass embarrass")
vim.cmd("ab equivalant equivalent")
vim.cmd("ab guage gauge")
vim.cmd("ab harrass harass")
vim.cmd("ab hte the")
vim.cmd("ab teh the")
vim.cmd("ab judgment judgement")
vim.cmd("ab liason liaison")
vim.cmd("ab lieutenent lieutenant")
vim.cmd("ab performence performance")
vim.cmd("ab permanant permanent")
vim.cmd("ab questionaire questionnaire")
vim.cmd("ab recieve receive")
vim.cmd("ab relevent relevant")
vim.cmd("ab rythm rhythm")
vim.cmd("ab seperate separate")
vim.cmd("ab shouldnt shouldn't")
vim.cmd("ab couldnt couldn't")
vim.cmd("ab supercede supersede")
vim.cmd("ab taht that")
vim.cmd("ab threshhold threshold")
vim.cmd("ab tomorow tomorrow")
vim.cmd("ab transfered transferred")
vim.cmd("ab vacume vacuum")
vim.cmd("ab wierd weird")
vim.cmd("ab wouldnt wouldn't")
vim.cmd("ab independant independent")
vim.cmd("ab independance independence")
vim.cmd("ab occured occurred")
vim.cmd("ab occurence occurrence")
vim.cmd("ab occurance occurrence")
vim.cmd("ab occurrance occurrence")
vim.cmd("ab reccomend recommend")
vim.cmd("ab reccommend recommend")
vim.cmd("ab monday Monday")
vim.cmd("ab tuesday Tuesday")
vim.cmd("ab wednesday Wednesday")
vim.cmd("ab thursday Thursday")
vim.cmd("ab friday Friday")
vim.cmd("ab saturday Saturday")
vim.cmd("ab sunday Sunday")

View File

@@ -1,129 +0,0 @@
local M = {}
M.config = function()
local filetypes = vim.api.nvim_create_augroup("filetypes", { clear = true })
local autocmd = vim.api.nvim_create_autocmd
-- Function below makes direnv impure by design. We need to keep the LSP servers and other nvim dependencies
-- in our path even after direnv overwrites the path. Whatever direnv puts in place will take precedence, but
-- we fall back to the various language tools installed with pwnvim using this hack
local initial_path = vim.env.PATH
autocmd("User DirenvLoaded",
{
callback = function()
if not string.find(vim.env.PATH, initial_path, 0, true) then
vim.env.PATH = vim.env.PATH .. ":" .. initial_path
end
end,
group = filetypes
})
autocmd("BufRead", { pattern = { "*.markdown", "*.md" }, command = "setlocal filetype=markdown", group = filetypes })
autocmd("BufRead", { pattern = { "*.sbt" }, command = "setlocal filetype=scala", group = filetypes })
autocmd("BufRead",
{ pattern = { "~/mail/*", "/tmp/mutt*", "~/.signature*" }, command = "setlocal filetype=mail", group = filetypes })
autocmd("BufRead", { pattern = { "~/.mutt/*" }, command = "setlocal filetype=muttrc", group = filetypes })
autocmd("BufRead", { pattern = { "*.*html*" }, command = "setlocal filetype=html", group = filetypes })
autocmd("BufRead", { pattern = { "*.css*" }, command = "setlocal filetype=css", group = filetypes })
autocmd("BufRead", { pattern = { "*.rss" }, command = "setlocal filetype=xml", group = filetypes })
autocmd("BufRead", { pattern = { "flake.lock" }, command = "setlocal filetype=json", group = filetypes })
autocmd("FileType",
{
pattern = { "sql", "mysql", "plsql" },
callback = function() require('cmp').setup.buffer({ sources = { { name = 'vim-dadbod-completion' } } }) end,
group = filetypes
})
autocmd("FileType",
{
pattern = { "c", "ruby", "php", "php3", "perl", "python", "mason", "vim", "sh", "zsh", "scala", "javascript",
"javascriptreact", "typescript", "typescriptreact", "html", "svelte", "css", "nix", "terraform", "hcl" },
callback = function() require('pwnvim.options').programming() end,
group = filetypes
})
autocmd("FileType",
{ pattern = { "lua", "xml" }, callback = function() require('pwnvim.filetypes').lua() end, group = filetypes })
autocmd("FileType",
{
pattern = { "groovy", "Jenkinsfile", "java" },
callback = function() require('pwnvim.filetypes').groovy() end,
group = filetypes
})
autocmd("FileType",
{
pattern = { "go", "gomod", "gowork", "gotmpl" },
callback = function() require('pwnvim.filetypes').go() end,
group = filetypes
})
autocmd("FileType",
{
pattern = { "md", "markdown", "vimwiki" },
callback = function() require('pwnvim.markdown').setup() end,
group = filetypes
})
-- autocmd("FileType",
-- { pattern = { "rust" }, callback = function() require('pwnvim.filetypes').rust() end, group = filetypes })
autocmd("FileType",
{ pattern = { "Outline" }, command = "setlocal nospell", group = filetypes })
autocmd("TermOpen", { pattern = { "*" }, command = "setlocal nospell", group = filetypes })
-- Run when page pager is invoked
autocmd('User',
{
pattern = { 'PageOpen', 'PageOpenFile' },
group = filetypes,
callback = function() require('pwnvim.filetypes').page() end
})
end
-- M.rust = function()
-- require('pwnvim.options').programming()
-- require('pwnvim.options').fourspaceindent()
-- vim.bo.makeprg = "cargo"
-- vim.cmd("compiler cargo")
-- vim.g.rustfmt_autosave = 1
-- vim.g.rust_fold = 1
-- vim.api.nvim_exec([[
-- augroup rustquickfix
-- autocmd!
-- autocmd BufReadPost quickfix setlocal foldmethod=expr
-- autocmd BufReadPost quickfix setlocal foldexpr=getline(v:lnum)[0:1]=='\|\|'
-- autocmd BufEnter quickfix setlocal foldexpr=getline(v:lnum)[0:1]=='\|\|'
-- autocmd BufReadPost quickfix setlocal foldlevel=0
-- augroup END
-- ]], false)
-- end
-- M.c = function()
-- require('pwnvim.options').programming()
-- require('pwnvim.options').fourspaceindent()
-- vim.bo.makeprg = "make"
-- end
M.lua = function()
require('pwnvim.options').programming()
require('pwnvim.options').twospaceindent()
end
M.groovy = function()
require('pwnvim.options').programming()
require('pwnvim.options').fourspaceindent()
end
M.go = function()
require('pwnvim.options').programming()
require('pwnvim.options').fourspaceindent()
end
M.page = function()
-- disable status bar -- handled in config
-- map space to ctrl-f
vim.api.nvim_buf_set_keymap(0, 'n', '<space>',
'<PageDown>', {})
end
M.reloadFile = function()
require("plenary.reload").reload_module '%'
vim.cmd("luafile %")
end
return M

View File

@@ -1,485 +0,0 @@
-- We use which-key in mappings, which is loaded before plugins, so set up here
local which_key = require("which-key")
which_key.setup({
plugins = {
marks = true, -- shows a list of your marks on ' and `
registers = true, -- shows your registers on " in NORMAL or <C-r> in INSERT mode
spelling = {
enabled = true, -- enabling this will show WhichKey when pressing z= to select spelling suggestions
suggestions = 20 -- how many suggestions should be shown in the list?
},
-- the presets plugin, adds help for a bunch of default keybindings in Neovim
-- No actual key bindings are created
presets = {
operators = true, -- adds help for operators like d, y, ... and registers them for motion / text object completion
motions = false, -- adds help for motions
text_objects = true, -- help for text objects triggered after entering an operator
windows = true, -- default bindings on <c-w>
nav = true, -- misc bindings to work with windows
z = true, -- bindings for folds, spelling and others prefixed with z
g = true -- bindings for prefixed with g
}
},
icons = {
breadcrumb = "»", -- symbol used in the command line area that shows your active key combo
separator = "", -- symbol used between a key and it's label
group = "+" -- symbol prepended to a group
},
popup_mappings = {
scroll_down = "<c-d>", -- binding to scroll down inside the popup
scroll_up = "<c-u>" -- binding to scroll up inside the popup
},
window = {
border = "rounded", -- none, single, double, shadow
position = "bottom", -- bottom, top
margin = { 1, 0, 1, 0 }, -- extra window margin [top, right, bottom, left]
padding = { 2, 2, 2, 2 }, -- extra window padding [top, right, bottom, left]
winblend = 0
},
layout = {
height = { min = 4, max = 25 }, -- min and max height of the columns
width = { min = 20, max = 50 }, -- min and max width of the columns
spacing = 3, -- spacing between columns
align = "left" -- align columns left, center or right
},
ignore_missing = true, -- enable this to hide mappings for which you didn't specify a label
hidden = {
"<silent>", "<CMD>", "<cmd>", "<Cmd>", "<cr>", "<CR>", "call", "lua",
"^:", "^ "
}, -- hide mapping boilerplate
show_help = true, -- show help message on the command line when the popup is visible
triggers = "auto" -- automatically setup triggers
-- triggers = {"<leader>"} -- or specify a list manually
})
-- This file is for mappings that will work regardless of filetype. Always available.
local options = { noremap = true, silent = true }
-- Make F1 act like escape for accidental hits
vim.api.nvim_set_keymap('', '#1', '<Esc>', options)
vim.api.nvim_set_keymap('!', '#1', '<Esc>', options)
-- TODO: try using the WinNew and WinClosed autocmd events with CHADtree filetype
-- to remap #2 to either open or close commands. Or BufDelete, BufAdd, BufWinLeave, BufWinEnter
-- Make F2 bring up a file browser
vim.api.nvim_set_keymap('', '#2', '<cmd>NvimTreeToggle<CR>', options)
vim.api.nvim_set_keymap('!', '#2', '<cmd>NvimTreeToggle<CR>', options)
vim.api.nvim_set_keymap('', '-', '<cmd>NvimTreeFindFile<CR>', options)
-- Make ctrl-p open a file finder
-- When using ctrl-p, screen out media files that we probably don't want
-- to open in vim. And if we really want, then we can use ,ff
vim.api
.nvim_set_keymap('', '<c-p>', ':silent Telescope find_files<CR>', options)
vim.api.nvim_set_keymap('!', '<c-p>', '<ESC>:silent Telescope find_files<CR>',
options)
-- Make F4 toggle showing invisible characters
vim.api
.nvim_set_keymap('', '_z', ':set list<CR>:map #4 _Z<CR>', { silent = true })
vim.api.nvim_set_keymap('', '_Z', ':set nolist<CR>:map #4 _z<CR>',
{ silent = true })
vim.api.nvim_set_keymap('', '#4', '_Z', {})
-- Enter the date on F8
vim.api.nvim_set_keymap('', '#8', '"=strftime("%Y-%m-%d")<CR>P', options)
vim.api.nvim_set_keymap('!', '#8', '<C-R>=strftime("%Y-%m-%d")<CR>', options)
-- Make F9 toggle distraction-free writing setup
vim.api.nvim_set_keymap('', '#9', ':TZAtaraxis<CR>', options)
vim.api.nvim_set_keymap('!', '#9', '<ESC>:TZAtaraxis<CR>', options)
-- Make F10 quicklook. Not sure how to do this best in linux so mac only for now
vim.api.nvim_set_keymap('', '<F10>', ':silent !qlmanage -p "%"<CR>', options)
vim.api.nvim_set_keymap('!', '<F10>', '<ESC>:silent !qlmanage -p "%"<CR>', options)
-- Make F12 restart highlighting
vim.api.nvim_set_keymap('', '<F12>', ':syntax sync fromstart<CR>', options)
vim.api
.nvim_set_keymap('!', '<F12>', '<C-o>:syntax sync fromstart<CR>', options)
-- Have ctrl-l continue to do what it did, but also temp clear search match highlighting
vim.api.nvim_set_keymap('', '<C-l>', ':<C-u>nohlsearch<CR><C-l>',
{ silent = true })
-- Yank to end of line using more familiar method
vim.api.nvim_set_keymap('', 'Y', 'y$', options)
-- Center screen vertically when navigating by half screens
vim.keymap.set("n", "<C-d>", "<C-d>zz")
vim.keymap.set("n", "<C-u>", "<C-u>zz")
-- Center search hits vertically on screen
vim.keymap.set("n", "n", "nzzzv")
vim.keymap.set("n", "N", "Nzzzv")
-- Move visually selected lines up and down
vim.keymap.set("v", "J", ":m '>+1<CR>gv=gv")
vim.keymap.set("v", "K", ":m '<-2<CR>gv=gv")
local global_leader_opts = {
mode = "n", -- NORMAL mode
prefix = "<leader>",
buffer = nil, -- Global mappings. Specify a buffer number for buffer local mappings
silent = true, -- use `silent` when creating keymaps
noremap = true, -- use `noremap` when creating keymaps
nowait = true -- use `nowait` when creating keymaps
}
local global_leader_opts_visual = {
mode = "v", -- VISUAL mode
prefix = "<leader>",
buffer = nil, -- Global mappings. Specify a buffer number for buffer local mappings
silent = true, -- use `silent` when creating keymaps
noremap = true, -- use `noremap` when creating keymaps
nowait = true -- use `nowait` when creating keymaps
}
local leader_mappings = {
["e"] = { "<cmd>NvimTreeToggle<cr>", "Explorer" },
["/"] = { "<cmd>nohlsearch<CR>", "No Highlight" },
["x"] = { "<cmd>Bdelete!<CR>", "Close Buffer" },
["q"] = {
[["<cmd>".(get(getqflist({"winid": 1}), "winid") != 0? "cclose" : "botright copen")."<cr>"]],
"Toggle Quicklist"
},
f = {
name = "Find",
f = { "<cmd>lua require('telescope.builtin').find_files()<CR>", "Files" },
g = { "<cmd>lua require('telescope.builtin').live_grep()<CR>", "Grep" },
b = {
"<cmd>lua require('telescope.builtin').buffers(require('telescope.themes').get_dropdown{previewer = false})<cr>",
"Buffers"
},
h = { "<cmd>lua require('telescope.builtin').oldfiles()<cr>", "History" },
q = { "<cmd>lua require('telescope.builtin').quickfix()<cr>", "Quickfix" },
l = { "<cmd>lua require('telescope.builtin').loclist()<cr>", "Loclist" },
p = { "<cmd>Telescope projects<cr>", "Projects" },
k = { "<cmd>Telescope keymaps<cr>", "Keymaps" },
t = {
"<cmd>lua require('telescope.builtin').grep_string{search = \"^\\\\s*[*-] \\\\[ \\\\]\", previewer = false, glob_pattern = \"*.md\", use_regex = true, disable_coordinates=true}<cr>",
"Todos" },
n = { "<Cmd>ZkNotes { match = {vim.fn.input('Search: ')} }<CR>", "Find" },
},
-- Quickly change indent defaults in a file
i = {
name = "Indent",
["1"] = { "<cmd>lua require('pwnvim.options').tabindent()<CR>", "Tab" },
["2"] = {
"<cmd>lua require('pwnvim.options').twospaceindent()<CR>", "Two Space"
},
["4"] = {
"<cmd>lua require('pwnvim.options').fourspaceindent()<CR>",
"Four Space"
},
r = { "<cmd>%retab!<cr>", "Change existing indent to current with retab" }
},
g = {
name = "Git",
s = { "<cmd>lua require('telescope.builtin').git_status()<cr>", "Status" },
b = {
"<cmd>lua require('telescope.builtin').git_branches()<cr>",
"Branches"
},
c = {
"<cmd>lua require('telescope.builtin').git_commits()<cr>", "Commits"
},
h = { "<cmd>lua require 'gitsigns'.toggle_current_line_blame<cr>", "Toggle Blame" },
["-"] = { "<cmd>lua require 'gitsigns'.reset_hunk()<cr>", "Reset Hunk" },
["+"] = { "<cmd>lua require 'gitsigns'.stage_hunk()<cr>", "Stage Hunk" }
},
n = {
name = "Notes",
d = {
"<cmd>ZkNew { dir = vim.env.ZK_NOTEBOOK_DIR .. '/Calendar', title = os.date('%Y%m%d') }<CR>",
"New diary"
},
e = { "<cmd>!mv \"<cfile>\" \"<c-r>=expand('%:p:h')<cr>/\"<cr>", "Embed file moving to current file's folder" },
f = { "<Cmd>ZkNotes { match = {vim.fn.input('Search: ') }}<CR>", "Find" },
g = {
"<cmd>lua require('pwnvim.plugins').grammar_check()<cr>",
"Check Grammar"
},
h = { "<cmd>edit ~/Notes/Notes/HotSheet.md<CR>", "Open HotSheet" },
i = {
c = {
"<cmd>r!/opt/homebrew/bin/icalBuddy --bullet '* ' --timeFormat '\\%H:\\%M' --dateFormat '' --noPropNames --noCalendarNames --excludeAllDayEvents --includeCals 'IC - Work' --includeEventProps datetime,title,attendees,location --propertyOrder datetime,title,attendees,location --propertySeparators '| |\\n * |\\n * | |' eventsToday<cr>",
"Insert today's calendar" },
o = { "<cmd>r!gtm-okr goals<cr>", "Insert OKRs" },
j = {
"<cmd>r!( (curl -s https://icanhazdadjoke.com/ | grep '\\\"subtitle\\\"') || curl -s https://icanhazdadjoke.com/ ) | sed 's/<[^>]*>//g' | sed -z 's/\\n/ /'<cr>",
"Insert joke" },
},
m = {
"<cmd>lua require('zk.commands').get('ZkNew')({ dir = vim.fn.input({prompt='Folder: ',default=vim.env.ZK_NOTEBOOK_DIR .. '/Notes/meetings',completion='dir'}), title = vim.fn.input('Title: ') })<CR>",
"New meeting"
},
n = {
"<Cmd>ZkNew { dir = vim.fn.input({prompt='Folder: ',default=vim.env.ZK_NOTEBOOK_DIR .. '/Notes',completion='dir'}), title = vim.fn.input('Title: ') }<CR>",
"New"
},
o = { "<cmd>ZkNotes<CR>", "Open" },
t = { "<cmd>ZkTags<CR>", "Open by tag" },
-- in open note (defined in plugins.lua as local-only shortcuts):
-- p: new peer note
-- l: show outbound links
-- r: show outbound links
-- i: info preview
},
t = {
name = "Tasks",
--d = { "<cmd>lua require('pwnvim.tasks').completeTask()<cr>", "Done" },
d = { function() require('pwnvim.tasks').completeTaskDirect() end, "Done" },
c = { function() require('pwnvim.tasks').createTaskDirect() end, "Create" },
s = { function() require('pwnvim.tasks').scheduleTaskPrompt() end, "Schedule" },
t = { function() require('pwnvim.tasks').scheduleTaskTodayDirect() end, "Today" },
}
}
local leader_visual_mappings = {
t = {
name = "Tasks",
a = { ':grep "^\\s*[*-] \\[ \\] "<cr>:Trouble quickfix<cr>', "All tasks quickfix" },
--d = { function() require("pwnvim.tasks").eachSelectedLine(require("pwnvim.tasks").completeTask) end, "Done" },
d = { ":luado return require('pwnvim.tasks').completeTask(line)<cr>", "Done" },
s = { require("pwnvim.tasks").scheduleTaskBulk, "Schedule" },
-- s needs a way to call the prompt then reuse the value
--t = { function() require("pwnvim.tasks").eachSelectedLine(require("pwnvim.tasks").scheduleTaskToday) end, "Today" },
t = { ":luado return require('pwnvim.tasks').scheduleTaskToday(line)<cr>", "Today" },
},
n = {
e = { "\"0y:!mv \"<c-r>0\" \"<c-r>=expand('%:p:h')<cr>/\"<cr>", "Embed file moving to current file's folder" },
f = { ":'<,'>ZkMatch<CR>", "Find Selected" }
},
i = leader_mappings.i,
f = leader_mappings.f,
e = leader_mappings.e,
q = leader_mappings.q,
x = leader_mappings.x
}
which_key.register(leader_mappings, global_leader_opts)
which_key.register(leader_visual_mappings, global_leader_opts_visual)
vim.api.nvim_set_keymap('', '<leader>fd',
':silent Telescope lsp_document_symbols<CR>', options)
-- Set cwd to current file's dir
vim.api.nvim_set_keymap('', '<leader>cd', ':cd %:h<CR>', options)
vim.api.nvim_set_keymap('', '<leader>lcd', ':lcd %:h<CR>', options)
-- Debug syntax files
vim.api.nvim_set_keymap('', '<leader>sd',
[[:echo map(synstack(line('.'), col('.')), 'synIDattr(v:val, "name")')<CR>]],
options)
-- """"""""" Global Shortcuts """""""""""""
vim.api.nvim_set_keymap('', '<D-j>', 'gj', options)
vim.api.nvim_set_keymap('', '<D-4>', 'g$', options)
vim.api.nvim_set_keymap('', '<D-6>', 'g^', options)
vim.api.nvim_set_keymap('', '<D-0>', 'g^', options)
-- Bubble lines up and down using the unimpaired plugin
vim.api.nvim_set_keymap('n', '<A-Up>', '[e', options)
vim.api.nvim_set_keymap('n', '<A-Down>', ']e', options)
vim.api.nvim_set_keymap('v', '<A-Up>', '[egv', options)
vim.api.nvim_set_keymap('v', '<A-Down>', ']egv', options)
-- Visually select the text that was last edited/pasted
-- Similar to gv but works after paste
vim.api.nvim_set_keymap('', 'gV', '`[v`]', options)
-- What do these do?
-- inoremap <C-U> <C-G>u<C-U>
-- nnoremap & :&&<CR>
-- xnoremap & :&&<CR>
-- Indent/outdent shortcuts
vim.api.nvim_set_keymap('n', '<D-[>', '<<', options)
vim.api.nvim_set_keymap('v', '<D-[>', '<gv', options)
vim.api.nvim_set_keymap('!', '<D-[>', '<C-o><<', options)
vim.api.nvim_set_keymap('n', '<D-]>', '>>', options)
vim.api.nvim_set_keymap('v', '<D-]>', '>gv', options)
vim.api.nvim_set_keymap('!', '<D-]>', '<C-o>>>', options)
-- keep visual block so you can move things repeatedly
vim.api.nvim_set_keymap('v', "<", "<gv", options)
vim.api.nvim_set_keymap('v', ">", ">gv", options)
-- TODO: this should be in programming setup
-- nmap <D-b> :make<CR>
-- imap <D-b> <C-o>:make<CR>
-- easy expansion of the active directory with %% on cmd
local options_nosilent = { noremap = true, silent = false }
vim.api.nvim_set_keymap('c', '%%', "<c-r>=expand('%:p:h')<cr>/", options_nosilent)
-- gx is a built-in to open URLs under the cursor, but when
-- not using netrw, it doesn't work right. Or maybe it's just me
-- but anyway this command works great.
-- /Users/pwalsh/Documents/md2rtf-style.html
-- ../README.md
-- ~/Desktop/Screen Shot 2018-04-06 at 5.19.32 PM.png
-- [abc](https://github.com/adsr/mle/commit/e4dc4314b02a324701d9ae9873461d34cce041e5.patch)
vim.api.nvim_set_keymap('', 'gx',
":silent !open \"<c-r><c-f>\" || xdg-open \"<c-r><c-f>\"<cr>",
options)
vim.api.nvim_set_keymap('v', 'gx',
"\"0y:silent !open \"<c-r>0\" || xdg-open \"<c-r>0\"<cr>gv",
options)
vim.api.nvim_set_keymap('', '<CR>',
":silent !open \"<c-r><c-f>\" || xdg-open \"<c-r><c-f>\"<cr>",
options)
vim.api.nvim_set_keymap('v', '<CR>',
"\"0y:silent !open \"<c-r>0\" || xdg-open \"<c-r>0\"<cr>gv",
options)
-- open/close folds with space bar
vim.api.nvim_set_keymap('', '<Space>',
[[@=(foldlevel('.')?'za':"\<Space>")<CR>]], options)
-- Make nvim terminal more sane
vim.api.nvim_set_keymap('t', '<Esc>', [[<C-\><C-n>]], options)
vim.api.nvim_set_keymap('t', '<M-[>', "<Esc>", options)
vim.api.nvim_set_keymap('t', '<C-v><Esc>', "<Esc>", options)
-- gui nvim stuff
-- Adjust font sizes
vim.api.nvim_set_keymap('', '<D-=>', [[:silent! let &guifont = substitute(
\ &guifont,
\ ':h\zs\d\+',
\ '\=eval(submatch(0)+1)',
\ '')<CR>]], options)
vim.api.nvim_set_keymap('', '<C-=>', [[:silent! let &guifont = substitute(
\ &guifont,
\ ':h\zs\d\+',
\ '\=eval(submatch(0)+1)',
\ '')<CR>]], options)
vim.api.nvim_set_keymap('', '<D-->', [[:silent! let &guifont = substitute(
\ &guifont,
\ ':h\zs\d\+',
\ '\=eval(submatch(0)-1)',
\ '')<CR>]], options)
vim.api.nvim_set_keymap('', '<C-->', [[:silent! let &guifont = substitute(
\ &guifont,
\ ':h\zs\d\+',
\ '\=eval(submatch(0)-1)',
\ '')<CR>]], options)
-- Need to map cmd-c and cmd-v to get natural copy/paste behavior
vim.api.nvim_set_keymap('n', '<D-v>', '"*p', options)
vim.api.nvim_set_keymap('v', '<D-v>', '"*p', options)
vim.api.nvim_set_keymap('!', '<D-v>', '<C-R>*', options)
vim.api.nvim_set_keymap('c', '<D-v>', '<C-R>*', options)
vim.api.nvim_set_keymap('v', '<D-c>', '"*y', options)
-- When pasting over selected text, keep original register value
vim.api.nvim_set_keymap('v', 'p', '"_dP', options)
-- cmd-w to close the current buffer
vim.api.nvim_set_keymap('', '<D-w>', ':bd<CR>', options)
vim.api.nvim_set_keymap('!', '<D-w>', '<ESC>:bd<CR>', options)
-- cmd-t or cmd-n to open a new buffer
vim.api.nvim_set_keymap('', '<D-t>', ':enew<CR>', options)
vim.api.nvim_set_keymap('!', '<D-t>', '<ESC>:enew<CR>', options)
vim.api.nvim_set_keymap('', '<D-n>', ':tabnew<CR>', options)
vim.api.nvim_set_keymap('!', '<D-n>', '<ESC>:tabnew<CR>', options)
-- cmd-s to save
vim.api.nvim_set_keymap('', '<D-s>', ':w<CR>', options)
vim.api.nvim_set_keymap('!', '<D-s>', '<ESC>:w<CR>', options)
-- cmd-q to quit
vim.api.nvim_set_keymap('', '<D-q>', ':q<CR>', options)
vim.api.nvim_set_keymap('!', '<D-q>', '<ESC>:q<CR>', options)
-- cmd-o to open
vim.api.nvim_set_keymap('', '<D-o>', ':Telescope file_browser cmd=%:h<CR>',
options)
vim.api.nvim_set_keymap('!', '<D-o>',
'<ESC>:Telescope file_browser cmd=%:h<CR>', options)
-- emacs bindings to jump around in lines
vim.api.nvim_set_keymap("i", "<C-e>", "<C-o>A", options)
vim.api.nvim_set_keymap("i", "<C-a>", "<C-o>I", options)
-- TODO:
-- Use ctrl-x, ctrl-u to complete :emoji: symbols, then use
-- ,e to turn it into a symbol if desired
-- vim.api.nvim_set_keymap('!', '<leader>e',
-- [[:%s/:\([^:]\+\):/\=emoji#for(submatch(1), submatch(0))/g<CR>]],
-- options)
-- Setup tpope unimpaired-like forward/backward shortcuts
which_key.register({
["[a"] = "Prev file arg",
["]a"] = "Next file arg",
["[b"] = { '<Cmd>BufferLineCyclePrev<CR>', "Prev buffer" },
["]b"] = { '<Cmd>BufferLineCycleNext<CR>', "Next buffer" },
["[c"] = "Prev git hunk",
["]c"] = "Next git hunk",
["[l"] = "Prev loclist item",
["]l"] = "Next loclist item",
["[q"] = "Prev quicklist item",
["]q"] = "Next quicklist item",
["[t"] = { '<Cmd>tabprevious<cr>', "Prev tab" },
["[T"] = { '<Cmd>tabprevious<cr>', "First tab" },
["]t"] = { '<Cmd>tabnext<cr>', "Next tab" },
["]T"] = { '<Cmd>tablast<cr>', "Last tab" },
["[n"] = "Prev conflict",
["]n"] = "Next conflict",
["[ "] = "Add blank line before",
["] "] = "Add blank line after",
["[e"] = "Swap line with previous",
["]e"] = "Swap line with next",
["[x"] = "XML encode",
["]x"] = "XML decode",
["[u"] = "URL encode",
["]u"] = "URL decode",
["[y"] = "C escape",
["]y"] = "C unescape",
["[d"] = { "<cmd>lua vim.diagnostic.goto_prev()<CR>", "Prev diagnostic" },
["]d"] = { "<cmd>lua vim.diagnostic.goto_next()<CR>", "Next diagnostic" },
["[1"] = { ':BufferLineGoToBuffer 1<CR>', "Go to buffer 1" },
["]1"] = { ':BufferLineGoToBuffer 1<CR>', "Go to buffer 1" },
["[2"] = { ':BufferLineGoToBuffer 2<CR>', "Go to buffer 2" },
["]2"] = { ':BufferLineGoToBuffer 2<CR>', "Go to buffer 2" },
["[3"] = { ':BufferLineGoToBuffer 3<CR>', "Go to buffer 3" },
["]3"] = { ':BufferLineGoToBuffer 3<CR>', "Go to buffer 3" },
["[4"] = { ':BufferLineGoToBuffer 4<CR>', "Go to buffer 4" },
["]4"] = { ':BufferLineGoToBuffer 4<CR>', "Go to buffer 4" },
["[5"] = { ':BufferLineGoToBuffer 5<CR>', "Go to buffer 5" },
["]5"] = { ':BufferLineGoToBuffer 5<CR>', "Go to buffer 5" },
["[6"] = { ':BufferLineGoToBuffer 6<CR>', "Go to buffer 6" },
["]6"] = { ':BufferLineGoToBuffer 6<CR>', "Go to buffer 6" },
["[7"] = { ':BufferLineGoToBuffer 7<CR>', "Go to buffer 7" },
["]7"] = { ':BufferLineGoToBuffer 7<CR>', "Go to buffer 7" },
["[8"] = { ':BufferLineGoToBuffer 8<CR>', "Go to buffer 8" },
["]8"] = { ':BufferLineGoToBuffer 8<CR>', "Go to buffer 8" },
["[9"] = { ':BufferLineGoToBuffer 9<CR>', "Go to buffer 9" },
["]9"] = { ':BufferLineGoToBuffer 9<CR>', "Go to buffer 9" },
["<S-h>"] = { ':BufferLineCyclePrev<CR>', "Go to next buffer" },
["<S-l>"] = { ':BufferLineCycleNext<CR>', "Go to prev buffer" },
}, { mode = 'n', silent = true })
-- Undotree
vim.keymap.set("n", "<leader>u", vim.cmd.UndotreeToggle)
-- Close buffer
vim.api.nvim_set_keymap('', '<D-w>', ':Bdelete<CR>', options)
vim.api.nvim_set_keymap('!', '<D-w>', '<ESC>:Bdelete<CR>', options)
vim.api.nvim_set_keymap('', '<A-w>', ':Bdelete<CR>', options)
vim.api.nvim_set_keymap('!', '<A-w>', '<ESC>:Bdelete<CR>', options)
vim.api.nvim_set_keymap('', '<M-w>', ':Bdelete<CR>', options)
vim.api.nvim_set_keymap('!', '<M-w>', '<ESC>:Bdelete<CR>', options)
-- Magic buffer-picking mode
vim.api.nvim_set_keymap('', '<M-b>', ':BufferPick<CR>', options)
vim.api.nvim_set_keymap('!', '<M-b>', '<ESC>:BufferPick<CR>', options)
vim.api.nvim_set_keymap('', '[0', ':BufferPick<CR>', options)
vim.api.nvim_set_keymap('', ']0', ':BufferPick<CR>', options)
vim.api.nvim_set_keymap('', '[\\', ':BufferPick<CR>', options)
vim.api.nvim_set_keymap('', ']\\', ':BufferPick<CR>', options)
-- Pane navigation integrated with tmux
vim.api.nvim_set_keymap('', '<c-h>', ':TmuxNavigateLeft<cr>', { silent = true })
vim.api.nvim_set_keymap('', '<c-j>', ':TmuxNavigateDown<cr>', { silent = true })
vim.api.nvim_set_keymap('', '<c-k>', ':TmuxNavigateUp<cr>', { silent = true })
vim.api.nvim_set_keymap('', '<c-l>', ':TmuxNavigateRight<cr>', { silent = true })
-- add mapping for :TmuxNavigatePrevious ? c-\, the default, used by toggleterm

View File

@@ -1,250 +0,0 @@
local M = {}
M.setup = function()
local bufnr = vim.api.nvim_get_current_buf()
vim.g.joinspaces = true
vim.wo.number = false
vim.wo.relativenumber = false
vim.wo.spell = true
vim.wo.list = false
-- vim.bo.formatoptions = "jcroqln"
vim.wo.foldmethod = "expr"
vim.wo.foldexpr = "nvim_treesitter#foldexpr()"
vim.wo.foldlevel = 3
vim.wo.foldenable = true
vim.bo.formatoptions = 'jtqlnr' -- no c (insert comment char on wrap), with r (indent)
vim.bo.comments = 'b:>,b:*,b:+,b:-'
vim.bo.suffixesadd = '.md'
vim.bo.syntax = "off" -- we use treesitter exclusively on markdown now
require('pwnvim.markdown').markdownsyntax()
-- TODO: make all this whichkey instead
local opts = { noremap = false, silent = true }
local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(0, ...) end
-- normal mode mappings
require("which-key").register(
{
["<leader>"] = {
m = { ':silent !open -a Marked\\ 2.app "%:p"<cr>', "Open Marked preview" },
},
["gl*"] = { [[<cmd>let p=getcurpos('.')<cr>:s/^/* /<cr>:nohlsearch<cr>:call setpos('.', p)<cr>2l]], "Add bullets" },
["gl>"] = { [[<cmd>let p=getcurpos('.')<cr>:s/^/> /<cr>:nohlsearch<cr>:call setpos('.', p)<cr>2l]], "Add quotes" },
["gl["] = { [[<cmd>let p=getcurpos('.')<cr>:s/^/* [ ] /<cr>:nohlsearch<cr>:call setpos('.', p)<cr>5l]], "Add task" },
["gt"] = { "<cmd>lua require('pwnvim.markdown').transformUrlUnderCursorToMdLink()<cr>", "Convert URL to link" },
["gp"] = { require('pwnvim.markdown').pasteUrl, "Paste URL as link" },
["<C-M-v>"] = { require('pwnvim.markdown').pasteUrl, "Paste URL as link" },
}, { mode = "n", buffer = bufnr, silent = true, noremap = true }
)
-- insert mode mappings
require("which-key").register(
{
["<C-M-v>"] = { require('pwnvim.markdown').pasteUrl, "Paste URL as link" },
}, { mode = "i", buffer = bufnr, silent = true, noremap = true }
)
-- visual mode mappings
require("which-key").register(
{
["<leader>"] = {
m = { ':silent !open -a Marked\\ 2.app "%:p"<cr>', "Open Marked preview" },
},
["gl*"] = { [[<cmd>let p=getcurpos('.')<cr>:s/^/* /<cr>:nohlsearch<cr>:call setpos('.', p)<cr>gv]], "Add bullets" },
["gl>"] = { [[<cmd>let p=getcurpos('.')<cr>:s/^/> /<cr>:nohlsearch<cr>:call setpos('.', p)<cr>gv]], "Add quotes" },
["gl["] = { [[<cmd>let p=getcurpos('.')<cr>:s/^/* [ ] /<cr>:nohlsearch<cr>:call setpos('.', p)<cr>gv]], "Add task" },
["gt"] = { "<cmd>lua require('pwnvim.markdown').transformUrlUnderCursorToMdLink()<cr>", "Convert URL to link" }
}, { mode = "v", buffer = bufnr, silent = true, noremap = true }
)
--Leave F7 at SymbolOutline which happens when zk LSP attaches
--buf_set_keymap('', '#7', ':Toc<CR>', opts)
--buf_set_keymap('!', '#7', '<ESC>:Toc<CR>', opts)
--TODO: add [t ]t for navigating tasks (instead of tabs) -- but can it work between files?
--TODO: add desc to opts
--buf_set_keymap('i', '#', '<plug>(mkdx-link-compl)', opts)
--buf_set_keymap('', '][', '<Plug>Markdown_MoveToNextSiblingHeader', opts)
--buf_set_keymap('', '[]', '<Plug>Markdown_MoveToPreviousSiblingHeader', opts)
--buf_set_keymap('', ']u', '<Plug>Markdown_MoveToParentHeader', opts)
--buf_set_keymap('', ']c', '<Plug>Markdown_MoveToCurHeader', opts)
--buf_set_keymap('', 'ge', '<Plug>Markdown_EditUrlUnderCursor', opts)
-- Handle cmd-b for bold
buf_set_keymap('!', '<D-b>', '****<C-O>h', opts)
buf_set_keymap('v', '<D-b>', 'Se', opts)
--buf_set_keymap('v', '<leader>b', 'S*gvS*', opts)
buf_set_keymap('v', '<leader>b', 'Se', opts) -- e is an alias configured at surround setup and equal to **
buf_set_keymap('n', '<D-b>', 'ysiwe', opts)
buf_set_keymap('n', '<leader>b', 'ysiwe', opts)
-- Handle cmd-i for italic
buf_set_keymap('!', '<D-i>', [[__<C-O>h]], opts)
buf_set_keymap('v', '<D-i>', 'S_', opts)
buf_set_keymap('v', '<leader>i', 'S_', opts)
buf_set_keymap('n', '<D-i>', 'ysiw_', opts)
buf_set_keymap('n', '<leader>i', 'ysiw_', opts)
-- Handle cmd-1 for inline code blocks (since cmd-` has special meaning already)
buf_set_keymap('!', '<D-1>', [[``<C-O>h]], opts)
buf_set_keymap('v', '<D-1>', 'S`', opts)
buf_set_keymap('v', '<leader>`', 'S`', opts)
buf_set_keymap('n', '<D-1>', 'ysiw`', opts)
buf_set_keymap('n', '<leader>`', 'ysiw`', opts)
-- Handle cmd-l and ,l for adding a link
buf_set_keymap('v', '<D-l>', 'S]%a(', opts)
buf_set_keymap('v', '<leader>l', 'S]%a(', opts)
buf_set_keymap('n', '<D-l>', 'ysiW]%a(', opts)
buf_set_keymap('n', '<leader>l', 'ysiW]%a(', opts)
buf_set_keymap('i', '<tab>', "<cmd>lua require('pwnvim.markdown').indent()<cr>", opts)
buf_set_keymap('i', '<s-tab>', "<cmd>lua require('pwnvim.markdown').outdent()<cr>", opts)
-- no idea why the lua version of adding the command is failing
-- vim.api.nvim_buf_add_user_command(0, 'PasteUrl', function(opts) require('pwnvim.markdown').pasteUrl() end, {})
vim.cmd("command! PasteUrl lua require('pwnvim.markdown').pasteUrl()")
-- This is wonderful when it's working, but I sometimes get too many open files errors that seem to come from this plugin. Plus
-- some weirdness where my entire terminal (kitty) completely hangs for a time. Especially when typing in an alt description.
-- So, sadly, commenting out for now. 2023-01-19
-- if vim.env.KITTY_INSTALLATION_DIR and not vim.g.neovide then
-- vim.cmd('packadd hologram.nvim')
-- require('hologram').setup {
-- auto_display = true -- WIP automatic markdown image display, may be prone to breaking
-- }
-- end
-- vim.cmd('packadd clipboard-image.nvim')
-- require 'clipboard-image'.setup {
-- default = {
-- img_name = function()
-- vim.fn.inputsave()
-- local name = vim.fn.input({ prompt = "Name: " })
-- -- TODO: swap spaces out for dashes
-- vim.fn.inputrestore()
-- return os.date('%Y-%m-%d') .. "-" .. name
-- end,
-- img_dir = { "%:p:h", "%:t:r:s?$?_attachments?" },
-- img_dir_txt = "%:t:r:s?$?_attachments?",
-- -- TODO: can I put the name as the title somehow?
-- affix = "![](%s)",
-- }
-- }
-- I have historically always used spaces for indents wherever possible including markdown
-- Changing now to use tabs because NotePlan 3 can't figure out nested lists that are space
-- indented and I go back and forth between that and nvim (mainly for iOS access to notes).
-- So, for now, this is the compatibility compromise. 2022-09-27
require('pwnvim.options').tabindent()
require('pwnvim.options').retab() -- turn spaces to tabs when markdown file is opened
end
M.markdownsyntax = function()
vim.api.nvim_exec([[
" markdownWikiLink is a new region
"syn region markdownWikiLink matchgroup=markdownLinkDelimiter start="\[\[" end="\]\]" contains=markdownUrl keepend oneline concealends
" markdownLinkText is copied from runtime files with 'concealends' appended
"syn region markdownLinkText matchgroup=markdownLinkTextDelimiter start="!\=\[\%(\%(\_[^][]\|\[\_[^][]*\]\)*]\%( \=[[(]\)\)\@=" end="\]\%( \=[[(]\)\@=" nextgroup=markdownLink,markdownId skipwhite contains=@markdownInline,markdownLineStart concealends
" markdownLink is copied from runtime files with 'conceal' appended
"syn region markdownLink matchgroup=markdownLinkDelimiter start="(" end=")" contains=markdownUrl keepend contained conceal
" syn match markdownTag '#\w\+'
" syn cluster markdownInline add=markdownTag
" Edit htmlTag to ignore tags starting with a number like <2022
" syn region htmlTag start=+<[^/0-9]+ end=+>+ fold contains=htmlTagN,htmlString,htmlArg,htmlValue,htmlTagError,htmlEvent,htmlCssDefinition,@htmlPreproc,@htmlArgCluster
" syn match mkdListItemCheckbox /\[[xXoO\> -]\]\ze\s\+/ contained contains=mkdListItem
let m = matchadd("bareLink", "\\<https:[a-zA-Z?&,;=$+%#/.!~':@0-9_-]*")
" let m = matchadd("markdownCheckboxChecked", "[*-] \\[x\\] ")
let m = matchadd("markdownCheckboxCanceled", "[*-] \\[-\\] .\\+")
let m = matchadd("markdownCheckboxPostponed", "[*-] \\[>\\] .\\+")
" below is because Noteplan uses capital X and default styling is a link on [X] so this will at least make it green
let m = matchadd("@text.todo.checked", "[*-] \\[[xX]\\] ")
let m = matchadd("markdownTag", '#\w\+')
let m = matchadd("markdownStrikethrough", "\\~\\~[^~]*\\~\\~")
let m = matchadd("doneTag", '@done(20[^)]*)')
let m = matchadd("highPrioTask", "[*-] \\[ \\] .\\+!!!")
]], false)
end
local check_backspace = function()
local col = vim.fn.col "." - 1
return col == 0 or vim.fn.getline(vim.fn.line(".")):sub(col, col):match "%s"
end
M.indent = function()
local line = vim.api.nvim_get_current_line()
if line:match("^%s*[*-]") then
local ctrlt = vim.api.nvim_replace_termcodes("<C-t>", true, false, true)
vim.api.nvim_feedkeys(ctrlt, "n", false)
--line = "\t" .. line
--vim.api.nvim_set_current_line(line)
--vim.cmd("normal l")
-- local norm_mode = vim.api.nvim_replace_termcodes("<C-o>", true, false, true)
-- local shiftwidth = vim.bo.shiftwidth + 1
-- vim.api.nvim_feedkeys(norm_mode .. ">>", "n", false)
-- vim.api.nvim_feedkeys(norm_mode .. shiftwidth .. "l", "n", false)
elseif check_backspace() then
-- we are at first col or there is whitespace immediately before cursor
-- send through regular tab character at current position
vim.api.nvim_feedkeys("\t", "n", false)
else
require 'cmp'.mapping.complete({})
end
end
M.outdent = function()
local line = vim.api.nvim_get_current_line()
if line:match("^%s*[*-]") then
local ctrld = vim.api.nvim_replace_termcodes("<C-d>", true, false, true)
vim.api.nvim_feedkeys(ctrld, "n", false)
-- TODO: shift width is correct if at least that many characters are between us and last column
-- but if we're on last column already, we'll auto move and compensate should be 0
-- local col = vim.api.nvim_win_get_cursor(0)
--local shiftwidth = vim.bo.shiftwidth
--vim.api.nvim_feedkeys(norm_mode .. "<<", "n", false)
--vim.api.nvim_feedkeys(norm_mode .. shiftwidth .. "h", "n", false)
end
end
M.getTitleFor = function(url)
local curl = require "plenary.curl"
if not string.match(url, "^https?:[^%s]*$") then
return "" -- doesn't look like a URL -- avoid curl sadness
end
local res = curl.request {
url = url,
method = "get",
accept = "text/html",
raw = { "-L" } -- follow redirects
}
local title = ""
if res then
title = string.match(res.body, "<title[^>]*>([^<]+)</title>")
if not title then
title = string.match(res.body, "<h1[^>]*>([^<]+)</h1>")
end
end
if not title then
title = "could not get title" -- TODO: put domain here
end
return title
end
M.transformUrlUnderCursorToMdLink = function()
--local url = vim.fn.expand("<cfile>")
local url = vim.fn.expand("<cWORD>")
local title = require("pwnvim.markdown").getTitleFor(url)
vim.cmd("normal! ciW[" .. title .. "](" .. url .. ")")
end
M.pasteUrl = function()
local url = vim.fn.getreg('*')
local title = require("pwnvim.markdown").getTitleFor(url)
vim.cmd("normal! a[" .. title .. "](" .. url .. ")")
-- cursor ends up one to the left, so move over right one if possible
local right = vim.api.nvim_replace_termcodes("<right>", true, false, true)
vim.api.nvim_feedkeys(right, "n", false)
end
return M

View File

@@ -1,427 +0,0 @@
local M = {}
SimpleUI = (os.getenv("SIMPLEUI") == "1" or os.getenv("TERM_PROGRAM") ==
"Apple_Terminal" or os.getenv("TERM") == "linux") and
not vim.g.neovide
M.defaults = function()
-- disable builtin vim plugins
vim.g.loaded_gzip = 0
vim.g.loaded_tar = 0
vim.g.loaded_tarPlugin = 0
vim.g.loaded_zipPlugin = 0
vim.g.loaded_2html_plugin = 0
vim.g.loaded_netrw = 1 -- disable netrw
vim.g.loaded_netrwPlugin = 1 -- disable netrw
-- we just use lua plugins here so disable others
vim.g.loaded_perl_provider = 0
vim.g.loaded_node_provider = 0
vim.g.loaded_python3_provider = 0
vim.g.loaded_ruby_provider = 0
-- vim.g.loaded_matchit = 0
-- vim.g.loaded_matchparen = 0
vim.g.loaded_spec = 0
vim.g.vim_markdown_no_default_key_mappings = 1
vim.g.markdown_folding = 1
vim.g.vim_markdown_strikethrough = 1
vim.g.vim_markdown_auto_insert_bullets = 1
vim.g.vim_markdown_new_list_item_indent = 0
vim.g.vim_markdown_conceal = 1
vim.g.vim_markdown_math = 0
vim.g.vim_markdown_conceal_code_blocks = 0
vim.g.vim_markdown_frontmatter = 1
vim.g.db_ui_use_nerd_fonts = true
-- this would allow spaces in filenames for commands like `gf` but results are really mixed.
-- commenting for now 2022-12-22
-- vim.opt.isfname:append { "32" }
vim.opt.grepprg =
"rg\\ --vimgrep\\ --no-heading\\ --smart-case\\ --color\\ never"
vim.opt.grepformat = "%f:%l:%c:%m,%f:%l:%m,%f"
-- ignore completions and menus for the below
vim.opt.wildignore =
"*/node_modules/*,_site,*/__pycache__/,*/venv/*,*/target/*,*/.vim$,\\~$,*/.log,*/.aux,*/.cls,*/.aux,*/.bbl,*/.blg,*/.fls,*/.fdb*/,*/.toc,*/.out,*/.glo,*/.log,*/.ist,*/.fdb_latexmk,*.bak,*.o,*.a,*.sw?,.git/,*.class,.direnv/,.DS_Store"
vim.opt.wildmenu = true -- cmd line completion a-la zsh
vim.opt.wildmode = "list:longest" -- matches mimic that of bash or zsh
vim.opt.swapfile = false
vim.opt.spell = true
vim.opt.spelllang = "en_us"
vim.opt.ruler = true -- show the cursor position all the time
vim.opt.cursorline = true -- add indicator for current line
vim.opt.secure = true -- don't execute shell cmds in .vimrc not owned by me
vim.opt.history = 50 -- keep 50 lines of command line history
vim.opt.shell = "zsh"
vim.opt.modelines = 0 -- Don't allow vim settings embedded in text files for security reasons
vim.opt.showcmd = true -- display incomplete commands
vim.opt.showmode = true -- display current mode
-- with backup off and writebackup on: backup current file, deleted afterwards
vim.opt.backup = false
vim.opt.writebackup = true
vim.opt.backupcopy = "auto"
vim.opt.hidden = true
vim.opt.cf = true -- jump to errors based on error files
vim.o.listchars = "tab:⇥ ,trail:␣,extends:⇉,precedes:⇇,nbsp:·"
vim.opt.list = true -- render special chars (tabs, trails, ...)
vim.opt.ttyfast = true
vim.opt.expandtab = true
vim.opt.splitbelow = true -- allow splits below
vim.opt.splitright = true -- and to the right
vim.opt.dictionary:append { '/usr/share/dict/words', '~/.aspell.english.pws' }
vim.opt.complete = vim.opt.complete + { 'k', ']' }
vim.opt.complete = vim.opt.complete - { 'i' }
vim.opt.encoding = "utf-8"
vim.opt.backspace = "indent,eol,start" -- allow backspacing over everything in insert mode
vim.opt.joinspaces = false -- don't insert two spaces after sentences on joins
vim.opt.binary = false
vim.opt.display = "lastline"
vim.opt.viewoptions = "folds,cursor,unix,slash" -- better unix / windows compatibility
vim.o.shortmess = "filnxtToSAcOF"
vim.opt.foldnestmax = 5
-- wrapping
vim.opt.wrap = true
vim.opt.sidescroll = 2 -- min number of columns to scroll from edge
vim.opt.scrolloff = 8 -- when 4 away from edge start scrolling
vim.opt.sidescrolloff = 8 -- keep cursor one col from end of line
vim.opt.textwidth = 0
vim.opt.breakindent = true
vim.opt.showbreak = "» "
vim.opt.breakat:remove { '/', '*', '_', '`' }
vim.opt.linebreak = true -- wraps on word boundaries but only if nolist is set
-- Make tabs be spaces of 4 characters by default
vim.opt.tabstop = 4
vim.opt.shiftwidth = 4
vim.opt.softtabstop = 4
vim.opt.expandtab = true -- turn tabs to spaces by default
vim.opt.autoindent = true -- autoindent to same level as previous line
vim.opt.smartindent = true -- indent after { and cinwords words
vim.opt.smartcase = true -- intelligently ignore case in searches
vim.opt.ignorecase = true -- default to not being case sensitive
vim.opt.smarttab = true
vim.opt.icm = "nosplit" -- show substitutions as you type
vim.opt.hlsearch = true
vim.opt.updatetime = 250 -- Decrease update time
vim.wo.signcolumn = 'yes'
vim.opt.visualbell = true
vim.opt.autoread = true -- auto reload files changed on disk if not changed in buffer
vim.opt.cursorline = false
vim.opt.ttyfast = true
vim.opt.formatoptions = 'jcroqlt' -- t=text, c=comments, q=format with "gq"
vim.opt.showmatch = true -- auto hilights matching bracket or paren
vim.opt.nrformats = vim.opt.nrformats - { 'octal' }
vim.opt.shiftround = true
vim.opt.ttimeout = true
vim.opt.ttimeoutlen = 50
vim.opt.fileformats = "unix,dos,mac"
vim.o.matchpairs = "(:),{:},[:],<:>"
vim.opt.number = false
vim.opt.relativenumber = false
-- noinsert: don't insert until selection made, noselect: don't select automatically
vim.opt.completeopt = "menu,menuone,noinsert,noselect" -- needed for autocompletion stuff
vim.opt.conceallevel = 2
vim.opt.fileencoding = "utf-8"
-- Globals
vim.g.vimsyn_embed = 'l' -- Highlight Lua code inside .vim files
-- vim.g.polyglot_disabled = { 'sensible', 'autoindent' } -- preserve in case I want to bring back polyglot
vim.g.foldlevelstart = 3
-- map the leader key
vim.api.nvim_set_keymap('n', ',', '', {})
vim.g.mapleader = ',' -- Namespace for custom shortcuts
if not SimpleUI then
vim.g.termguicolors = true
vim.o.termguicolors = true
else
vim.g.termguicolors = false
vim.o.termguicolors = false
end
vim.o.background = "dark"
if not SimpleUI then
require("onedarkpro").setup({
-- Call :OnedarkproCache if you make changes below and to speed startups
caching = true,
highlights = {
mkdLink = { fg = "${blue}", style = "underline" },
bareLink = { fg = "${blue}", style = "underline" },
mkdURL = { fg = "${green}", style = "underline" },
mkdInlineURL = { fg = "${blue}", style = "underline" },
mkdListItem = { fg = "${cyan}" },
markdownListMarker = { fg = "${cyan}" },
mkdListItemCheckbox = { fg = "${green}" },
-- markdownCheckbox = { fg = "${purple}" },
-- markdownCheckboxUnchecked = { fg = "${purple}" },
-- markdownCheckboxChecked = { fg = "${green}" },
markdownCheckboxCanceled = {
fg = "${comment}",
style = "strikethrough"
},
markdownCheckboxPostponed = { fg = "${comment}" },
markdownStrikethrough = {
fg = "${comment}",
style = "strikethrough"
},
markdownTag = { fg = "${comment}" },
doneTag = { fg = "${comment}", style = "italic" },
highPrioTask = { fg = "${red}", style = "bold" },
-- mkdLinkTitle
-- mkdID
-- mkdDelimiter
-- mkdInlineURL
-- mkdCode
-- mkdFootnote
-- mkdMath
-- htmlLink
TSURI = { fg = "${blue}", style = "underline" },
TSPunctSpecial = { fg = "${red}" },
markdownTSTitle = { fg = "${cyan}", style = "bold" },
markdownAutomaticLink = { fg = "${blue}", style = "underline" },
markdownLink = { fg = "${green}", style = "underline" },
markdownLinkText = { fg = "${blue}", style = "underline" },
markdownUrl = { fg = "${green}", style = "underline" },
markdownWikiLink = { fg = "${blue}", style = "underline" },
markdownH1 = { fg = "${yellow}", style = "bold" },
markdownH2 = { fg = "${yellow}", style = "bold" },
markdownH3 = { fg = "${yellow}" },
markdownH4 = { fg = "${green}", style = "italic" },
markdownH5 = { fg = "${green}", style = "italic" },
markdownH6 = { fg = "${green}", style = "italic" },
htmlH1 = { fg = "${yellow}", style = "bold" },
htmlH2 = { fg = "${yellow}", style = "bold" },
htmlH3 = { fg = "${yellow}" },
htmlH4 = { fg = "${green}", style = "italic" },
htmlH5 = { fg = "${green}", style = "italic" },
htmlH6 = { fg = "${green}", style = "italic" },
markdownBold = { fg = "#ffffff", style = "bold" },
htmlBold = { fg = "#ffffff", style = "bold" },
markdownItalic = { fg = "#eeeeee", style = "italic" },
htmlItalic = { fg = "#eeeeee", style = "italic" },
markdownBoldItalic = { fg = "#ffffff", style = "bold,italic" },
htmlBoldItalic = { fg = "#ffffff", style = "bold,italic" },
SpellBad = { style = "undercurl", sp = "${red}" },
SpellCap = { style = "undercurl", sp = "${cyan}" },
SpellRare = { style = "undercurl", sp = "Magenta" },
SpellLocal = { style = "undercurl", sp = "${cyan}" },
IndentBlanklineChar = { fg = "#444444" },
-- Todo = { fg = "#282c34", bg = "${highlight}", style = "bold" },
VertSplit = { fg = "#202020", bg = "#606060" },
Folded = { fg = "#c0c8d0", bg = "#384058" },
["@comment.markdown"] = { fg = "${comment}" },
["@field.markdown_inline"] = { fg = "${purple}" },
["@text.literal.markdown_inline"] = { fg = "${green}" },
["@text.reference.markdown_inline"] = {
fg = "${blue}",
style = "underline"
},
["@text.underline"] = { style = "underline" },
["@text.strong.markdown_inline"] = {
fg = "#ffffff",
style = "bold"
},
["@text.emphasis.markdown_inline"] = {
fg = "#eeeeee",
style = "italic"
},
["@strikethrough.markdown_inline"] = {
fg = "${comment}",
style = "strikethrough"
},
["@tag"] = { fg = "${comment}" },
["@block_quote.markdown"] = { fg = "${purple}", style = "italic" },
["@text.title.markdown"] = { fg = "${yellow}", style = "bold" },
-- ["@parameter.markdown_inline"] = { fg = theme.palette.fg },
["@punctuation.special.markdown"] = { fg = "${cyan}" },
["@punctuation.delimiter.markdown_inline"] = { fg = "${orange}" },
["@text.uri.markdown_inline"] = { fg = "${blue}" },
["@text.todo.unchecked"] = {
fg = "#ffffff",
bg = "",
style = "bold"
},
["@text.todo.checked"] = { fg = "${green}", style = "bold" },
TelescopeBorder = {
fg = "${telescope_results}",
bg = "${telescope_results}"
},
TelescopePromptBorder = {
fg = "${telescope_prompt}",
bg = "${telescope_prompt}"
},
TelescopePromptCounter = { fg = "${fg}" },
TelescopePromptNormal = {
fg = "${fg}",
bg = "${telescope_prompt}"
},
TelescopePromptPrefix = {
fg = "${purple}",
bg = "${telescope_prompt}"
},
TelescopePromptTitle = {
fg = "${telescope_prompt}",
bg = "${purple}"
},
TelescopePreviewTitle = {
fg = "${telescope_results}",
bg = "${green}"
},
TelescopeResultsTitle = {
fg = "${telescope_results}",
bg = "${telescope_results}"
},
TelescopeMatching = { fg = "${blue}" },
TelescopeNormal = { bg = "${telescope_results}" },
TelescopeSelection = { bg = "${telescope_prompt}" }
},
styles = { -- Choose from "bold,italic,underline"
virtual_text = "italic" -- Style that is applied to virtual text
},
plugins = { all = true },
options = {
bold = not SimpleUI,
italic = not SimpleUI,
underline = not SimpleUI,
undercurl = not SimpleUI,
cursorline = true,
transparency = false,
terminal_colors = false,
highlight_inactive_windows = true
},
colors = {
onedark = {
telescope_prompt = "#2e323a",
telescope_results = "#21252d"
},
onelight = {
telescope_prompt = "#f5f5f5",
telescope_results = "#eeeeee"
}
}
})
end
local cscheme
if SimpleUI then
cscheme = "ir_black"
else
cscheme = "onedark"
end
vim.cmd("colorscheme " .. cscheme)
vim.api.nvim_exec([[
filetype plugin indent on
syntax on
syntax sync minlines=5000
]], false)
-- Brief highlight on yank
vim.api.nvim_exec([[
augroup YankHighlight
autocmd!
autocmd TextYankPost * silent! lua vim.highlight.on_yank()
augroup end
]], false)
end
M.gui = function()
vim.opt.title = true
vim.opt.switchbuf = "useopen,usetab,newtab"
-- vim.opt.guifont = "Liga DejaVuSansMono Nerd Font:h16"
-- vim.opt.guifont = "FiraCode Nerd Font:h16" -- no italics
-- if vim.loop.os_uname().sysname == "Darwin" then
-- if vim.fn.has('mac') == 1 then
-- vim.opt.guifont = "Hasklug Nerd Font:h18"
-- else
-- vim.opt.guifont = "Hasklug Nerd Font:h9"
-- end
vim.g.neovide_transparency = 0.92
vim.g.neovide_cursor_animation_length = 0.01
vim.g.neovide_cursor_trail_length = 0.1
vim.g.neovide_cursor_antialiasing = true
vim.g.neovide_refresh_rate = 60
vim.g.neovide_remember_window_size = true
vim.g.neovide_input_macos_alt_is_meta = false
vim.g.neovide_hide_mouse_when_typing = false
vim.opt.mouse = "nv" -- only use mouse in normal and visual modes (notably not insert and command)
vim.opt.mousemodel = "popup_setpos"
-- use the system clipboard for all unnamed yank operations
vim.opt.clipboard = "unnamedplus"
vim.cmd([[set guioptions="gmrLae"]])
-- nvim-qt options
-- Disable GUI Tabline
vim.api.nvim_exec([[
if exists(':GuiTabline')
GuiTabline 0
endif
]], false)
end
M.twospaceindent = function()
vim.bo.textwidth = 0
vim.bo.tabstop = 2
vim.bo.shiftwidth = 2
vim.bo.softtabstop = 2
vim.bo.expandtab = true -- turn tabs to spaces by default
vim.bo.autoindent = true
-- vim.cmd('retab')
end
M.fourspaceindent = function()
vim.bo.textwidth = 0
vim.bo.tabstop = 4
vim.bo.shiftwidth = 4
vim.bo.softtabstop = 4
vim.bo.expandtab = true -- turn tabs to spaces by default
vim.bo.autoindent = true
-- vim.cmd('retab')
end
M.tabindent = function()
vim.bo.textwidth = 0
vim.bo.tabstop = 4
vim.bo.shiftwidth = 4
vim.bo.softtabstop = 4
vim.bo.expandtab = false -- don't turn tabs to spaces
vim.bo.autoindent = true
end
M.retab = function() vim.cmd('%retab!') end
M.programming = function()
vim.opt.number = true
vim.wo.number = true
vim.wo.spell = false
vim.wo.relativenumber = false
vim.wo.cursorline = true -- add indicator for current line
M.twospaceindent()
-- Could be a performance penalty on this
-- Will make periodic checks to see if the file changed
vim.api.nvim_exec([[
augroup programming
autocmd!
autocmd CursorHold,CursorHoldI * silent! checktime
augroup END
]], false)
-- Load direnv when we're in a programming file as we may want
-- the nix environment provided. Run explicitly since the autocmds
-- might not otherwise fire.
-- vim.cmd('packadd direnv.vim')
-- vim.cmd('DirenvExport')
end
return M

View File

@@ -1,885 +0,0 @@
-- This is a mega file. Rather than make each plugin have its own config file,
-- which is how I managed my packer-based nvim config prior to Nix, I'm
-- putting everything in here in sections and themed functions. It just makes it
-- easier for me to quickly update things and it's cleaner when there's
-- interdependencies between plugins. We'll see how it goes.
local M = {}
local signs = require("pwnvim.signs")
----------------------- UI --------------------------------
-- Tree, GitSigns, Indent markers, Colorizer, bufferline, lualine, treesitter
M.ui = function()
-- following options are the default
-- each of these are documented in `:help nvim-tree.OPTION_NAME`
-- local nvim_tree_config = require("nvim-tree.config")
-- local tree_cb = nvim_tree_config.nvim_tree_callback
require("pwnvim.plugins.nvim-tree")
require("nvim-surround").setup({
aliases = {
["e"] = "**" -- e for emphasis -- bold in markdown
}
})
require("pwnvim.plugins.todo-comments")
require("pwnvim.plugins.gitsigns")
require("diffview").setup {}
if not SimpleUI then require("colorizer").setup({}) end
require("pwnvim.plugins.lualine")
require("pwnvim.plugins.treesitter")
require("pwnvim.plugins.bufferline")
end -- UI setup
----------------------- DIAGNOSTICS --------------------------------
M.diagnostics = function(groovyls_cmd, groovy_lsp_settings)
-- IMPORTANT: make sure to setup neodev BEFORE lspconfig
require("neodev").setup({
-- help for neovim lua api
override = function(root_dir, library)
if string.match(root_dir, "neovim") or
string.match(root_dir, "pwnvim") or
string.match(root_dir, "lua") then
library.enabled = true
library.plugins = true
library.types = true
library.runtime = true
end
end,
lspconfig = true
})
require "fidget".setup {} -- shows status of lsp clients as they issue updates
vim.diagnostic.config({
virtual_text = false,
signs = { active = { signs.signs } },
update_in_insert = true,
underline = true,
severity_sort = true,
float = {
focusable = false,
style = "minimal",
border = "rounded",
source = "always",
header = "",
prefix = ""
}
})
vim.lsp.handlers["textDocument/hover"] = vim.lsp.with(
vim.lsp.handlers.hover,
{ border = "rounded" })
vim.lsp.handlers["textDocument/signatureHelp"] =
vim.lsp.with(vim.lsp.handlers.signature_help, { border = "rounded" })
require("trouble").setup {
group = true, -- group results by file
icons = true,
auto_preview = true,
signs = {
error = signs.error,
warning = signs.warn,
hint = signs.hint,
information = signs.info,
other = ""
}
}
local function attached(client, bufnr)
local function buf_set_keymap(...)
vim.api.nvim_buf_set_keymap(bufnr, ...)
end
local opts = { noremap = true, silent = false }
if client.name == "tsserver" or client.name == "jsonls" or client.name ==
"nil" or client.name == "eslint" or client.name == "html" or
client.name == "cssls" or client.name == "tailwindcss" then
-- Most of these are being turned off because prettier handles the use case better
client.server_capabilities.documentFormattingProvider = false
client.server_capabilities.documentRangeFormattingProvider = false
else
client.server_capabilities.documentFormattingProvider = true
client.server_capabilities.documentRangeFormattingProvider = true
require("lsp-format").on_attach(client)
end
print("LSP attached " .. client.name)
vim.api.nvim_buf_set_option(bufnr, "formatexpr",
"v:lua.vim.lsp.formatexpr()")
vim.api.nvim_buf_set_option(bufnr, "omnifunc", "v:lua.vim.lsp.omnifunc")
vim.api.nvim_buf_set_option(bufnr, "tagfunc", "v:lua.vim.lsp.tagfunc")
local which_key = require("which-key")
local local_leader_opts = {
mode = "n", -- NORMAL mode
prefix = "<leader>",
buffer = bufnr, -- Local mappings.
silent = true, -- use `silent` when creating keymaps
noremap = true, -- use `noremap` when creating keymaps
nowait = true -- use `nowait` when creating keymaps
}
local local_leader_opts_visual = {
mode = "v", -- VISUAL mode
prefix = "<leader>",
buffer = bufnr, -- Local mappings.
silent = true, -- use `silent` when creating keymaps
noremap = true, -- use `noremap` when creating keymaps
nowait = true -- use `nowait` when creating keymaps
}
require("symbols-outline").setup({
keymaps = { close = { "<Esc>", "q", "#7" } }
})
local leader_mappings = {
["q"] = { "<cmd>TroubleToggle<CR>", "Show Trouble list" },
l = {
name = "Local LSP",
s = { "<cmd>SymbolsOutline<CR>", "Show Symbols" },
d = {
"<Cmd>lua vim.lsp.buf.definition()<CR>", "Go to definition"
},
D = {
"<cmd>lua vim.lsp.buf.implementation()<CR>",
"Implementation"
},
i = { "<Cmd>lua vim.lsp.buf.hover()<CR>", "Info hover" },
I = {
"<Cmd>Telescope lsp_implementations<CR>", "Implementations"
},
r = { "<cmd>Telescope lsp_references<CR>", "References" },
f = { "<cmd>Lspsaga code_action<CR>", "Fix Code Actions" },
t = { "<cmd>lua vim.lsp.buf.signature_help()<CR>", "Signature" },
e = {
"<cmd>lua vim.diagnostic.open_float()<CR>",
"Show Line Diags"
}
},
f = {
["sd"] = {
"<cmd>Telescope lsp_document_symbols<CR>",
"Find symbol in document"
},
["sw"] = {
"<cmd>Telescope lsp_workspace_symbols<CR>",
"Find symbol in workspace"
}
}
}
which_key.register(leader_mappings, local_leader_opts)
-- Create a new note after asking for its title.
buf_set_keymap('', "#7", "<cmd>SymbolsOutline<CR>", opts)
buf_set_keymap('!', "#7", "<cmd>SymbolsOutline<CR>", opts)
buf_set_keymap('', 'K', '<cmd>lua vim.lsp.buf.hover()<CR>', opts)
-- override standard tag jump
buf_set_keymap('', 'C-]', '<cmd>lua vim.lsp.buf.definition()<CR>', opts)
buf_set_keymap('!', 'C-]', '<cmd>lua vim.lsp.buf.definition()<CR>', opts)
-- Set some keybinds conditional on server capabilities
if client.server_capabilities.document_formatting then
which_key.register({
l = {
["="] = {
"<cmd>lua vim.lsp.buf.formatting_sync()<CR>", "Format"
}
}
}, local_leader_opts)
-- vim.cmd([[
-- augroup LspFormatting
-- autocmd! * <buffer>
-- autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync()
-- augroup END
-- ]])
end
if client.server_capabilities.implementation then
which_key.register({
l = {
["I"] = {
"<cmd>Telescope lsp_implementations<CR>",
"Implementations"
}
}
}, local_leader_opts)
end
if client.server_capabilities.document_range_formatting then
which_key.register({
l = {
["="] = {
"<cmd>lua vim.lsp.buf.range_formatting()<CR>",
"Format Range"
}
}
}, local_leader_opts_visual)
end
if client.server_capabilities.rename then
which_key.register({
l = { ["R"] = { "<cmd>lua vim.lsp.buf.rename()<CR>", "Rename" } }
}, local_leader_opts)
end
end
-- LSP stuff - minimal with defaults for now
local null_ls = require("null-ls")
-- https://github.com/jose-elias-alvarez/null-ls.nvim/tree/main/lua/null-ls/builtins/formatting
local formatting = null_ls.builtins.formatting
-- https://github.com/jose-elias-alvarez/null-ls.nvim/tree/main/lua/null-ls/builtins/diagnostics
local diagnostics = null_ls.builtins.diagnostics
local codeactions = null_ls.builtins.code_actions
require("lsp-format").setup {}
null_ls.setup {
debug = false,
sources = {
-- formatting.lua_format,
formatting.alejandra, -- for nix
formatting.prismaFmt, -- for node prisma db orm
formatting.npm_groovy_lint, -- groovy lsp
formatting.packer, -- hcl formatter
formatting.prettier.with {
-- extra_args = {
-- "--use-tabs", "--single-quote", "--jsx-single-quote"
-- },
-- Disable markdown because formatting on save conflicts in weird ways
-- with the taskwiki (roam-task) stuff.
filetypes = {
"javascript", "javascriptreact", "typescript",
"typescriptreact", "vue", "scss", "less", "html", "css",
"json", "jsonc", "yaml", "graphql", "handlebars", "svelte"
},
disabled_filetypes = { "markdown" }
},
diagnostics.eslint_d.with {
args = {
"-f", "json", "--stdin", "--stdin-filename", "$FILENAME"
}
},
-- diagnostics.vale,
codeactions.eslint_d, -- for nix
codeactions.gitsigns, -- for nix
codeactions.statix, -- for nix
diagnostics.statix, -- for nix
null_ls.builtins.hover.dictionary,
codeactions.shellcheck,
diagnostics.shellcheck,
diagnostics.npm_groovy_lint -- groovy lsp
-- removed formatting.rustfmt since rust_analyzer seems to do the same thing
},
on_attach = attached
}
local lspconfig = require("lspconfig")
local cmp_nvim_lsp = require("cmp_nvim_lsp")
local capabilities = vim.tbl_extend('keep', vim.lsp.protocol
.make_client_capabilities(),
cmp_nvim_lsp.default_capabilities());
-- require('rust-tools').setup({
-- server = {
-- on_attach = attached,
-- capabilities = capabilities,
-- standalone = false
-- },
-- tools = {
-- autoSetHints = true,
-- inlay_hints = { auto = true, only_current_line = true },
-- runnables = { use_telescope = true }
-- }
-- })
require('crates').setup {}
require('cmp-npm').setup({})
lspconfig.tsserver.setup { capabilities = capabilities, on_attach = attached }
lspconfig.lua_ls.setup {
on_attach = attached,
capabilities = capabilities,
filetypes = { "lua" },
settings = {
Lua = {
runtime = {
-- Tell the language server which version of Lua you're using (most likely LuaJIT in the case of Neovim)
version = 'LuaJIT'
},
diagnostics = {
-- Get the language server to recognize the `vim` global
globals = { 'vim', "string", "require" }
},
workspace = {
-- Make the server aware of Neovim runtime files
library = vim.api.nvim_get_runtime_file("", true),
checkThirdParty = false
},
-- Do not send telemetry data containing a randomized but unique identifier
telemetry = { enable = false },
completion = { enable = true, callSnippet = "Replace" }
}
}
}
lspconfig.tailwindcss.setup {
on_attach = attached,
capabilities = capabilities,
settings = {
files = { exclude = { "**/.git/**", "**/node_modules/**", "**/*.md" } }
}
}
-- nil_ls is a nix lsp
lspconfig.nil_ls.setup { on_attach = attached, capabilities = capabilities }
lspconfig.cssls.setup {
on_attach = attached,
capabilities = capabilities,
settings = { css = { lint = { unknownAtRules = "ignore" } } }
}
lspconfig.eslint.setup { on_attach = attached, capabilities = capabilities }
lspconfig.html.setup { on_attach = attached, capabilities = capabilities }
lspconfig.bashls.setup { on_attach = attached, capabilities = capabilities }
-- TODO: investigate nvim-metals and remove line below
lspconfig.metals.setup { on_attach = attached, capabilities = capabilities } -- for scala
lspconfig.pylsp.setup { on_attach = attached, capabilities = capabilities } -- for python
lspconfig.jsonls.setup {
on_attach = attached,
settings = {
json = {
schemas = require('schemastore').json.schemas(),
validate = { enable = true }
}
},
setup = {
commands = {
Format = {
function()
vim.lsp.buf.range_formatting({}, { 0, 0 },
{ vim.fn.line "$", 0 })
end
}
}
},
capabilities = capabilities
}
lspconfig.terraformls.setup { on_attach = attached, capabilities = capabilities } -- terraform lsp
lspconfig.tflint.setup { on_attach = attached, capabilities = capabilities } -- terraform lsp
lspconfig.groovyls.setup { on_attach = attached, capabilities = capabilities, cmd = groovyls_cmd, settings =
groovy_lsp_settings } -- groovy lsp
lspconfig.golangci_lint_ls.setup { capabilities = capabilities, on_attach = attached } -- go support
lspconfig.gopls.setup { capabilities = capabilities, on_attach = attached } -- go support
require 'lspsaga'.init_lsp_saga({
use_saga_diagnostic_sign = not SimpleUI,
use_diagnostic_virtual_text = false,
code_action_prompt = {
enable = true,
sign = false,
sign_priority = 20,
virtual_text = true
}
-- TODO: re-enable this at next update - getting error 2022-08-02
-- code_action_lightbulb = {
-- enable = false,
-- sign = true,
-- enable_in_insert = true,
-- sign_priority = 20,
-- virtual_text = false,
-- },
})
end -- Diagnostics setup
----------------------- TELESCOPE --------------------------------
M.telescope = function()
local actions = require('telescope.actions')
local action_state = require('telescope.actions.state')
local function quicklook_selected_entry(prompt_bufnr)
local entry = action_state.get_selected_entry()
-- actions.close(prompt_bufnr)
vim.cmd("silent !qlmanage -p '" .. entry.value .. "'")
end
local function yank_selected_entry(prompt_bufnr)
local entry = action_state.get_selected_entry()
actions.close(prompt_bufnr)
-- Put it in the unnamed buffer and the system clipboard both
vim.api.nvim_call_function("setreg", { '"', entry.value })
vim.api.nvim_call_function("setreg", { "*", entry.value })
end
local function system_open_selected_entry(prompt_bufnr)
local entry = action_state.get_selected_entry()
actions.close(prompt_bufnr)
os.execute("open '" .. entry.value .. "'")
end
require('telescope').setup {
file_ignore_patterns = {
"*.bak", ".git/", "node_modules", ".zk/", "Caches/"
},
prompt_prefix = SimpleUI and ">" or "",
selection_caret = SimpleUI and "" or "",
-- path_display = { "smart" },
defaults = {
path_display = function(_, path)
local tail = require("telescope.utils").path_tail(path)
return string.format("%s (%s)", tail,
require("telescope.utils").path_smart(
path:gsub("/Users/[^/]*/", "~/"):gsub(
"/[^/]*$", ""):gsub(
"/Library/Containers/co.noteplan.NotePlan3/Data/Library/Application Support/co.noteplan.NotePlan3",
"/NotePlan")))
end,
-- path_display = { "truncate" },
mappings = {
n = {
["<C-y>"] = yank_selected_entry,
["<C-o>"] = system_open_selected_entry,
["<F10>"] = quicklook_selected_entry,
["q"] = require("telescope.actions").close
},
i = {
["<C-y>"] = yank_selected_entry,
["<F10>"] = quicklook_selected_entry,
["<C-o>"] = system_open_selected_entry
}
},
vimgrep_arguments = {
"rg", "--color=never", "--no-heading", "--with-filename",
"--line-number", "--column", "--smart-case"
},
-- Telescope smart history
history = {
path = '~/.local/share/nvim/databases/telescope_history.sqlite3',
limit = 100
},
layout_strategy = "flex",
layout_config = {
horizontal = { prompt_position = "bottom", preview_width = 0.55 },
vertical = { mirror = false },
width = 0.87,
height = 0.80,
preview_cutoff = 1
},
color_devicons = not SimpleUI,
set_env = { ["COLORTERM"] = "truecolor" }, -- default = nil,
file_previewer = require("telescope.previewers").vim_buffer_cat.new,
grep_previewer = require("telescope.previewers").vim_buffer_vimgrep
.new,
qflist_previewer = require("telescope.previewers").vim_buffer_qflist
.new
},
extensions = {
fzy_native = {
override_generic_sorter = true,
override_file_sorter = true
}
}
}
require 'telescope'.load_extension('fzy_native')
require("telescope").load_extension("zk")
if vim.fn.has('mac') ~= 1 then
-- doesn't currently work on mac
require 'telescope'.load_extension('media_files')
end
end -- telescope
----------------------- COMPLETIONS --------------------------------
-- cmp, luasnip
M.completions = function()
require("luasnip/loaders/from_vscode").lazy_load()
local luasnip = require("luasnip")
local check_backspace = function()
local col = vim.fn.col "." - 1
return col == 0 or
vim.fn.getline(vim.fn.line(".")):sub(col, col):match "%s"
end
local cmp = require 'cmp'
cmp.setup {
enabled = function()
local context = require 'cmp.config.context'
local buftype = vim.api.nvim_buf_get_option(0, "buftype")
-- prevent completions in prompts like telescope prompt
if buftype == "prompt" then return false end
-- allow completions in command mode
if vim.api.nvim_get_mode().mode == 'c' then return true end
-- forbid completions in comments
return not context.in_treesitter_capture("comment") and
not context.in_syntax_group("Comment")
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 = false
},
["<Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_next_item()
elseif luasnip.expandable() then
luasnip.expand({})
elseif luasnip.expand_or_jumpable() then
luasnip.expand_or_jump()
elseif check_backspace() then
fallback()
else
cmp.mapping.complete({})
-- fallback()
end
end, { "i", "s" }),
["<S-Tab>"] = cmp.mapping(function(fallback)
if cmp.visible() then
cmp.select_prev_item()
elseif luasnip.jumpable(-1) then
luasnip.jump(-1)
else
fallback()
end
end, { "i", "s" })
},
window = { documentation = cmp.config.window.bordered() },
sources = {
{ name = 'nvim_lsp' }, { name = 'nvim_lsp_signature_help' },
{ name = 'nvim_lua' }, { name = 'emoji' }, { name = 'luasnip' },
{ name = 'path' }, { name = "crates" },
{ name = 'npm', keyword_length = 3 },
{ name = "buffer", keyword_length = 3 }
},
formatting = {
fields = { "kind", "abbr", "menu" },
format = function(entry, vim_item)
-- Kind icons
vim_item.kind = string.format("%s",
signs.kind_icons[vim_item.kind])
vim_item.menu = ({
nvim_lsp = "[LSP]",
nvim_lsp_signature_help = "[LSPS]",
luasnip = "[Snippet]",
buffer = "[Buffer]",
path = "[Path]"
})[entry.source.name]
return vim_item
end
},
snippet = { expand = function(args) luasnip.lsp_expand(args.body) end }
}
cmp.setup.cmdline('/', {
mapping = cmp.mapping.preset.cmdline(),
sources = { { name = 'buffer' } }
})
cmp.setup.cmdline(':', {
mapping = cmp.mapping.preset.cmdline(),
sources = cmp.config.sources({ { name = 'path' } }, {
{ name = 'cmdline', option = { ignore_cmds = { 'Man', '!' } } }
})
})
end -- completions
----------------------- NOTES --------------------------------
-- zk (zettelkasten lsp), taskwiki, focus mode, grammar
M.notes = function()
require("zk").setup({
picker = "telescope",
-- automatically attach buffers in a zk notebook that match the given filetypes
lsp = {
auto_attach = {
enabled = true,
filetypes = { "markdown", "vimwiki", "md" }
},
config = {
on_attach = function(_, bufnr)
print("ZK attached")
local which_key = require("which-key")
local local_leader_opts = {
mode = "n", -- NORMAL mode
prefix = "<leader>",
buffer = bufnr, -- Local mappings.
silent = true, -- use `silent` when creating keymaps
noremap = true, -- use `noremap` when creating keymaps
nowait = true -- use `nowait` when creating keymaps
}
local local_leader_opts_visual = {
mode = "v", -- VISUAL mode
prefix = "<leader>",
buffer = bufnr, -- Local mappings.
silent = true, -- use `silent` when creating keymaps
noremap = true, -- use `noremap` when creating keymaps
nowait = true -- use `nowait` when creating keymaps
}
local leader_mappings = {
K = { "<Cmd>lua vim.lsp.buf.hover()<CR>", "Info preview" },
n = {
-- Create the note in the same directory as the current buffer after asking for title
p = {
"<Cmd>ZkNew { dir = vim.fn.expand('%:p:h'), title = vim.fn.input('Title: ') }<CR>",
"New peer note (same dir)"
},
l = { "<Cmd>ZkLinks<CR>", "Show note links" },
-- the following duplicate with the ,l_ namespace on purpose because of programming muscle memory
r = {
"<cmd>Telescope lsp_references<CR>",
"References to this note"
}
},
l = {
name = "Local LSP",
-- Open notes linking to the current buffer.
r = {
"<cmd>Telescope lsp_references<CR>",
"References to this note"
},
i = {
"<Cmd>lua vim.lsp.buf.hover()<CR>",
"Info preview"
},
f = {
"<cmd>Lspsaga code_action<CR>",
"Fix Code Actions"
},
e = {
"<cmd>lua vim.diagnostic.open_float()<CR>",
"Show Line Diags"
}
}
}
which_key.register(leader_mappings, local_leader_opts)
local leader_mappings_visual = {
n = {
p = {
":'<,'>ZkNewFromTitleSelection { dir = vim.fn.expand('%:p:h') }<CR>",
"New peer note (same dir) selection for title"
}
-- Create a new note in the same directory as the current buffer, using the current selection for title.
}
}
which_key.register(leader_mappings_visual,
local_leader_opts_visual)
local opts = { noremap = true, silent = true }
-- TODO: Make <CR> magic...
-- in normal mode, if on a link, it should open the link (note or url)
-- in visual mode, it should prompt for folder, create a note, and make a link
-- Meanwhile, just go to definition
vim.api.nvim_buf_set_keymap(bufnr, "n", "<CR>",
"<Cmd>lua vim.lsp.buf.definition()<CR>",
opts)
-- Preview a linked note.
vim.api.nvim_buf_set_keymap(bufnr, "", "K",
"<Cmd>lua vim.lsp.buf.hover()<CR>",
opts)
require('pwnvim.options').tabindent()
end
}
}
})
-- Focus mode dimming of text out of current block
--[[ require("twilight").setup {
dimming = {
alpha = 0.25, -- amount of dimming
-- we try to get the foreground from the highlight groups or fallback color
color = { "Normal", "#ffffff" },
term_bg = "#000000", -- if guibg=NONE, this will be used to calculate text color
inactive = true -- when true, other windows will be fully dimmed (unless they contain the same buffer)
},
context = 12, -- amount of lines we will try to show around the current line
treesitter = true, -- use treesitter when available for the filetype
-- treesitter is used to automatically expand the visible text,
-- but you can further control the types of nodes that should always be fully expanded
expand = { -- for treesitter, we we always try to expand to the top-most ancestor with these types
"function", "method", "table", "if_statement"
},
exclude = {} -- exclude these filetypes
} ]]
-- Focus mode / centering
require("true-zen").setup {
-- your config goes here
-- or just leave it empty :)
modes = {
-- configurations per mode
ataraxis = {
shade = "dark", -- if `dark` then dim the padding windows, otherwise if it's `light` it'll brighten said windows
backdrop = 0, -- percentage by which padding windows should be dimmed/brightened. Must be a number between 0 and 1. Set to 0 to keep the same background color
minimum_writing_area = {
-- minimum size of main window
width = 70,
height = 44
},
quit_untoggles = true, -- type :q or :qa to quit Ataraxis mode
padding = {
-- padding windows
left = 52,
right = 52,
top = 0,
bottom = 0
},
callbacks = {
-- run functions when opening/closing Ataraxis mode
open_pre = function()
vim.opt.scrolloff = 999 -- keep cursor in vertical middle of screen
end,
open_pos = nil,
close_pre = nil,
close_pos = function()
vim.opt.scrolloff = 8
end
}
},
minimalist = {
ignored_buf_types = { "nofile" }, -- save current options from any window except ones displaying these kinds of buffers
options = {
-- options to be disabled when entering Minimalist mode
number = false,
relativenumber = false,
showtabline = 0,
signcolumn = "no",
statusline = "",
cmdheight = 1,
laststatus = 0,
showcmd = false,
showmode = false,
ruler = false,
numberwidth = 1
},
callbacks = {
-- run functions when opening/closing Minimalist mode
open_pre = nil,
open_pos = nil,
close_pre = nil,
close_pos = nil
}
},
narrow = {
--- change the style of the fold lines. Set it to:
--- `informative`: to get nice pre-baked folds
--- `invisible`: hide them
--- function() end: pass a custom func with your fold lines. See :h foldtext
folds_style = "informative",
run_ataraxis = true, -- display narrowed text in a Ataraxis session
callbacks = {
-- run functions when opening/closing Narrow mode
open_pre = nil,
open_pos = nil,
close_pre = nil,
close_pos = nil
}
},
focus = {
callbacks = {
-- run functions when opening/closing Focus mode
open_pre = nil,
open_pos = nil,
close_pre = nil,
close_pos = nil
}
}
},
integrations = {
tmux = false, -- hide tmux status bar in (minimalist, ataraxis)
kitty = {
-- increment font size in Kitty. Note: you must set `allow_remote_control socket-only` and `listen_on unix:/tmp/kitty` in your personal config (ataraxis)
enabled = false, -- disabled 2023-03-20 because it doesn't reset the font size on exit
font = "+2"
},
twilight = false, -- enable twilight text dimming outside cursor block
lualine = true -- hide nvim-lualine (ataraxis)
}
}
-- Grammar
vim.g["grammarous#disabled_rules"] = {
['*'] = {
'WHITESPACE_RULE', 'EN_QUOTES', 'ARROWS', 'SENTENCE_WHITESPACE',
'WORD_CONTAINS_UNDERSCORE', 'COMMA_PARENTHESIS_WHITESPACE',
'EN_UNPAIRED_BRACKETS', 'UPPERCASE_SENTENCE_START',
'ENGLISH_WORD_REPEAT_BEGINNING_RULE', 'DASH_RULE', 'PLUS_MINUS',
'PUNCTUATION_PARAGRAPH_END', 'MULTIPLICATION_SIGN', 'PRP_CHECKOUT',
'CAN_CHECKOUT', 'SOME_OF_THE', 'DOUBLE_PUNCTUATION', 'HELL',
'CURRENCY', 'POSSESSIVE_APOSTROPHE', 'ENGLISH_WORD_REPEAT_RULE',
'NON_STANDARD_WORD'
}
}
-- Grammar stuff
vim.cmd(
[[command StartGrammar2 lua require('pwnvim.plugins').grammar_check()]])
end -- notes
M.grammar_check = function()
vim.cmd('packadd vim-grammarous')
local opts = { noremap = false, silent = true }
local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(0, ...) end
buf_set_keymap('', '<leader>gf', '<Plug>(grammarous-fixit)', opts)
buf_set_keymap('', '<leader>gx', '<Plug>(grammarous-remove-error)', opts)
buf_set_keymap('', ']g', '<Plug>(grammarous-move-to-next-error)', opts)
buf_set_keymap('', '[g', '<Plug>(grammarous-move-to-previous-error)', opts)
vim.cmd('GrammarousCheck')
end
----------------------- MISC --------------------------------
-- rooter, kommentary, autopairs, tmux, toggleterm
M.misc = function()
vim.g.lf_map_keys = 0 -- lf.vim disable default keymapping
-- Change project directory using local cd only
-- vim.g.rooter_cd_cmd = 'lcd'
-- Look for these files/dirs as hints
-- vim.g.rooter_patterns = {
-- '.git', '_darcs', '.hg', '.bzr', '.svn', 'Makefile', 'package.json',
-- '.zk', 'Cargo.toml', 'build.sbt', 'Package.swift', 'Makefile.in'
-- }
require('project_nvim').setup({
active = true,
on_config_done = nil,
manual_mode = false,
detection_methods = { "pattern", "lsp" },
patterns = {
".git", "_darcs", ".hg", ".bzr", ".svn", "Makefile", "package.json",
".zk", "build.sbt", "Package.swift", "Makefile.in", "README.md",
"flake.nix"
},
show_hidden = false,
silent_chdir = true,
ignore_lsp = {}
})
require('telescope').load_extension('projects')
require('Comment').setup()
require("which-key").register({
["<leader>c<space>"] = {
'<Plug>(comment_toggle_linewise_current)', "Toggle comments"
},
["g/"] = { '<Plug>(comment_toggle_linewise_current)', "Toggle comments" }
}, { mode = "n", silent = true, norewrap = true })
require("which-key").register({
["<leader>c<space>"] = {
'<Plug>(comment_toggle_linewise_visual)', "Toggle comments"
},
["g/"] = { '<Plug>(comment_toggle_linewise_visual)', "Toggle comments" }
}, { mode = "v", silent = true, norewrap = true })
require('nvim-autopairs').setup({})
vim.g.tmux_navigator_no_mappings = 1
require("toggleterm").setup {
open_mapping = [[<c-\>]],
insert_mappings = true, -- from normal or insert mode
start_in_insert = true,
hide_numbers = true,
direction = 'vertical',
size = function(_) return vim.o.columns * 0.3 end,
close_on_exit = true
}
vim.api.nvim_set_keymap('t', [[<C-\]], "<Cmd>ToggleTermToggleAll<cr>",
{ noremap = true })
end -- misc
return M

View File

@@ -1,58 +0,0 @@
require 'bufferline'.setup {
options = {
numbers = "none", -- | "ordinal" | "buffer_id" | "both" | function({ ordinal, id, lower, raise }): string,
close_command = "Bdelete! %d", -- can be a string | function, see "Mouse actions"
right_mouse_command = "Bdelete! %d", -- can be a string | function, see "Mouse actions"
left_mouse_command = "buffer %d", -- can be a string | function, see "Mouse actions"
middle_mouse_command = nil, -- can be a string | function, see "Mouse actions"
indicator = {
style = "icon",
icon = "",
},
-- buffer_close_icon = '',
modified_icon = "",
close_icon = SimpleUI and "x" or "",
-- close_icon = '',
-- hover doesn't work in tmux
-- hover = {
-- enabled = true,
-- delay = 200,
-- reveal = { 'close' }
-- },
left_trunc_marker = SimpleUI and "⬅️" or "",
right_trunc_marker = SimpleUI and "➡️" or "",
max_name_length = 40,
max_prefix_length = 30, -- prefix used when a buffer is de-duplicated
tab_size = 20,
-- name_formatter = function(buf) -- buf contains a "name", "path" and "bufnr"
-- -- remove extension from markdown files for example
-- if buf.name:match('%.md') then
-- return vim.fn.fnamemodify(buf.name, ':t:r')
-- end
-- end,
diagnostics = false, -- | "nvim_lsp" | "coc",
diagnostics_update_in_insert = false,
offsets = { { filetype = "NvimTree", text = "", padding = 1 } },
show_buffer_close_icons = true,
show_close_icon = true,
show_buffer_icons = not SimpleUI,
color_icons = not SimpleUI,
buffer_close_icon = SimpleUI and "x" or "",
show_tab_indicators = true,
persist_buffer_sort = false, -- whether or not custom sorted buffers should persist
-- can also be a table containing 2 custom separators
-- [focused and unfocused]. eg: { '|', '|' }
separator_style = "thick", -- | "thick" | "thin" | { 'any', 'any' },
enforce_regular_tabs = false, -- if true, all tabs same width
always_show_bufferline = true
},
highlights = {
indicator_selected = {
fg = {
attribute = "fg",
highlight = "LspDiagnosticsDefaultHint"
},
bg = { attribute = "bg", highlight = "Normal" }
}
}
}

View File

@@ -1,99 +0,0 @@
require("gitsigns").setup {
signs = {
add = {
hl = 'GitSignsAdd',
text = '',
numhl = 'GitSignsAddNr',
linehl = 'GitSignsAddLn'
},
change = {
hl = 'GitSignsChange',
text = '',
numhl = 'GitSignsChangeNr',
linehl = 'GitSignsChangeLn'
},
delete = {
hl = 'GitSignsDelete',
text = '_',
numhl = 'GitSignsDeleteNr',
linehl = 'GitSignsDeleteLn'
},
topdelete = {
hl = 'GitSignsDelete',
text = '',
numhl = 'GitSignsDeleteNr',
linehl = 'GitSignsDeleteLn'
},
changedelete = {
hl = 'GitSignsChange',
text = '~',
numhl = 'GitSignsChangeNr',
linehl = 'GitSignsChangeLn'
}
},
on_attach = function(bufnr)
local gs = package.loaded.gitsigns
local function map(mode, l, r, opts)
opts = opts or {}
opts.buffer = bufnr
vim.keymap.set(mode, l, r, opts)
end
-- Navigation
map('n', ']c', function()
if vim.wo.diff then return ']c' end
vim.schedule(function() gs.next_hunk() end)
return '<Ignore>'
end, { expr = true })
map('n', '[c', function()
if vim.wo.diff then return '[c' end
vim.schedule(function() gs.prev_hunk() end)
return '<Ignore>'
end, { expr = true })
-- Actions -- normal mode
require("which-key").register(
{
["<leader>"] = {
h = {
name = "hunk (git)",
s = { ':Gitsigns stage_hunk<CR>', "Stage hunk" },
r = { ':Gitsigns reset_hunk<CR>', "Reset hunk" },
S = { gs.stage_buffer, "Stage buffer" },
u = { gs.undo_stage_hunk, "Undo stage hunk" },
R = { gs.reset_buffer, "Reset buffer" },
p = { gs.preview_hunk, "Preview hunk" },
b = { function() gs.blame_line { full = true } end, "Blame hunk" },
d = { gs.diffthis, "Diff this to index" },
D = { function() gs.diffthis('~') end, "Diff this to previous" },
},
t = {
name = "git toggles",
b = { gs.toggle_current_line_blame, "Toggle current line blame" },
d = { gs.toggle_deleted, "Toggle deleted" },
}
}
}, { mode = "n", buffer = bufnr, silent = true, norewrap = true }
)
-- Actions -- visual and select mode
require("which-key").register(
{
["<leader>"] = {
h = {
name = "hunk (git)",
s = { ':Gitsigns stage_hunk<CR>', "Stage hunk" },
r = { ':Gitsigns reset_hunk<CR>', "Reset hunk" },
}
}
}, { mode = "v", buffer = bufnr, silent = true, norewrap = true }
)
-- Actions -- operator pending mode
require("which-key").register(
{
["ih"] = { ':<C-U>Gitsigns select_hunk<CR>', "Select git hunk" }
}, { mode = "o", buffer = bufnr, silent = true, norewrap = true }
)
end
}

View File

@@ -1,30 +0,0 @@
if not SimpleUI then
vim.g.indentLine_enabled = 1
vim.g.indent_blankline_char = ''
-- vim.g.indent_blankline_char = "▏"
vim.g.indent_blankline_filetype_exclude = { 'help', 'packer' }
vim.g.indent_blankline_buftype_exclude = { 'terminal', 'nofile' }
vim.g.indent_blankline_char_highlight = 'LineNr'
vim.g.indent_blankline_show_trailing_blankline_indent = false
vim.g.indent_blankline_filetype_exclude = {
"help", "startify", "dashboard", "packer", "neogitstatus", "NvimTree",
"Trouble"
}
vim.g.indent_blankline_use_treesitter = true
vim.g.indent_blankline_show_current_context = true
vim.g.indent_blankline_context_patterns = {
"class", "return", "function", "method", "^if", "^while", "jsx_element",
"^for", "^object", "^table", "block", "arguments", "if_statement",
"else_clause", "jsx_element", "jsx_self_closing_element",
"try_statement", "catch_clause", "import_statement", "operation_type"
}
-- HACK: work-around for https://github.com/lukas-reineke/indent-blankline.nvim/issues/59
vim.wo.colorcolumn = "99999"
require('indent_blankline').setup({
show_current_context = true,
use_treesitter = true,
buftype_exclude = { 'terminal' },
filetype_exclude = { 'help', 'markdown' },
})
end

View File

@@ -1,27 +0,0 @@
require('lualine').setup {
options = {
theme = 'papercolor_light',
icons_enabled = not SimpleUI,
component_separators = { left = SimpleUI and '>' or '', right = SimpleUI and '<' or '' },
disabled_filetypes = { 'pager' },
section_separators = { left = SimpleUI and '>' or '', right = SimpleUI and '<' or '' }
},
extensions = { 'quickfix', 'nvim-tree', 'fugitive' },
sections = {
lualine_a = { 'mode' },
lualine_b = { 'branch' },
lualine_c = { 'nvim-tree', 'filename' },
lualine_x = { 'encoding', 'fileformat', 'filetype' },
lualine_y = { 'progress' },
lualine_z = {
{
'diagnostics',
sources = { 'nvim_diagnostic' },
-- displays diagnostics from defined severity
sections = { 'error', 'warn' }, -- 'info', 'hint'},}}
color_error = "#E06C75", -- changes diagnostic's error foreground color
color_warn = "#E5C07B"
}
}
}
}

View File

@@ -1,164 +0,0 @@
local signs = require("pwnvim.signs")
--
-- This function has been generated from your
-- view.mappings.list
-- view.mappings.custom_only
-- remove_keymaps
--
-- You should add this function to your configuration and set on_attach = on_attach in the nvim-tree setup call.
--
-- Although care was taken to ensure correctness and completeness, your review is required.
--
-- Please check for the following issues in auto generated content:
-- "Mappings removed" is as you expect
-- "Mappings migrated" are correct
--
-- Please see https://github.com/nvim-tree/nvim-tree.lua/wiki/Migrating-To-on_attach for assistance in migrating.
--
local function on_attach(bufnr)
local api = require('nvim-tree.api')
local function opts(desc)
return { desc = 'nvim-tree: ' .. desc, buffer = bufnr, noremap = true, silent = true, nowait = true }
end
-- Default mappings. Feel free to modify or remove as you wish.
--
-- BEGIN_DEFAULT_ON_ATTACH
vim.keymap.set('n', '<C-]>', api.tree.change_root_to_node, opts('CD'))
vim.keymap.set('n', '<C-e>', api.node.open.replace_tree_buffer, opts('Open: In Place'))
vim.keymap.set('n', '<C-k>', api.node.show_info_popup, opts('Info'))
vim.keymap.set('n', '<C-r>', api.fs.rename_sub, opts('Rename: Omit Filename'))
vim.keymap.set('n', '<C-t>', api.node.open.tab, opts('Open: New Tab'))
vim.keymap.set('n', '<C-v>', api.node.open.vertical, opts('Open: Vertical Split'))
vim.keymap.set('n', '<C-x>', api.node.open.horizontal, opts('Open: Horizontal Split'))
vim.keymap.set('n', '<BS>', api.node.navigate.parent_close, opts('Close Directory'))
vim.keymap.set('n', '<CR>', api.node.open.edit, opts('Open'))
vim.keymap.set('n', '<Tab>', api.node.open.preview, opts('Open Preview'))
vim.keymap.set('n', '>', api.node.navigate.sibling.next, opts('Next Sibling'))
vim.keymap.set('n', '<', api.node.navigate.sibling.prev, opts('Previous Sibling'))
vim.keymap.set('n', '.', api.node.run.cmd, opts('Run Command'))
vim.keymap.set('n', '-', api.tree.change_root_to_parent, opts('Up'))
vim.keymap.set('n', 'a', api.fs.create, opts('Create'))
vim.keymap.set('n', 'bmv', api.marks.bulk.move, opts('Move Bookmarked'))
vim.keymap.set('n', 'B', api.tree.toggle_no_buffer_filter, opts('Toggle No Buffer'))
vim.keymap.set('n', 'c', api.fs.copy.node, opts('Copy'))
vim.keymap.set('n', 'C', api.tree.toggle_git_clean_filter, opts('Toggle Git Clean'))
vim.keymap.set('n', '[c', api.node.navigate.git.prev, opts('Prev Git'))
vim.keymap.set('n', ']c', api.node.navigate.git.next, opts('Next Git'))
vim.keymap.set('n', 'd', api.fs.remove, opts('Delete'))
vim.keymap.set('n', 'D', api.fs.trash, opts('Trash'))
vim.keymap.set('n', 'E', api.tree.expand_all, opts('Expand All'))
vim.keymap.set('n', 'e', api.fs.rename_basename, opts('Rename: Basename'))
vim.keymap.set('n', ']e', api.node.navigate.diagnostics.next, opts('Next Diagnostic'))
vim.keymap.set('n', '[e', api.node.navigate.diagnostics.prev, opts('Prev Diagnostic'))
vim.keymap.set('n', 'F', api.live_filter.clear, opts('Clean Filter'))
vim.keymap.set('n', 'f', api.live_filter.start, opts('Filter'))
vim.keymap.set('n', 'g?', api.tree.toggle_help, opts('Help'))
vim.keymap.set('n', 'gy', api.fs.copy.absolute_path, opts('Copy Absolute Path'))
vim.keymap.set('n', 'H', api.tree.toggle_hidden_filter, opts('Toggle Dotfiles'))
vim.keymap.set('n', 'I', api.tree.toggle_gitignore_filter, opts('Toggle Git Ignore'))
vim.keymap.set('n', 'J', api.node.navigate.sibling.last, opts('Last Sibling'))
vim.keymap.set('n', 'K', api.node.navigate.sibling.first, opts('First Sibling'))
vim.keymap.set('n', 'm', api.marks.toggle, opts('Toggle Bookmark'))
vim.keymap.set('n', 'o', api.node.open.edit, opts('Open'))
vim.keymap.set('n', 'O', api.node.open.no_window_picker, opts('Open: No Window Picker'))
vim.keymap.set('n', 'p', api.fs.paste, opts('Paste'))
vim.keymap.set('n', 'P', api.node.navigate.parent, opts('Parent Directory'))
vim.keymap.set('n', 'q', api.tree.close, opts('Close'))
vim.keymap.set('n', 'r', api.fs.rename, opts('Rename'))
vim.keymap.set('n', 'R', api.tree.reload, opts('Refresh'))
vim.keymap.set('n', 's', api.node.run.system, opts('Run System'))
vim.keymap.set('n', 'S', api.tree.search_node, opts('Search'))
vim.keymap.set('n', 'U', api.tree.toggle_custom_filter, opts('Toggle Hidden'))
vim.keymap.set('n', 'W', api.tree.collapse_all, opts('Collapse'))
vim.keymap.set('n', 'x', api.fs.cut, opts('Cut'))
vim.keymap.set('n', 'y', api.fs.copy.filename, opts('Copy Name'))
vim.keymap.set('n', 'Y', api.fs.copy.relative_path, opts('Copy Relative Path'))
vim.keymap.set('n', '<2-LeftMouse>', api.node.open.edit, opts('Open'))
vim.keymap.set('n', '<2-RightMouse>', api.tree.change_root_to_node, opts('CD'))
-- END_DEFAULT_ON_ATTACH
-- Mappings migrated from view.mappings.list
--
-- You will need to insert "your code goes here" for any mappings with a custom action_cb
vim.keymap.set('n', 'l', api.node.open.edit, opts('Open'))
vim.keymap.set('n', '<CR>', api.node.open.edit, opts('Open'))
vim.keymap.set('n', 'o', api.node.open.edit, opts('Open'))
vim.keymap.set('n', 'h', api.node.navigate.parent_close, opts('Close Directory'))
vim.keymap.set('n', '<F10>', function()
local node = api.tree.get_node_under_cursor()
-- your code goes here
end, opts('quicklook'))
vim.keymap.set('n', 'v', api.node.open.vertical, opts('Open: Vertical Split'))
end
require 'nvim-tree'.setup {
renderer = {
icons = {
webdev_colors = true,
git_placement = "before",
padding = " ",
symlink_arrow = "",
show = {
file = not SimpleUI,
folder = true,
folder_arrow = true,
git = true
},
glyphs = {
default = SimpleUI and "🖹" or "",
symlink = SimpleUI and "🔗" or "",
git = {
unstaged = SimpleUI and "" or "",
staged = "",
unmerged = SimpleUI and "⚡︎" or "",
renamed = "",
deleted = SimpleUI and "" or "",
untracked = "U",
ignored = ""
},
folder = {
default = SimpleUI and "📁" or "",
open = SimpleUI and "📂" or "",
empty = SimpleUI and "🗀" or "",
empty_open = SimpleUI and "🗁" or "",
symlink = SimpleUI and "🔗" or ""
}
}
}
},
-- disables netrw completely
disable_netrw = true,
-- hijack netrw window on startup
hijack_netrw = true,
-- open the tree when running this setup function
update_cwd = true,
-- update_to_buf_dir = { enable = true, auto_open = true },
update_focused_file = { enable = true, update_cwd = true },
-- show lsp diagnostics in the signcolumn
diagnostics = {
enable = true,
icons = { hint = signs.hint, info = signs.info, warning = signs.warn, error = signs.error }
},
git = {
enable = true,
timeout = 400 -- (in ms)
},
on_attach = on_attach,
view = {
width = 30,
-- height = 30,
hide_root_folder = false,
side = "left",
-- auto_resize = true,
number = false,
relativenumber = false
}
}

View File

@@ -1,58 +0,0 @@
local signs = require("pwnvim.signs")
require("todo-comments").setup {
-- your configuration comes here
-- or leave it empty to use the default settings
-- refer to the configuration section below
signs = false, -- show icons in the signs column
keywords = {
FIX = {
icon = "", -- icon used for the sign, and in search results
color = "error", -- can be a hex color, or a named color (see below)
alt = { "ERROR", "FIXME", "BUG", "FIXIT", "ISSUE", "!!!" }, -- a set of other keywords that all map to this FIX keywords
-- signs = false, -- configure signs for some keywords individually
},
TODO = { icon = "", color = "info", alt = { "PWTODO", "TK" } },
HACK = { icon = "", color = "warning" },
WARN = { icon = signs.warn, color = "warning", alt = { "WARNING", "XXX" } },
PERF = { icon = "", alt = { "OPTIM", "PERFORMANCE", "OPTIMIZE" } },
NOTE = { icon = "", color = "hint", alt = { "INFO" } },
TEST = { icon = "", color = "test", alt = { "TESTING", "PASSED", "FAILED" } },
},
merge_keywords = true, -- when true, custom keywords will be merged with the defaults
-- highlighting of the line containing the todo comment
-- * before: highlights before the keyword (typically comment characters)
-- * keyword: highlights of the keyword
-- * after: highlights after the keyword (todo text)
highlight = {
multiline = false,
before = "", -- "fg" or "bg" or empty
keyword = "wide", -- "fg", "bg", "wide" or empty. (wide is the same as bg, but will also highlight surrounding characters)
after = "fg", -- "fg" or "bg" or empty
pattern = [[<(KEYWORDS)]], -- pattern or table of patterns, used for highlightng (vim regex)
comments_only = false, -- uses treesitter to match keywords in comments only
max_line_len = 400, -- ignore lines longer than this
exclude = {}, -- list of file types to exclude highlighting
},
-- list of named colors where we try to extract the guifg from the
-- list of hilight groups or use the hex color if hl not found as a fallback
colors = {
error = { "DiagnosticError", "ErrorMsg", "#DC2626" },
warning = { "DiagnosticWarning", "WarningMsg", "#FBBF24" },
info = { "DiagnosticInfo", "#2563EB" },
hint = { "DiagnosticHint", "#10B981" },
default = { "Identifier", "#7C3AED" },
},
search = {
command = "rg",
args = {
"--color=never",
"--no-heading",
"--with-filename",
"--line-number",
"--column",
},
-- regex that will be used to match keywords.
-- don't replace the (KEYWORDS) placeholder
pattern = [[\b(KEYWORDS)]], -- match without the extra colon. You'll likely get false positives
},
}

View File

@@ -1,60 +0,0 @@
require 'nvim-treesitter.configs'.setup {
auto_install = false,
autotag = { enable = true },
highlight = {
enable = true,
--disable = { "markdown", "markdown_inline" }, -- 2022-11-30 conflicts with markdown plugin, which detects more things like bold+italic and strikethrough
--additional_vim_regex_highlighting = { "markdown" } -- leaving in case we bring back markdown plugin
},
indent = { enable = true, disable = { "yaml" } },
incremental_selection = { enable = true },
context_commentstring = {
enable = true,
},
textobjects = {
select = {
enable = true,
lookahead = true,
keymaps = {
-- You can use the capture groups defined in textobjects.scm
["af"] = { query = "@function.outer", desc = "Select outer function" },
["if"] = { query = "@function.inner", desc = "Select inner function" },
["ac"] = { query = "@class.outer", desc = "Select outer class" },
["ic"] = { query = "@class.inner", desc = "Select inner class" },
["im"] = { query = "@block.inner", desc = "Select inner block" },
["am"] = { query = "@block.outer", desc = "Select outer block" },
-- ["il"] = { query = "@list.inner", desc = "Select inner list" },
-- ["al"] = { query = "@list.outer", desc = "Select outer list" },
-- ["ih"] = { query = "@section.inner", desc = "Select inner section" },
-- ["ah"] = { query = "@section.outer", desc = "Select outer section" },
},
},
move = {
enable = true,
set_jumps = true, -- whether to set jumps in the jumplist
goto_next_start = {
["]m"] = "@function.outer",
["]]"] = { query = "@class.outer", desc = "Next class start" },
},
goto_next_end = {
["]M"] = "@function.outer",
["]["] = "@class.outer",
},
goto_previous_start = {
["[m"] = "@function.outer",
["[["] = "@class.outer",
},
goto_previous_end = {
["[M"] = "@function.outer",
["[]"] = "@class.outer",
},
},
}
}
require 'treesitter-context'.setup {
max_lines = 0, -- no max window height
patterns = {
markdown = { "atx_heading" }
},
}

View File

@@ -1,77 +0,0 @@
local M = {}
M.error = SimpleUI and "🛑" or ""
M.warn = SimpleUI and "⚠️" or ""
M.hint = SimpleUI and "" or ""
M.info = SimpleUI and "" or ""
M.signs = {
{ name = "DiagnosticSignError", text = M.error },
{ name = "DiagnosticSignWarn", text = M.warn },
{ name = "DiagnosticSignHint", text = M.hint },
{ name = "DiagnosticSignInfo", text = M.info }
}
if SimpleUI then
M.kind_icons = {
Text = "T",
Method = "m",
Function = "f",
Constructor = "c",
Field = "f",
Variable = "v",
Class = "",
Interface = "i",
Module = "m",
Property = "p",
Unit = "u",
Value = "v",
Enum = "e",
Keyword = "",
Snippet = "s",
Color = "",
File = "F",
Reference = "r",
Folder = "🖿",
EnumMember = "em",
Constant = "c",
Struct = "s",
Event = "e",
Operator = "o",
TypeParameter = "t"
}
else
M.kind_icons = {
Text = "",
Method = "m",
Function = "",
Constructor = "",
Field = "",
Variable = "",
Class = "",
Interface = "",
Module = "",
Property = "",
Unit = "",
Value = "",
Enum = "",
Keyword = "",
Snippet = "",
Color = "",
File = "",
Reference = "",
Folder = "",
EnumMember = "",
Constant = "",
Struct = "",
Event = "",
Operator = "",
TypeParameter = ""
}
end
for _, sign in ipairs(M.signs) do
vim.fn.sign_define(sign.name,
{ texthl = M.name, text = M.text, numhl = "" })
end
return M

View File

@@ -1,196 +0,0 @@
local M = {}
M.completeTaskDirect = function()
local line = vim.api.nvim_get_current_line()
local nline = require("pwnvim.tasks").completeTask(line)
vim.api.nvim_set_current_line(nline)
end
M.completeTask = function(line)
local nline = line:gsub("%[[ oO]%]", "[x]", 1)
if line ~= nline then -- substitution successful, now add date completed
nline = nline .. ' @done(' .. os.date("%Y-%m-%d %-I:%M %p") .. ")"
return nline
else -- or do nothing
return line
end
end
M.scheduleTaskDirect = function(newyear, newmonth, newday)
local line = vim.api.nvim_get_current_line()
local nline = require("pwnvim.tasks").scheduleTask(line, newyear, newmonth, newday)
vim.api.nvim_set_current_line(nline)
end
M.scheduleTask = function(line, newyear, newmonth, newday)
newmonth = string.format("%02d", newmonth)
newday = string.format("%02d", newday)
local buf = vim.api.nvim_get_current_buf()
local win = vim.api.nvim_get_current_win()
-- Step 1: change current task to [>]
local nline = line:gsub("%[[ oO>-]%] ", "[>] ", 1)
if line == nline then
-- no changes then abort
return line
end
-- Step 2: add scheduled date to end as ">YYYY-mm-dd" removing any existing ">date" tags
nline = nline:gsub(">[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]?", "")
nline = nline .. " >" .. newyear .. "-" .. newmonth .. "-" .. newday
--vim.api.nvim_set_current_line(nline)
-- Step 3: try to get the date from the current note
local date = require("pwnvim.tasks").getDateFromCurrentFile()
-- Step 4: add "<YYYY-mm-dd" to end of the copied task if it doesn't already have a date
-- and if we can glean a source date from a date in the filename or frontmatter
-- or worst case, just don't put that
if line:match("<%d+-%d+-%d+") == nil and date ~= nil then
line = line .. " <" .. date
end
-- Step 5: take current task and copy it to Calendar/YYYYmmdd.md
local target = vim.env.ZK_NOTEBOOK_DIR .. '/Calendar/' .. newyear .. newmonth .. newday .. '.md'
vim.api.nvim_command('edit ' .. target)
vim.api.nvim_buf_set_lines(0, -1, -1, false, { line })
vim.api.nvim_set_current_win(win)
vim.api.nvim_set_current_buf(buf)
return nline
end
M.scheduleTaskBulk = function()
require("pwnvim.tasks").datePromptThen(function(year, month, day)
vim.cmd("'<,'>luado return require('pwnvim.tasks').scheduleTask(line,'" ..
year .. "','" .. month .. "','" .. day .. "')")
end)
end
M.scheduleTaskPrompt = function()
require("pwnvim.tasks").datePromptThen(require("pwnvim.tasks").scheduleTaskDirect)
end
M.datePromptThen = function(myfunc)
local days = {}
-- Generate dates for next two weeks with handy shortcut labels
for i = 0, 14, 1 do
local day
if i == 0 then
day = os.date("%Y-%m-%d (today)", os.time() + 86400 * i)
elseif i == 1 then
day = os.date("%Y-%m-%d (tomorrow)", os.time() + 86400 * i)
elseif i > 7 then
day = os.date("%Y-%m-%d (next %a)", os.time() + 86400 * i)
else
day = os.date("%Y-%m-%d (%a)", os.time() + 86400 * i)
end
table.insert(days, day)
end
-- These will pop up in telescope for quick filtering
vim.ui.select(days, { prompt = 'Pick a date:' }, function(choice)
if choice then
local t = {}
for w in string.gmatch(choice, "(%d+)") do
table.insert(t, w)
end
if #t == 3 then
myfunc(t[1], t[2], t[3])
end
else
-- if no choice was made, assume a desire to specify something outside the 14 days
M.datePromptRawThen(myfunc)
end
end)
end
-- Just give three prompts for year/month/day
M.datePromptRawThen = function(myfunc)
local defaultyear = os.date("%Y")
local defaultmonth = os.date("%m")
local defaultday = os.date("%d")
vim.ui.input({ prompt = "Enter year: ", default = defaultyear }, function(year)
vim.ui.input({ prompt = "Enter month: ", default = defaultmonth }, function(month)
vim.ui.input({ prompt = "Enter day: ", default = defaultday }, function(day)
month = string.format("%02d", month)
day = string.format("%02d", day)
myfunc(year, month, day)
end)
end)
end)
end
M.scheduleTaskTodayDirect = function()
local year = os.date("%Y")
local month = os.date("%m")
local day = os.date("%d")
require("pwnvim.tasks").scheduleTaskDirect(year, month, day)
end
M.scheduleTaskToday = function(line)
local year = os.date("%Y")
local month = os.date("%m")
local day = os.date("%d")
return require("pwnvim.tasks").scheduleTask(line, year, month, day)
end
M.getDateFromCurrentFile = function()
local srcfilename = vim.api.nvim_buf_get_name(0)
local date = srcfilename:match("%d+-%d+-%d+")
-- TODO: also check for filenames that are "YYYYmmdd.md"
if date == nil then
local srcheader = vim.api.nvim_buf_get_lines(0, 0, 10, false)
for _, l in ipairs(srcheader) do
date = l:match("^[dD]ate: (%d+-%d+-%d+)")
if date ~= nil then break end
end
end
return date
end
M.createTask = function(line)
local nline = line:gsub("^%s*[-*] ", "%0[ ] ", 1)
if line == nline then
nline = line:gsub("^%s*", "%0* [ ] ", 1)
end
return nline
end
M.createTaskDirect = function()
local line = vim.api.nvim_get_current_line()
local nline = require("pwnvim.tasks").createTask(line)
vim.api.nvim_set_current_line(nline)
vim.cmd("normal 4l")
end
local function visual_selection_range()
local _, csrow, cscol, _ = unpack(vim.fn.getpos("'<"))
local _, cerow, cecol, _ = unpack(vim.fn.getpos("'>"))
if csrow < cerow or (csrow == cerow and cscol <= cecol) then
return csrow - 1, cscol - 1, cerow - 1, cecol
else
return cerow - 1, cecol - 1, csrow - 1, cscol
end
end
M.eachSelectedLine = function(myfunc)
-- local rowstart, _, rowend, _ = visual_selection_range()
local rowstart = vim.api.nvim_buf_get_mark(0, "<")[1] - 1
local rowend = vim.api.nvim_buf_get_mark(0, ">")[1] - 1
local buf = vim.api.nvim_get_current_buf()
local win = vim.api.nvim_get_current_win()
print("row start:" .. rowstart .. " row end:" .. rowend)
for i = rowstart, rowend do
print("i:" .. i)
vim.api.nvim_set_current_buf(buf)
vim.api.nvim_set_current_win(win)
vim.api.nvim_win_set_cursor(win, { i + 1, 0 })
-- All we're really doing here is putting the cursor on each line of the selection
myfunc()
end
end
return M