https://github.com/chrisgrieser/nvim-various-textobjs

Bundle of more than 30 new text objects for Neovim.

https://github.com/chrisgrieser/nvim-various-textobjs

Science Score: 36.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
    Found .zenodo.json file
  • DOI references
  • Academic publication links
    Links to: researchgate.net
  • Committers with academic emails
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (6.6%) to scientific vocabulary

Keywords

indentation neovim-plugin nvim-plugin subword text-obj text-object text-objects

Keywords from Contributors

archival projection reference-management pdf-summarization alfred-workflow sequences interactive generic hacking shellcodes
Last synced: 5 months ago · JSON representation

Repository

Bundle of more than 30 new text objects for Neovim.

Basic Info
  • Host: GitHub
  • Owner: chrisgrieser
  • License: mit
  • Language: Lua
  • Default Branch: main
  • Homepage:
  • Size: 634 KB
Statistics
  • Stars: 712
  • Watchers: 7
  • Forks: 25
  • Open Issues: 1
  • Releases: 0
Topics
indentation neovim-plugin nvim-plugin subword text-obj text-object text-objects
Created about 3 years ago · Last pushed 6 months ago
Metadata Files
Readme Funding License

README.md

nvim-various-textobjs 🟪🔷🟡

badge

Bundle of more than 30 new text objects for Neovim.

Table of contents

List of text objects

| text object | description | inner / outer | forward-seeking | default keymaps | | :----------------------- | :-------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------- | :-------------- | :----------------------: | | indentation | surrounding lines with same or higher indentation | see overview from vim-indent-object | - | ii, ai, aI, (iI) | | restOfIndentation | lines downwards with same or higher indentation | - | - | R | | greedyOuterIndentation | outer indentation, expanded to blank lines; useful to get functions with annotations | outer includes a blank (like ap/ip) | - | ag/ig | | subword | segment of a camelCase, snakecase, and kebab-case words | outer includes one trailing/leading `or-| \- |iS/aS| |toNextClosingBracket| from cursor to next closing],), or}, can span multiple lines | \- | small |C| |toNextQuotationMark| from cursor to next unescaped",', or , can span multiple lines | \- | small | `Q` | | `anyQuote` | between any unescaped `"`, `'`, or in one line | outer includes the quotation marks | small |iq/aq| |anyBracket| between any(),[], or{}in one line | outer includes the brackets | small |io/ao| |restOfParagraph| like}, but linewise | \- | \- |r| |entireBuffer| entire buffer as one text object | \- | \- |gG| |nearEoL| from cursor position to end of line minus one character | \- | \- |n| |lineCharacterwise| current line, but characterwise | outer includes indentation & trailing spaces | small, if on blank |i/a| |column| column down until indent or shorter line; accepts{count}for multiple columns | \- | \- ||| |value| value of key-value pair, or right side of assignment, excluding trailing comment (does not work for multi-line assignments) | outer includes trailing,or;| small |iv/av| |key| key of key-value pair, or left side of an assignment | outer includes the=or:| small |ik/ak| |url|httplinks or any other protocol | \- | big |L| |number| numbers, similar to| inner: only digits, outer: number including minus sign and decimal *point* | small |in/an| |diagnostic| nvim diagnostic | \- | ∞ |!| |closedFold| closed fold | outer includes one line after the last folded line | big |iz/az| |chainMember| section of a chain connected with.(or:) likefoo.barorfoo.baz(para)| outer includes one.(or:) | small |im/am| |visibleInWindow| all lines visible in the current window | \- | \- |gw| |restOfWindow| from the cursorline to the last line in the window | \- | \- |gW| |lastChange| last non-deletion-change, yank, or paste (paste-manipulation plugins may interfere) | \- | \- |g;| |notebookCell| cell delimited by [double percent comment][jupytext], such as# %%| outer includes the top cell border | \- |iN/aN| |emoji| single emoji (or Nerdfont glyph) | \- | small |.| |argument| comma-separated argument (not as accurate as the treesitter-textobjects, use as fallback) | outer includes the,| small |i,/a,| |filepath| unix-filepath; supports~or$HOME, but not spaces in the filepath. | inner is only the filename | big |iF/aF| |color| hex; rgb or hsl in CSS format; ANSI color code | inner includes only the color value | small |i#/a#| |doubleSquareBrackets| text enclosed by[[]]| outer includes the four square brackets | small |iD/aD` |

[!TIP] For some text objects, you can also use caW or cl if your cursor is standing on the object in question. However, these text objects become useful when utilizing their forward-seeking behavior: Objects like cL (url) or c. (emoji) will seek forward to the next occurrence and then change them in one go. This saves you the need to navigate to them before you can use caW or cl.

| filetype-specific text objects | description | inner / outer | forward-seeking | default keymaps | filetypes (for default keymaps) | | :----------------------------- | :------------------------------------------------------------------------------------------------- | :-----------------------------------------------| :-------------- | :-----------------: | :---------------------------------- | | mdLink | Markdown link like [title](url) | inner is only the link title (between the []) | small | il/al | markdown | | mdEmphasis | Markdown text enclosed by *, **, _, __, ~~, or == | inner is only the emphasis content | small | ie/ae | markdown | | mdFencedCodeBlock | Markdown fenced code (enclosed by three backticks) | outer includes the enclosing backticks | big | iC/aC | markdown | | cssSelector | class in CSS such as .my-class | outer includes trailing comma and space | small | ic/ac | css, scss | | htmlAttribute | attribute in HTML/XML like href="foobar.com" | inner is only the value inside the quotes | small | ix/ax | html, xml, css, scss, vue, svelte | | shellPipe | segment until/after a pipe character (\|) | outer includes the pipe | small | iP/aP | bash, zsh, fish, sh |

Installation

Variant 1: Have nvim-various-textobjs set up all the keybindings from the table above for you.

```lua -- lazy.nvim { "chrisgrieser/nvim-various-textobjs", event = "VeryLazy", opts = { keymaps = { useDefaults = true } }, },

-- packer use { "chrisgrieser/nvim-various-textobjs", config = function () require("various-textobjs").setup({ keymaps = { useDefaults = true } }) end, } ```

Variant 2: Use your own keybindings. See the Configuration section for information on how to set your own keymaps.

```lua -- lazy.nvim { "chrisgrieser/nvim-various-textobjs", keys = { -- ... }, },

-- packer use { "chrisgrieser/nvim-various-textobjs" } ```

[!TIP] You can also use the keymaps.disabledDefaults config option to disable only some default keymaps.

Configuration

Options

The .setup() call is optional if you do not want to use the default keymaps.

``lua -- default config require("various-textobjs").setup { keymaps = { -- See overview table in README for the defaults. (Note that lazy-loading -- this plugin, the default keymaps cannot be set up. if you set this to --true, you thus need to addlazy = false` to your lazy.nvim config.) useDefaults = false,

    -- disable only some default keymaps, for example { "ai", "!" }
    -- (only relevant when you set `useDefaults = true`)
    ---@type string[]
    disabledDefaults = {},
},

forwardLooking = {
    -- Number of lines to seek forwards for a text object. See the overview
    -- table in the README for which text object uses which value.
    small = 5,
    big = 15,
},
behavior = {
    -- save position in jumplist when using text objects
    jumplist = true, 
},

-- extra configuration for specific text objects
textobjs = {
    indentation = {
        -- `false`: only indentation decreases delimit the text object
        -- `true`: indentation decreases as well as blank lines serve as delimiter
        blanksAreDelimiter = false,
    },
    subword = {
        -- When deleting the start of a camelCased word, the result should
        -- still be camelCased and not PascalCased (see #113).
        noCamelToPascalCase = true,
    },
    diagnostic = {
        wrap = true,
    },
    url = {
        patterns = {
            [[%l%l%l+://[^%s)%]}"'`>]+]],
        },
    },
},

notify = {
    icon = "󰠱", -- only used with notification plugins like `nvim-notify`
    whenObjectNotFound = true,
},

-- show debugging messages on use of certain text objects
debug = false,

} ```

Use your own keybindings

If you want to set your own keybindings, you can do so by calling the respective functions. The function names correspond to the text object names from the overview table.

[!NOTE] For dot-repeat to work, you have to call the motions as Ex-commands. Using function() require("various-textobjs").diagnostic() end as third argument of the keymap will not work.

``lua -- example:U` for url textobj vim.keymap.set({ "o", "x" }, "U", 'lua require("various-textobjs").url()')

-- example: as for outer subword, is for inner subword vim.keymap.set({ "o", "x" }, "as", 'lua require("various-textobjs").subword("outer")') vim.keymap.set({ "o", "x" }, "is", 'lua require("various-textobjs").subword("inner")') ```

For most text objects, there is only one parameter which accepts "inner" or "outer". The exceptions are the indentation and column text objects:

lua -- THE INDENTATION TEXTOBJ requires two parameters, the first for exclusion of -- the starting border, the second for the exclusion of ending border vim.keymap.set( { "o", "x" }, "ii", '<cmd>lua require("various-textobjs").indentation("inner", "inner")<CR>' ) vim.keymap.set( { "o", "x" }, "ai", '<cmd>lua require("various-textobjs").indentation("outer", "inner")<CR>' )

lua -- THE COLUMN TEXTOBJ takes an optional parameter for direction: -- "down" (default), "up", "both" vim.keymap.set( { "o", "x" }, "|", '<cmd>lua require("various-textobjs").column("down")<CR>' ) vim.keymap.set( { "o", "x" }, "a|", '<cmd>lua require("various-textobjs").column("both")<CR>' )

Advanced usage / API

All text objects can also be used as an API to modify their behavior or create custom commands. Here are some examples:

Go to next occurrence of a text object

When called in normal mode, nvim-various-textobjs selects the next occurrence of the text object. Thus, you can easily create custom motions that go to the next occurrence of the text object:

lua local function gotoNextInnerNumber() require("various-textobjs").number("inner") local mode = vim.fn.mode() if mode:find("[Vv]") then -- only switches to visual when textobj found vim.cmd.normal { mode, bang = true } -- leaves visual mode end end,

Dynamically switch text object settings

Some text objects have specific settings allowing you to configure their behavior. In case you want to have two keymaps, one for each behavior, you can use this plugin's setup call before calling the respective text object.

``lua -- Example: one keymap forhttpurls only, one forftpurls only vim.keymap.set({ "o", "x" }, "H", function() require("various-textobjs").setup { textobjs = { url = { patterns = { [[https?://[^%s)%]}"'>]+]] }, }, }, } return "lua require('various-textobjs').url()" end, { expr = true, desc = "http-url textobj" })

vim.keymap.set({ "o", "x" }, "F", function() require("various-textobjs").setup { textobjs = { url = { patterns = { [[ftp://[^%s)%]}"'>]+]] }, }, }, } return "<cmd>lua require('various-textobjs').url()<CR>" end, { expr = true, desc = "ftp-url textobj" }) ``

ii on unindented line should select entire buffer

Using a simple if-else-block, you can create a hybrid of the inner indentation text object and the entire-buffer text object, if you prefer that kind of behavior:

lua -- when on unindented line, `ii` should select entire buffer vim.keymap.set("o", "ii", function() if vim.fn.indent(".") == 0 then require("various-textobjs").entireBuffer() else require("various-textobjs").indentation("inner", "inner") end end)

Smarter gx & gf

The code below retrieves the next URL (within the amount of lines configured in the setup call), and opens it in your browser. As opposed to vim's built-in gx, this is forward-seeking, meaning your cursor does not have to stand on the URL.

```lua vim.keymap.set("n", "gx", function() require("various-textobjs").url() -- select URL

local foundURL = vim.fn.mode() == "v" -- only switches to visual mode when textobj found
if not foundURL then return end

local url = vim.fn.getregion(vim.fn.getpos("."), vim.fn.getpos("v"), { type = "v" })[1]
vim.ui.open(url) -- requires nvim 0.10
vim.cmd.normal { "v", bang = true } -- leave visual mode

end, { desc = "URL Opener" }) ```

Similarly, we can also create a forward-looking version of gf:

```lua vim.keymap.set("n", "gf", function() require("various-textobjs").filepath("outer") -- select filepath

local foundPath = vim.fn.mode() == "v" -- only switches to visual mode when textobj found
if not foundPath then return end

local path = vim.fn.getregion(vim.fn.getpos("."), vim.fn.getpos("v"), { type = "v" })[1]

local exists = vim.uv.fs_stat(vim.fs.normalize(path)) ~= nil
if exists then
    vim.ui.open(path)
else
    vim.notify("Path does not exist.", vim.log.levels.WARN)
end

end, { desc = "URL Opener" }) ```

Delete surrounding indentation

Using the indentation text object, you can also create custom indentation-related utilities. A common operation is to remove the line before and after an indentation. Take for example this case where you are removing the foo condition:

```lua -- before if foo then print("bar") -- <- cursor is on this line print("baz") end

-- after print("bar") print("baz") ```

The code below achieves this by dedenting the inner indentation text object (essentially running <ii), and deleting the two lines surrounding it. As for the mapping, dsi should make sense since this command is similar to the ds operator from vim-surround but performed on an indentation text object. (It is also an intuitive mnemonic: Delete Surrounding Indentation.)

```lua vim.keymap.set("n", "dsi", function() -- select outer indentation require("various-textobjs").indentation("outer", "outer")

-- plugin only switches to visual mode when a textobj has been found
local indentationFound = vim.fn.mode():find("V")
if not indentationFound then return end

-- dedent indentation
vim.cmd.normal { "<", bang = true }

-- delete surrounding lines
local endBorderLn = vim.api.nvim_buf_get_mark(0, ">")[1]
local startBorderLn = vim.api.nvim_buf_get_mark(0, "<")[1]
vim.cmd(tostring(endBorderLn) .. " delete") -- delete end first so line index is not shifted
vim.cmd(tostring(startBorderLn) .. " delete")

end, { desc = "Delete Surrounding Indentation" }) ```

Yank surrounding indentation

Similarly, you can also create a ysii command to yank the two lines surrounding an indentation text object. (Not using ysi, since that blocks surround commands like ysi)). Using nvim_win_[gs]et_cursor(), you make the operation sticky, meaning the cursor is not moved.

``lua -- NOTE this function usesvim.hl.range` requires nvim 0.11 vim.keymap.set("n", "ysii", function() local startPos = vim.api.nvimwinget_cursor(0)

-- identify start- and end-border
require("various-textobjs").indentation("outer", "outer")
local indentationFound = vim.fn.mode():find("V")
if not indentationFound then return end
vim.cmd.normal { "V", bang = true } -- leave visual mode so the '< '> marks are set

-- copy them into the + register
local startLn = vim.api.nvim_buf_get_mark(0, "<")[1] - 1
local endLn = vim.api.nvim_buf_get_mark(0, ">")[1] - 1
local startLine = vim.api.nvim_buf_get_lines(0, startLn, startLn + 1, false)[1]
local endLine = vim.api.nvim_buf_get_lines(0, endLn, endLn + 1, false)[1]
vim.fn.setreg("+", startLine .. "\n" .. endLine .. "\n")

-- highlight yanked text
local dur = 1500
local ns = vim.api.nvim_create_namespace("ysii")
local bufnr = vim.api.nvim_get_current_buf()
vim.hl.range(bufnr, ns, "IncSearch", { startLn, 0 }, { startLn, -1 }, { timeout = dur })
vim.hl.range(bufnr, ns, "IncSearch", { endLn, 0 }, { endLn, -1 }, { timeout = dur })

-- restore cursor position
vim.api.nvim_win_set_cursor(0, startPos)

end, { desc = "Yank surrounding indentation" }) ```

Indent last paste

The lastChange text object can be used to indent the last text that was pasted. This is useful in languages such as Python where indentation is meaningful and thus formatters are not able to automatically indent everything for you.

If you do not use P for upwards paste, "shift paste" serves as a great mnemonic.

lua vim.keymap.set("n", "P", function() require("various-textobjs").lastChange() local changeFound = vim.fn.mode():find("v") if changeFound then vim.cmd.normal { ">", bang = true } end end

Other ideas?

If you have some other useful ideas, feel free to share them in this repo's discussion page.

Limitations & non-goals

  • This plugin uses pattern matching, so it can be inaccurate in some edge cases.
  • Counts are not supported for most text objects.
  • Most characterwise text objects do not match multi-line objects. Most notably, this affects the value text object.
  • nvim-treesitter-textobjects already does an excellent job when it comes to using Treesitter for text objects, such as function arguments or loops. This plugin's goal is therefore not to provide text objects already offered by nvim-treesitter-textobjects.
  • Some text objects (argument, key, value) are also offered by nvim-treesitter-textobjects, and usually, the treesitter version of them is more accurate, since nvim-various-textobjs uses pattern matching, which can only get you so far. However, nvim-treesitter-textobjects does not support all objects for all languages, so nvim-various-textobjs version exists to provide a fallback for those languages.

Other text object plugins

Credits

Thanks
- To the Valuable Dev for their blog post on how to get started with creating custom text objects. - To @vypxl and @ii14 for figuring out dot-repeatability.

In my day job, I am a sociologist studying the social mechanisms underlying the digital economy. For my PhD project, I investigate the governance of the app economy and how software ecosystems manage the tension between innovation and compatibility. If you are interested in this subject, feel free to get in touch.

Buy Me a Coffee at ko-fi.com

Owner

  • Name: Chris Grieser
  • Login: chrisgrieser
  • Kind: user
  • Location: Berlin, Germany
  • Company: Technical University of Berlin

Researcher in sociology & software developer

GitHub Events

Total
  • Issues event: 34
  • Watch event: 112
  • Delete event: 4
  • Issue comment event: 59
  • Push event: 190
  • Pull request event: 16
  • Fork event: 5
  • Create event: 2
Last Year
  • Issues event: 34
  • Watch event: 112
  • Delete event: 4
  • Issue comment event: 59
  • Push event: 190
  • Pull request event: 16
  • Fork event: 5
  • Create event: 2

Committers

Last synced: 12 months ago

All Time
  • Total Commits: 624
  • Total Committers: 20
  • Avg Commits per committer: 31.2
  • Development Distribution Score (DDS): 0.058
Past Year
  • Commits: 194
  • Committers: 10
  • Avg Commits per committer: 19.4
  • Development Distribution Score (DDS): 0.057
Top Committers
Name Email Commits
pseudometa 7****r 588
Steven Xu s****u@g****m 9
Kevin Traver k****r@k****m 4
xeluxee 8****e 3
Ofir Gal o****r@g****e 2
TheSast 2****t 2
francisco souza 1****a 2
phanium n****u@q****m 2
Aaron Kollasch a****n@k****v 1
Aleksandrs Stier 3****r 1
Daniel Santos Dantas d****l@s****v 1
David O'Trakoun d****g 1
Feiyou Guo f****o@g****m 1
FireIsGood f****e@g****m 1
James Karefylakis j****k 1
Jean Sidharta j****a@g****m 1
Thomas Friedel t****l@g****m 1
Yuta Katayama 8****t 1
dependabot[bot] 4****] 1
gnudad g****d@i****m 1
Committer Domains (Top 20 + Academic)

Issues and Pull Requests

Last synced: 6 months ago

All Time
  • Total issues: 77
  • Total pull requests: 48
  • Average time to close issues: about 1 month
  • Average time to close pull requests: 6 days
  • Total issue authors: 51
  • Total pull request authors: 22
  • Average comments per issue: 2.56
  • Average comments per pull request: 2.23
  • Merged pull requests: 39
  • Bot issues: 0
  • Bot pull requests: 6
Past Year
  • Issues: 17
  • Pull requests: 14
  • Average time to close issues: 3 days
  • Average time to close pull requests: 20 days
  • Issue authors: 16
  • Pull request authors: 5
  • Average comments per issue: 1.47
  • Average comments per pull request: 1.43
  • Merged pull requests: 11
  • Bot issues: 0
  • Bot pull requests: 6
Top Authors
Issue Authors
  • andrewferrier (7)
  • kola-web (5)
  • gerazov (3)
  • singlexyz (3)
  • kevintraver (3)
  • mawkler (3)
  • astier (2)
  • tuurep (2)
  • adriafarres (2)
  • ces42 (1)
  • matthias-Q (1)
  • daniilrozanov (1)
  • thenbe (1)
  • qw457812 (1)
  • fsouza (1)
Pull Request Authors
  • stevenxxiu (19)
  • TheSast (6)
  • dependabot[bot] (6)
  • kevintraver (5)
  • r-tae (4)
  • phanen (4)
  • fsouza (3)
  • ivomac (2)
  • gnudad (2)
  • uwla (2)
  • FireIsGood (2)
  • jamylak (2)
  • Jeansidharta (2)
  • aaronkollasch (1)
  • FeiyouG (1)
Top Labels
Issue Labels
bug (32) new textobj (16) change to existing textobj (14) enhancement (8) Stale (2) help wanted (1) documentation (1)
Pull Request Labels
dependencies (6) github_actions (4)

Dependencies

.github/workflows/panvimdoc.yml actions
  • actions/checkout v2 composite
  • kdheepak/panvimdoc main composite
  • stefanzweifel/git-auto-commit-action v4 composite
.github/workflows/stale-bot.yml actions
  • actions/stale v8 composite
.github/workflows/stylua.yml actions
  • JohnnyMorganz/stylua-action v2 composite
  • actions/checkout v3 composite