Showing preview only (205K chars total). Download the full file or copy to clipboard to get everything.
Repository: milanglacier/yarepl.nvim
Branch: main
Commit: ca3406284311
Files: 21
Total size: 196.6 KB
Directory structure:
gitextract_jym55huq/
├── .editorconfig
├── .github/
│ └── workflows/
│ └── luarocks-release.yaml
├── .gitignore
├── .stylua.toml
├── AGENTS.md
├── CHANGELOG.md
├── LICENSE
├── README.md
├── extensions/
│ └── README.md
├── lua/
│ ├── telescope/
│ │ └── _extensions/
│ │ ├── REPLShow.lua
│ │ └── yarepl_show.lua
│ └── yarepl/
│ ├── extensions/
│ │ ├── aider.lua
│ │ ├── code_cell.lua
│ │ ├── codex.lua
│ │ ├── fzf.lua
│ │ ├── opencode.lua
│ │ ├── snacks.lua
│ │ └── utility.lua
│ └── init.lua
├── neovim.toml
└── selene.toml
================================================
FILE CONTENTS
================================================
================================================
FILE: .editorconfig
================================================
root = true
[*]
end_of_line = LF
insert_final_newline = true
trim_trailing_whitespace = true
[*.lua]
indent_style = space
indent_size = 4
================================================
FILE: .github/workflows/luarocks-release.yaml
================================================
name: LuaRocks release
on:
push:
tags: # Will upload to luarocks.org when a tag is pushed
- "*"
pull_request: # Will test a local install without uploading to luarocks.org
jobs:
luarocks-release:
runs-on: ubuntu-latest
name: LuaRocks upload
steps:
- name: Checkout
uses: actions/checkout@v3
- name: LuaRocks Upload
uses: nvim-neorocks/luarocks-tag-release@v7
env:
LUAROCKS_API_KEY: ${{ secrets.LUAROCKS_API_KEY }}
with:
labels: |
neovim
yarepl.nvim
================================================
FILE: .gitignore
================================================
.tags
.luarc.json
scratch.lua
.aider*
.env
.codex
.nvim_log
================================================
FILE: .stylua.toml
================================================
column_width = 120
line_endings = "Unix"
indent_type = "Spaces"
indent_width = 4
quote_style = "AutoPreferSingle"
no_call_parentheses = true
================================================
FILE: AGENTS.md
================================================
# Repository Guidelines
## Project Structure & Module Organization
- `lua/yarepl/` contains core plugin logic, REPL management, and built-in commands.
- `lua/yarepl/extensions/` hosts optional integrations (aider, codex, code-cell, fzf, snacks).
- `lua/telescope/_extensions/` provides the telescope REPL picker integration.
- `extensions/README.md` documents extension usage and keymaps.
- `assets/` stores screenshots used in the README.
## Build, Test, and Development Commands
There is no build step; this is a Lua-based Neovim plugin.
- Manual validation: open Neovim and `:Lazy load yarepl.nvim` or `:source` your config to test behavior.
## Coding Style & Naming Conventions
- Indentation: 4 spaces in Lua files (no tabs).
- Lua modules are named by path (e.g., `require('yarepl.extensions.aider')`).
- Prefer descriptive module/file names over abbreviations.
- Keep new user-facing commands consistent with existing `REPL*` naming.
## Testing Guidelines
- No automated test suite is currently present.
- If you add tests, document the framework and commands in this file and the README.
## Commit & Pull Request Guidelines
- Commit messages follow a Conventional Commits style, e.g., `feat: add option`, `fix: update logic`, `doc: update codex doc.`
- PRs should include:
- A clear summary of behavior changes.
- Any relevant Neovim version requirements.
- Screenshots/GIFs for UI/UX changes (especially for picker or window behavior).
## Agent-Specific Instructions
- Follow `AGENTS.md` in the repo root for contributor guidance.
================================================
FILE: CHANGELOG.md
================================================
# Version 0.14.0 (2026-04-05)
## Breaking Changes
- **Lowercase `<Plug>` Keymaps**: Renamed `<Plug>(Yarepl-*)` mappings to
`<Plug>(yarepl-*)` to follow the more common Vim plugin convention of using
lowercase `<Plug>` names. This also applies to extension mappings such as
`<Plug>(yarepl-opencode-*)`.
## Features
- **OpenCode Extension**: a lightweight minimal extension for `opencode`.
# Version 0.13.0 (2026-03-30)
## Breaking Changes
- **Unified Commands**: Replaced `REPL*`, `Codex*`, and `Aider*` commands with
a unified `Yarepl` command interface. Legacy commands remain functional but
show deprecation warnings.
- **Unified Keymaps**: Replaced `<Plug>(REPL*)` keymaps with `<Plug>(yarepl-*)`
keymaps.
## Features
- **Telescope Extension**: Changed default action to `REPLFocus` for better
workflow.
## Bug Fixes
- **Send Operator**: Fixed handling of missing, empty, or inverted ranges for
the `send_operator` command.
# Version 0.12.0 (2026-01-23)
## Features
- **REPLStartOrHideOrFocus**: Added a new command `REPLStartOrHideOrFocus` to
Toggles the visibility (focus/hide) of an existing REPL, or creates a new one
if it does not exist.
- **Highlight Range**: Added an option to highlight the region sent to the REPL.
- **Character-wise Sending**: Added support for sending character-wise regions to the REPL.
- **Source Command Hint**: Added `show_source_command_hint` option to display
the first line of the source command as virtual text.
- **Formatter**: Added `bracketed_pasting_delayed_cr` formatter for better
compatibility with REPLs like Claude Code and OpenAI Codex.
- **Extensions (Codex/Aider)**:
- Added a new extension for OpenAI's Codex.
- Display the REPL name and ID in the winbar for the default `wincmd` in
Aider and Codex.
- Default floating window position changed to bottom-right corner.
## Breaking Change
- **REPLStart**: The semantics have changed. When a name is provided (e.g.,
`2REPLStart ipython`), the count now refers to the Nth _matching_ REPL, rather
than the global REPL ID. When the count is not provided, it now forces the
creation of a new REPL instance instead of focusing an existing REPL with ID
`1`.
- **Config**: Removed `source_func` option. Use `source_syntax` instead, which
now accepts both string syntax values and functions.
- **OS/Windows**: Renamed `os.windows.send_delayed_cr_after_sending` to
`os.windows.send_delayed_final_cr` to align with REPL meta options.
- **Extensions**: Codex and Aider floating windows now default to the
bottom-right corner instead of occupying most of the screen.
## Bug Fixes
- **IPython Source**: Fixed temporary file handling in IPython source function
to allow proper PDB debugging context.
# Version 0.11 (2025-04-08)
## Features
- Added command `REPLSourceOperator` and `REPLSourceVisual`
See [comparison in
README](https://github.com/milanglacier/yarepl.nvim?tab=readme-ov-file#replsourcevisual)
for a detailed comparison between `REPLSendVisual` and `REPLSourceVisual`.
# Version 0.10.1 (2025-02-14)
- Add luarocks release
# Version 0.10 (2025-02-08)
- Initial release
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
================================================
FILE: README.md
================================================
- [yarepl.nvim](#yareplnvim)
- [Showcase](#showcase)
- [Why yarepl.nvim?](#why-yareplnvim)
- [Installation](#installation)
- [Configuration](#configuration)
- [Setup](#setup)
- [Commands](#commands)
- [Yarepl start](#yarepl-start)
- [Yarepl start_or_focus_or_hide](#yarepl-start_or_focus_or_hide)
- [Yarepl attach_buffer](#yarepl-attach_buffer)
- [Yarepl detach_buffer](#yarepl-detach_buffer)
- [Yarepl cleanup](#yarepl-cleanup)
- [Yarepl focus](#yarepl-focus)
- [Yarepl hide](#yarepl-hide)
- [Yarepl hide_or_focus](#yarepl-hide_or_focus)
- [Yarepl close](#yarepl-close)
- [Yarepl swap](#yarepl-swap)
- [Yarepl send_visual](#yarepl-send_visual)
- [Yarepl source_visual](#yarepl-source_visual)
- [Yarepl send_line](#yarepl-send_line)
- [Yarepl send_operator](#yarepl-send_operator)
- [Yarepl source_operator](#yarepl-source_operator)
- [Yarepl exec](#yarepl-exec)
- [Keymaps](#keymaps)
- [Window configuration](#window-configuration)
- [Customizing REPLs](#customizing-repls)
- [Delayed Final CR Option](#delayed-final-cr-option)
- [Customizing the Source Syntax](#customizing-the-source-syntax)
- [Example keybinding setup](#example-keybinding-setup)
- [Extensions](#extensions)
- [aider](#aider)
- [codex](#codex)
- [opencode](#opencode)
- [code-cell](#code-cell)
- [fzf-lua](#fzf-lua)
- [telescope](#telescope)
- [Snacks.picker](#snackspicker)
- [Set up project-level REPLs](#set-up-project-level-repls)
- [Create persistent REPLs in tmux](#create-persistent-repls-in-tmux)
- [FAQ](#faq)
- [Why lazy loading with `lazy.nvim` doesn't work?](#why-lazy-loading-with-lazynvim-doesnt-work)
- [How do I avoid clutter from the bufferline plugin?](#how-do-i-avoid-clutter-from-the-bufferline-plugin)
- [Yarepl send_visual is not functioning properly](#yarepl-send_visual-is-not-functioning-properly)
- [`<Plug>(yarepl-send-visual)` Only Sends to First REPL](#plugyarepl-send-visual-only-sends-to-first-repl)
- [Limitations](#limitations)
- [Acknowledgements](#acknowledgements)
**Breaking change:** `<Plug>` mappings now use lowercase `yarepl` names. If you
previously mapped `<Plug>(Yarepl-start)` or `<Plug>(Yarepl-codex-exec)`, update
them to `<Plug>(yarepl-start)` and `<Plug>(yarepl-codex-exec)`. This change
aligns with the common convention of using lowercase `<Plug>` names across Vim
plugins. This change also takes effect immediately.
The old `REPL*` commands and `<Plug>(REPL*)` maps are now named under
`Yarepl`. Use commands like `:Yarepl start`, `:Yarepl attach_buffer`,
`:Yarepl send_visual`, and `:Yarepl exec`. The matching plug maps are named
like `<Plug>(yarepl-start)` and `<Plug>(yarepl-send-visual)`. The command part
uses snake style, while `<Plug>` names use kebab style.
The legacy commands and keymaps (`REPL*`) still function for now, but they will
be removed on `2026-06-01`.
If you previously used `REPLStart`, `REPLSendVisual`, or
`<Plug>(REPLStart-ipython)`, the replacement is the same idea with a different
wrapper: `:Yarepl start`, `:Yarepl send_visual`, and
`<Plug>(yarepl-start-ipython)`.
The unified `Yarepl` entry point keeps the plugin easier to extend and makes
completion, counts, and future subcommands behave consistently instead of
spreading the same actions across a growing list of top-level commands.
# yarepl.nvim
Yet Another REPL is a flexible REPL / CLI App management tool that supports
multiple paradigms for interacting with them. This plugin also works with
project-level config and tmux, and includes native dot-repeat without requiring
vim-repeat.
Flexibility and parallelism are core priorities. With yarepl.nvim, you can
effortlessly interact with multiple CLI Apps through various paradigms:
- Send text from multiple buffers (same or different file types) to a single
REPL / CLI App.
- Send text from a single buffer to multiple CLI Apps (same program or different)
- Attach a buffer to a dedicated CLI Apps
The plugin features integration with `aider.chat`, `OpenAI Codex CLI`, and
`OpenCode`, and provides convenient code cell text object definitions. Choose
your preferred
fuzzy finder among `telescope`, `fzf-lua`, or `Snacks.picker` to preview active
REPLs. These features are available as [extensions](#extensions).
# Showcase

This image highlights an AI-driven coding assistant and REPL,
[aider.chat](https://aider.chat), managed by `yarepl`.

This example showcases the Codex CLI integration running side by side with a
Neovim buffer, all managed through `yarepl`.
`yarepl` enables integration with the OpenAI's Codex CLI and Aider.chat. For
more details, refer to the [Extensions](#extensions) section.
# Why yarepl.nvim?
With multiple projects at hand, I require the ability to send text from
different files to REPLs with the same type (such as multiple ipython REPLs).
In instances where I'm performing time-consuming tasks, but need to conduct
further experimentation on the current file, I also require the capability to
send text from the same buffer to multiple REPLs.
Furthermore, when conducting mixed-language programming in a literate
programming style in text format such as `rmarkdown`, `quarto`, or plain
`markdown`, I need to send text in the buffer to different REPLs such as R and
Python .
Additionally, `yarepl.nvim` features a `source_syntax` capability that allows
sourcing large code chunks from temporary files instead of sending them
directly to the REPL. This prevents cluttering your interaction history and
provides better handling of substantial code content, especially useful on
Windows where large stdin processing can be problematic. The plugin writes
selected code regions/content to temporary files and provides convenient syntax
definitions for how each REPL should source files.
As a CLI fnatic, to communicate with chatgpt, I prefer through a REPL `aichat`.
Additionally, I require a set of global hotkeys and an isolated REPL
environment to facilitate communication with `aichat` separately without any
interference with other REPLs.
Unfortunately, currently available REPL plugins do not afford me such great
flexibility in managing REPL in multiple ways. This is why `yarepl.nvim` was
created.
# Installation
`nvim 0.9` is required. Although `nvim 0.8` may also work, there are no plans
to ensure backward compatibility with `nvim 0.8` if there are any compatibility
issues.
**lazy.nvim**:
```lua
{ 'milanglacier/yarepl.nvim', config = true }
```
**rocks.nvim**:
`Yarepl` is available on luarocks.org. Simply run `Rocks install yarepl.nvim`
to install it like any other luarocks package.
`yarepl.nvim` does not require any dependencies but functions better with the following plugins:
1. `telescope.nvim` or `fzf-lua`. `yarepl.nvim` provides extensions for REPL
previewer.
2. A UI frontend that provides an alternative frontend for `vim.ui.select`.
Some options are `dressing.nvim` or `telescope-ui-select.nvim` (only one of
them needs to be installed).
# Configuration
## Setup
```lua
-- below is the default configuration, there's no need to copy paste them if
-- you are satisfied with the default configuration, just calling
-- `require('yarepl').setup {}` is sufficient.
local yarepl = require 'yarepl'
yarepl.setup {
-- see `:h buflisted`, whether the REPL buffer should be buflisted.
buflisted = true,
-- whether the REPL buffer should be a scratch buffer.
scratch = true,
-- the filetype of the REPL buffer created by `yarepl`
ft = 'REPL',
-- How yarepl open the REPL window, can be a string or a lua function.
-- See below example for how to configure this option
wincmd = 'belowright 15 split',
-- The available REPL palattes that `yarepl` can create REPL based on.
-- To disable a built-in meta, set its key to `false`, e.g., `metas = { R = false }`
metas = {
aichat = { cmd = 'aichat', formatter = 'bracketed_pasting', source_syntax = 'aichat' },
radian = { cmd = 'radian', formatter = 'bracketed_pasting_no_final_new_line', source_syntax = 'R' },
-- builtin command names search a .venv/bin/ipython first, then fall back to PATH
ipython = { cmd = 'builtin:ipython', formatter = 'bracketed_pasting', source_syntax = 'ipython' },
python = { cmd = 'builtin:python', formatter = 'trim_empty_lines', source_syntax = 'python' },
R = { cmd = 'R', formatter = 'trim_empty_lines', source_syntax = 'R' },
bash = {
cmd = 'bash',
formatter = vim.fn.has 'linux' == 1 and 'bracketed_pasting' or 'trim_empty_lines',
source_syntax = 'bash',
},
zsh = { cmd = 'zsh', formatter = 'bracketed_pasting', source_syntax = 'bash' },
},
-- when a REPL process exits, should the window associated with those REPLs closed?
close_on_exit = true,
-- whether automatically scroll to the bottom of the REPL window after sending
-- text? This feature would be helpful if you want to ensure that your view
-- stays updated with the latest REPL output.
scroll_to_bottom_after_sending = true,
-- Format REPL buffer names as #repl_name#n (e.g., #ipython#1) instead of using terminal defaults
format_repl_buffers_names = true,
-- Highlight the operated range when using send/source operators
highlight_on_send_operator = { enabled = false, hl_group = 'IncSearch', timeout = 150 },
os = {
-- Some hacks for Windows. macOS and Linux users can simply ignore
-- them. The default options are recommended for Windows user.
windows = {
-- Send a final `\r` to the REPL with delay,
send_delayed_final_cr = true,
},
},
-- Display the first line as virtual text to indicate the actual
-- command sent to the REPL.
source_command_hint = {
enabled = false,
hl_group = 'Comment',
},
}
```
## Commands
`yarepl` doesn't set any default keybindings. Instead, it offers a variety of
commands that you can use to create your own keybindings. We'll also provide an
example configuration for keybindings based on these commands. Additionally,
`yarepl` provides a collection of `<Plug>` keymaps, which you can bind them to
your favorite mappings.
Here is a list of available commands:
### Yarepl start
Creates a REPL with id `i` from the list of available REPLs.
You can create a REPL with a specific id by providing a count, such as
`3Yarepl start` for a REPL with id `3`. If no count is provided, a new REPL
with increamental ID will be created. You can also provide a name as an
argument. If no argument is given, you'll be prompted to select a REPL from the
list of available ones. If the id is already in use, it will focus on the REPL
with that id.
When a name is provided and a count is also provided (for example, `2Yarepl
start ipython`), the count selects the Nth REPL with that name. If there are
fewer than N existing REPLs with that name, a new one is created. When a name
is provided without a count (`Yarepl start ipython`), it always creates a new
REPL of that name.
If you append a `!` to the command, the current buffer will attach to the newly
created REPL, for instance, `Yarepl start!` or `3Yarepl start!`. Note that
attachment only happens when a new REPL is created.
### Yarepl start_or_focus_or_hide
Toggles the visibility (focus/hide) of an existing REPL, or creates a new one
if it does not exist.
The rules for counts and optional REPL names mirror those of `Yarepl start`,
including named selection logic like `2Yarepl start_or_focus_or_hide ipython`.
Here are examples of how to use this command:
1. `Yarepl start_or_focus_or_hide` will hide or focus REPL 1 when it exists,
otherwise it creates a new REPL.
2. `Yarepl start_or_focus_or_hide ipython` will hide or focus the first
`ipython` REPL, otherwise it creates a new `ipython` REPL.
3. `3Yarepl start_or_focus_or_hide` will hide or focus REPL 3 when it exists,
otherwise it creates a new REPL.
4. `3Yarepl start_or_focus_or_hide ipython` will hide or focus the 3rd
`ipython` REPL, otherwise it creates a new `ipython` REPL.
**Important difference**: without a count, `Yarepl start` always attempts to
start a new REPL, whereas `Yarepl start_or_focus_or_hide` first attempts to
focus/hide an existing REPL and creates a new one only if none is found.
### Yarepl attach_buffer
Attaches the current buffer to REPL `i`, for instance, `3Yarepl attach_buffer`
will attach the current buffer to REPL 3. If no count is provided, you'll be
prompted to select the REPL you want to attach the current buffer to. If you
add a trailing `!`, it will attempt to detach the current buffer from any REPL.
### Yarepl detach_buffer
Detach current buffer from any REPL.
### Yarepl cleanup
Cleans up any invalid REPLs and rearranges the sequence of REPL ids. Usually,
there's no need to use this command manually since invalid REPLs are cleaned up
automatically at the appropriate time.
### Yarepl focus
Focuses on REPL `i` or the REPL that the current buffer is attached to.
You can provide an optional argument, and the function will attempt to focus on
the closest REPL with the specified name. If no count is supplied, it will try
to focus on the REPL that the current buffer is attached to. If the current
buffer isn't attached to any REPL, it will use REPL 1. If you add a count `i`,
it will focus on the REPL `i`.
Here are some examples of how to use this command:
1. `Yarepl focus` will try to focus on the REPL that the current buffer is
attached to. If the current buffer isn't attached to any REPL, it will use
REPL 1.
2. `Yarepl focus ipython` will try to focus on the closest REPL with the name
`ipython` starting from id `1`.
3. `3Yarepl focus` will focus on REPL 3.
4. `3Yarepl focus ipython` will try to focus on the closest REPL with the name
`ipython` starting from id `3`.
### Yarepl hide
Hides REPL `i` or the REPL that the current buffer is attached to.
If you provide an optional argument, the function will attempt to hide the
closest REPL with the specified name. When no count is supplied, it will try to
hide the REPL that the current buffer is attached to. If the current buffer
isn't attached to any REPL, it will use REPL 1. If you add a count `i`, it
will hide REPL `i`.
Here are examples of how to use this command:
1. `Yarepl hide` will try to hide the REPL that the current buffer is attached
to. If the current buffer isn't attached to any REPL, it will use REPL 1.
2. `Yarepl hide ipython` will try to hide the closest REPL with the name
`ipython` starting from id `1`.
3. `3Yarepl hide` will hide REPL 3.
4. `3Yarepl hide ipython` will try to hide the closest REPL with the name
`ipython` starting from id `3`.
### Yarepl hide_or_focus
Hides or focuses on REPL `i` or the REPL that the current buffer is attached
to.
If you provide an optional argument, the function will attempt to hide or
focus on the closest REPL with the specified name. When no count is supplied,
it will try to hide or focus on the REPL that the current buffer is attached to.
If the current buffer isn't attached to any REPL, it will use REPL 1. If you
add a count `i`, it will hide REPL `i`.
Here are examples of how to use this command:
1. `Yarepl hide_or_focus` will try to hide or focus on the REPL that the
current buffer is attached to. If the current buffer isn't attached to any
REPL, it will use REPL 1.
2. `Yarepl hide_or_focus ipython` will try to hide or focus on the closest
REPL with the name `ipython` starting from id `1`.
3. `3Yarepl hide_or_focus` will hide or focus on REPL 3.
4. `3Yarepl hide_or_focus ipython` will try to hide or focus on the closest
REPL with the name `ipython` starting from id `3`.
### Yarepl close
Closes REPL `i` or the REPL that the current buffer is attached to.
If you provide an optional argument, the function will attempt to close the
closest REPL with the specified name. If no count is supplied, it will try to
close the REPL that the current buffer is attached to. If the current buffer
isn't attached to any REPL, it will use REPL 1. If you add a count `i`, it
will close REPL `i`.
Here are examples of how to use this command:
1. `Yarepl close` will try to close the REPL that the current buffer is
attached to. If the current buffer isn't attached to any REPL, it will use
REPL 1.
2. `Yarepl close ipython` will try to close the closest REPL with the name
`ipython` and starting from id `1`.
3. `3Yarepl close` will close REPL 3.
4. `3Yarepl close ipython` will try to close the closest REPL with the name
`ipython` starting from id `3`.
### Yarepl swap
Swaps two REPLs. If no REPL ID is provided, you'll be prompted to select both
REPLs. If you provide one REPL ID, you'll be prompted to select the second
REPL.
### Yarepl send_visual
Sends the visual range to REPL `i` or the REPL that the current buffer
is attached to.
If you provide an optional argument, the function will attempt to send to the
closest REPL with the specified name. When no count is supplied, it first
checks whether the current buffer is attached to a REPL with that name and uses
it. If the buffer isn't attached to a matching REPL, it will use REPL 1 to
find the closest match. If you add a count `i`, it will send to the closest
REPL with that name relative to `i`.
Optional highlighting for the operated range is available for both
`Yarepl send_operator` and `Yarepl source_operator` by setting
`highlight_on_send_operator.enabled = true` in your setup.
Here are examples of how to use this command:
1. `Yarepl send_visual` sends the visual range to the REPL that the current
buffer is attached to. If the buffer is not attached to any REPL, it uses
REPL 1.
2. `3Yarepl send_visual` sends the visual range to REPL 3.
3. `Yarepl send_visual ipython` sends the visual range to the attached ipython
REPL if there is one for the current buffer; otherwise, it uses the closest
ipython REPL relative to id `1`.
4. `3Yarepl send_visual ipython` sends the visual range to the closest ipython
REPL relative to id `3`.
Note that due to a limitation of vim, when using `Yarepl send_visual` via
cmdline rather than in a keymap, you must press `Control+u` before using the
command. For example, `V3j:<Control+u>3Yarepl send_visual` sends the selected
three lines to REPL `3`. However, you do not need to specify `Control+u` in
your keymap as the function will do this for you.
### Yarepl source_visual
Similar to `Yarepl send_visual`, the key distinction with `Yarepl source_visual`
is that it first writes the visually selected code to a temporary file. It then
sends a one-liner command to the REPL to source this file, instead of sending
the content directly.
The primary advantage of `Yarepl source_visual` lies in handling large code
content. Instead of sending huge code chunks directly to the REPL, it prevents
cluttering your interaction history, maintaining a cleaner session.
Additionally, on Windows, sourcing from a file mitigates potential issues with
stdin processing when the REPL must read substantial input, as the file-based
approach significantly reduces the data read from the stdin.
However, one notable drawback involves the security implications of temporary
file creation. Since the REPL executes code from this file, any vulnerability
in temporary file handling, such as exposure to malicious attack, could pose
security risks. Thus, while beneficial in certain scenarios, this method
requires careful consideration of its potential drawbacks.
Note that the REPL configuration requires a corresponding `source_syntax`
implementation. For more information, refer to the section [Customizing the
Source Syntax](#customizing-the-source-syntax). Built-in source
implementations are available for Python, R, and Bash.
Consider enabling `config.source_command_hint.enabled = true`. When enabled,
the first non-empty line of the code chunk displays as virtual text alongside
the source command sent to the REPL, providing a useful hint about the actual
command being executed.
### Yarepl send_line
Sends current line to REPL `i` or the REPL that current buffer is attached to.
If you provide an optional argument, the function will attempt to send to the
closest REPL with the specified name. When no count is supplied, it first
checks whether the current buffer is attached to a REPL with that name and uses
it. If the buffer isn't attached to a matching REPL, it will use REPL 1 to
find the closest match. If you add a count `i`, it will send to the closest
REPL with that name relative to `i`.
Here are examples of how to use this command:
1. `Yarepl send_line` sends the current line to the REPL that the current
buffer is attached to. If the buffer is not attached to any REPL, it uses
REPL 1.
2. `3Yarepl send_line` sends the current line to REPL 3.
3. `Yarepl send_line ipython` sends the current line to the attached ipython
REPL if there is one for the current buffer; otherwise, it uses the closest
ipython REPL relative to id `1`.
4. `3Yarepl send_line ipython` sends the current line to the closest ipython
REPL relative to id `3`.
### Yarepl send_operator
The operator to send the text to REPL `i` or the REPL that the current buffer
is attached to.
If you provide an optional argument, the function will attempt to send to the
closest REPL with the specified name. When no count is supplied, it first
checks whether the current buffer is attached to a REPL with that name and uses
it. If the buffer isn't attached to a matching REPL, it will use REPL 1 to
find the closest match. If you add a count `i`, it will send to the closest
REPL with that name relative to `i`.
Here are examples of how to use this command:
1. `Yarepl send_operator` acts as the operator to send the text to the REPL
that the current buffer is attached to. If the buffer is not attached to any
REPL, it uses REPL 1.
2. `3Yarepl send_operator` sends the motion to REPL 3.
3. `Yarepl send_operator ipython` sends the motion to the attached ipython REPL
if there is one for the current buffer; otherwise, it uses the closest
ipython REPL relative to id `1`.
4. `3Yarepl send_operator ipython` sends the motion to the closest ipython
REPL relative to id `3`.
`Yarepl send_operator` is **dot-repeatable**, you do not need to install
vim-repeat to make it work.
### Yarepl source_operator
The `Yarepl source_operator` is analogous to the `Yarepl send_operator`. To
understand the distinction between these two operators, refer to the section on
`Yarepl source_visual`, which contrasts `Yarepl send_visual` with
`Yarepl source_visual`. This comparison provides a clear analogy that
highlights the differences between `Yarepl send_operator` and
`Yarepl source_operator`.
### Yarepl exec
Sends the command typed in the cmdline to REPL `i` or the REPL that the current
buffer is attached to.
If the first argument of this command is `$NAME`, the function will attempt to
send to a REPL with the specified `NAME`. If no count is supplied, it first
checks whether the current buffer is attached to a REPL with that name and uses
it. If the buffer isn't attached to a matching REPL, it will use REPL 1 to
find the closest match. If you add a count `i`, it will send to the closest
REPL with that name relative to `i`.
Here are examples of how to use this command:
1. `Yarepl exec %run a_file.py` will send the command `%run a_file.py` to the
REPL 1.
2. `3Yarepl exec print("hello world")` will send the command `print("hello
world")` to the REPL 3.
3. `Yarepl exec $ipython %whos` will send the command `%whos` to the closest
ipython REPL relative to id 1.
4. `Yarepl exec $ipython %whos` will send the command `%whos` to the closest
ipython REPL relative to id 3.
5. `Yarepl exec print("hello world")^Mprint("hello world again")` will send the
following two lines to the REPL current buffer is attached to or REPL 1.
```python
print("hello world")
print("hello world again")
```
Note:
1. To type a **literal** `<Enter>` (`^M`) in `cmdline`, you must press
`<Ctrl-v> <Enter>` rather than directly type `Enter`.
2. Some neovim command will interpolate `%` to the file name of current buffer.
But `Yarepl exec` will not do this for you. The interpolation only happens for
the first `$` to get the desired `REPL` name.
## Keymaps
`yarepl` provides the following keymaps:
- `<Plug>(yarepl-start)`
- `<Plug>(yarepl-start-or-focus-or-hide)`
- `<Plug>(yarepl-focus)`
- `<Plug>(yarepl-hide)`
- `<Plug>(yarepl-hide-or-focus)`
- `<Plug>(yarepl-send-line)`
- `<Plug>(yarepl-send-operator)`
- `<Plug>(yarepl-send-visual)`
- `<Plug>(yarepl-source-operator)`
- `<Plug>(yarepl-source-visual)`
- `<Plug>(yarepl-close)`
- `<Plug>(yarepl-exec)`
The keymap variant behaves exactly the same as its command variant. For
example, you map `<Leader>s` to `<Plug>(yarepl-start)`, then type `<Leader>s`
is equivalent to `:Yarepl start`. Type `3<Leader>s` is equivalent to
`:3Yarepl start`.
And for each meta you registered (say you have a meta named `ipython`), the following keymaps will be registered:
- `<Plug>(yarepl-start-ipython)`
- `<Plug>(yarepl-start-or-focus-or-hide-ipython)`
- `<Plug>(yarepl-focus-ipython)`
- `<Plug>(yarepl-hide-ipython)`
- `<Plug>(yarepl-hide-or-focus-ipython)`
- `<Plug>(yarepl-send-line-ipython)`
- `<Plug>(yarepl-send-operator-ipython)`
- `<Plug>(yarepl-send-visual-ipython)`
- `<Plug>(yarepl-source-operator-ipython)`
- `<Plug>(yarepl-source-visual-ipython)`
- `<Plug>(yarepl-close-ipython)`
- `<Plug>(yarepl-exec-ipython)`
For keymaps with a meta, as you would expected, say you bind `<LocalLeader>s`
to `<Plug>(yarepl-start-ipython)`, then type `<LocalLeader>s` is equivalent to
`:Yarepl start ipython`. Type `3<LocalLeader>s` is equivalent to
`:3Yarepl start ipython`.
Note that any letters that are not alphanumeric or `-`/`_` will be replaced
with `-`. Say you have a meta named `python a`, the corresponding keymap to
access them will be `<Plug>(yarepl-start-python-a)`.
When you are binding those plug keymaps to your own keybindings, make sure this is
a recursive map. e.g. `vim.keymap.set('n', '<Plug>(yarepl-start-ipython)', { noremap = false })`.
# Window configuration
if `wincmd` is a string, `yarepl` will execute it as a vimscript command.
```lua
wincmd = 'belowright 15 split'
-- will create a horizontal split below the current using window and takes up 15 lines for the new window
wincmd = 'vertical 30 split'
-- will create a vertical split right to the current using window and takes up 30 columns for the new window
```
In addition to passing a string to `wincmd`, you can also pass a Lua function.
This function accepts two parameters: the buffer number of the REPL buffer, and
the name of the REPL (the keys of `metas`).
```lua
wincmd = function(bufnr, name)
vim.api.nvim_open_win(bufnr, true, {
relative = 'editor',
row = math.floor(vim.o.lines * 0.25),
col = math.floor(vim.o.columns * 0.25),
width = math.floor(vim.o.columns * 0.5),
height = math.floor(vim.o.lines * 0.5),
style = 'minimal',
title = name,
border = 'rounded',
title_pos = 'center',
})
end
```
This function creates a floating window at the center of the Vim screen with
specific size and styling.
You can further customize the behavior by applying the `wincmd` configuration
to specific `meta` entries. When a `meta` includes its own `wincmd` setting, it
overrides the global `wincmd`.
```lua
float_wincmd = function(bufnr, name)
vim.api.nvim_open_win(bufnr, true, {
relative = 'editor',
row = math.floor(vim.o.lines * 0.25),
col = math.floor(vim.o.columns * 0.25),
width = math.floor(vim.o.columns * 0.5),
height = math.floor(vim.o.lines * 0.5),
style = 'minimal',
title = name,
border = 'rounded',
title_pos = 'center',
})
end
yarepl.setup {
metas = {
-- REPL local settings
ipython = { wincmd = 'topleft 25 split' },
radian = { wincmd = float_wincmd },
}
-- global settings
wincmd = 'belowright 15 split',
}
```
Similar to `wincmd` (which allows you to configure a global default with
meta-local overrides), you can also set meta-local overrides for
`source_command_hint`. The configuration option name for meta-local overrides
is identical to the global setting.
# Customizing REPLs
You can disable a built-in REPL meta by set the key to `false`:
```lua
metas = {
R = false
}
```
To modify a built-in meta's settings, simply override the specific option.
There's no need to copy the default values for other options:
```lua
metas = {
ipython = { cmd = { 'ipython', '--simple-prompt' } }
}
```
The built-in command names `builtin:ipython` and `builtin:python` look for
`.venv/bin` on Unix-like systems or `.venv/Scripts` on Windows before falling
back to the executable on `PATH`.
You can add your own REPL meta by following this example:
```lua
function send_line_verbatim(lines)
-- each line is a string
return lines
end
function ipython_or_python()
-- find_binary searches upward from the current directory until it finds the binary
-- search_root: relative path to search (e.g., ".venv/bin")
-- binary_name: executable to locate (e.g., "ipython")
-- fallback_binary: returned if no match is found (e.g., 'ipython' from PATH)
local ipython_cmd = yarepl.cmd_builtin.find_binary(".venv/bin", "ipython", 'ipython')
if vim.fn.executable(ipython_cmd) == 1 then
return { ipython_cmd, '--simple-prompt' }
end
-- Fall back to python3 using the same search logic
return yarepl.cmd_builtin.find_binary(".venv/bin", "python3", 'python3')
end
function ipython_or_python_formatter(lines)
if vim.fn.executable 'ipython' == 1 then
return yarepl.formatter.bracketed_pasting(lines)
else
return yarepl.formatter.trim_empty_lines(lines)
end
end
metas = {
ipython_new = { cmd = { 'ipython', '--simple-prompt' }, formatter = send_line_verbatim },
ipython_or_python = { cmd = ipython_or_python, formatter = ipython_or_python_formatter },
}
```
`cmd` can be three types: a string, a list of strings, or a function that
returns either a string or list of strings. It can also be one of yarepl's
builtin command names, such as `builtin:ipython` or `builtin:python`.
If you want to build your own path lookup logic, use
`require('yarepl').cmd_builtin.find_binary(search_root, binary_name, fallback_binary)`
inside a custom `cmd` function. The helper searches upward from the current
directory for `search_root/binary_name` and returns `fallback_binary` when no
matching binary is found.
`formatter` can be either:
1. A string that matches a builtin formatter name:
- `bracketed_pasting`: wrap the content within bracketed paste sequences
- `bracketed_pasting_no_final_new_line`: similar to `bracketed_pasting`, but does not add a new line at the end
- `bracketed_pasting_delayed_cr`: similar to `bracketed_pasting`, but use with `send_delayed_final_cr = true`
- `trim_empty_lines`: remove empty lines from the input
2. A function that takes a list of strings as input and returns a list of
strings to send to the REPL
[Here is a more complex example for ghci, a haskell repl.](https://github.com/milanglacier/yarepl.nvim/issues/21)
`yarepl` offers a convenient helper function that simplifies the process of
creating a custom formatter without starting from scratch. For usage examples
and general guidelines on setting your own REPL formatter, expand the
**Details** section below.
<details>
Some REPLs can distinguish between pasted text and text from the user manual
input by using prefix and suffix sequences, such as bracketed paste.
For modern REPLs with bracketed pasting support (which is usually the case), it
is recommended to use "`bracketed_pasting`"
Here are some tips for writing your own formatter function:
1. You may want to add a new entry `"\r"` at the end of the list to indicate
the end of input.
2. If your REPL cannot distinguish between copy-pasted text and text from user
manual input, you may want to replace `\t` with 4 or 8 spaces since sending
a raw `\t` may be interpreted as invoking completion.
3. Do not include `\n` in any line as the `chansend` function will
automatically replace it with `\0`.
4. You may want to remove any empty lines from the input (a list of strings)
since `chansend` function translates an empty string `""` into `"\n"`. For
some REPLs without bracketed pasting support (such as Python), a plain
`"\n"` may be treated as the end of input, blocking the rest of the code in
the same function.
5. If your REPL cannot distinguish between copy-pasted text and text from user
manual input and your REPL will do auto-indent for you, you may want to
remove any leading spaces from each line to prevent double indentation.
6. The returned list of strings will be sent to the `chansend` function for
reference.
```lua
-- Calling this function will return a function that takes a list of strings as
-- input and returns a list of strings. This can be used as the formatter function
-- of meta.
-- these are the default config
yarepl.formatter.factory {
-- Specifies whether to return tabs in the string as spaces.
replace_tab_by_space = false,
-- Specifies the number of spaces to replace the tab (if enabled).
number_of_spaces_to_replace_tab = 8,
-- For a list of strings containing more than one string:
when_multi_lines = {
-- The prefixing code sent to the repl firstly.
open_code = '',
-- The suffixing code sent to the repl finally.
end_code = '\r',
-- Whether to remove empty lines from the list of strings.
trim_empty_lines = false,
-- Whether to remove leading spaces at the beginning of each line.
remove_leading_spaces = false,
-- If gsub_pattern and gsub_repl are not empty, `string.gsub` will
-- be called with `gsub_pattern` and `gsub_repl` on each line. Note
-- that you should use Lua pattern instead of Vim regex pattern.
-- The gsub calls happen after `trim_empty_lines`,
-- `remove_leading_spaces`, and `replace_tab_by_space`, and before
-- prepending and appending `open_code` and `end_code`.
gsub_pattern = '',
gsub_repl = '',
},
-- For a list containing only one string:
when_single_line = {
-- The prefixing code sent to the repl firstly.
open_code = '',
-- The suffixing code sent to the repl finally.
end_code = '\r',
-- the same as the specs of `when_multi_lines`
gsub_pattern = '',
gsub_repl = '',
},
os = {
-- Some hacks for Windows. macOS and Linux users can simply ignore
-- them. The default options are recommended for Windows user.
windows = {
-- Join the lines with `\r` before sending to REPL.
join_lines_with_cr = true,
},
},
}
-- `yarepl` provides four builtin formatters that can be referenced by name:
-- 1. 'bracketed_pasting' - Uses bracketed paste mode for modern REPLs
-- 2. 'bracketed_pasting_no_final_new_line' - Same as above but without final newline
-- 3. 'bracketed_pasting_delayed_cr': similar to `bracketed_pasting`, but use with `send_delayed_final_cr = true`
-- 4. 'trim_empty_lines' - Trims empty lines from input
-- You can also create custom formatters by calling `yarepl.formatter.factory`:
yarepl.formatter.trim_empty_lines = yarepl.formatter.factory {
when_multi_lines = {
trim_empty_lines = true,
remove_leading_spaces = false,
},
}
yarepl.formatter.bracketed_pasting = yarepl.formatter.factory {
when_multi_lines = {
open_code = '\27[200~',
end_code = '\27[201~\r',
trim_empty_lines = false,
remove_leading_spaces = false,
},
}
```
</details>
## Delayed Final CR Option
`send_delayed_final_cr` (optional, defaults to `false`): Some REPLs do not
recognize the final CR (return)'s purpose is to tell the REPL that we want to
"finalize" (or evaluate) that command when it is input with a large chunk of
text when bracketed pasting is enabled. To mitigate this, we have to send the
final CR with a delay (to let the REPL realize that we want to evaluate that
command). In general we should ignore this option (keep it as the default
`false`). When you do enable this option, prefer using the
`bracketed_pasting_delayed_cr` formatter so that the final CR is not included
in the initial stream (it will be sent by the delayed event). The observed
exceptions are Claude Code, Codex, and Opencode which should use `true`. PRs
are welcome if you find other REPLs that require setting this option to `true`.
Example usage:
```lua
metas = {
claude_code = {
cmd = 'claude',
formatter = 'bracketed_pasting_delayed_cr',
source_syntax = '@{{file}}',
send_delayed_final_cr = true
},
ipython = {
cmd = 'ipython',
formatter = 'bracketed_pasting',
send_delayed_final_cr = false -- this is the default, can be omitted
},
-- yarepl provides builtin extension to use with codex.
codex = require('yarepl.extensions.codex').create_codex_meta(),
}
```
# Customizing the Source Syntax
To utilize `Yarepl source_operator` and `Yarepl source_visual`, your REPL meta
configuration must include either `source_syntax`.
Here's an example setup using `yarepl` with a source syntax:
```lua
local yarepl = require 'yarepl'
yarepl.setup {
metas = {
radian = {
cmd = 'radian',
formatter = 'bracketed_pasting_no_final_new_line',
source_syntax = 'eval(parse(text = "{{file}}"))',
},
}
}
```
When `source_syntax` is specified, the selected code content is initially
written to a temporary file. Here, `{{file}}` serves as a placeholder, which is
replaced by the temporary file path. The interpolated string is subsequently
sent to the REPL.
Several built-in `source_syntax` options can be accessed as strings: `R`,
`aichat`, `bash`, `ipython` and `python`.
For a more flexible "sourcing" behavior, you can also define `source_syntax` as
a function, instead of using a string with `{{file}}`. This function must take
a string and return a string. The input is the selected code, and the output is
what gets sent to the REPL.
A common approach involves writing the input string to a temporary file, then
returning a string that sources this file. The exact "sourcing" syntax depends
on the target programming language.
Here's an example setup using `yarepl` with a source function:
<details>
```lua
local yarepl = require 'yarepl'
local python_source_func = function(str)
local file = make_tmp_file(str)
if not file then
return
end
local cmd = string.format('exec(open("%s", "r").read())', file)
return cmd
end
yarepl.setup {
metas = {
ipython = {
cmd = 'ipython',
formatter = 'bracketed_pasting',
source_syntax = python_source_func,
},
}
}
```
</details>
# Example keybinding setup
If you don't want to use those `<Plug>` keymaps provided by the plugin but
instead want to build the keymaps by your own, please check the
[wiki.](https://github.com/milanglacier/yarepl.nvim/wiki/Example-Keymap-setup-without-using-%60-Plug-%60)
Here is the keybindings setup from the maintainer:
```lua
local keymap = vim.api.nvim_set_keymap
local bufmap = vim.api.nvim_buf_set_keymap
keymap('n', '<Leader>cs', '<Plug>(yarepl-start-aichat)', {
desc = 'Start an Aichat REPL',
})
keymap('n', '<Leader>cf', '<Plug>(yarepl-focus-aichat)', {
desc = 'Focus on Aichat REPL',
})
keymap('n', '<Leader>ch', '<Plug>(yarepl-hide-aichat)', {
desc = 'Hide Aichat REPL',
})
keymap('v', '<Leader>cr', '<Plug>(yarepl-send-visual-aichat)', {
desc = 'Send visual region to Aichat',
})
keymap('v', '<Leader>cR', '<Plug>(yarepl-source-visual-aichat)', {
desc = 'Source visual region to Aichat',
})
keymap('n', '<Leader>crr', '<Plug>(yarepl-send-line-aichat)', {
desc = 'Send lines to Aichat',
})
keymap('n', '<Leader>cr', '<Plug>(yarepl-send-operator-aichat)', {
desc = 'Send Operator to Aichat',
})
keymap('n', '<Leader>cr', '<Plug>(yarepl-source-operator-aichat)', {
desc = 'Source Operator to Aichat',
})
keymap('n', '<Leader>ce', '<Plug>(yarepl-exec-aichat)', {
desc = 'Execute command in aichat',
})
keymap('n', '<Leader>cq', '<Plug>(yarepl-close-aichat)', {
desc = 'Quit Aichat',
})
local ft_to_repl = {
r = 'radian',
R = 'radian',
rmd = 'radian',
quarto = 'radian',
markdown = 'radian',
python = 'ipython',
sh = 'bash',
}
autocmd('FileType', {
pattern = { 'quarto', 'markdown', 'markdown.pandoc', 'rmd', 'python', 'sh', 'REPL', 'r' },
group = my_augroup,
desc = 'set up REPL keymap',
callback = function()
local repl = ft_to_repl[vim.bo.filetype]
repl = repl and ('-' .. repl) or ''
bufmap(0, 'n', '<LocalLeader>rs', string.format('<Plug>(yarepl-start%s)', repl), {
desc = 'Start an REPL',
})
bufmap(0, 'n', '<LocalLeader>rf', '<Plug>(yarepl-focus)', {
desc = 'Focus on REPL',
})
bufmap(0, 'n', '<LocalLeader>rv', '<CMD>Telescope yarepl_show<CR>', {
desc = 'View REPLs in telescope',
})
bufmap(0, 'n', '<LocalLeader>rh', '<Plug>(yarepl-hide)', {
desc = 'Hide REPL',
})
bufmap(0, 'v', '<LocalLeader>s', '<Plug>(yarepl-send-visual)', {
desc = 'Send visual region to REPL',
})
bufmap(0, 'v', '<LocalLeader>S', '<Plug>(yarepl-source-visual)', {
desc = 'Source visual region to REPL',
})
bufmap(0, 'n', '<LocalLeader>ss', '<Plug>(yarepl-send-line)', {
desc = 'Send line to REPL',
})
bufmap(0, 'n', '<LocalLeader>s', '<Plug>(yarepl-send-operator)', {
desc = 'Send operator to REPL',
})
bufmap(0, 'n', '<LocalLeader>S', '<Plug>(yarepl-source-operator)', {
desc = 'Source operator to REPL',
})
bufmap(0, 'n', '<LocalLeader>re', '<Plug>(yarepl-exec)', {
desc = 'Execute command in REPL',
expr = true,
})
bufmap(0, 'n', '<LocalLeader>rq', '<Plug>(yarepl-close)', {
desc = 'Quit REPL',
})
bufmap(0, 'n', '<LocalLeader>rc', '<CMD>Yarepl cleanup<CR>', {
desc = 'Clear REPLs.',
})
bufmap(0, 'n', '<LocalLeader>rS', '<CMD>Yarepl swap<CR>', {
desc = 'Swap REPLs.',
})
bufmap(0, 'n', '<LocalLeader>r?', '<Plug>(yarepl-start)', {
desc = 'Start an REPL from available REPL metas',
})
bufmap(0, 'n', '<LocalLeader>ra', '<CMD>Yarepl attach_buffer<CR>', {
desc = 'Attach current buffer to a REPL',
})
bufmap(0, 'n', '<LocalLeader>rd', '<CMD>Yarepl detach_buffer<CR>', {
desc = 'Detach current buffer to any REPL',
})
end,
})
```
With the keybinding setup, prefixing keybindings with <Leader>c ensures that
the text is always sent to the aichat REPL, a REPL for chatgpt.
For maximum flexibility with other programming languages, the maintainer
desires the ability to easily switch between two modes:
1. Sending text from multiple files to a REPL via `2<LocalLeader>s`, regardless
of which buffer the maintainer is visiting. This guarantees that the text is
always sent to `RPEL 2`.
2. Sending text to a dedicated REPL for each buffer. To avoid the hassle of
remembering the exact ID associated with the desired REPL, the maintainer
can use `<LocalLeader>ra` to attach the current buffer to a REPL.
Subsequently, the `<LocalLeader>s` key can be directly used to send the text
to the desired REPL.
# Extensions
The `Extensions` module contains extended functionalities built upon the core
of yarepl.nvim. While not considered as core part of yarepl, it offers valuable
additional features. For comprehensive information about the features, please
refer to [extensions/README.md](extensions/README.md).
Currently, the module includes:
## aider
This module enhances AI-assisted coding capabilities through
[aider.chat](https://aider.chat) integration.
## codex
This module enhances AI-assisted coding capabilities through [OpenAI's Codex
CLI](https://github.com/openai/codex) integration.
## opencode
This module enhances AI-assisted coding capabilities through
[OpenCode](https://opencode.ai) integration. Its extension-specific `<Plug>`
maps follow the same lowercase naming pattern, for example
`<Plug>(yarepl-opencode-exec)`.
## code-cell
This module simplifies the creation of code cell text objects, allowing you to
utilize them with `Yarepl send_operator` or other operators such as paste, delete,
and formatting.
## fzf-lua
This module provides a fuzzy finder interface to preview active REPLs with `fzf-lua`.
## telescope
This module provides a fuzzy finder interface to preview active REPLs with `telescope`.
## Snacks.picker
This module provides a fuzzy finder interface to preview active REPLs with `Snacks.picker`.
# Set up project-level REPLs
You may want to have the ability to control the REPL metas at the project
level. For example, you may want to open `ipython` installed in a conda
environment for one project and a different `ipython` installed in another
conda environment for another project.
One way to achieve this is to:
- Enable the built-in `exrc`, which requires `nvim 0.9` for security reasons.
To enable `exrc`, add the following line to your Neovim config:
```lua
vim.o.exrc = true
```
Then, configure `yarepl` like so:
```lua
vim.g.yarepl_ipython_paths = vim.g.yarepl_ipython_paths or {}
local yarepl = require 'yarepl'
require('yarepl').setup {
metas = {
ipython = {
cmd = function()
local cwd = vim.fn.getcwd()
if vim.g.yarepl_ipython_paths and vim.g.yarepl_ipython_paths[cwd] then
return vim.g.yarepl_ipython_paths[cwd]
else
return 'ipython'
end
end,
},
},
}
```
Now, in the project root directory `~/projects/project1`, create a file
called `.nvim.lua` with the following lines:
```lua
local cwd = vim.fn.getcwd()
if vim.g.yarepl_ipython_paths then
vim.g.yarepl_ipython_paths[cwd] = '~/mambaforge/envs/a-conda-env/bin/ipython'
else
vim.g.yarepl_ipython_paths = {
[cwd] = '~/mambaforge/envs/a-conda-env/bin/ipython',
}
end
```
The first time you open `project1`, Neovim will prompt you to decide whether
you want to load the `.nvim.lua` file. Please allow it.
**Note:** The `.nvim.lua` file will be automatically loaded only once when
Neovim starts. Thus, if you switch working directories during the time Neovim
is running, the `.nvim.lua` file won't be loaded at the new working directory.
To manually load the `.nvim.lua` file after switching to a new working
directory, try `:luafile .nvim.lua`.
# Create persistent REPLs in tmux
If you would like to maintain a persistent REPL process even after exiting
neovim, you can utilize tmux. To achieve this, the following configuration
creates a REPL meta named `ipy_tmux` that attaches to a tmux session named
`ipython`. If the session does not exist, a new tmux session named `ipython` is
created, and an `ipython` REPL is started.
```lua
metas = {
ipy_tmux = {
cmd = 'tmux attach -t ipython || tmux new -s ipython ipython',
formatter = yarepl.formatter.bracketed_pasting,
},
}
```
# FAQ
## Why lazy loading with `lazy.nvim` doesn't work?
We recommend using `event = 'VeryLazy'` to do the lazy loading. If you want to
use `keys` to lazy load this plugin, make sure you are using recursive mapping:
```lua
-- Recommended
return {
'milanglacier/yarepl.nvim',
event = 'VeryLazy',
config = function()
-- add your configs here
end,
}
-- Also works, but use with caution!
return {
'milanglacier/yarepl.nvim',
keys = {
{ '<Leader>s', '<Plug>(yarepl-start)', noremap = false, mode = 'n' },
{ '<LocalLeader>o', '<Plug>(yarepl-start-ipython)', noremap = false, ft = 'python', mode = 'n' },
},
config = function()
-- your config here
end,
}
```
## How do I avoid clutter from the bufferline plugin?
If you are using a bufferline plugin and do not want the REPL buffers to
clutter your bufferline, pass `buflisted = false` in the `setup` function.
In case you have unlisted the REPLs and need to view the running ones, use
`Telescope yarepl_show`.
## Yarepl send_visual is not functioning properly
Refer to [Yarepl send_visual](#yarepl-send_visual)
## `<Plug>(yarepl-send-visual)` Only Sends to First REPL
When using which-key.nvim and binding `<Plug>(yarepl-send-visual)` or its variants
(like `<Plug>(yarepl-send-visual-ipython)`) to keybindings that start with leader
or local leader keys, visual selections will always be sent to the first REPL,
regardless of any numeric prefix entered.
This behavior occurs due to a conflict with which-key.nvim, as it consumes the
count input before it reaches `<Plug>(yarepl-send-visual)`, resulting in a count
value of `0`.
To resolve this issue, you have several options:
1. Disable which-key.nvim in visual mode
2. Bind `<Plug>(yarepl-send-visual)` to key sequences that don't trigger which-key
(e.g., `<A-s>`)
3. Use alternative methods such as `Yarepl attach_buffer` to connect the
current buffer to a REPL other than the first one
# Limitations
- Currently, `yarepl` does not support sending block-wise visual selections. If
a user attempts to send code while in block-wise visual mode, it will
automatically fall back to sending the selection line-wise.
# Acknowledgements
- [iron.nvim](https://github.com/Vigemus/iron.nvim)
- [toggleterm.nvim](https://github.com/akinsho/toggleterm.nvim)
================================================
FILE: extensions/README.md
================================================
- [Aider](#aider)
- [Overview](#overview)
- [Features](#features)
- [Commands](#commands)
- [Keymaps](#keymaps)
- [Usage](#usage)
- [Example keybinding Setup](#example-keybinding-setup)
- [Customization](#customization)
- [Note](#note)
- [Codex](#codex)
- [Overview](#overview-1)
- [Features](#features-1)
- [Commands](#commands-1)
- [Keymaps](#keymaps-1)
- [Usage](#usage-1)
- [Example keybinding Setup](#example-keybinding-setup-1)
- [Customization](#customization-1)
- [OpenCode](#opencode)
- [Overview](#overview-2)
- [Features](#features-2)
- [Commands](#commands-2)
- [Keymaps](#keymaps-2)
- [Usage](#usage-2)
- [Example keybinding Setup](#example-keybinding-setup-2)
- [Customization](#customization-2)
- [Code Cell](#code-cell)
- [Overview](#overview-3)
- [Features](#features-3)
- [Usage](#usage-3)
- [Example Configuration](#example-configuration)
- [Telescope Integration](#telescope-integration)
- [Fzf-lua Integration](#fzf-lua-integration)
- [Snacks.picker Integration](#snackspicker-integration)
**Breaking change:** extension `<Plug>` mappings now use lowercase `yarepl`
names. Update old forms like `<Plug>(Yarepl-aider-send-visual)`, to
`<Plug>(yarepl-aider-send-visual)`,
Aider, Codex, and OpenCode also live under the unified `Yarepl` command tree.
The old top-level commands are being replaced by forms like `:Yarepl aider
exec`, `:Yarepl aider set_prefix /ask`, `:Yarepl codex send_status`, `:Yarepl
codex send_open_editor`, and `:Yarepl opencode send_models`.
If you were used to `AiderExec`, `AiderSetPrefix`, `CodexExec`, or
`<Plug>(AiderSendYes)`, the new names are the same actions with a more regular
shape: snake-style subcommands on the command line, kebab-style names inside
`<Plug>(...)`.
The legacy commands and keymaps (`REPL*`) still function for now, but they will
be removed on `2026-06-01`.
This keeps the extension side predictable. You get one command namespace, the
same completion behavior everywhere, and a single place to add new actions
instead of another standalone command for each one.
# Aider
## Overview
This is an auxiliary functionality for
yarepl designed to enhance
the integration with the [aider](https://github.com/paul-gauthier/aider) AI
coding assistant. It provides a set of commands and keymaps to streamline the
interaction between Neovim and aider, making it easier to use AI-assisted
coding within your editor.
## Features
- Seamless integration with yarepl.nvim for aider sessions
- Custom prefix handling for aider commands
- Predefined shortcuts for common aider actions
- Configurable aider arguments
## Commands
The `yarepl.extensions.aider` module offers command-line completions for the
unified Aider subcommands.
- `Yarepl aider set_prefix`: Specify a `/` prefix for Aider commands, such as
`/ask`, `/architect`, `/context`, etc. When sending buffer content to the
Aider REPL, the specified prefix will be prepended to the buffer content.
- `Yarepl aider remove_prefix`: Remove the current prefix.
- `Yarepl aider send_yes`: Send `y` to aider.
- `Yarepl aider send_no`: Send `n` to aider.
- `Yarepl aider send_abort`: Send abort signal (`C-c`) to aider.
- `Yarepl aider send_exit`: Send exit signal (`C-d`) to aider.
- `Yarepl aider send_diff`: Send `/diff` to aider.
- `Yarepl aider send_paste`: Send `/paste` to aider, particularly useful for
sending images.
- `Yarepl aider send_clear`: Send `/clear` to aider.
- `Yarepl aider send_undo`: Send `/undo` to aider.
- `Yarepl aider send_reset`: Send `/reset` to aider.
- `Yarepl aider send_drop`: Send `/drop` to aider.
- `Yarepl aider send_ls`: Send `/ls` to aider.
- `Yarepl aider send_ask_mode`: Switch aider to _ask_ mode.
- `Yarepl aider send_arch_mode`: Switch aider to _architect_ mode.
- `Yarepl aider send_code_mode`: Switch aider to _code_ mode.
- `Yarepl aider send_context_mode`: Switch aider to _context_ mode.
**Note**: `send_context_mode` requires `aider v0.79.0+`
- `Yarepl aider exec`: Send the prompt written in cmdline to aider with `/`
prefix completion.
- `Yarepl aider set_args`: Set the command line args to launch aider with
autocompletion, for example `Yarepl aider set_args --model gpt-4o`.
## Keymaps
In addition to the general `<Plug>` maps created by yarepl.nvim, aider.lua
provides a set of additional `<Plug>` mappings to enhance the experience with
aider:
- `<Plug>(yarepl-aider-send-line)`: Send current line to aider.
- `<Plug>(yarepl-aider-send-visual)`: Send visual selection to aider.
- `<Plug>(yarepl-aider-send-operator)`: Operator to send text to aider.
- `<Plug>(yarepl-aider-exec)`: Type the prompt in cmdline and send it to aider.
- `<Plug>(yarepl-aider-send-yes)`: Send `y` to aider.
- `<Plug>(yarepl-aider-send-no)`: Send `n` to aider.
- `<Plug>(yarepl-aider-send-abort)`: Send abort signal (`C-c`) to aider.
- `<Plug>(yarepl-aider-send-exit)`: Send exit signal (`C-d`) to aider.
- `<Plug>(yarepl-aider-send-diff)`
- `<Plug>(yarepl-aider-send-paste)`: Send `/paste`, particularly useful for
sending images.
- `<Plug>(yarepl-aider-send-clear)`
- `<Plug>(yarepl-aider-send-undo)`
- `<Plug>(yarepl-aider-send-reset)`
- `<Plug>(yarepl-aider-send-drop)`
- `<Plug>(yarepl-aider-send-ls)`
- `<Plug>(yarepl-aider-send-ask-mode)`: Switch aider to _ask_ mode.
- `<Plug>(yarepl-aider-send-arch-mode)`: Switch aider to _architect_ mode.
- `<Plug>(yarepl-aider-send-code-mode)`: Switch aider to _code_ mode.
- `<Plug>(yarepl-aider-send-context-mode)`: Switch aider to _context_ mode.
## Usage
Make sure you have added aider into your repl meta:
```lua
require('yarepl').setup {
metas = { aider = require('yarepl.extensions.aider').create_aider_meta() }
}
```
### Example keybinding Setup
Here's an example of how you can set up your keybindings in your Neovim
configuration:
In this example, `<Leader>a` is used as the prefix for aider-related
keybindings. You can customize these to your preference.
For more detailed information on using aider, refer to the [aider
documentation](https://aider.chat/).
```lua
local keymap = vim.api.nvim_set_keymap
-- general keymap from yarepl
keymap('n', '<Leader>cs', '<Plug>(yarepl-start-aider)', { desc = 'Start aider' })
keymap('n', '<Leader>cf', '<Plug>(yarepl-focus-aider)', { desc = 'Focus aider' })
keymap('n', '<Leader>ch', '<Plug>(yarepl-hide-aider)', { desc = 'Hide aider' })
keymap('v', '<Leader>cr', '<Plug>(yarepl-send-visual-aider)', { desc = 'Send visual to aider' })
keymap('n', '<Leader>crr', '<Plug>(yarepl-send-line-aider)', { desc = 'Send line to aider' })
keymap('n', '<Leader>cr', '<Plug>(yarepl-send-operator-aider)', { desc = 'Send operator to aider' })
-- special keymap from aider
keymap('n', '<Leader>ae', '<Plug>(yarepl-aider-exec)', {
desc = 'Execute command in aider',
})
keymap('n', '<Leader>ay', '<Plug>(yarepl-aider-send-yes)', {
desc = 'Send y to aider',
})
keymap('n', '<Leader>an', '<Plug>(yarepl-aider-send-no)', {
desc = 'Send n to aider',
})
keymap('n', '<Leader>ap', '<Plug>(yarepl-aider-send-paste)', {
desc = 'Send /paste to aider',
})
keymap('n', '<Leader>aa', '<Plug>(yarepl-aider-send-abort)', {
desc = 'Send abort to aider',
})
keymap('n', '<Leader>aq', '<Plug>(yarepl-aider-send-exit)', {
desc = 'Send exit to aider',
})
keymap('n', '<Leader>ag', '<cmd>Yarepl aider set_prefix<cr>', {
desc = 'set aider prefix',
})
keymap('n', '<Leader>ama', '<Plug>(yarepl-aider-send-ask-mode)', {
desc = 'Switch aider to ask mode',
})
keymap('n', '<Leader>amA', '<Plug>(yarepl-aider-send-arch-mode)', {
desc = 'Switch aider to architect mode',
})
keymap('n', '<Leader>amc', '<Plug>(yarepl-aider-send-code-mode)', {
desc = 'Switch aider to code mode',
})
keymap('n', '<Leader>aG', '<cmd>Yarepl aider remove_prefix<cr>', {
desc = 'remove aider prefix',
})
keymap('n', '<Leader>a<space>', '<cmd>checktime<cr>', {
desc = 'sync file changes by aider to nvim buffer',
})
```
## Customization
`yarepl.extensions.aider` comes with the following default:
```lua
require('yarepl.extensions.aider').setup {
aider_cmd = 'aider',
--NOTE: make sure you pass a list of string, not string,
aider_args = { '--watch-files' },
-- Display a winbar (e.g., "aider#<id>") in the floating window.
show_winbar_in_float_win = true,
-- The default wincmd is to open aider in a floating window at the bottom-right corner
wincmd = require('yarepl.extensions.aider').config.wincmd,
}
```
## Note
I recommend explore the `inline comment as instruction` feature in `aider`,
which is enabled by default for this extension. See the
[documentation](https://aider.chat/docs/usage/watch.html).
# Codex
## Overview
This extension integrates the Codex CLI with yarepl to provide a smooth
workflow inside Neovim. It offers commands, keymaps, and a ready-to-use meta to
launch and interact with Codex.
## Features
- Seamless yarepl integration for Codex sessions
- Completions for common slash-style Codex commands
- Predefined shortcuts for frequent actions (Abort, Exit, Diff, Status, etc.)
- Configurable Codex command and arguments
- Floating window default for a focused REPL experience
## Commands
- `Yarepl codex set_args`: Set CLI arguments for launching Codex with
completion support, for example `Yarepl codex set_args --model gpt-5`.
- `Yarepl codex send_abort`: Send Ctrl-C to Codex.
- `Yarepl codex send_exit`: Send Ctrl-D to Codex.
- `Yarepl codex send_diff`: Send `/diff` to Codex.
- `Yarepl codex send_status`: Send `/status` to Codex.
- `Yarepl codex send_model`: Send `/model` to Codex.
- `Yarepl codex send_new`: Send `/new` to Codex.
- `Yarepl codex send_approvals`: Send `/approvals` to Codex.
- `Yarepl codex send_compact`: Send `/compact` to Codex.
- `Yarepl codex send_open_editor`: Ask Codex to open the editor (`Ctrl-G`).
- `Yarepl codex send_transcript_enter`: Send `Ctrl-T`.
- `Yarepl codex send_transcript_quit`: Send `q`.
- `Yarepl codex send_transcript_begin`: Send `Home`.
- `Yarepl codex send_transcript_end`: Send `End`.
- `Yarepl codex send_page_up`: Send `PageUp`.
- `Yarepl codex send_page_down`: Send `PageDown`.
- `Yarepl codex exec`: Type a prompt or slash command in the cmdline and send
it to Codex, with completion for common prefixes like `/model`,
`/approvals`, `/init`, `/new`, `/compact`, `/diff`, `/mention`, `/status`.
All commands accept an optional count to target a specific Codex REPL id.
## Keymaps
In addition to the general `<Plug>` maps created by yarepl once the `codex`
meta is registered (e.g. `<Plug>(yarepl-codex-send-line)`), this extension
defines extra convenience maps:
- `<Plug>(yarepl-codex-exec)`: Type in cmdline and send to Codex.
- `<Plug>(yarepl-codex-send-abort)`: Send Ctrl-C.
- `<Plug>(yarepl-codex-send-exit)`: Send Ctrl-D.
- `<Plug>(yarepl-codex-send-diff)`
- `<Plug>(yarepl-codex-send-status)`
- `<Plug>(yarepl-codex-send-model)`
- `<Plug>(yarepl-codex-send-new)`
- `<Plug>(yarepl-codex-send-approvals)`
- `<Plug>(yarepl-codex-send-compact)`
- `<Plug>(yarepl-codex-send-open-editor)`: Ask Codex to open the editor
(`Ctrl-G`).
- `<Plug>(yarepl-codex-send-transcript-enter)`
- `<Plug>(yarepl-codex-send-transcript-quit)`
- `<Plug>(yarepl-codex-send-transcript-begin)`: Send `<Home>`.
- `<Plug>(yarepl-codex-send-transcript-end)`: Send `<End>`.
- `<Plug>(yarepl-codex-send-page-up)`
- `<Plug>(yarepl-codex-send-page-down)`
You can prefix a count (e.g. `2`) before a mapping to target that REPL id.
## Usage
Add the Codex meta to your setup:
```lua
require('yarepl').setup {
metas = {
codex = require('yarepl.extensions.codex').create_codex_meta(),
},
}
```
For the best experience using the `Open Editor` (Ctrl‑G) command with Codex,
install the [neovim-remote](https://github.com/mhinz/neovim-remote) plugin
(until Neovim provides an official `--remote-wait`) and set your `EDITOR`
inside Neovim to an `nvr` command. For example:
```lua
vim.env.EDITOR = 'nvr -cc tabnew --remote-wait'
```
To return from an nvr instance to Codex, use `:w | bdelete` instead of `:wq`,
as nvr only exits when the buffer is deleted, allowing Codex to receive the
updated content. You can also define a convenient `WQ` command with this
Vimscript one-liner:
```vim
command! WQ w | bdelete
```
### Example keybinding Setup
```lua
local keymap = vim.api.nvim_set_keymap
-- general yarepl keymaps for the codex meta
keymap('n', '<Leader>cs', '<Plug>(yarepl-start-codex)', { desc = 'Start codex' })
keymap('n', '<Leader>cf', '<Plug>(yarepl-focus-codex)', { desc = 'Focus codex' })
keymap('n', '<Leader>ch', '<Plug>(yarepl-hide-codex)', { desc = 'Hide codex' })
keymap('v', '<Leader>cr', '<Plug>(yarepl-send-visual-codex)', { desc = 'Send visual to codex' })
keymap('n', '<Leader>crr', '<Plug>(yarepl-send-line-codex)', { desc = 'Send line to codex' })
keymap('n', '<Leader>cr', '<Plug>(yarepl-send-operator-codex)', { desc = 'Send operator to codex' })
-- codex-specific convenience keymaps
keymap('n', '<Leader>ce', '<Plug>(yarepl-codex-exec)', { desc = 'Exec in Codex' })
keymap('n', '<Leader>ca', '<Plug>(yarepl-codex-send-abort)', { desc = 'Abort' })
keymap('n', '<Leader>cD', '<Plug>(yarepl-codex-send-exit)', { desc = 'Exit' })
keymap('n', '<Leader>cd', '<Plug>(yarepl-codex-send-diff)', { desc = 'Diff' })
keymap('n', '<Leader>ct', '<Plug>(yarepl-codex-send-status)', { desc = 'Status' })
keymap('n', '<Leader>cm', '<Plug>(yarepl-codex-send-model)', { desc = 'Model' })
keymap('n', '<Leader>cn', '<Plug>(yarepl-codex-send-new)', { desc = 'New' })
keymap('n', '<Leader>cA', '<Plug>(yarepl-codex-send-approvals)', { desc = 'Approvals' })
keymap('n', '<Leader>cc', '<Plug>(yarepl-codex-send-compact)', { desc = 'Compact' })
keymap('n', '<Leader>co', '<Plug>(yarepl-codex-send-open-editor)', { desc = 'Open editor' })
-- transcript and navigation helpers
keymap('n', '<Leader>cte', '<Plug>(yarepl-codex-send-transcript-enter)', { desc = 'Transcript mode' })
keymap('n', '<Leader>ctq', '<Plug>(yarepl-codex-send-transcript-quit)', { desc = 'Transcript quit' })
keymap('n', '<Leader>ctg', '<Plug>(yarepl-codex-send-transcript-begin)', { desc = 'Transcript begin' })
keymap('n', '<Leader>ctG', '<Plug>(yarepl-codex-send-transcript-end)', { desc = 'Transcript end' })
keymap('n', '<Leader>ctk', '<Plug>(yarepl-codex-send-page-up)', { desc = 'Transcript page up' })
keymap('n', '<Leader>ctj', '<Plug>(yarepl-codex-send-page-down)', { desc = 'Transcript page down' })
keymap('n', '<Leader>c<space>', '<cmd>checktime<cr>', {
desc = 'sync file changes by codex to nvim buffer',
})
```
## Customization
Default configuration:
```lua
require('yarepl.extensions.codex').setup {
codex_cmd = 'codex',
codex_args = {},
-- Warn when $EDITOR is unset or not using nvr (for OpenEditor).
warn_on_EDITOR_env_var = true,
-- Display a winbar (e.g., "codex#<id>") in the floating window.
show_winbar_in_float_win = true,
-- The default is a floating window at the bottom right corner; you can override it
wincmd = require('yarepl.extensions.codex').config.wincmd,
}
```
# OpenCode
## Overview
This extension integrates the OpenCode with yarepl. It provides a ready to use
REPL meta, completions for common slash commands, and convenience commands for
the most used TUI keybinds.
## Features
- Seamless yarepl integration for OpenCode sessions
- Completions for common OpenCode slash commands
- Convenience shortcuts for OpenCode's `ctrl+x` leader commands
- Configurable OpenCode command and arguments
- Floating window default for a focused REPL experience
## Commands
- `Yarepl opencode set_args`: Set CLI arguments for launching OpenCode with
completion support, for example `Yarepl opencode set_args --model xxx`
- `Yarepl opencode send_compact`: Send `/compact` to OpenCode.
- `Yarepl opencode send_connect`: Send `/connect` to OpenCode.
- `Yarepl opencode send_open_editor`: Send `ctrl+x e` to OpenCode.
- `Yarepl opencode send_exit`: Send `/exit` to OpenCode.
- `Yarepl opencode send_export`: Send `/export` to OpenCode.
- `Yarepl opencode send_help`: Send `/help` to OpenCode.
- `Yarepl opencode send_init`: Send `/init` to OpenCode.
- `Yarepl opencode send_models`: Send `/models` to OpenCode.
- `Yarepl opencode send_new`: Send `/new` to OpenCode.
- `Yarepl opencode send_redo`: Send `/redo` to OpenCode.
- `Yarepl opencode send_sessions`: Send `/sessions` to OpenCode.
- `Yarepl opencode send_share`: Send `/share` to OpenCode.
- `Yarepl opencode send_thinking`: Send `/thinking` to OpenCode.
- `Yarepl opencode send_undo`: Send `/undo` to OpenCode.
- `Yarepl opencode send_unshare`: Send `/unshare` to OpenCode.
- `Yarepl opencode send_scroll_up`: Send `ctrl+alt+u` to OpenCode.
- `Yarepl opencode send_scroll_down`: Send `ctrl+alt+d` to OpenCode.
- `Yarepl opencode exec`: Send the prompt written in cmdline to OpenCode, with
completion for common prefixes like `/compact`, `/connect`, `/editor`,
`/models`, `/sessions`, `/thinking`, and `/undo`.
All commands accept an optional count to target a specific OpenCode REPL id.
## Keymaps
In addition to the general `<Plug>` maps created by yarepl once the `opencode`
meta is registered, this extension defines extra convenience maps:
- `<Plug>(yarepl-opencode-exec)`: Type in cmdline and send to OpenCode.
- `<Plug>(yarepl-opencode-send-compact)`
- `<Plug>(yarepl-opencode-send-connect)`
- `<Plug>(yarepl-opencode-send-open-editor)`: Send `ctrl+x e`.
- `<Plug>(yarepl-opencode-send-exit)`
- `<Plug>(yarepl-opencode-send-export)`
- `<Plug>(yarepl-opencode-send-help)`
- `<Plug>(yarepl-opencode-send-init)`
- `<Plug>(yarepl-opencode-send-models)`
- `<Plug>(yarepl-opencode-send-new)`
- `<Plug>(yarepl-opencode-send-redo)`
- `<Plug>(yarepl-opencode-send-sessions)`
- `<Plug>(yarepl-opencode-send-share)`
- `<Plug>(yarepl-opencode-send-thinking)`
- `<Plug>(yarepl-opencode-send-undo)`
- `<Plug>(yarepl-opencode-send-unshare)`
- `<Plug>(yarepl-opencode-send-scroll-up)`: Send `ctrl+alt+u`.
- `<Plug>(yarepl-opencode-send-scroll-down)`: Send `ctrl+alt+d`.
You can prefix a count (e.g. `2`) before a mapping to target that REPL id.
## Usage
Add the OpenCode meta to your setup:
```lua
require('yarepl').setup {
metas = {
opencode = require('yarepl.extensions.opencode').create_opencode_meta(),
},
}
```
### Example keybinding Setup
```lua
local keymap = vim.api.nvim_set_keymap
-- general yarepl keymaps for the opencode meta
keymap('n', '<Leader>os', '<Plug>(yarepl-start-opencode)', { desc = 'Start OpenCode' })
keymap('n', '<Leader>of', '<Plug>(yarepl-focus-opencode)', { desc = 'Focus OpenCode' })
keymap('n', '<Leader>oh', '<Plug>(yarepl-hide-opencode)', { desc = 'Hide OpenCode' })
keymap('v', '<Leader>or', '<Plug>(yarepl-send-visual-opencode)', { desc = 'Send visual to OpenCode' })
keymap('n', '<Leader>orr', '<Plug>(yarepl-send-line-opencode)', { desc = 'Send line to OpenCode' })
keymap('n', '<Leader>or', '<Plug>(yarepl-send-operator-opencode)', { desc = 'Send operator to OpenCode' })
-- opencode-specific convenience keymaps
keymap('n', '<Leader>oe', '<Plug>(yarepl-opencode-exec)', { desc = 'Exec in OpenCode' })
keymap('n', '<Leader>oo', '<Plug>(yarepl-opencode-send-open-editor)', { desc = 'Open editor' })
keymap('n', '<Leader>ou', '<Plug>(yarepl-opencode-send-scroll-up)', { desc = 'Scroll up' })
keymap('n', '<Leader>od', '<Plug>(yarepl-opencode-send-scroll-down)', { desc = 'Scroll down' })
```
## Customization
Default configuration:
```lua
require('yarepl.extensions.opencode').setup {
opencode_cmd = 'opencode',
opencode_args = {},
-- Display a winbar (e.g., "opencode#<id>") in the floating window.
show_winbar_in_float_window = true,
-- The default is a floating window at the bottom right corner; you can override it
wincmd = require('yarepl.extensions.opencode').config.wincmd,
}
```
# Code Cell
## Overview
The code cell extension provides text objects for working with code cells in various file types. Code cells are sections of code delimited by specific patterns, commonly used in literate programming and notebook-style documents.
## Features
- Text objects for selecting code cells
- Support for both "inner" and "around" selections
- Configurable patterns for different file types
- Automatic setup based on file type
## Usage
The extension creates text objects for code cell selection using defined start
and end patterns.
### Example Configuration
The module requires explicit configuration to activate, as it has no default
settings. Below is a sample configuration that enables:
- Markdown-style code blocks (triple backticks) in rmd, quarto, and markdown files
- Python/R-style code cells (`# %%`) in python and R files
````lua
require('yarepl.extensions.code_cell').register_text_objects {
{
key = 'c',
start_pattern = '```.+',
end_pattern = '^```$',
ft = { 'rmd', 'quarto', 'markdown' },
desc = 'markdown code cells',
},
{
key = '<Leader>c',
start_pattern = '^# ?%%%%.*',
end_pattern = '^# ?%%%%.*',
ft = { 'r', 'python' },
desc = 'r/python code cells',
},
}
````
**Usage Examples**:
Markdown files (using key `c`):
- `ic`: Select cell content (excludes delimiters)
- `ac`: Select entire cell (includes delimiters)
Python/R files (using `<Leader>c`):
- `i<Leader>c`: Select content between `# %%` markers
- `a<Leader>c`: Select content including `# %%` markers
Note: Use Lua patterns rather than Vim regex patterns.
These text objects function in both operator-pending and visual modes.
To send code cells to REPL, map `<Plug>(yarepl-send-operator)` to `<Leader>s`, then
use `<Leader>sic` to send the current cell.
# Telescope Integration
`yarepl` has integrated with Telescope and can be enabled by adding the
following line to your config:
```lua
require('telescope').load_extension 'yarepl_show'
```
Once added, you can use `Telescope yarepl_show` to preview the active REPL
buffers. This integration allows you to preview active REPL buffers. Pressing
`<CR>` will open the selected REPL buffer using `wincmd`, either with a
meta-local `wincmd` or the global `wincmd`, depending on the context.
# Fzf-lua Integration
`yarepl` has integrated with `Fzf-lua` and can be enabled by adding the
following line to your config:
```lua
vim.keymap.set('n', '<Leader>rv', function() require('yarepl.extensions.fzf').repl_show() end)
```
This integration allows you to preview active REPL buffers. Pressing `<CR>`
will open the selected REPL buffer using `wincmd`, either with a meta-local
`wincmd` or the global `wincmd`, depending on the context.
For users familiar with `Fzf-lua`'s API, custom options can be passed to the
function to tailor its behavior, similar to any other `Fzf-lua` pickers. For
example:
```lua
require('yarepl.extensions.fzf').repl_show {
winopts = {
title = 'REPL>',
previewer = {
layout = 'horizontal'
}
}
}
```
# Snacks.picker Integration
`yarepl` has integrated with `Snacks.picker` and can be enabled by adding the
following line to your config:
```lua
vim.keymap.set('n', '<Leader>rv', function() require('yarepl.extensions.snacks').repl_show() end)
```
This integration allows you to preview active REPL buffers. Pressing `<CR>`
will open the selected REPL buffer using `wincmd`, either with a meta-local
`wincmd` or the global `wincmd`, depending on the context.
For users familiar with `Snacks.picker`'s API, custom options can be passed to
the function to tailor its behavior, similar to other `Snacks` pickers.
```lua
require('yarepl.extensions.snacks').repl_show {
prompt = 'Yarepl REPL',
}
```
================================================
FILE: lua/telescope/_extensions/REPLShow.lua
================================================
local finders = require 'telescope.finders'
local pickers = require 'telescope.pickers'
local conf = require('telescope.config').values
local function REPLShow(opts)
-- Deprecate REPLShow in favor of yarepl_show
vim.deprecate('REPLShow', 'yarepl_show', '2026-06-01', 'yarepl.nvim', false)
vim.cmd.REPLCleanup()
local repls = require('yarepl')._repls
local buffers = {}
for _, repl in ipairs(repls) do
table.insert(buffers, { bufnr = repl.bufnr, name = vim.api.nvim_buf_get_name(repl.bufnr) })
end
if #buffers == 0 then
return
end
local function focus_repl(prompt_bufnr)
local actions = require 'telescope.actions'
local action_state = require 'telescope.actions.state'
local selection = action_state.get_selected_entry()
if not selection then
return
end
for id, repl in ipairs(repls) do
if repl.bufnr == selection.bufnr then
actions.close(prompt_bufnr)
-- Open the REPL buffer with configured wincmd.
vim.cmd(id .. 'REPLFocus')
return
end
end
end
pickers
.new(opts, {
prompt_title = 'REPL Buffers',
finder = finders.new_table {
results = buffers,
entry_maker = function(entry)
return {
value = entry.name,
display = ' ' .. entry.name,
ordinal = entry.name,
bufnr = entry.bufnr,
lnum = vim.api.nvim_buf_line_count(entry.bufnr),
}
end,
},
previewer = conf.grep_previewer(opts),
sorter = conf.generic_sorter(opts),
default_selection_index = 1,
attach_mappings = function(_, _)
local actions = require 'telescope.actions'
actions.select_default:replace(focus_repl)
return true
end,
})
:find()
end
return require('telescope').register_extension {
exports = {
REPLShow = REPLShow,
},
}
================================================
FILE: lua/telescope/_extensions/yarepl_show.lua
================================================
local finders = require 'telescope.finders'
local pickers = require 'telescope.pickers'
local conf = require('telescope.config').values
local function yarepl_show(opts)
vim.cmd 'Yarepl cleanup'
local repls = require('yarepl')._repls
local buffers = {}
for _, repl in ipairs(repls) do
table.insert(buffers, { bufnr = repl.bufnr, name = vim.api.nvim_buf_get_name(repl.bufnr) })
end
if #buffers == 0 then
return
end
local function focus_repl(prompt_bufnr)
local actions = require 'telescope.actions'
local action_state = require 'telescope.actions.state'
local selection = action_state.get_selected_entry()
if not selection then
return
end
for id, repl in ipairs(repls) do
if repl.bufnr == selection.bufnr then
actions.close(prompt_bufnr)
-- Open the REPL buffer with configured wincmd.
vim.cmd(id .. 'Yarepl focus')
return
end
end
end
pickers
.new(opts, {
prompt_title = 'REPL Buffers',
finder = finders.new_table {
results = buffers,
entry_maker = function(entry)
return {
value = entry.name,
display = ' ' .. entry.name,
ordinal = entry.name,
bufnr = entry.bufnr,
lnum = vim.api.nvim_buf_line_count(entry.bufnr),
}
end,
},
previewer = conf.grep_previewer(opts),
sorter = conf.generic_sorter(opts),
default_selection_index = 1,
attach_mappings = function(_, _)
local actions = require 'telescope.actions'
actions.select_default:replace(focus_repl)
return true
end,
})
:find()
end
return require('telescope').register_extension {
exports = {
yarepl_show = yarepl_show,
},
}
================================================
FILE: lua/yarepl/extensions/aider.lua
================================================
local keymap = vim.api.nvim_set_keymap
local util = require 'yarepl.extensions.utility'
local M = {}
local function default_wincmd(bufnr, name)
local winid = vim.api.nvim_open_win(bufnr, true, {
relative = 'laststatus',
row = 0,
col = math.floor(vim.o.columns * 0.5),
width = math.floor(vim.o.columns * 0.5),
height = math.floor(vim.o.lines * 0.7),
style = 'minimal',
title = name,
border = 'rounded',
title_pos = 'center',
})
if M.config.show_winbar_in_float_window then
vim.wo[winid].winbar = '%t'
end
end
-- Predefined prefix setters
local prefixes = {
'',
'/add',
'/architect',
'/ask',
'/chat-mode',
'/clear',
'/code',
'/commit',
'/copy',
'/copy-context',
'/diff',
'/drop',
'/editor',
'/exit',
'/git',
'/help',
'/lint',
'/load',
'/ls',
'/map',
'/map-refresh',
'/model',
'/models',
'/multiline-mode',
'/paste',
'/quit',
'/read-only',
'/report',
'/reset',
'/run',
'/save',
'/settings',
'/test',
'/tokens',
'/undo',
'/voice',
'/web',
'/think-tokens',
'/reasoning-effort',
'/editor-model',
'/weak-model',
'/editor',
'/edit',
'/context',
}
local aider_args = {
'--reasoning-effort',
'--watch-files',
'--model',
'--opus',
'--sonnet',
'--4',
'--4o',
'--mini',
'--4-turbo',
'--35turbo',
'--deepseek',
'--o1-mini',
'--o1-preview',
'--architect',
'--weak-model',
'--editor-model',
'--editor-edit-format',
'--show-model-warnings',
'--no-show-model-warnings',
'--cache-prompts',
'--no-cache-prompts',
'--map-refresh',
'--map-multiplier-no-files',
'--restore-chat-history',
'--no-restore-chat-history',
'--pretty',
'--no-pretty',
'--stream',
'--no-stream',
'--user-input-color',
'--tool-output-color',
'--tool-error-color',
'--tool-warning-color',
'--assistant-output-color',
'--completion-menu-color',
'--completion-menu-bg-color',
'--completion-menu-current-color',
'--completion-menu-current-bg-color',
'--code-theme',
'--show-diffs',
'--git',
'--no-git',
'--gitignore',
'--no-gitignore',
'--aiderignore',
'--subtree-only',
'--auto-commits',
'--no-auto-commits',
'--dirty-commits',
'--no-dirty-commits',
'--attribute-author',
'--no-attribute-author',
'--attribute-committer',
'--no-attribute-committer',
'--attribute-commit-message-author',
'--no-attribute-commit-message-author',
'--attribute-commit-message-committer',
'--no-attribute-commit-message-committer',
'--commit',
'--commit-prompt',
'--dry-run',
'--no-dry-run',
'--skip-sanity-check-repo',
'--lint',
'--lint-cmd',
'--auto-lint',
'--no-auto-lint',
'--test-cmd',
'--auto-test',
'--no-auto-test',
'--test',
'--file',
'--read',
'--vim',
'--chat-language',
'--install-main-branch',
'--apply',
'--yes-always',
'-v',
'--show-repo-map',
'--show-prompts',
'--message',
'--message-file',
'--encoding',
'-c',
'--gui',
'--suggest-shell-commands',
'--no-suggest-shell-commands',
'--voice-format',
'--voice-language',
'--multiline',
'--reasoning-effort',
'--thinking-tokens',
'--auto-accept-architect',
'--no-auto-accept-architect',
}
-- Create a closure for prefix handling
local function create_prefix_handler()
local yarepl = require 'yarepl'
local current_prefix = ''
local add_prefix = function(strings)
if #current_prefix > 0 and #strings > 0 then
strings[1] = current_prefix .. ' ' .. strings[1]
end
return yarepl.formatter.bracketed_pasting(strings)
end
return {
set_prefix = function(prefix)
if not vim.tbl_contains(prefixes, prefix) then
vim.notify('Unknown prefix for aider: ' .. prefix, vim.log.levels.WARN)
return
end
current_prefix = prefix
end,
formatter = add_prefix,
}
end
-- Initialize the prefix handler
local prefix_handler = create_prefix_handler()
M.set_prefix = prefix_handler.set_prefix
M.config = {
show_winbar_in_float_window = true,
wincmd = default_wincmd,
formatter = prefix_handler.formatter,
aider_args = { '--watch-files' },
aider_cmd = 'aider',
}
M.setup = function(params)
M.config = vim.tbl_deep_extend('force', M.config, params or {})
end
M.create_aider_meta = function()
return {
cmd = function()
local args
-- build up the command to launch aider based on M.config.aider_args
-- (the command line options) and the M.config.aider_cmd.
if type(M.config.aider_cmd) == 'string' then
args = vim.deepcopy(M.config.aider_args)
table.insert(args, 1, M.config.aider_cmd)
elseif type(M.config.aider_cmd) == 'table' then
args = vim.deepcopy(M.config.aider_cmd)
for _, arg in ipairs(M.config.aider_args) do
table.insert(args, arg)
end
else
vim.notify('invalid aider cmd type', vim.log.levels.ERROR)
return
end
return args
end,
formatter = M.config.formatter,
wincmd = M.config.wincmd,
}
end
local shortcuts = {
{ name = 'send_yes', legacy_name = 'Yes', key = 'y' },
{ name = 'send_no', legacy_name = 'No', key = 'n' },
{ name = 'send_abort', legacy_name = 'Abort', key = '\3' }, -- Ctrl-c
{ name = 'send_exit', legacy_name = 'Exit', key = '\4' }, -- Ctrl-d
{ name = 'send_diff', legacy_name = 'Diff', key = '/diff' },
{ name = 'send_paste', legacy_name = 'Paste', key = '/paste' },
{ name = 'send_clear', legacy_name = 'Clear', key = '/clear' },
{ name = 'send_undo', legacy_name = 'Undo', key = '/undo' },
{ name = 'send_reset', legacy_name = 'Reset', key = '/reset' },
{ name = 'send_drop', legacy_name = 'Drop', key = '/drop' },
{ name = 'send_ls', legacy_name = 'Ls', key = '/ls' },
{ name = 'send_ask_mode', legacy_name = 'AskMode', key = '/ask' },
{ name = 'send_arch_mode', legacy_name = 'ArchMode', key = '/architect' },
{ name = 'send_code_mode', legacy_name = 'CodeMode', key = '/code' },
{ name = 'send_context_mode', legacy_name = 'ContextMode', key = '/context' },
}
-------------------------------------
-- New unified Yarepl aider commands
-------------------------------------
local aider_commands = {}
local aider_completions = {}
for _, shortcut in ipairs(shortcuts) do
aider_commands[shortcut.name] = function(opts)
local id = opts.count
util.send_to_repl_raw('aider', id, shortcut.key .. '\r')
end
aider_completions[shortcut.name] = true
end
aider_commands.set_args = function(opts)
M.config.aider_args = opts.fargs or {}
end
aider_completions.set_args = function()
return aider_args
end
aider_commands.set_prefix = function(opts)
local prefix = opts.args
if prefix == '' then
vim.ui.select(prefixes, {
prompt = 'Select prefix: ',
}, function(choice)
if not choice then
return
end
M.set_prefix(choice)
end)
else
M.set_prefix(prefix)
end
end
aider_completions.set_prefix = function()
return prefixes
end
aider_commands.remove_prefix = function()
M.set_prefix ''
end
aider_completions.remove_prefix = true
aider_commands.exec = function(opts)
local id = opts.count
local command = opts.args
util.send_to_repl_raw('aider', id, command .. '\r')
end
aider_completions.exec = function()
return prefixes
end
local yarepl = require 'yarepl'
yarepl.commands.aider = function(opts)
local fargs = opts.fargs
if #fargs == 0 then
vim.notify('Yarepl aider: subcommand required', vim.log.levels.ERROR)
return
end
local subcmd = table.remove(fargs, 1)
local handler = aider_commands[subcmd]
if not handler then
vim.notify('Yarepl aider: unknown subcommand: ' .. subcmd, vim.log.levels.ERROR)
return
end
handler { args = table.concat(fargs, ' '), fargs = fargs, count = opts.count, bang = opts.bang }
end
yarepl.completions.aider = aider_completions
-------------------------------------
-- New <Plug(yarepl-aider-*) keymaps
-------------------------------------
for _, shortcut in ipairs(shortcuts) do
local plug_name = shortcut.name:gsub('_', '-')
keymap('n', '<Plug>(yarepl-aider-' .. plug_name .. ')', '', {
noremap = true,
callback = function()
util.run_cmd_with_count('Yarepl aider ' .. shortcut.name)
end,
})
end
keymap('n', '<Plug>(yarepl-aider-exec)', '', {
noremap = true,
callback = function()
return util.partial_cmd_with_count_expr 'Yarepl aider exec '
end,
expr = true,
})
-------------------------------------
-- Legacy commands with deprecation notices
-------------------------------------
vim.api.nvim_create_user_command('AiderSetArgs', function(opts)
vim.deprecate('AiderSetArgs', 'Yarepl aider set_args', '2026-06-01', 'yarepl.nvim', false)
M.config.aider_args = opts.fargs or {}
end, {
nargs = '*',
complete = function()
return aider_args
end,
})
vim.api.nvim_create_user_command('AiderSetPrefix', function(opts)
vim.deprecate('AiderSetPrefix', 'Yarepl aider set_prefix', '2026-06-01', 'yarepl.nvim', false)
local prefix = opts.args
if prefix == '' then
vim.ui.select(prefixes, {
prompt = 'Select prefix: ',
}, function(choice)
if not choice then
return
end
M.set_prefix(choice)
end)
else
M.set_prefix(prefix)
end
end, {
nargs = '?',
complete = function()
return prefixes
end,
})
vim.api.nvim_create_user_command('AiderRemovePrefix', function()
vim.deprecate('AiderRemovePrefix', 'Yarepl aider remove_prefix', '2026-06-01', 'yarepl.nvim', false)
M.set_prefix ''
end, {})
for _, shortcut in ipairs(shortcuts) do
vim.api.nvim_create_user_command('AiderSend' .. shortcut.legacy_name, function(opts)
vim.deprecate(
'AiderSend' .. shortcut.legacy_name,
'Yarepl aider ' .. shortcut.name,
'2026-06-01',
'yarepl.nvim',
false
)
local id = opts.count
util.send_to_repl_raw('aider', id, shortcut.key .. '\r')
end, { count = true })
end
vim.api.nvim_create_user_command('AiderExec', function(opts)
vim.deprecate('AiderExec', 'Yarepl aider exec', '2026-06-01', 'yarepl.nvim', false)
local id = opts.count
local command = opts.args
util.send_to_repl_raw('aider', id, command .. '\r')
end, {
count = true,
nargs = '*',
complete = function()
return prefixes
end,
})
-------------------------------------
-- Legacy <Plug>(Aider*) keymaps with deprecation notices
-------------------------------------
for _, shortcut in ipairs(shortcuts) do
local old_plug = '<Plug>(AiderSend' .. shortcut.legacy_name .. ')'
local new_plug = '<Plug>(yarepl-aider-' .. shortcut.name:gsub('_', '-') .. ')'
keymap('n', old_plug, '', {
noremap = true,
callback = function()
vim.deprecate(old_plug, new_plug, '2026-06-01', 'yarepl.nvim', false)
util.run_cmd_with_count('AiderSend' .. shortcut.legacy_name)
end,
})
end
keymap('n', '<Plug>(AiderExec)', '', {
noremap = true,
callback = function()
vim.deprecate('<Plug>(AiderExec)', '<Plug>(yarepl-aider-exec)', '2026-06-01', 'yarepl.nvim', false)
return util.partial_cmd_with_count_expr 'AiderExec'
end,
expr = true,
})
return M
================================================
FILE: lua/yarepl/extensions/code_cell.lua
================================================
local M = {}
local autocmd = vim.api.nvim_create_autocmd
local augroup = vim.api.nvim_create_augroup('yarepl.code_cell', {})
local bufmap = vim.api.nvim_buf_set_keymap
function M.textobj_code_cell(around_or_inner, start_pattern, end_pattern)
local has_same_start_end_pattern = start_pattern == end_pattern
-- \22 is Ctrl-V
local is_in_visual_mode = vim.tbl_contains({ 'v', 'V', '\22' }, vim.fn.mode())
-- send `<ESC>` key to clear visual marks such that we can update the
-- visual range.
if is_in_visual_mode then
vim.api.nvim_feedkeys('\27', 'nx', false)
end
local row = vim.api.nvim_win_get_cursor(0)[1]
local max_row = vim.api.nvim_buf_line_count(0)
-- nvim_buf_get_lines is 0 indexed, while nvim_win_get_cursor is 1 indexed
local chunk_start = nil
for row_idx = row, 1, -1 do
local line_content = vim.api.nvim_buf_get_lines(0, row_idx - 1, row_idx, false)[1]
-- upward searching if find the end_pattern first which means
-- the cursor pos is not in a chunk, then early return
-- this method only works when start and end pattern are not same
---@diagnostic disable-next-line undefined-filed
if not has_same_start_end_pattern and line_content:match(end_pattern) then
return
end
---@diagnostic disable-next-line undefined-filed
if line_content:match(start_pattern) then
chunk_start = row_idx
break
end
end
-- if find chunk_start then find chunk_end
local chunk_end = nil
if chunk_start then
if chunk_start == max_row then
return
end
for row_idx = chunk_start + 1, max_row, 1 do
local line_content = vim.api.nvim_buf_get_lines(0, row_idx - 1, row_idx, false)[1]
---@diagnostic disable-next-line undefined-filed
if line_content:match(end_pattern) then
chunk_end = row_idx
break
end
end
end
if chunk_start and chunk_end then
if around_or_inner == 'i' then
vim.api.nvim_win_set_cursor(0, { chunk_start + 1, 0 })
local internal_length = chunk_end - chunk_start - 2
if internal_length == 0 then
vim.cmd.normal { 'V', bang = true }
elseif internal_length > 0 then
vim.cmd.normal { 'V' .. internal_length .. 'j', bang = true }
end
end
if around_or_inner == 'a' then
vim.api.nvim_win_set_cursor(0, { chunk_start, 0 })
local chunk_length = chunk_end - chunk_start
vim.cmd.normal { 'V' .. chunk_length .. 'j', bang = true }
end
end
end
function M.set_code_cell_keymaps(start_pattern, end_pattern, key, desc)
for _, mode in ipairs { 'o', 'x' } do
for _, around_or_inner in ipairs { 'a', 'i' } do
bufmap(0, mode, around_or_inner .. key, '', {
silent = true,
desc = desc,
callback = function()
M.textobj_code_cell(around_or_inner, start_pattern, end_pattern)
end,
})
end
end
end
function M.register_text_objects(options)
for _, opt in ipairs(options) do
autocmd('FileType', {
group = augroup,
desc = 'Setup yarepl code cell text objects: ' .. opt.desc,
callback = function()
M.set_code_cell_keymaps(opt.start_pattern, opt.end_pattern, opt.key, opt.desc)
end,
pattern = opt.ft,
})
end
end
return M
================================================
FILE: lua/yarepl/extensions/codex.lua
================================================
local keymap = vim.api.nvim_set_keymap
local util = require 'yarepl.extensions.utility'
local M = {}
local function default_wincmd(bufnr, name)
local winid = vim.api.nvim_open_win(bufnr, true, {
relative = 'laststatus',
row = 0,
col = math.floor(vim.o.columns * 0.5),
width = math.floor(vim.o.columns * 0.5),
height = math.floor(vim.o.lines * 0.7),
style = 'minimal',
title = name,
border = 'rounded',
title_pos = 'center',
})
if M.config.show_winbar_in_float_window then
vim.wo[winid].winbar = '%t'
end
end
local prefixes = {
'/model',
'/approvals',
'/init',
'/new',
'/compact',
'/diff',
'/mention',
'/status',
}
local codex_args = {
'--config',
'--image',
'--model',
'--oss',
'--profile',
'--sandbox',
'--ask-for-approval',
'--full-auto',
'--dangerously-bypass-approvals-and-sandbox',
'--cd',
}
M.config = {
show_winbar_in_float_window = true,
wincmd = default_wincmd,
source_syntax = 'read the instruction from {{file}}',
codex_args = {},
formatter = 'bracketed_pasting_delayed_cr',
codex_cmd = 'codex',
warn_on_EDITOR_env_var = true,
}
M.setup = function(params)
M.config = vim.tbl_deep_extend('force', M.config, params or {})
end
M.create_codex_meta = function()
return {
cmd = function()
local args
-- build up the command to launch codex based on M.config.codex_args
-- (the command line options) and the M.config.codex_cmd.
if type(M.config.codex_cmd) == 'string' then
args = vim.deepcopy(M.config.codex_args)
table.insert(args, 1, M.config.codex_cmd)
elseif type(M.config.codex_cmd) == 'table' then
args = vim.deepcopy(M.config.codex_cmd)
for _, arg in ipairs(M.config.codex_args) do
table.insert(args, arg)
end
else
vim.notify('invalid codex cmd type', vim.log.levels.ERROR)
return
end
return args
end,
formatter = M.config.formatter,
wincmd = M.config.wincmd,
source_syntax = M.config.source_syntax,
send_delayed_final_cr = true,
}
end
local shortcuts = {
-- Ctrl-c
{ name = 'send_abort', legacy_name = 'Abort', key = '\3', requires_cr = false },
-- Ctrl-d
{ name = 'send_exit', legacy_name = 'Exit', key = '\4', requires_cr = false },
{ name = 'send_diff', legacy_name = 'Diff', key = '/diff', requires_cr = true },
{ name = 'send_status', legacy_name = 'Status', key = '/status', requires_cr = true },
{ name = 'send_model', legacy_name = 'Model', key = '/model', requires_cr = true },
{ name = 'send_new', legacy_name = 'New', key = '/new', requires_cr = true },
{ name = 'send_approvals', legacy_name = 'Approvals', key = '/approvals', requires_cr = true },
{ name = 'send_compact', legacy_name = 'Compact', key = '/compact', requires_cr = true },
-- Ctrl-g
{
name = 'send_open_editor',
legacy_name = 'OpenEditor',
key = '\7',
requires_cr = false,
pre_hook = function()
if M.config.warn_on_EDITOR_env_var and ((not vim.env.EDITOR) or (not vim.env.EDITOR:find 'nvr')) then
vim.notify('current $EDITOR command is not nvr, please consider using nvr', vim.log.levels.WARN)
end
end,
},
--Ctrl-t
{ name = 'send_transcript_enter', legacy_name = 'TranscriptEnter', key = '\20', requires_cr = false },
{ name = 'send_transcript_quit', legacy_name = 'TranscriptQuit', key = 'q', requires_cr = false },
-- Home
{ name = 'send_transcript_begin', legacy_name = 'TranscriptBegin', key = '\27[1~', requires_cr = false },
-- End
{ name = 'send_transcript_end', legacy_name = 'TranscriptEnd', key = '\27[4~', requires_cr = false },
{ name = 'send_page_up', legacy_name = 'PageUp', key = '\27[5~', requires_cr = false },
{ name = 'send_page_down', legacy_name = 'PageDown', key = '\27[6~', requires_cr = false },
}
-------------------------------------
-- New unified Yarepl codex commands
-------------------------------------
local codex_commands = {}
local codex_completions = {}
for _, shortcut in ipairs(shortcuts) do
codex_commands[shortcut.name] = function(opts)
if type(shortcut.pre_hook) == 'function' then
shortcut.pre_hook()
end
local id = opts.count
util.send_to_repl_raw('codex', id, shortcut.key, shortcut.requires_cr)
end
codex_completions[shortcut.name] = true
end
codex_commands.set_args = function(opts)
M.config.codex_args = opts.fargs or {}
end
codex_completions.set_args = function()
return codex_args
end
codex_commands.exec = function(opts)
local id = opts.count
local command = opts.args
util.send_to_repl_raw('codex', id, command, true)
end
codex_completions.exec = function()
return prefixes
end
local yarepl = require 'yarepl'
yarepl.commands.codex = function(opts)
local fargs = opts.fargs
if #fargs == 0 then
vim.notify('Yarepl codex: subcommand required', vim.log.levels.ERROR)
return
end
local subcmd = table.remove(fargs, 1)
local handler = codex_commands[subcmd]
if not handler then
vim.notify('Yarepl codex: unknown subcommand: ' .. subcmd, vim.log.levels.ERROR)
return
end
handler { args = table.concat(fargs, ' '), fargs = fargs, count = opts.count, bang = opts.bang }
end
yarepl.completions.codex = codex_completions
-------------------------------------
-- New <Plug(yarepl-codex-*) keymaps
-------------------------------------
for _, shortcut in ipairs(shortcuts) do
local plug_name = shortcut.name:gsub('_', '-')
keymap('n', '<Plug>(yarepl-codex-' .. plug_name .. ')', '', {
noremap = true,
callback = function()
util.run_cmd_with_count('Yarepl codex ' .. shortcut.name)
end,
})
end
keymap('n', '<Plug>(yarepl-codex-exec)', '', {
noremap = true,
callback = function()
return util.partial_cmd_with_count_expr 'Yarepl codex exec '
end,
expr = true,
})
-------------------------------------
-- Legacy commands with deprecation notices
-------------------------------------
vim.api.nvim_create_user_command('CodexSetArgs', function(opts)
vim.deprecate('CodexSetArgs', 'Yarepl codex set_args', '2026-06-01', 'yarepl.nvim', false)
M.config.codex_args = opts.fargs or {}
end, {
nargs = '*',
complete = function()
return codex_args
end,
})
for _, shortcut in ipairs(shortcuts) do
vim.api.nvim_create_user_command('CodexSend' .. shortcut.legacy_name, function(opts)
vim.deprecate(
'CodexSend' .. shortcut.legacy_name,
'Yarepl codex ' .. shortcut.name,
'2026-06-01',
'yarepl.nvim',
false
)
if type(shortcut.pre_hook) == 'function' then
shortcut.pre_hook()
end
local id = opts.count
util.send_to_repl_raw('codex', id, shortcut.key, shortcut.requires_cr)
end, { count = true })
end
vim.api.nvim_create_user_command('CodexExec', function(opts)
vim.deprecate('CodexExec', 'Yarepl codex exec', '2026-06-01', 'yarepl.nvim', false)
local id = opts.count
local command = opts.args
util.send_to_repl_raw('codex', id, command, true)
end, {
count = true,
nargs = '*',
complete = function()
return prefixes
end,
})
-------------------------------------
-- Legacy <Plug>(Codex*) keymaps with deprecation notices
-------------------------------------
for _, shortcut in ipairs(shortcuts) do
local old_plug = '<Plug>(CodexSend' .. shortcut.legacy_name .. ')'
local new_plug = '<Plug>(yarepl-codex-' .. shortcut.name:gsub('_', '-') .. ')'
keymap('n', old_plug, '', {
noremap = true,
callback = function()
vim.deprecate(old_plug, new_plug, '2026-06-01', 'yarepl.nvim', false)
util.run_cmd_with_count('CodexSend' .. shortcut.legacy_name)
end,
})
end
keymap('n', '<Plug>(CodexExec)', '', {
noremap = true,
callback = function()
vim.deprecate('<Plug>(CodexExec)', '<Plug>(yarepl-codex-exec)', '2026-06-01', 'yarepl.nvim', false)
return util.partial_cmd_with_count_expr 'CodexExec'
end,
expr = true,
})
return M
================================================
FILE: lua/yarepl/extensions/fzf.lua
================================================
local fzf = require 'fzf-lua'
local builtin = require 'fzf-lua.previewer.builtin'
local Previewer = builtin.buffer_or_file:extend()
function Previewer:new(o, opts, fzf_win)
Previewer.super.new(self, o, opts, fzf_win)
setmetatable(self, Previewer)
return self
end
local function get_buf_name_without_dir(bufnr)
return vim.fn.fnamemodify(vim.api.nvim_buf_get_name(bufnr), ':t')
end
function Previewer:parse_entry(entry_str)
local repls = require('yarepl')._repls
for _, repl in ipairs(repls) do
if get_buf_name_without_dir(repl.bufnr) == entry_str then
return { bufnr = repl.bufnr, path = entry_str }
end
end
return { path = entry_str }
end
local repl_show = function(opts)
local repls = require('yarepl')._repls
local buffers = {}
for _, repl in ipairs(repls) do
table.insert(buffers, get_buf_name_without_dir(repl.bufnr))
end
if #buffers == 0 then
return
end
local default_opts = {}
default_opts.previewer = Previewer
default_opts.actions = {
['default'] = function(e)
local entry_str = e[1]
for id, repl in ipairs(repls) do
if get_buf_name_without_dir(repl.bufnr) == entry_str then
-- the default action is to open the REPL buffer with configured wincmd
vim.cmd(id .. 'Yarepl focus')
return
end
end
end,
}
opts = vim.tbl_deep_extend('force', default_opts, opts or {})
fzf.fzf_exec(buffers, opts)
end
local M = { repl_show = repl_show }
return M
================================================
FILE: lua/yarepl/extensions/opencode.lua
================================================
local keymap = vim.api.nvim_set_keymap
local util = require 'yarepl.extensions.utility'
local M = {}
local function default_wincmd(bufnr, name)
local winid = vim.api.nvim_open_win(bufnr, true, {
relative = 'laststatus',
row = 0,
col = math.floor(vim.o.columns * 0.5),
width = math.floor(vim.o.columns * 0.5),
height = math.floor(vim.o.lines * 0.7),
style = 'minimal',
title = name,
border = 'rounded',
title_pos = 'center',
})
if M.config.show_winbar_in_float_window then
vim.wo[winid].winbar = '%t'
end
end
local opencode_args = {
'--continue',
'--session',
'--fork',
'--prompt',
'--agent',
'--model',
'--pure',
'--print-logs',
'--log-level',
'--port',
'--hostname',
'--mdns',
'--mdns-domain',
'--cors',
'--help',
}
local slash_commands = {
'/clear',
'/compact',
'/connect',
'/continue',
'/editor',
'/exit',
'/export',
'/help',
'/init',
'/models',
'/new',
'/q',
'/quit',
'/redo',
'/resume',
'/sessions',
'/share',
'/summarize',
'/themes',
'/thinking',
'/undo',
'/unshare',
}
M.config = {
show_winbar_in_float_window = true,
wincmd = default_wincmd,
formatter = 'bracketed_pasting_delayed_cr',
opencode_args = {},
opencode_cmd = 'opencode',
warn_on_EDITOR_env_var = true,
}
M.setup = function(params)
M.config = vim.tbl_deep_extend('force', M.config, params or {})
end
M.create_opencode_meta = function()
return {
cmd = function()
local args
if type(M.config.opencode_cmd) == 'string' then
args = vim.deepcopy(M.config.opencode_args)
table.insert(args, 1, M.config.opencode_cmd)
elseif type(M.config.opencode_cmd) == 'table' then
args = vim.deepcopy(M.config.opencode_cmd)
for _, arg in ipairs(M.config.opencode_args) do
table.insert(args, arg)
end
else
vim.notify('invalid opencode cmd type', vim.log.levels.ERROR)
return
end
return args
end,
formatter = M.config.formatter,
wincmd = M.config.wincmd,
send_delayed_final_cr = true,
}
end
local shortcuts = {
{ name = 'send_compact', key = '/compact', requires_cr = true },
{ name = 'send_connect', key = '/connect', requires_cr = true },
{
name = 'send_open_editor',
key = '\24e',
requires_cr = false,
pre_hook = function()
if M.config.warn_on_EDITOR_env_var and ((not vim.env.EDITOR) or (not vim.env.EDITOR:find 'nvr')) then
vim.notify('current $EDITOR command is not nvr, please consider using nvr', vim.log.levels.WARN)
end
end,
},
{ name = 'send_exit', key = '/exit', requires_cr = true },
{ name = 'send_export', key = '/export', requires_cr = true },
{ name = 'send_help', key = '/help', requires_cr = true },
{ name = 'send_init', key = '/init', requires_cr = true },
{ name = 'send_models', key = '/models', requires_cr = true },
{ name = 'send_new', key = '/new', requires_cr = true },
{ name = 'send_redo', key = '/redo', requires_cr = true },
{ name = 'send_sessions', key = '/sessions', requires_cr = true },
{ name = 'send_share', key = '/share', requires_cr = true },
{ name = 'send_thinking', key = '/thinking', requires_cr = true },
{ name = 'send_undo', key = '/undo', requires_cr = true },
{ name = 'send_unshare', key = '/unshare', requires_cr = true },
{ name = 'send_scroll_up', key = '\27\21', requires_cr = false },
{ name = 'send_scroll_down', key = '\27\4', requires_cr = false },
}
local opencode_commands = {}
local opencode_completions = {}
for _, shortcut in ipairs(shortcuts) do
opencode_commands[shortcut.name] = function(opts)
if type(shortcut.pre_hook) == 'function' then
shortcut.pre_hook()
end
local id = opts.count
util.send_to_repl_raw('opencode', id, shortcut.key, shortcut.requires_cr)
end
opencode_completions[shortcut.name] = true
end
opencode_commands.exec = function(opts)
local id = opts.count
local command = opts.args
util.send_to_repl_raw('opencode', id, command, true)
end
opencode_completions.exec = function()
return slash_commands
end
opencode_commands.set_args = function(opts)
M.config.opencode_args = opts.fargs or {}
end
opencode_completions.set_args = function()
return opencode_args
end
local yarepl = require 'yarepl'
yarepl.commands.opencode = function(opts)
local fargs = opts.fargs
if #fargs == 0 then
vim.notify('Yarepl opencode: subcommand required', vim.log.levels.ERROR)
return
end
local subcmd = table.remove(fargs, 1)
local handler = opencode_commands[subcmd]
if not handler then
vim.notify('Yarepl opencode: unknown subcommand: ' .. subcmd, vim.log.levels.ERROR)
return
end
handler { args = table.concat(fargs, ' '), fargs = fargs, count = opts.count, bang = opts.bang }
end
yarepl.completions.opencode = opencode_completions
for _, shortcut in ipairs(shortcuts) do
local plug_name = shortcut.name:gsub('_', '-')
keymap('n', '<Plug>(yarepl-opencode-' .. plug_name .. ')', '', {
noremap = true,
callback = function()
util.run_cmd_with_count('Yarepl opencode ' .. shortcut.name)
end,
})
end
keymap('n', '<Plug>(yarepl-opencode-exec)', '', {
noremap = true,
callback = function()
return util.partial_cmd_with_count_expr 'Yarepl opencode exec '
end,
expr = true,
})
return M
================================================
FILE: lua/yarepl/extensions/snacks.lua
================================================
local M = {}
local function get_buf_name_without_dir(bufnr)
return vim.fn.fnamemodify(vim.api.nvim_buf_get_name(bufnr), ':t')
end
---@param opts snacks.picker.Config?
M.repl_show = function(opts)
local has_snacks, snacks = pcall(require, 'snacks.picker')
if not has_snacks then
vim.notify('Snacks is not installed!', vim.log.levels.ERROR)
return
end
local repls = require('yarepl')._repls
---@type snacks.picker.Config
local source = {
finder = function()
local items = {}
for _, repl in ipairs(repls) do
table.insert(items, {
buf = repl.bufnr,
text = get_buf_name_without_dir(repl.bufnr),
})
end
return items
end,
format = function(item, _)
return { { item.text } }
end,
confirm = function(picker, item)
for id, repl in ipairs(repls) do
if repl.bufnr == item.buf then
-- the default action is to open the REPL buffer with configured wincmd
picker:close()
vim.schedule(function()
vim.cmd(id .. 'Yarepl focus')
end)
return
end
end
end,
}
source = vim.tbl_deep_extend('force', source, opts or {})
snacks.pick(nil, source)
end
return M
================================================
FILE: lua/yarepl/extensions/utility.lua
================================================
local M = {}
-- Execute a user command with a count prefix, using the current v:count.
function M.run_cmd_with_count(cmd)
require('yarepl').run_cmd_with_count(cmd)
end
-- Build an expression for mappings that need to pass a count to a user command.
function M.partial_cmd_with_count_expr(cmd)
return require('yarepl').partial_cmd_with_count_expr(cmd)
end
-- Send raw strings to a named REPL
---@param meta_name string
---@param id integer
---@param lines string
---@param send_delayed_final_cr boolean?
---@return nil
function M.send_to_repl_raw(meta_name, id, lines, send_delayed_final_cr)
local yarepl = require 'yarepl'
---@diagnostic disable-next-line redefined-local
local lines = vim.split(lines, '\r')
local bufnr = vim.api.nvim_get_current_buf()
yarepl._send_strings(id, meta_name, bufnr, lines, false, false, send_delayed_final_cr)
end
return M
================================================
FILE: lua/yarepl/init.lua
================================================
local M = {}
local api = vim.api
local fn = vim.fn
local is_win32 = vim.fn.has 'win32' == 1
---@class yarepl.REPLMeta
---@field cmd string[]|string|fun(): string|string[] The command to start the REPL, a builtin cmd name (e.g., 'builtin:ipython'), or a function that returns the command
---@field formatter string|fun(lines: string[]): string[] The formatter name or function to process lines before sending
---@field source_syntax string The syntax type for sourcing code (e.g., 'python', 'R', 'bash')
---@field wincmd? string|fun(bufnr: number, name: string) The window command or function to create/focus the REPL window
---@field source_command_hint? table Configuration for showing source command hints
---@field send_delayed_final_cr? boolean Whether to send a delayed carriage return after commands
---@class yarepl.REPLInstance
---@field bufnr number
---@field term number
---@field name string
M.formatter = {}
M.cmd_builtin = {}
M.commands = {}
M.completions = {}
M._virt_text_ns_id = api.nvim_create_namespace 'YareplVirtualText'
local default_config = function()
return {
buflisted = true,
scratch = true,
ft = 'REPL',
wincmd = 'belowright 15 split',
---@type table<string, yarepl.REPLMeta>
metas = {
aichat = { cmd = 'aichat', formatter = 'bracketed_pasting', source_syntax = 'aichat' },
radian = { cmd = 'radian', formatter = 'bracketed_pasting_no_final_new_line', source_syntax = 'R' },
ipython = { cmd = 'builtin:ipython', formatter = 'bracketed_pasting', source_syntax = 'ipython' },
python = { cmd = 'builtin:python', formatter = 'trim_empty_lines', source_syntax = 'python' },
R = { cmd = 'R', formatter = 'trim_empty_lines', source_syntax = 'R' },
-- bash version >= 4.4 supports bracketed paste mode. but macos
-- shipped with bash 3.2, so we don't use bracketed paste mode for
-- macOS
bash = {
cmd = 'bash',
formatter = vim.fn.has 'linux' == 1 and 'bracketed_pasting' or 'trim_empty_lines',
source_syntax = 'bash',
},
zsh = { cmd = 'zsh', formatter = 'bracketed_pasting', source_syntax = 'bash' },
},
close_on_exit = true,
scroll_to_bottom_after_sending = true,
-- Format REPL buffer names as #repl_name#n (e.g., #ipython#1) instead of using terminal defaults
format_repl_buffers_names = true,
highlight_on_send_operator = { enabled = false, hl_group = 'IncSearch', timeout = 150 },
os = {
windows = {
send_delayed_final_cr = true,
},
},
-- Display the first line as virtual text to indicate the actual
-- command sent to the REPL.
source_command_hint = {
enabled = false,
hl_group = 'Comment',
},
}
end
---@type yarepl.REPLInstance[]
M._repls = {}
---@type table<number, yarepl.REPLInstance>
M._bufnrs_to_repls = {}
local function repl_is_valid(repl)
return repl ~= nil and api.nvim_buf_is_loaded(repl.bufnr)
end
-- rearrange repls such that there's no gap in the repls table.
local function repl_cleanup()
local valid_repls = {}
local valid_repls_id = {}
for id, repl in pairs(M._repls) do
if repl_is_valid(repl) then
table.insert(valid_repls_id, id)
end
end
for bufnr, repl in pairs(M._bufnrs_to_repls) do
if not repl_is_valid(repl) then
M._bufnrs_to_repls[bufnr] = nil
end
if not api.nvim_buf_is_loaded(bufnr) then
M._bufnrs_to_repls[bufnr] = nil
end
end
table.sort(valid_repls_id)
for _, id in ipairs(valid_repls_id) do
table.insert(valid_repls, M._repls[id])
end
M._repls = valid_repls
if M._config.format_repl_buffers_names then
for id, repl in pairs(M._repls) do
-- to avoid name conflict, we add a temp prefix
api.nvim_buf_set_name(repl.bufnr, string.format('#%s#temp#%d', repl.name, id))
end
for id, repl in pairs(M._repls) do
api.nvim_buf_set_name(repl.bufnr, string.format('#%s#%d', repl.name, id))
end
end
end
local function focus_repl(repl)
if not repl_is_valid(repl) then
-- if id is nil, print it as -1
vim.notify [[REPL doesn't exist!]]
return
end
local win = fn.bufwinid(repl.bufnr)
if win ~= -1 then
api.nvim_set_current_win(win)
else
local wincmd = M._config.metas[repl.name].wincmd or M._config.wincmd
if type(wincmd) == 'function' then
wincmd(repl.bufnr, repl.name)
else
vim.cmd(wincmd)
api.nvim_set_current_buf(repl.bufnr)
end
end
end
local function create_repl(id, repl_name)
if repl_is_valid(M._repls[id]) then
vim.notify(string.format('REPL %d already exists, no new REPL is created', id))
return
end
if not M._config.metas[repl_name] then
vim.notify 'No REPL palatte is found'
return
end
local bufnr = api.nvim_create_buf(M._config.buflisted, M._config.scratch)
vim.bo[bufnr].filetype = M._config.ft
local cmd
if type(M._config.metas[repl_name].cmd) == 'function' then
cmd = M._config.metas[repl_name].cmd()
else
cmd = M._config.metas[repl_name].cmd
end
local wincmd = M._config.metas[repl_name].wincmd or M._config.wincmd
if type(wincmd) == 'function' then
wincmd(bufnr, repl_name)
else
vim.cmd(wincmd)
api.nvim_set_current_buf(bufnr)
end
local opts = {}
opts.on_exit = function()
if M._config.close_on_exit then
local bufwinid = fn.bufwinid(bufnr)
while bufwinid ~= -1 do
api.nvim_win_close(bufwinid, true)
bufwinid = fn.bufwinid(bufnr)
end
-- It is possible that this buffer has already been deleted, before
-- the process is exit.
if api.nvim_buf_is_loaded(bufnr) then
api.nvim_buf_delete(bufnr, { force = true })
end
end
repl_cleanup()
end
---@diagnostic disable-next-line: redefined-local
local function termopen(cmd, opts)
if vim.fn.has 'nvim-0.11' == 1 then
opts.term = true
return vim.fn.jobstart(cmd, opts)
else
---@diagnostic disable-next-line: deprecated
return vim.fn.termopen(cmd, opts)
end
end
local term = termopen(cmd, opts)
if M._config.format_repl_buffers_names then
api.nvim_buf_set_name(bufnr, string.format('#%s#%d', repl_name, id))
end
M._repls[id] = { bufnr = bufnr, term = term, name = repl_name }
end
-- get the id of the closest repl whose name is `NAME` from the `ID`
local function find_closest_repl_from_id_with_name(id, name)
local closest_id = nil
local closest_distance = math.huge
for repl_id, repl in pairs(M._repls) do
if repl.name == name then
local distance = math.abs(repl_id - id)
if distance < closest_distance then
closest_id = repl_id
closest_distance = distance
end
if distance == 0 then
break
end
end
end
return closest_id
end
local function repl_swap(id_1, id_2)
local repl_1 = M._repls[id_1]
local repl_2 = M._repls[id_2]
M._repls[id_1] = repl_2
M._repls[id_2] = repl_1
repl_cleanup()
end
local function find_repl_by_name_index(name, index)
local count = 0
for _, repl in ipairs(M._repls) do
if repl_is_valid(repl) and repl.name == name then
count = count + 1
if count == index then
return repl
end
end
end
return nil
end
local function attach_buffer_to_repl(bufnr, repl)
if not repl_is_valid(repl) then
vim.notify [[REPL doesn't exist!]]
return
end
if not api.nvim_buf_is_loaded(bufnr) then
vim.notify [[Invalid buffer!]]
return
end
M._bufnrs_to_repls[bufnr] = repl
end
M.bufnr_is_attached_to_repl = function(bufnr)
if not repl_is_valid(M._bufnrs_to_repls[bufnr]) then
return false
else
return true
end
end
---@param id number? the id of the repl,
---@param name string? the name of the closest repl that will try to find
---@param bufnr number? the buffer number of the buffer
---@return yarepl.REPLInstance? repl the repl object or nil if not found
-- get the repl specified by `id` and `name`. If `id` is 0, then will try to
-- find the REPL `bufnr` is attached to, if not find, will use `id = 1`. If
-- `name` is not nil or not an empty string, then will try to find the REPL
-- with `name` relative to `id`.
function M._get_repl(id, name, bufnr)
local has_name = name ~= nil and name ~= ''
-- No count: prefer the attached REPL; if a name is supplied, require it to match.
if id == nil or id == 0 then
local attached_repl = M._bufnrs_to_repls[bufnr]
if has_name and repl_is_valid(attached_repl) and attached_repl.name == name then
return attached_repl
end
if not has_name and repl_is_valid(attached_repl) then
return attached_repl
end
id = 1
end
local repl = M._repls[id]
if has_name then
local closest_id = find_closest_repl_from_id_with_name(id, name)
repl = M._repls[closest_id]
end
if repl_is_valid(repl) then
return repl
end
return nil
end
local function repl_win_scroll_to_bottom(repl)
if not repl_is_valid(repl) then
vim.notify [[REPL doesn't exist!]]
return
end
local repl_win = fn.bufwinid(repl.bufnr)
if repl_win ~= -1 then
local lines = api.nvim_buf_line_count(repl.bufnr)
api.nvim_win_set_cursor(repl_win, { lines, 0 })
end
end
local function post_create_repl(id, bufnr, opts)
if not repl_is_valid(M._repls[id]) then
return
end
if opts.bang then
attach_buffer_to_repl(bufnr, M._repls[id])
end
if M._config.scroll_to_bottom_after_sending then
repl_win_scroll_to_bottom(M._repls[id])
end
end
-- Currently, block-wise sending is not supported.
---@param mode "operator"|"visual"
---@param submode string
local function get_lines(mode, submode)
local begin_mark = mode == 'operator' and "'[" or "'<"
local end_mark = mode == 'operator' and "']" or "'>"
local begin_pos = fn.getpos(begin_mark)
local end_pos = fn.getpos(end_mark)
local begin_line = begin_pos[2]
local begin_col = begin_pos[3]
local end_line = end_pos[2]
local end_col = end_pos[3]
-- https://github.com/milanglacier/yarepl.nvim/pull/42 Handle missing,
-- empty, or inverted ranges that occur when canceling a leap.nvim motion.
if
begin_line == 0
or end_line == 0
or begin_line > end_line
or (begin_line == end_line and begin_col > end_col)
then
return {}
end
if submode == 'char' or submode == 'v' then
local lines = api.nvim_buf_get_text(0, begin_line - 1, begin_col - 1, end_line - 1, -1, {})
if #lines > 0 and #lines[#lines] > 0 then
if begin_line == end_line then
end_col = end_col - begin_col + 1
end
local offset = vim.str_utf_end(lines[#lines], end_col)
lines[#lines] = lines[#lines]:sub(1, end_col + offset)
end
return lines
else
-- Line-wise mode, or fallback to line-wise for unsupported block-wise mode.
return api.nvim_buf_get_lines(0, begin_line - 1, end_line, false)
end
end
---@param motion_type string
local function highlight_range(motion_type)
local highlight_config = M._config.highlight_on_send_operator
local type_map = {
line = 'V',
char = 'v',
block = '\22', -- Control-V
V = 'V',
v = 'v',
['\22'] = '\22',
}
local regtype = type_map[motion_type] or 'v'
vim.highlight.on_yank {
higroup = highlight_config.hl_group,
timeout = highlight_config.timeout,
event = {
operator = 'y',
regtype = regtype,
inclusive = true,
visual = false,
},
}
end
---Get the formatter function from either a string name or function
---@param formatter string|function The formatter name or function
---@return function Formatter function to use
---@throws string Error if formatter name is unknown
local function get_formatter(formatter)
if type(formatter) == 'string' then
return M.formatter[formatter] or error('Unknown formatter: ' .. formatter)
end
return formatter
end
---Search upward from cwd for a binary inside a configurable directory using vim.fs.
---@param search_root string The relative directory to search in (e.g., '.venv/bin', 'venv/bin')
---@param binary_name string The binary name to search for (e.g., 'ipython', 'python3')
---@param fallback_binary? string The fallback command to return if nothing is found
---@return string The full path if found, otherwise the fallback command
function M.cmd_builtin.find_binary(search_root, binary_name, fallback_binary)
local binary_path = vim.fs.joinpath(search_root, binary_name)
local paths = vim.fs.find(binary_path, {
upward = true,
type = 'file',
})
if #paths > 0 and vim.fn.executable(paths[1]) == 1 then
return paths[1]
end
return fallback_binary or binary_name
end
M.cmd_builtin['builtin:ipython'] = function()
local search_root = is_win32 and '.venv/Scripts' or '.venv/bin'
local binary = is_win32 and 'ipython.exe' or 'ipython'
return M.cmd_builtin.find_binary(search_root, binary, 'ipython')
end
M.cmd_builtin['builtin:python'] = function()
local search_root = is_win32 and '.venv/Scripts' or '.venv/bin'
local binary = is_win32 and 'python.exe' or 'python3'
local fallback_binary = is_win32 and 'python' or 'python3'
return M.cmd_builtin.find_binary(search_root, binary, fallback_binary)
end
---Resolve the cmd from either a string name or function
---@param cmd string|string[]|function The cmd name, cmd list, or function
---@return string|string[]|function The resolved cmd or function
local function resolve_cmd(cmd)
if type(cmd) == 'string' and M.cmd_builtin[cmd] then
return M.cmd_builtin[cmd]
end
return cmd
end
function M.formatter.factory(opts)
if type(opts) ~= 'table' then
error 'opts must be a table'
end
local config = {
replace_tab_by_space = false,
number_of_spaces_to_replace_tab = 8,
when_multi_lines = {
open_code = '',
end_code = '\r',
trim_empty_lines = false,
remove_leading_spaces = false,
-- If gsub_pattern and gsub_repl are not empty, `string.gsub` will
-- be called with `gsub_pattern` and `gsub_repl` on each line. Note
-- that you should use Lua pattern instead of Vim regex pattern.
-- The gsub calls happen after `trim_empty_lines`,
-- `remove_leading_spaces`, and `replace_tab_by_space`, and before
-- prepending and appending `open_code` and `end_code`.
gsub_pattern = '',
gsub_repl = '',
},
when_single_line = {
open_code = '',
end_code = '\r',
gsub_pattern = '',
gsub_repl = '',
},
os = {
windows = {
join_lines_with_cr = true,
},
},
}
config = vim.tbl_deep_extend('force', config, opts)
return function(lines)
if #lines == 1 then
if config.replace_tab_by_space then
lines[1] = lines[1]:gsub('\t', string.rep(' ', config.number_of_spaces_to_replace_tab))
end
lines[1] = lines[1]:gsub(config.when_single_line.gsub_pattern, config.when_single_line.gsub_repl)
lines[1] = config.when_single_line.open_code .. lines[1] .. config.when_single_line.end_code
return lines
end
local formatted_lines = {}
local line = lines[1]
line = line:gsub(config.when_multi_lines.gsub_pattern, config.when_multi_lines.gsub_repl)
line = config.when_multi_lines.open_code .. line
table.insert(formatted_lines, line)
for i = 2, #lines do
line = lines[i]
if config.when_multi_lines.trim_empty_lines and line == '' then
goto continue
end
if config.when_multi_lines.remove_leading_spaces then
line = line:gsub('^%s+', '')
end
if config.replace_tab_by_space then
line = line:gsub('\t', string.rep(' ', config.number_of_spaces_to_replace_tab))
end
line = line:gsub(config.when_multi_lines.gsub_pattern, config.when_multi_lines.gsub_repl)
table.insert(formatted_lines, line)
::continue::
end
if config.when_multi_lines.end_code then
table.insert(formatted_lines, config.when_multi_lines.end_code)
end
-- The `chansend` function joins lines with `\n`, which can result in a
-- large number of unnecessary blank lines being sent to the REPL. For
-- example, `{ "hello", "world", "again!" }` would be sent to the REPL
-- as:
-- ```
-- hello
--
-- world
--
-- again!
-- ```
-- To prevent this issue, we manually join lines with `\r` on Windows.
if is_win32 and config.os.windows.join_lines_with_cr then
formatted_lines = { table.concat(formatted_lines, '\r') }
end
return formatted_lines
end
end
M.formatter.trim_empty_lines = M.formatter.factory {
when_multi_lines = {
trim_empty_lines = true,
},
}
M.formatter.bracketed_pasting = M.formatter.factory {
when_multi_lines = {
open_code = '\27[200~',
end_code = '\27[201~\r',
},
}
M.formatter.bracketed_pasting_no_final_new_line = M.formatter.factory {
when_multi_lines = {
open_code = '\27[200~',
end_code = '\27[201~',
},
}
-- This formatter is only used with `send_delayed_final_cr` enabled, since the
-- final cr is send via a delayed event, so we don't including the final new
-- line in the code blocks we initially send to REPL.
M.formatter.bracketed_pasting_delayed_cr = M.formatter.factory {
when_single_line = {
end_code = '',
},
when_multi_lines = {
open_code = '\27[200~',
end_code = '\27[201~',
},
}
--- Displays the source comment as virtual text in the REPL buffer.
---@param repl table The REPL object.
---@param original_content? string[] The original strings/code block sent by the user.
---@param source_command? string The first line of the command sent to REPL, used for anchoring.
local function show_source_command_hint(repl, original_content, source_command)
if not repl_is_valid(repl) then
return
end
if not source_command or source_command == '' then
return
end
source_command = source_command:match '^([^\n]*)'
local meta = M._config.metas[repl.name]
local config = meta.source_command_hint
local code_part_for_display = ''
if original_content and #original_content > 0 then
for _, line_str in ipairs(original_content) do
local trimmed_line = vim.trim(line_str)
if #trimmed_line > 0 then
code_part_for_display = trimmed_line
break
end
end
end
if code_part_for_display == '' then
return
end
local comment_text = string.format(' %s - %s', os.date '%H:%M:%S', code_part_for_display)
local delay_ms = 400
vim.defer_fn(function()
if not repl_is_valid(repl) then
return
end
local buf = repl.bufnr
local lines = api.nvim_buf_get_lines(buf, 0, -1, false)
local matched_line
for i = #lines, 1, -1 do
if lines[i]:find(source_command, 1, true) then
matched_line = i - 1
break
end
end
if matched_line then
---@diagnostic disable-next-line: need-check-nil
local hl_group = config.hl_group
local virt_lines_opts = {
virt_text = { { comment_text, hl_group } },
virt_text_pos = 'eol',
}
api.nvim_buf_set_extmark(buf, M._virt_text_ns_id, matched_line, 0, virt_lines_opts)
end
end, delay_ms)
end
---@param id number the id of the repl,
---@param name string? the name of the closest repl that will try to find
---@param bufnr number? the buffer number from which to find the attached REPL.
---@param strings string[] a list of strings
---@param use_formatter boolean? whether use formatter (e.g. bracketed_pasting)? Default: true
---@param source_content boolean? Whether use source_syntax (defined by REPL meta) Default: false
---@param send_delayed_final_cr boolean? Default: depends on REPL meta or config.os.windows.
-- Send a list of strings to the repl specified by `id` and `name` and `bufnr`.
-- If `id` is 0, then will try to find the REPL that `bufnr` is attached to. If
-- a `name` is provided and that attached REPL matches it, the attached REPL is
-- used. Otherwise it will use `id = 1`. If `name` is not nil or not an empty
-- string, then will try to find the REPL with `name` relative to `id`. If
-- `bufnr` is nil or `bufnr` = 0, will find the REPL that current buffer is
-- attached to.
M._send_strings = function(id, name, bufnr, strings, use_formatter, source_content, send_delayed_final_cr)
use_formatter = use_formatter == nil and true or use_formatter
if bufnr == nil or bufnr == 0 then
bufnr = api.nvim_get_current_buf()
end
local repl = M._get_repl(id, name, bufnr)
if not repl then
vim.notify [[REPL doesn't exist!]]
return
end
local meta = M._config.metas[repl.name]
if send_delayed_final_cr == nil then
if is_win32 and M._config.os.windows.send_delayed_final_cr then
send_delayed_final_cr = true
else
send_delayed_final_cr = meta.send_delayed_final_cr
end
end
if source_content then
local source_syntax = M.source_syntaxes[meta.source_syntax] or meta.source_syntax
if not source_syntax then
vim.notify(
'No source syntax or source function is available for '
.. repl.name
.. '. Fallback to send string directly.'
)
end
local content = table.concat(strings, '\n')
local source_command_sent_to_repl
if type(source_syntax) == 'string' then
source_command_sent_to_repl = M.source_file_with_source_syntax(content, source_syntax)
elseif type(source_syntax) == 'function' then
source_command_sent_to_repl = source_syntax(content)
end
if source_command_sent_to_repl and source_command_sent_to_repl ~= '' then
if meta.source_command_hint.enabled then
show_source_command_hint(repl, strings, source_command_sent_to_repl)
end
strings = vim.split(source_command_sent_to_repl, '\n')
end
else
strings = strings
end
if use_formatter then
strings = meta.formatter(strings)
end
fn.chansend(repl.term, strings)
-- See https://github.com/milanglacier/yarepl.nvim/issues/12 and
-- https://github.com/urbainvaes/vim-ripple/issues/12 for more information.
-- It may be necessary to use a delayed `<CR>` on Windows to ensure that
-- the code is executed in the REPL. Some REPLs also need this delayed CR
-- to recognize that we want to finalize/evaluate the command.
if send_delayed_final_cr then
vim.defer_fn(function()
if repl_is_valid(repl) then
fn.chansend(repl.term, '\r')
end
end, 300)
end
if M._config.scroll_to_bottom_after_sending then
repl_win_scroll_to_bottom(repl)
end
end
M._send_operator_internal = function(motion)
-- hack: allow dot-repeat
if motion == nil then
vim.go.operatorfunc = [[v:lua.require'yarepl'._send_operator_internal]]
api.nvim_feedkeys('g@', 'ni', false)
return
end
local id = vim.b[0].repl_id
local name = vim.b[0].closest_repl_name
local current_bufnr = api.nvim_get_current_buf()
local lines = get_lines('operator', motion)
if #lines == 0 then
vim.notify 'No motion!'
return
end
M._send_strings(id, name, current_bufnr, lines)
if M._config.highlight_on_send_operator.enabled then
highlight_range(motion)
end
end
M._source_operator_internal = function(motion)
-- hack: allow dot-repeat
if motion == nil then
vim.go.operatorfunc = [[v:lua.require'yarepl'._source_operator_internal]]
api.nvim_feedkeys('g@', 'ni', false)
return
end
local id = vim.b[0].repl_id
local name = vim.b[0].closest_repl_name
local current_bufnr = api.nvim_get_current_buf()
local lines = get_lines('operator', motion)
if #lines == 0 then
vim.notify 'No motion!'
return
end
M._send_strings(id, name, current_bufnr, lines, nil, true)
if M._config.highlight_on_send_operator.enabled then
highlight_range(motion)
end
end
function M.run_cmd_with_count(cmd)
vim.cmd(string.format('%d%s', vim.v.count, cmd))
end
function M.partial_cmd_with_count_expr(cmd)
-- <C-U> is equivalent to \21, we want to clear the range before
-- next input to ensure the count is recognized correctly.
return ':\21' .. vim.v.count .. cmd
end
local function add_keymap(meta_name)
-- replace non alpha numeric and - _ keys to dash
if meta_name then
meta_name = meta_name:gsub('[^%w-_]', '-')
end
local suffix = meta_name and ('-' .. meta_name) or ''
local mode_commands = {
{ 'n', 'REPLStart', 'start' },
{ 'n', 'REPLStartOrFocusOrHide', 'start-or-focus-or-hide' },
{ 'n', 'REPLFocus', 'focus' },
{ 'n', 'REPLHide', 'hide' },
{ 'n', 'REPLHideOrFocus', 'hide-or-focus' },
{ 'n', 'REPLSendLine', 'send-line' },
{ 'n', 'REPLSendOperator', 'send-operator' },
{ 'v', 'REPLSendVisual', 'send-visual' },
{ 'n', 'REPLSourceOperator', 'source-operator' },
{ 'v', 'REPLSourceVisual', 'source-visual' },
{ 'n', 'REPLClose', 'close' },
}
for _, spec in ipairs(mode_commands) do
api.nvim_set_keymap(spec[1], string.format('<Plug>(%s%s)', spec[2], suffix), '', {
noremap = true,
callback = function()
vim.deprecate(
string.format('<Plug>(%s%s)', spec[2], suffix),
string.format('<Plug>(yarepl-%s%s)', spec[3], suffix),
'2026-06-01',
'yarepl.nvim',
false
)
if meta_name then
M.run_cmd_with_count(spec[2] .. ' ' .. meta_name)
else
M.run_cmd_with_count(spec[2])
end
end,
})
end
-- setting up keymaps for REPLExec is more complicated, setting it independently
api.nvim_set_keymap('n', string.format('<Plug>(%s%s)', 'REPLExec', suffix), '', {
noremap = true,
callback = function()
vim.deprecate(
string.format('<Plug>(REPLExec%s)', suffix),
string.format('<Plug>(yarepl-exec%s)', suffix),
'2026-06-01',
'yarepl.nvim',
false
)
if meta_name then
return M.partial_cmd_with_count_expr('REPLExec $' .. meta_name)
else
return M.partial_cmd_with_count_expr 'REPLExec '
end
end,
expr = true,
})
end
M.commands.start = function(opts)
local repl_name = opts.args
local current_bufnr = api.nvim_get_current_buf()
if repl_name == '' then
local id = opts.count == 0 and #M._repls + 1 or opts.count
local repl = M._repls[id]
if repl_is_valid(repl) then
vim.notify(string.format('REPL %d already exists', id))
focus_repl(repl)
return
end
local repls = {}
for name, _ in pairs(M._config.metas) do
table.insert(repls, name)
end
vim.ui.select(repls, {
prompt = 'Select REPL: ',
}, function(choice)
if not choice then
return
end
repl_name = choice
create_repl(id, repl_name)
post_create_repl(id, current_bufnr, opts)
end)
else
local id = #M._repls + 1
if opts.count ~= 0 then
local repl = find_repl_by_name_index(repl_name, opts.count)
if repl then
focus_repl(repl)
return
end
end
create_repl(id, repl_name)
post_create_repl(id, current_bufnr, opts)
end
end
M.commands.cleanup = repl_cleanup
M.commands.focus = function(opts)
local id = opts.count
local name = opts.args
local current_buffer = api.nvim_get_current_buf()
local repl = M._get_repl(id, name, current_buffer)
if not repl then
vim.notify [[REPL doesn't exist!]]
return
end
focus_repl(repl)
end
M.commands.hide = function(opts)
local id = opts.count
local name = opts.args
local current_buffer = api.nvim_get_current_buf()
local repl = M._get_repl(id, name, current_buffer)
if not repl then
vim.notify [[REPL doesn't exist!]]
return
end
local bufnr = repl.bufnr
local win = fn.bufwinid(bufnr)
while win ~= -1 do
api.nvim_win_close(win, true)
win = fn.bufwinid(bufnr)
end
end
local function hide_or_focus_repl(repl)
if not repl_is_valid(repl) then
vim.notify [[REPL doesn't exist!]]
return
end
local bufnr = repl.bufnr
local win = fn.bufwinid(bufnr)
if win ~= -1 then
while win ~= -1 do
api.nvim_win_close(win, true)
win = fn.bufwinid(bufnr)
end
else
focus_repl(repl)
end
end
M.commands.hide_or_focus = function(opts)
local id = opts.count
local name = opts.args
local current_buffer = api.nvim_get_current_buf()
local repl = M._get_repl(id, name, current_buffer)
if not repl then
vim.notify [[REPL doesn't exist!]]
return
end
hide_or_focus_repl(repl)
end
M.commands.start_or_focus_or_hide = function(opts)
local id = opts.count
local name = opts.args
local has_name = name ~= nil and name ~= ''
local repl
if id == 0 then
if has_name then
repl = find_repl_by_name_index(name, 1)
else
repl = M._repls[1]
end
if repl_is_valid(repl) then
hide_or_focus_repl(repl)
return
end
else
if has_name then
repl = find_repl_by_name_index(name, id)
else
repl = M._repls[id]
end
if repl_is_valid(repl) then
hide_or_focus_repl(repl)
return
end
end
M.commands.start(opts)
end
M.commands.close = function(opts)
local id = opts.count
local name = opts.args
local current_buffer = api.nvim_get_current_buf()
local repl = M._get_repl(id, name, current_buffer)
if not repl then
vim.notify [[REPL doesn't exist!]]
return
end
fn.chansend(repl.term, string.char(4))
end
M.commands.swap = function(opts)
local id_1 = tonumber(opts.fargs[1])
local id_2 = tonumber(opts.fargs[2])
if id_1 ~= nil and id_2 ~= nil then
repl_swap(id_1, id_2)
return
end
local repl_ids = {}
for id, _ in pairs(M._repls) do
table.insert(repl_ids, id)
end
table.sort(repl_ids)
if id_1 == nil then
vim.ui.select(repl_ids, {
prompt = 'select first REPL',
format_item = function(item)
return item .. ' ' .. M._repls[item].name
end,
}, function(id1)
if not id1 then
return
end
vim.ui.select(repl_ids, {
prompt = 'select second REPL',
format_item = function(item)
return item .. ' ' .. M._repls[item].name
end,
}, function(id2)
if not id2 then
return
end
repl_swap(id1, id2)
end)
end)
elseif id_2 == nil then
vim.ui.select(repl_ids, {
prompt = 'select second REPL',
format_item = function(item)
return item .. ' ' .. M._repls[item].name
end,
}, function(id2)
if not id2 then
return
end
repl_swap(id_1, id2)
end)
end
end
M.commands.attach_buffer = function(opts)
local current_buffer = api.nvim_get_current_buf()
if opts.bang then
M._bufnrs_to_repls[current_buffer] = nil
return
end
local repl_id = opts.count
local repl_ids = {}
for id, _ in pairs(M._repls) do
table.insert(repl_ids, id)
end
-- count = 0 means no count is provided
if repl_id == 0 then
vim.ui.select(repl_ids, {
prompt = 'select REPL that you want to attach to',
format_item = function(item)
return item .. ' ' .. M._repls[item].name
end,
}, function(id)
if not id then
return
end
attach_buffer_to_repl(current_buffer, M._repls[id])
end)
else
attach_buffer_to_repl(current_buffer, M._repls[repl_id])
end
end
M.commands.detach_buffer = function()
local current_buffer = api.nvim_get_current_buf()
M._bufnrs_to_repls[current_buffer] = nil
end
M.commands.send_visual = function(opts)
local id = opts.count
local name = opts.args
local current_buffer = api.nvim_get_current_buf()
api.nvim_feedkeys('\27', 'nx', false)
local visual_mode = vim.fn.visualmode()
local lines = get_lines('visual', visual_mode)
if #lines == 0 then
vim.notify 'No visual range!'
return
end
M._send_strings(id, name, current_buffer, lines, nil, opts.source_content)
end
M.commands.send_line = function(opts)
local id = opts.count
local name = opts.args
local current_buffer = api.nvim_get_current_buf()
local line = api.nvim_get_current_line()
M._send_strings(id, name, current_buffer, { line })
end
M.commands.send_operator = function(opts)
local repl_name = opts.args
local id = opts.count
if repl_name ~= '' then
vim.b[0].closest_repl_name = repl_name
else
vim.b[0].closest_repl_name = nil
end
if id ~= 0 then
vim.b[0].repl_id = id
else
vim.b[0].repl_id = nil
end
vim.go.operatorfunc = opts.source_content and [[v:lua.require'yarepl'._source_operator_internal]]
or [[v:lua.require'yarepl'._send_operator_internal]]
api.nvim_feedkeys('g@', 'ni', false)
end
M.commands.source_visual = function(opts)
opts.source_content = true
M.commands.send_visual(opts)
end
M.commands.source_operator = function(opts)
opts.source_content = true
M.commands.send_operator(opts)
end
M.commands.exec = function(opts)
local first_arg = opts.fargs[1]
local current_buffer = api.nvim_get_current_buf()
local name = ''
local command = opts.args
for repl_name, _ in pairs(M._config.metas) do
if '$' .. repl_name == first_arg then
name = first_arg:sub(2)
break
end
end
if name ~= '' then
command = command:gsub('^%$' .. name .. '%s+', '')
end
local id = opts.count
local command_list = vim.split(command, '\r')
M._send_strings(id, name, current_buffer, command_list)
end
---@param content string
---@param keep_file boolean? Whether keep the temporary file after temporary execution
---@return string? The file name of the temporary file
function M.make_tmp_file(content, keep_file)
local tmp_file = os.tmpname() .. '_yarepl'
local f = io.open(tmp_file, 'w+')
if f == nil then
M.notify('Cannot open temporary message file: ' .. tmp_file, 'error', vim.log.levels.ERROR)
return
end
f:write(content)
f:close()
if not keep_file then
vim.defer_fn(function()
os.remove(tmp_file)
end, 5000)
end
return tmp_file
end
---@param content string
---@param source_syntax string
---@param keep_file boolean?
---@reutrn string? The syntax to source the file
function M.source_file_with_source_syntax(content, source_syntax, keep_file)
local tmp_file = os.tmpname() .. '_yarepl'
local f = io.open(tmp_file, 'w+')
if f == nil then
M.notify('Cannot open temporary message file: ' .. tmp_file, 'error', vim.log.levels.ERROR)
return
end
f:write(content)
f:close()
if not keep_file then
vim.defer_fn(function()
os.remove(tmp_file)
end, 5000)
end
-- replace {{file}} placeholder with the temp file name
source_syntax = source_syntax:gsub('{{file}}', tmp_file)
return source_syntax
end
---@type table<string, string | fun(str: string): string?>
M.source_syntaxes = {}
M.source_syntaxes.python = function(str)
-- Preserve the temporary file since PDB requires its existence for
-- displaying context via the `list` command
return M.source_file_with_source_syntax(
str,
'exec(compile(open("{{file}}", "r").read(), "{{file}}", "exec"))',
true
)
end
M.source_syntaxes.ipython = function(str)
-- The `-i` flag ensures the current environment is inherited when
-- executing the file
return M.source_file_with_source_syntax(str, '%run -i "{{file}}"', true)
end
M.source_syntaxes.bash = 'source "{{file}}"'
M.source_syntaxes.R = 'eval(parse(text = readr::read_file("{{file}}")))'
M.source_syntaxes.aichat = '.file "{{file}}"'
-- New <Plug>(yarepl-*) keymaps
local function add_yarepl_keymap(meta_name)
if meta_name then
meta_name = meta_name:gsub('[^%w-_]', '-')
end
local suffix = meta_name and ('-' .. meta_name) or ''
local mode_commands = {
{ 'n', 'start' },
{ 'n', 'start_or_focus_or_hide' },
{ 'n', 'focus' },
{ 'n', 'hide' },
{ 'n', 'hide_or_focus' },
{ 'n', 'send_line' },
{ 'n', 'send_operator' },
{ 'v', 'send_visual' },
{ 'n', 'source_operator' },
{ 'v', 'source_visual' },
{ 'n', 'close' },
}
for _, spec in ipairs(mode_commands) do
local plug_name = spec[2]:gsub('_', '-')
api.nvim_set_keymap(spec[1], string.format('<Plug>(yarepl-%s%s)', plug_name, suffix), '', {
noremap = true,
callback = function()
if meta_name then
M.run_cmd_with_count('Yarepl ' .. spec[2] .. ' ' .. meta_name)
else
M.run_cmd_with_count('Yarepl ' .. spec[2])
end
end,
})
end
api.nvim_set_keymap('n', string.format('<Plug>(yarepl-exec%s)', suffix), '', {
noremap = true,
callback = function()
if meta_name then
return M.partial_cmd_with_count_expr('Yarepl exec $' .. meta_name)
else
return M.partial_cmd_with_count_expr 'Yarepl exec '
end
end,
expr = true,
})
end
M._add_yarepl_keymap = add_yarepl_keymap
M.setup = function(opts)
M._config = vim.tbl_deep_extend('force', default_config(), opts or {})
-- Check for deprecated option
if opts and opts.os and opts.os.windows and opts.os.windows.send_delayed_cr_after_sending ~= nil then
vim.deprecate(
'os.windows.send_delayed_cr_after_sending',
'os.windows.send_delayed_final_cr',
'2026-06-01',
'yarepl.nvim',
false
)
M._config.os.windows.send_delayed_final_cr = opts.os.windows.send_delayed_cr_after_sending
end
for name, meta in pairs(M._config.metas) do
-- remove the disabled builtin meta passed from user config
if not meta then
M._config.metas[name] = nil
else
-- Convert string formatter names to actual formatter functions
if meta.formatter then
meta.formatter = get_formatter(meta.formatter)
end
-- Resolve string cmd names to builtin cmd functions
if meta.cmd then
meta.cmd = resolve_cmd(meta.cmd)
end
meta.source_command_hint =
vim.tbl_deep_extend('force', M._config.source_command_hint, meta.source_command_hint or {})
end
end
add_keymap()
add_yarepl_keymap()
for meta_name, _ in pairs(M._config.metas) do
add_keymap(meta_name)
add_yarepl_keymap(meta_name)
end
end
local function list_metas()
local metas = {}
for name, _ in pairs(M._config.metas) do
table.insert(metas, name)
end
return metas
end
local function deprecate_command(old, new)
return function(opts)
vim.deprecate(old, 'Yarepl ' .. new, '2026-06-01', 'yarepl.nvim', false)
M.commands[new](opts)
end
end
api.nvim_create_user_command('REPLStart', deprecate_command('REPLStart', 'start'), {
count = true,
bang = true,
nargs = '?',
complete = list_metas,
desc = [[
Create REPL `i` from the list of available REPLs.
]],
})
api.nvim_create_user_command(
'REPLStartOrFocusOrHide',
deprecate_command('REPLStartOrFocusOrHide', 'start_or_focus_or_hide'),
{
count = true,
bang = true,
nargs = '?',
complete = list_metas,
desc = [[
Start a REPL or toggle focus/hide on an existing REPL.
]],
}
)
api.nvim_create_user_command(
'REPLCleanup',
deprecate_command('REPLCleanup', 'cleanup'),
{ desc = 'clean invalid repls, and rearrange the repls order.' }
)
api.nvim_create_user_command('REPLFocus', deprecate_command('REPLFocus', 'focus'), {
count = true,
nargs = '?',
desc = [[
Focus on REPL `i` or the REPL that current buffer is attached to.
]],
})
api.nvim_create_user_command('REPLHide', deprecate_command('REPLHide', 'hide'), {
count = true,
nargs = '?',
desc = [[
Hide REPL `i` or the REPL that current buffer is attached to.
]],
})
api.nvim_create_user_command('REPLHideOrFocus', deprecate_command('REPLHideOrFocus', 'hide_or_focus'), {
count = true,
nargs = '?',
desc = [[
Hide or focus REPL `i` or the REPL that current buffer is attached to.
]],
})
api.nvim_create_user_command('REPLClose', deprecate_command('REPLClose', 'close'), {
count = true,
nargs = '?',
desc = [[
Close REPL `i` or the REPL that current buffer is attached to.
]],
})
api.nvim_create_user_command('REPLSwap', deprecate_command('REPLSwap', 'swap'), {
desc = [[Swap two REPLs]],
nargs = '*',
})
api.nvim_create_user_command('REPLAttachBufferToREPL', deprecate_command('REPLAttachBufferToREPL', 'attach_buffer'), {
count = true,
bang = true,
desc = [[
Attach current buffer to REPL `i`
]],
})
api.nvim_create_user_command('REPLDetachBufferToREPL', deprecate_command('REPLDetachBufferToREPL', 'detach_buffer'), {
count = true,
desc = [[Detach current buffer to any REPL.]],
})
api.nvim_create_user_command('REPLSendVisual', deprecate_command('REPLSendVisual', 'send_visual'), {
count = true,
nargs = '?',
desc = [[
Send visual range to REPL `i` or the REPL that current buffer is attached to.
]],
})
api.nvim_create_user_command('REP
gitextract_jym55huq/ ├── .editorconfig ├── .github/ │ └── workflows/ │ └── luarocks-release.yaml ├── .gitignore ├── .stylua.toml ├── AGENTS.md ├── CHANGELOG.md ├── LICENSE ├── README.md ├── extensions/ │ └── README.md ├── lua/ │ ├── telescope/ │ │ └── _extensions/ │ │ ├── REPLShow.lua │ │ └── yarepl_show.lua │ └── yarepl/ │ ├── extensions/ │ │ ├── aider.lua │ │ ├── code_cell.lua │ │ ├── codex.lua │ │ ├── fzf.lua │ │ ├── opencode.lua │ │ ├── snacks.lua │ │ └── utility.lua │ └── init.lua ├── neovim.toml └── selene.toml
Condensed preview — 21 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (208K chars).
[
{
"path": ".editorconfig",
"chars": 140,
"preview": "root = true\n\n[*]\nend_of_line = LF\ninsert_final_newline = true\ntrim_trailing_whitespace = true\n\n[*.lua]\nindent_style = sp"
},
{
"path": ".github/workflows/luarocks-release.yaml",
"chars": 566,
"preview": "name: LuaRocks release\non:\n push:\n tags: # Will upload to luarocks.org when a tag is pushed\n - \"*\"\n pull_reque"
},
{
"path": ".gitignore",
"chars": 60,
"preview": ".tags\n.luarc.json\nscratch.lua\n.aider*\n.env\n.codex\n.nvim_log\n"
},
{
"path": ".stylua.toml",
"chars": 141,
"preview": "column_width = 120\nline_endings = \"Unix\"\nindent_type = \"Spaces\"\nindent_width = 4\nquote_style = \"AutoPreferSingle\"\nno_cal"
},
{
"path": "AGENTS.md",
"chars": 1558,
"preview": "# Repository Guidelines\n\n## Project Structure & Module Organization\n\n- `lua/yarepl/` contains core plugin logic, REPL ma"
},
{
"path": "CHANGELOG.md",
"chars": 3148,
"preview": "# Version 0.14.0 (2026-04-05)\n\n## Breaking Changes\n\n- **Lowercase `<Plug>` Keymaps**: Renamed `<Plug>(Yarepl-*)` mapping"
},
{
"path": "LICENSE",
"chars": 35149,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "README.md",
"chars": 50323,
"preview": "- [yarepl.nvim](#yareplnvim)\n- [Showcase](#showcase)\n- [Why yarepl.nvim?](#why-yareplnvim)\n- [Installation](#installatio"
},
{
"path": "extensions/README.md",
"chars": 23666,
"preview": "- [Aider](#aider)\n - [Overview](#overview)\n - [Features](#features)\n - [Commands](#commands)\n - [Keymaps](#keymaps)\n"
},
{
"path": "lua/telescope/_extensions/REPLShow.lua",
"chars": 2200,
"preview": "local finders = require 'telescope.finders'\nlocal pickers = require 'telescope.pickers'\n\nlocal conf = require('telescope"
},
{
"path": "lua/telescope/_extensions/yarepl_show.lua",
"chars": 2084,
"preview": "local finders = require 'telescope.finders'\nlocal pickers = require 'telescope.pickers'\n\nlocal conf = require('telescope"
},
{
"path": "lua/yarepl/extensions/aider.lua",
"chars": 12046,
"preview": "local keymap = vim.api.nvim_set_keymap\nlocal util = require 'yarepl.extensions.utility'\n\nlocal M = {}\n\nlocal function de"
},
{
"path": "lua/yarepl/extensions/code_cell.lua",
"chars": 3619,
"preview": "local M = {}\n\nlocal autocmd = vim.api.nvim_create_autocmd\nlocal augroup = vim.api.nvim_create_augroup('yarepl.code_cell'"
},
{
"path": "lua/yarepl/extensions/codex.lua",
"chars": 8517,
"preview": "local keymap = vim.api.nvim_set_keymap\nlocal util = require 'yarepl.extensions.utility'\n\nlocal M = {}\n\nlocal function de"
},
{
"path": "lua/yarepl/extensions/fzf.lua",
"chars": 1627,
"preview": "local fzf = require 'fzf-lua'\nlocal builtin = require 'fzf-lua.previewer.builtin'\n\nlocal Previewer = builtin.buffer_or_f"
},
{
"path": "lua/yarepl/extensions/opencode.lua",
"chars": 5804,
"preview": "local keymap = vim.api.nvim_set_keymap\nlocal util = require 'yarepl.extensions.utility'\n\nlocal M = {}\n\nlocal function de"
},
{
"path": "lua/yarepl/extensions/snacks.lua",
"chars": 1458,
"preview": "local M = {}\n\nlocal function get_buf_name_without_dir(bufnr)\n return vim.fn.fnamemodify(vim.api.nvim_buf_get_name(buf"
},
{
"path": "lua/yarepl/extensions/utility.lua",
"chars": 886,
"preview": "local M = {}\n\n-- Execute a user command with a count prefix, using the current v:count.\nfunction M.run_cmd_with_count(cm"
},
{
"path": "lua/yarepl/init.lua",
"chars": 47876,
"preview": "local M = {}\nlocal api = vim.api\nlocal fn = vim.fn\nlocal is_win32 = vim.fn.has 'win32' == 1\n\n---@class yarepl.REPLMeta\n-"
},
{
"path": "neovim.toml",
"chars": 350,
"preview": "[selene]\nbase = \"lua51\"\nname = \"neovim\"\n\n[vim]\nany = true\n\n[[assert.args]]\ntype = \"bool\"\n\n[[assert.args]]\ntype = \"string"
},
{
"path": "selene.toml",
"chars": 77,
"preview": "std = \"neovim\"\n\n[rules]\nglobal_usage = \"allow\"\nmultiple_statements = \"allow\"\n"
}
]
About this extraction
This page contains the full source code of the milanglacier/yarepl.nvim GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 21 files (196.6 KB), approximately 51.6k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.