Giter Club home page Giter Club logo

nvim-puppeteer's Introduction

nvim-puppeteer 🎎

Shield

Master of strings. Automatically convert strings to f-strings or template strings and back.

Features

  • When typing {} in a Python string automatically converts it to an f-string.
  • Adding ${} or a line break in a JavaScript string automatically converts it to a template string. (Also works in related languages like JS-React or Typescript.)
  • Typing %s in a non-pattern Lua string automatically converts it to a formatted string. (Opt-in, as this has some caveats.)
  • Removing the {}, ${}, or %s converts it back to a regular string.
  • Also works with multi-line strings and undos.
  • Zero configuration. Just install and you are ready to go.

Requirements

  • nvim 0.9 or higher.
  • The respective Treesitter parsers: :TSInstall python javascript typescript. (Installing them requires nvim-treesitter.)

Installation

-- lazy.nvim
{ 
	"chrisgrieser/nvim-puppeteer",
	lazy = false, -- plugin lazy-loads itself. Can also load on filetypes.
},

-- packer
use { "chrisgrieser/nvim-puppeteer" }

There is no .setup() call. The plugin already automatically lazy-loads itself (and is lightweight to begin with).

You can disable nvim-puppeteer only for specific filetypes via:

Configuration

Shown are the default values.

-- list of filestypes (please see the README before enabling this plugin for lua)
vim.g.puppeteer_disable_filetypes = { "lua" }

-- quotation mark to use when converting back to normal string (" or ')
vim.g.puppeteer_js_quotation_mark = '"'

Note

When using lazy.nvim, vim.g.… variables must be set in init, not in config.

User Commands

The plugin is enabled by default and lazy-loaded upon opening a relevant file type. In case you wish to turn of puppeteer for the current buffer, the following user commands are provided:

  • PuppeteerToggle: Toggle puppeteer for the current buffer.
  • PuppeteerDisable: Disable puppeteer for the current buffer.
  • PuppeteerEnable: Enable puppeteer for the current buffer.

Special Case: Formatted Strings in Lua

Through string.format, there are also formatted strings in Lua. However, auto-conversions are far more difficult in lua %s is used as a placeholder for string.format and as class in lua patterns at the same time. While it is possible to identify in some cases whether a lua string is used as pattern, there are certain cases where that is not possible:

-- desired: conversion to format string when typing the placeholder "%s"
local str = "foobar %s baz" -- before
local str = ("foobar %s baz"):format() -- after

-- problem case that can be dealt with: "%s" used as class in lua pattern
local found = str:find("foobar %s")

-- problem case that cannot be dealt with: "%s" in string, which
-- is only later used as pattern
local pattern = "foobar %s baz"
-- some code…
str:find(pattern)

Since the auto-conversion of lua strings can result in undesired false conversions, the feature is opt-in only. This way, you can decide for yourself whether the occasional false positive is worth it for you or not.

-- Enable auto-conversion of lua strings by removing lua from the disabled
-- filetypes (default: {"lua"}).
vim.g.puppeteer_disable_filetypes = {}

Tip

You can also use PuppeteerToggle to temporarily disable the plugin for the current buffer, if a specific lua string is giving you trouble.

Credits

About Me
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.

Blog
I also occasionally blog about vim: Nano Tips for Vim

Profiles

Buy Me a Coffee at ko-fi.com

nvim-puppeteer's People

Contributors

chrisgrieser avatar guivazcabral avatar quitlox avatar skoch13 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

nvim-puppeteer's Issues

Feature Request: mini.surround support

Feature Requested

Great plugin!

I'd love to replace my usage of https://github.com/roobert/f-string-toggle.nvim

I have run up against one issue: when using mini.surround for deleting the brackets within a python f-string, (e.g: gzd{) the string state doesn't update.

I've tried to debug this by using set verbose=9 to capture the potential autocmd that could be used as a hook, however, it's too verbose and I believe some kind of custom function may need making that involves filtering the output, etc.

Opening this in case you know off-hand the correct autocmd to hook off to fix support, before I try and investigate further.

Thanks again for the plugin!

Relevant Screenshot

No response

Checklist

  • The feature would be useful to more users than just me.

Feature Request: Add an option to set the quote style to use

Feature Requested

Given this JS code:

const test = `test ${myVar}`;
//                ^ cursor is here

With cursor on the space character in the template string, I press dt` and get:

const test = "test";

I prefer to get:

const test = 'test';

Could you please add a configuration option to set the quote style to use ?

Relevant Screenshot

No response

Checklist

  • The feature would be useful to more users than just me.

[Bug]: does nothing?

Bug Description

Can't get the plugin to work, like, at all. Even tried explicitly enabling it by calling :PuppeteerEnable. Tried in both JS and Python, new strings, existing strings, nothing works.

Relevant Screenshot

No response

To Reproduce

  1. Install the plugin using lazy.nvim:
    {
      'chrisgrieser/nvim-puppeteer',
      lazy = false,
    },
    
  2. Expect it to work.

neovim version

NVIM v0.9.4
Build type: RelWithDebInfo
LuaJIT 2.1.1692716794
Compilation: /usr/bin/cc -O2 -g -Og -g -Wall -Wextra -pedantic -Wno-unused-parameter -Wstrict-prototypes -std=gnu99 -Wshadow -Wconversion -Wvla -Wdouble-promotion -Wmissing-noreturn -Wmissing-format-attribute -Wmissing-prototypes -fno-common -Wno-unused-result -Wimplicit-fallthrough -fdiagnostics-color=always -fstack-protector-strong -DUNIT_TESTING -DINCLUDE_GENERATED_DECLARATIONS -D_GNU_SOURCE -I/home/kwyntes/bouw/neovim/.deps/usr/include/luajit-2.1 -I/usr/include -I/home/kwyntes/bouw/neovim/.deps/usr/include -I/home/kwyntes/bouw/neovim/build/src/nvim/auto -I/home/kwyntes/bouw/neovim/build/include -I/home/kwyntes/bouw/neovim/build/cmake.config -I/home/kwyntes/bouw/neovim/src -I/usr/include -I/home/kwyntes/bouw/neovim/.deps/usr/include -I/home/kwyntes/bouw/neovim/.deps/usr/include -I/home/kwyntes/bouw/neovim/.deps/usr/include -I/home/kwyntes/bouw/neovim/.deps/usr/include -I/home/kwyntes/bouw/neovim/.deps/usr/include -I/home/kwyntes/bouw/neovim/.deps/usr/include

   system vimrc file: "$VIM/sysinit.vim"
  fall-back for $VIM: "/usr/local/share/nvim"

Make sure you have done the following

  • I have updated to the latest version of the plugin.

[Bug]: Handling of dunder variables is broken

Bug Description

nvim-puppeteer breaks on f-strings containing dunder variables.

Relevant Screenshot

No response

To Reproduce

Example 1:

  • Type text = "hello from {__file__}"
  • Puppeteer does not add the f
  • Add the f manually
  • Puppeteer removes the f
  • Workaround to fix is adding a space between f "" and removing the space

Example 2:

  • Type a correct text = f"hello from {__file__}"
  • Try to change message to f"hi from {__file__}"
  • Puppeteer removes the f
  • I didn't find a workaround

neovim version

0.9.1

Make sure you have done the following

  • I have updated to the latest version of the plugin.

Feature Request: support SvelteJS and/or add a filetype option

Feature Requested

Thank you very much for this plugin.

Could you please support the svelte filetype with templateStr ?

It would also be very useful to have an configuration option to define which filetypes are enabled.

Relevant Screenshot

No response

Checklist

  • The feature would be useful to more users than just me.

[Bug]: Puppeteer recognizes path parameters in FastAPI routes as f-strigns

Bug Description

When creating FastAPI routes you often write strings that look a lot like f-strings but should not be turned into f-strings automatically. See here for an example: https://fastapi.tiangolo.com/tutorial/path-params/

puppeteer turns these strings into f-strings and requires workarounds to remove the f-string

Relevant Screenshot

No response

To Reproduce

No response

neovim version

latest

Make sure you have done the following

  • I have updated to the latest version of the plugin.

[Bug]: replaceNodeText sometimes called with wrong end_row

Bug Description

I have had this issue for a while now, that when I rename a variable in a large python files via python-lsp-server I get the following error.
I could not yet reproduce this error for smaller python files.

Renamed 1 instance in 1 file
Error detected while processing TextChanged Autocommands for "<buffer=2>":
Error executing lua callback: ...-puppeteer-unstable-2023-11-13_1a941a8/lua/puppeteer.lua:10: Invalid 'end_row': out of range
stack traceback:
        [C]: in function 'nvim_buf_set_text'
        ...-puppeteer-unstable-2023-11-13_1a941a8/lua/puppeteer.lua:10: in function 'replaceNodeText'
        ...-puppeteer-unstable-2023-11-13_1a941a8/lua/puppeteer.lua:93: in function <...-puppeteer-unstable-2023-11-13_1a941a8/lua/puppeteer.lua:70>

I have also updated my treesitter grammars, but the error persists.
In my current config I am using inc-rename.nvim to rename the variable, but I just tried the native vim.lsp.buf.rename() as well, which also throws the same error.

Relevant Screenshot

No response

To Reproduce

Will try to add a minimal config and file which triggers this issue.

neovim version

NVIM v0.10.0-dev-9dc4404
Build type: Release
LuaJIT 2.1.1693350652

and

NVIM v0.10.0-dev-7ca2d64
Build type: Release
LuaJIT 2.1.1693350652

Make sure you have done the following

  • I have updated to the latest version of the plugin.

Feature Request: TSX/JSX file type support

Feature Requested

The same functionality but for tsx and jsx file types, it works great in .ts but can't replicate in .tsx, happy to contribute if you can point me in the right direction!

P.S. fantastic work!

Relevant Screenshot

No response

Checklist

  • The feature would be useful to more users than just me.

[Bug]: using undo breaks puppeteer

Bug Description

Let's say we have this code: print(f"These are the numbers: {' '.join([str(i) for i in [1, 2, 3]])}")

We want to change the ' '.join to ', '.join. But we accidentally type ci". Now we want to undo, hitting ESC, which causes puppeteer to remove the f but without actually making a change that nvim knows about. Then we hit u. Nvim reverts the undo, but the f is still missing from the string. We then try to fix it by prepending it, but puppeteer will remove it again. The only fix is to prepend f "" and then removing the space.

Neovim should know about the changes that puppeteer makes in order for this to work.

Relevant Screenshot

No response

To Reproduce

No response

neovim version

0.9.1

Make sure you have done the following

  • I have updated to the latest version of the plugin.

[Bug]: Doesn't respect multiline strings on js/ts

Bug Description

The plugin changes backticks to regular quotes on a multiline string when no interpolation is detected, which is a syntax error.

Relevant Screenshot

No response

To Reproduce

  • Create a multiline string with backticks:
const multiline = `This is
a multiline string`
  • Exit insert mode. It turns into
const multiline = "This is
a multiline string"

neovim version

NVIM v0.9.1

Make sure you have done the following

  • I have updated to the latest version of the plugin.

[Bug]: Puppeteer gets in the way when using GraphQL or other tools that require curly braced strings

Bug Description

When using GraphQL in Python you often deal with multiline strings like this:

"""
{
  project(name: "GraphQL") {
    tagline
  }
}
"""

Whenever you change anything on these strings puppeteer will turn them (falsely) into f-strings and won't let you turn them into normal strings again.

A couple of Ideas how to fix/work-around this:

  1. Don't touch multiline strings (breaks legitimate multiline strings)
  2. Try to figure out (using Tree-Sitter, LSP, Linters or something like this) if the resulting f-string actually makes sense or would be bogus. Don't f-stringify if it would result in an error
  3. Detect when the user removed the f so you don't have to fight with puppeteer to get your will

Relevant Screenshot

No response

To Reproduce

No response

neovim version

0.9

Make sure you have done the following

  • I have updated to the latest version of the plugin.

[Bug]: Initial quotes aren't preserved for JS files

Bug Description

Hi,

Thank you for an amazing plugin! The only issue I faced recently is that undoing or removing ${foo} from a string changes backticks to double quotes, despite originally being single quotes. Please see the attached video.

Relevant Screenshot

Screenshot2023-09-19.at.22.42.02.mp4

To Reproduce

I believe this is the line to blame

text = '"' .. text:sub(2, -2) .. '"'

neovim version

0.9.2

Make sure you have done the following

  • I have updated to the latest version of the plugin.

[Bug]: Converting python raw-string to f-string

Bug Description

The plugin will convert a python raw-string to a f-string.

local isFString = text:find("^f")
local hasBraces = text:find("{.-}")

I change it to

	local isFString = text:find("^[(f)(rf)]")
	local hasBraces = text:find("[^(\\x)]{.-[^%d,]+.-}")

not sure if this will fix all situations.

Relevant Screenshot

No response

To Reproduce

"\d{3}" -> f"\d{3}"

neovim version

NVIM v0.10.0-dev-8405649
Build type: RelWithDebInfo
LuaJIT 2.1.1697887905

Make sure you have done the following

  • I have updated to the latest version of the plugin.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.