1

Regenerate nvim config

This commit is contained in:
2024-06-02 03:29:20 +02:00
parent 75eea0c030
commit ef2e28883d
5576 changed files with 604886 additions and 503 deletions

View File

@ -0,0 +1,13 @@
# These are supported funding model platforms
github: akinsho
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']

View File

@ -0,0 +1,67 @@
name: 🐞 Bug
description: File a bug/issue
title: "[BUG] <title>"
labels: [ Bug, Needs Triage ]
body:
- type: checkboxes
attributes:
label: Is there an existing issue for this?
description: |
Please search to see if an issue already exists for the bug you encountered.
Do not open an issue using just a premade configuration, the most productive
way to debug an issue is using a minimal init.lua that does nothing other than
load this plugin and do the few other steps required to reproduce the issue.
Please note if you have not tested your issue with a minimal configuration I will close
it. Many problems are caused by misconfiguration and interactions this takes up a lot of
my time to narrow down. Please always use a minimal config when reporting bugs.
options:
- label: I have searched the existing issues
required: true
- type: textarea
attributes:
label: Current Behavior
description: A concise description of what you're experiencing.
validations:
required: true
- type: textarea
attributes:
label: Expected Behavior
description: A concise description of what you expected to happen.
validations:
required: true
- type: textarea
attributes:
label: Steps To Reproduce
description: Steps to reproduce the behavior.
placeholder: |
1. In this environment...
2. With this config...
3. Run '...'
4. See error...
validations:
required: true
- type: textarea
attributes:
label: Environment
description: |
examples:
- **OS**: Ubuntu 20.04
- **neovim version**: 0.8.3
- **Shell**: bash
value: |
- OS:
- neovim version:
- Shell:
render: Markdown
validations:
required: false
- type: textarea
attributes:
label: Anything else?
description: |
Links? References? Anything that will give us more context about the issue you are encountering!
Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in.
validations:
required: false

View File

@ -0,0 +1,98 @@
name: CI
on:
push:
pull_request:
jobs:
tests:
strategy:
matrix:
os: [ ubuntu-latest ]
runs-on: ${{ matrix.os }}
permissions:
# Give the default GITHUB_TOKEN write permission to commit and push the
# added or changed files to the repository.
contents: write
steps:
- uses: actions/checkout@v3
- name: Install Neovim
shell: bash
run: |
mkdir -p /tmp/nvim
wget -q https://github.com/neovim/neovim/releases/download/nightly/nvim.appimage -O /tmp/nvim/nvim.appimage
cd /tmp/nvim
chmod a+x ./nvim.appimage
./nvim.appimage --appimage-extract
echo "/tmp/nvim/squashfs-root/usr/bin/" >> $GITHUB_PATH
- name: Run Tests
run: |
nvim --version
[ ! -d tests ] && exit 0
nvim --headless -u tests/minimal_init.lua -c "PlenaryBustedDirectory tests/ {minimal_init = 'tests/minimal_init.lua', sequential = true}"
stylua:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
token: ${{ secrets.WORKFLOW_ACCESS_TOKEN }}
- uses: JohnnyMorganz/stylua-action@v2
with:
version: latest
token: ${{ secrets.WORKFLOW_ACCESS_TOKEN }}
args: --config-path=stylua.toml lua/
- uses: stefanzweifel/git-auto-commit-action@v4
with:
commit_message: "style(format): run stylua"
branch: ${{ github.head_ref }}
- name: Push changes
uses: ad-m/github-push-action@master
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
branch: ${{ github.ref }}
docs:
runs-on: ubuntu-latest
if: ${{ github.ref == 'refs/heads/main' }}
steps:
- uses: actions/checkout@v3
- name: panvimdoc
uses: kdheepak/panvimdoc@main
with:
vimdoc: toggleterm
version: "Neovim >= 0.8.0"
demojify: true
treesitter: true
- name: Push changes
uses: stefanzweifel/git-auto-commit-action@v4
with:
token: ${{ secrets.WORKFLOW_ACCESS_TOKEN }}
commit_message: "chore(build): auto-generate vimdoc"
commit_user_name: "github-actions[bot]"
commit_user_email: "github-actions[bot]@users.noreply.github.com"
commit_author: "github-actions[bot] <github-actions[bot]@users.noreply.github.com>"
release:
name: release
if: ${{ github.ref == 'refs/heads/main' }}
needs:
- docs
- tests
runs-on: ubuntu-latest
steps:
- uses: google-github-actions/release-please-action@v3
id: release
with:
release-type: simple
package-name: toggleterm.nvim
- uses: actions/checkout@v3
- name: tag stable versions
if: ${{ steps.release.outputs.release_created }}
run: |
git config user.name github-actions[bot]
git config user.email github-actions[bot]@users.noreply.github.com
git remote add gh-token "https://${{ secrets.GITHUB_TOKEN }}@github.com/google-github-actions/release-please-action.git"

View File

@ -0,0 +1 @@
.tests/

View File

@ -0,0 +1,11 @@
{
"$schema": "https://raw.githubusercontent.com/sumneko/vscode-lua/master/setting/schema.json",
"Lua.diagnostics.disable": [
"redundant-parameter",
"return-type-mismatch",
"assign-type-mismatch",
"cast-local-type",
"missing-parameter"
],
"Lua.workspace.checkThirdParty": false
}

View File

@ -0,0 +1,111 @@
# Changelog
## [2.11.0](https://github.com/akinsho/toggleterm.nvim/compare/v2.10.0...v2.11.0) (2024-04-22)
### Features
* add string array support to `open_mapping` setting. ([#557](https://github.com/akinsho/toggleterm.nvim/issues/557)) ([5ec59c3](https://github.com/akinsho/toggleterm.nvim/commit/5ec59c3a8ae4f220e40f0d37e1732354ee3ba181))
* support the CR for nushell ([#561](https://github.com/akinsho/toggleterm.nvim/issues/561)) ([72d2aa2](https://github.com/akinsho/toggleterm.nvim/commit/72d2aa290a8bcd3155d851b3d7a28ea20a1dc1f1))
### Bug Fixes
* autochdir for custom terminals ([#553](https://github.com/akinsho/toggleterm.nvim/issues/553)) ([dca1c80](https://github.com/akinsho/toggleterm.nvim/commit/dca1c80fb8ec41c97e7c3ef308719d8143fbbb05))
* clear command ([#565](https://github.com/akinsho/toggleterm.nvim/issues/565)) ([fef08f3](https://github.com/akinsho/toggleterm.nvim/commit/fef08f32b9ca7d08eefc5af34dc416a3ac259bc8))
* cmd and path now work with paths containing spaces ([#483](https://github.com/akinsho/toggleterm.nvim/issues/483)) ([f059a52](https://github.com/akinsho/toggleterm.nvim/commit/f059a52c3f8adb285cff66882462f67603c1f9ba))
* column indexing ([#572](https://github.com/akinsho/toggleterm.nvim/issues/572)) ([9e65d60](https://github.com/akinsho/toggleterm.nvim/commit/9e65d60cfa0c33a9ddc9cc9ec77471753f1984df))
* cursor position after motion ([#563](https://github.com/akinsho/toggleterm.nvim/issues/563)) ([75d3de9](https://github.com/akinsho/toggleterm.nvim/commit/75d3de9d261431dd4d6a68134bb46907c91c2023))
* ensure `on_choice` operates on exact `items` element ([#566](https://github.com/akinsho/toggleterm.nvim/issues/566)) ([d3fff44](https://github.com/akinsho/toggleterm.nvim/commit/d3fff44252b57da0dc918b5eb7aeee258603a2a7))
## [2.10.0](https://github.com/akinsho/toggleterm.nvim/compare/v2.9.0...v2.10.0) (2024-02-12)
### Features
* enable title for floating terminals ([#534](https://github.com/akinsho/toggleterm.nvim/issues/534)) ([d3aa6e8](https://github.com/akinsho/toggleterm.nvim/commit/d3aa6e88c2dcbefd240ffb77a2c77b486a19fa5f))
### Bug Fixes
* send_lines_to_terminal now honours ID variable when trim_spaces = false ([#541](https://github.com/akinsho/toggleterm.nvim/issues/541)) ([63ac4c8](https://github.com/akinsho/toggleterm.nvim/commit/63ac4c8529604ad247d9426644128de6ebb1f43a))
## [2.9.0](https://github.com/akinsho/toggleterm.nvim/compare/v2.8.0...v2.9.0) (2023-12-06)
### Features
* allow operator mapping to send to terminal ([#507](https://github.com/akinsho/toggleterm.nvim/issues/507)) ([5b84866](https://github.com/akinsho/toggleterm.nvim/commit/5b848664989b6deb2c28dad5135c89720915675a))
### Bug Fixes
* **commands:** call ToggleTermSetName with count ([#497](https://github.com/akinsho/toggleterm.nvim/issues/497)) ([ef1bbff](https://github.com/akinsho/toggleterm.nvim/commit/ef1bbff59c9ab5b468062c33ca183541a3849547)), closes [#496](https://github.com/akinsho/toggleterm.nvim/issues/496)
* **terminal:** clear correctly on windows ([#513](https://github.com/akinsho/toggleterm.nvim/issues/513)) ([0731e99](https://github.com/akinsho/toggleterm.nvim/commit/0731e99de590fb7451eb4fee99470506e012b34d))
## [2.8.0](https://github.com/akinsho/toggleterm.nvim/compare/v2.7.1...v2.8.0) (2023-09-11)
### Features
* add `Terminal.find` function ([#486](https://github.com/akinsho/toggleterm.nvim/issues/486)) ([01a84bc](https://github.com/akinsho/toggleterm.nvim/commit/01a84bc642484681933140537c3ff99b10b8a866))
* add name param to ToggleTerm and TermExec ([#479](https://github.com/akinsho/toggleterm.nvim/issues/479)) ([81ea9f7](https://github.com/akinsho/toggleterm.nvim/commit/81ea9f71a3fd7621fd02b2c74861595378a3c938))
### Bug Fixes
* **#487:** avoid terminal id collisions in __add ([#490](https://github.com/akinsho/toggleterm.nvim/issues/490)) ([6bec54e](https://github.com/akinsho/toggleterm.nvim/commit/6bec54e73807919b15fc92824fb48be32fb7e8ea))
* determine custom terminal ids on spawn ([#488](https://github.com/akinsho/toggleterm.nvim/issues/488)) ([8572917](https://github.com/akinsho/toggleterm.nvim/commit/8572917413dd039d1a53b007df5c571e2a3b8ad7))
* TermExec cmd with config.shell as function ([#467](https://github.com/akinsho/toggleterm.nvim/issues/467)) ([83871e3](https://github.com/akinsho/toggleterm.nvim/commit/83871e3c34837117644d83f422ee6c869b61891f))
### Reverts
* determine custom terminal ids on spawn ([#488](https://github.com/akinsho/toggleterm.nvim/issues/488)) ([0e4dcb8](https://github.com/akinsho/toggleterm.nvim/commit/0e4dcb8f0914bd191f732cae826df59f174359fe))
## [2.7.1](https://github.com/akinsho/toggleterm.nvim/compare/v2.7.0...v2.7.1) (2023-07-10)
### Bug Fixes
* handle errors when switching buffer [#453](https://github.com/akinsho/toggleterm.nvim/issues/453) ([#454](https://github.com/akinsho/toggleterm.nvim/issues/454)) ([029ad96](https://github.com/akinsho/toggleterm.nvim/commit/029ad968fd5a06ac5e29afe083d0a61be68e792b))
* replace vim.wo with nvim_set_option_value ([#449](https://github.com/akinsho/toggleterm.nvim/issues/449)) ([7da102a](https://github.com/akinsho/toggleterm.nvim/commit/7da102a9c2fa1dd190c11faea03ee1c47af03d02))
* **terminal:** allow resizing hidden terminals ([bacbaa7](https://github.com/akinsho/toggleterm.nvim/commit/bacbaa7480344e4cfcebdf46fdfc058b3cb04648)), closes [#459](https://github.com/akinsho/toggleterm.nvim/issues/459)
## [2.7.0](https://github.com/akinsho/toggleterm.nvim/compare/v2.6.0...v2.7.0) (2023-05-22)
### Features
* add a terminal select command ([#429](https://github.com/akinsho/toggleterm.nvim/issues/429)) ([c8574d7](https://github.com/akinsho/toggleterm.nvim/commit/c8574d7a7d2e5682de4479463ddba794390c0e40))
* allow changing terminal dir in background ([#438](https://github.com/akinsho/toggleterm.nvim/issues/438)) ([f5cf0b1](https://github.com/akinsho/toggleterm.nvim/commit/f5cf0b1eebd95ba4edc69e2fbd13e1a289048d5d))
### Bug Fixes
* **float:** ensure sidescroll is zero ([43b75f4](https://github.com/akinsho/toggleterm.nvim/commit/43b75f43aa7590228d88945525c737f0ddc05c22))
## [2.6.0](https://github.com/akinsho/toggleterm.nvim/compare/v2.5.0...v2.6.0) (2023-04-09)
### Features
* **config:** allow `shell` parameter to be a function ([#423](https://github.com/akinsho/toggleterm.nvim/issues/423)) ([a7857b6](https://github.com/akinsho/toggleterm.nvim/commit/a7857b6cbfdfc98df2a7b61591be16e1020c7a82))
## [2.5.0](https://github.com/akinsho/toggleterm.nvim/compare/2.4.0...v2.5.0) (2023-03-31)
### ⚠ BREAKING CHANGES
* switch persist_mode to false ([#410](https://github.com/akinsho/toggleterm.nvim/issues/410))
### Features
* support z-index option for floating windows ([#418](https://github.com/akinsho/toggleterm.nvim/issues/418)) ([0aa9364](https://github.com/akinsho/toggleterm.nvim/commit/0aa936445b895cd5d3387860f96ce424ce32b072))
* switch persist_mode to false ([#410](https://github.com/akinsho/toggleterm.nvim/issues/410)) ([98e15df](https://github.com/akinsho/toggleterm.nvim/commit/98e15df2c838fe5c3cae1efa36fa5c255fc75aa8))
* **terminal:** add mechanism to fetch last focused terminal ([#411](https://github.com/akinsho/toggleterm.nvim/issues/411)) ([bfb7a72](https://github.com/akinsho/toggleterm.nvim/commit/bfb7a7254b5d897a5b889484c6a5142951a18b29))
### Miscellaneous Chores
* release 2.5.0 ([f14cbfd](https://github.com/akinsho/toggleterm.nvim/commit/f14cbfd3141ce35d2738084e40bccf2176a474b2))

View File

@ -0,0 +1,675 @@
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>.

View File

@ -0,0 +1,553 @@
<!-- panvimdoc-ignore-start -->
<h1 align="center">
toggleterm.nvim
</h1>
<!-- panvimdoc-ignore-end -->
<!-- panvimdoc-ignore-start -->
<p align="center">A <i>neovim</i> plugin to persist and toggle multiple terminals during an editing session</p>
<!-- panvimdoc-ignore-end -->
<!-- panvimdoc-ignore-start -->
![toggleterm in action](https://user-images.githubusercontent.com/22454918/224485816-8b0cb1b8-b0e6-4da6-9d71-a7299d39f1a0.gif)
<!-- panvimdoc-ignore-end -->
### Multiple orientations
- **Float**
<!-- panvimdoc-ignore-start -->
![floating window](https://user-images.githubusercontent.com/22454918/115306123-42d2ac00-a15f-11eb-84fc-c4246ee82a09.png)
<!-- panvimdoc-ignore-end -->
- **Vertical**
<!-- panvimdoc-ignore-start -->
![vertical-terms](https://user-images.githubusercontent.com/22454918/224485828-cd509271-8288-46e2-afb4-4e520fa049cb.png)
<!-- panvimdoc-ignore-end -->
- **Tab**
<!-- panvimdoc-ignore-start -->
![tab orientation](https://user-images.githubusercontent.com/22454918/133490969-6a59e623-79db-4ca7-a73b-ef4b24a73b91.gif)
<!-- panvimdoc-ignore-end -->
### Send commands to different terminals
<!-- panvimdoc-ignore-start -->
![exec](https://user-images.githubusercontent.com/22454918/112119367-36d1e980-8bb5-11eb-9787-5936391127a3.gif)
<!-- panvimdoc-ignore-end -->
### Winbar (Experimental/Nightly ONLY)
<!-- panvimdoc-ignore-start -->
<img width="1728" alt="image" src="https://user-images.githubusercontent.com/22454918/179199998-75ec16cb-8271-490e-925f-6c82c50ffc5d.png">
<!-- panvimdoc-ignore-end -->
## Requirements
This plugin only works in _Neovim 0.7_ or newer.
## Installation
Using [packer](https://github.com/wbthomason/packer.nvim) in lua
```lua
use {"akinsho/toggleterm.nvim", tag = '*', config = function()
require("toggleterm").setup()
end}
```
Using [lazy.nvim](https://github.com/folke/lazy.nvim) in lua
```lua
{
-- amongst your other plugins
{'akinsho/toggleterm.nvim', version = "*", config = true}
-- or
{'akinsho/toggleterm.nvim', version = "*", opts = {--[[ things you want to change go here]]}}
}
```
Using [vim-plug](https://github.com/junegunn/vim-plug) in vimscript
```vim
Plug 'akinsho/toggleterm.nvim', {'tag' : '*'}
lua require("toggleterm").setup()
```
You can/should specify a tag for the current major version of the plugin, to avoid breaking changes as this plugin evolves.
To use a version of this plugin compatible with nvim versions less than 0.7 please use the tag `v1.*`.
## Notices
- **28/07/1990** — If using `persist_mode` terminal mappings should be changed to use `wincmd` instead otherwise persist mode will not work correctly. See [here](#terminal-window-mappings) for details.
## Why?
Neovim's terminal is a very cool, but not super ergonomic tool to use. I find that I often want to
set a process going and leave it to continue to run in the background. I don't need to see it all the time.
I just need to be able to refer back to it at intervals. I also sometimes want to create a new terminal and run a few commands.
Sometimes I want these side by side, and I _really_ want these terminals to be easy to access.
I also want my terminal to look different from non-terminal buffers, so I use `winhighlight` to darken them based on the `Normal`
background colour.
This is the exact use case this was designed for. If that's your use case this might work for you.
## Roadmap
All I really want this plugin to be is what I described above. A wrapper around the terminal functionality.
It basically (almost) does all that I need it to.
I won't be turning this into a REPL plugin or doing a bunch of complex stuff.
If you find any issues, _please_ consider a _pull request_ not an issue.
I'm also going to be pretty conservative about what I add.
### Setup
This plugin must be explicitly enabled by using `require("toggleterm").setup{}`
Setting the `open_mapping` key to use for toggling the terminal(s) will set up mappings for _normal_ mode. The `open_mapping` can be a key string or an array of key strings.
If you prefix the mapping with a number that particular terminal will be opened. Otherwise if a prefix is not set, then the last toggled terminal will be opened. In case there are multiple terminals opened they'll all be closed, and on the next mapping key they'll be restored.
If you set the `insert_mappings` key to `true`, the mapping will also take effect in insert mode; similarly setting `terminal_mappings` to `true` will have the mappings take effect in the opened terminal.
However you will not be able to use a count with the open mapping in terminal and insert modes. You can create buffer specific mappings to exit terminal mode and then use a count with the open mapping. Check _Terminal window mappings_ for an example of how to do this.
alternatively you can do this manually (not recommended but, your prerogative)
```vim
" set
autocmd TermEnter term://*toggleterm#*
\ tnoremap <silent><c-t> <Cmd>exe v:count1 . "ToggleTerm"<CR>
" By applying the mappings this way you can pass a count to your
" mapping to open a specific window.
" For example: 2<C-t> will open terminal 2
nnoremap <silent><c-t> <Cmd>exe v:count1 . "ToggleTerm"<CR>
inoremap <silent><c-t> <Esc><Cmd>exe v:count1 . "ToggleTerm"<CR>
```
**NOTE**: Please ensure you have set `hidden` in your neovim config, otherwise the terminals will be discarded when closed.
**WARNING**: Please do not copy and paste this configuration! It is here to show what options are available. It is not written to be used as is.
```lua
require("toggleterm").setup{
-- size can be a number or function which is passed the current terminal
size = 20 | function(term)
if term.direction == "horizontal" then
return 15
elseif term.direction == "vertical" then
return vim.o.columns * 0.4
end
end,
open_mapping = [[<c-\>]], -- or { [[<c-\>]], [[<c-¥>]] } if you also use a Japanese keyboard.
on_create = fun(t: Terminal), -- function to run when the terminal is first created
on_open = fun(t: Terminal), -- function to run when the terminal opens
on_close = fun(t: Terminal), -- function to run when the terminal closes
on_stdout = fun(t: Terminal, job: number, data: string[], name: string) -- callback for processing output on stdout
on_stderr = fun(t: Terminal, job: number, data: string[], name: string) -- callback for processing output on stderr
on_exit = fun(t: Terminal, job: number, exit_code: number, name: string) -- function to run when terminal process exits
hide_numbers = true, -- hide the number column in toggleterm buffers
shade_filetypes = {},
autochdir = false, -- when neovim changes it current directory the terminal will change it's own when next it's opened
highlights = {
-- highlights which map to a highlight group name and a table of it's values
-- NOTE: this is only a subset of values, any group placed here will be set for the terminal window split
Normal = {
guibg = "<VALUE-HERE>",
},
NormalFloat = {
link = 'Normal'
},
FloatBorder = {
guifg = "<VALUE-HERE>",
guibg = "<VALUE-HERE>",
},
},
shade_terminals = true, -- NOTE: this option takes priority over highlights specified so if you specify Normal highlights you should set this to false
shading_factor = '<number>', -- the percentage by which to lighten terminal background, default: -30 (gets multiplied by -3 if background is light)
start_in_insert = true,
insert_mappings = true, -- whether or not the open mapping applies in insert mode
terminal_mappings = true, -- whether or not the open mapping applies in the opened terminals
persist_size = true,
persist_mode = true, -- if set to true (default) the previous terminal mode will be remembered
direction = 'vertical' | 'horizontal' | 'tab' | 'float',
close_on_exit = true, -- close the terminal window when the process exits
-- Change the default shell. Can be a string or a function returning a string
shell = vim.o.shell,
auto_scroll = true, -- automatically scroll to the bottom on terminal output
-- This field is only relevant if direction is set to 'float'
float_opts = {
-- The border key is *almost* the same as 'nvim_open_win'
-- see :h nvim_open_win for details on borders however
-- the 'curved' border is a custom border type
-- not natively supported but implemented in this plugin.
border = 'single' | 'double' | 'shadow' | 'curved' | ... other options supported by win open
-- like `size`, width, height, row, and col can be a number or function which is passed the current terminal
width = <value>,
height = <value>,
row = <value>,
col = <value>,
winblend = 3,
zindex = <value>,
title_pos = 'left' | 'center' | 'right', position of the title of the floating window
},
winbar = {
enabled = false,
name_formatter = function(term) -- term: Terminal
return term.name
end
},
}
```
### Usage
### `ToggleTerm`
This is the command the mappings call under the hood. You can use it directly
and prefix it with a count to target a specific terminal. This function also takes
arguments `size`, `dir`, `direction` and `name`. e.g.
```vim
:ToggleTerm size=40 dir=~/Desktop direction=horizontal name=desktop
```
If `dir` is specified on creation toggle term will open at the specified directory.
If the terminal has already been opened at a particular directory it will remain in that directory.
The directory can also be specified as `git_dir` which toggleterm will then
use to try and derive the git repo directory.
_NOTE_: This will not work for `git-worktrees` or other more complex setups.
If `size` is specified, and the command opens a split (horizontal/vertical) terminal,
the height/width of all terminals in the same direction will be changed to `size`.
If `direction` is specified, and the command opens a terminal,
the terminal will be changed to the specified direction.
If `name` is specified, the display name is set for the toggled terminal. This name will be visible
when using `TermSelect` command to indicate the specific terminal.
`size` and `direction` are ignored if the command closes a terminal.
#### Caveats
- Having multiple terminals with different directions open at the same time is unsupported.
### `ToggleTermToggleAll`
This command allows you to open all the previously toggled terminal in one go
or close all the open terminals at once.
### `TermExec`
This command allows you to open a terminal with a specific action.
e.g. `2TermExec cmd="git status" dir=~/<my-repo-path>` will run git status in terminal 2.
note that the `cmd` argument **must be quoted**.
_NOTE:_ the `dir` argument can also be _optionally_ quoted if it contains spaces.
The `cmd` and `dir` arguments can also expand the same special keywords as `:h expand` e.g.
`TermExec cmd="echo %"` will be expanded to `TermExec cmd="echo /file/example"`
These special keywords can be escaped using the `\` character, if you want to print character as is.
The `size`, `direction` and `name` arguments are like the `size`, `direction` and `name` arguments of `ToggleTerm`.
By default, focus is returned to the original window after executing the command
(except for floating terminals). Use argument `go_back=0` to disable this behaviour.
You can send commands to a terminal without opening its window by using the `open=0` argument.
see `:h expand()` for more details
### TermSelect
This command uses `vim.ui.select` to allow a user to select a terminal to open
or to focus it if it's already open. This can be useful if you have a lot of
terminals and want to open a specific one.
### Sending lines to the terminal
You can "send lines" to the toggled terminals with the following commands:
- `:ToggleTermSendCurrentLine <T_ID>`: sends the whole line where you are standing with your cursor
- `:ToggleTermSendVisualLines <T_ID>`: sends all the (whole) lines in your visual selection
- `:ToggleTermSendVisualSelection <T_ID>`: sends only the visually selected text (this can be a block of text or a selection in a single line)
(`<T_ID` is an optional terminal ID parameter, which defines where should we send the lines.
If the parameter is not provided, then the default is the `first terminal`)
Alternatively, for more fine-grained control and use in mappings, in lua:
```lua
local trim_spaces = true
vim.keymap.set("v", "<space>s", function()
require("toggleterm").send_lines_to_terminal("single_line", trim_spaces, { args = vim.v.count })
end)
-- Replace with these for the other two options
-- require("toggleterm").send_lines_to_terminal("visual_lines", trim_spaces, { args = vim.v.count })
-- require("toggleterm").send_lines_to_terminal("visual_selection", trim_spaces, { args = vim.v.count })
-- For use as an operator map:
-- Send motion to terminal
vim.keymap.set("n", [[<leader><c-\>]], function()
set_opfunc(function(motion_type)
require("toggleterm").send_lines_to_terminal(motion_type, false, { args = vim.v.count })
end)
vim.api.nvim_feedkeys("g@", "n", false)
end)
-- Double the command to send line to terminal
vim.keymap.set("n", [[<leader><c-\><c-\>]], function()
set_opfunc(function(motion_type)
require("toggleterm").send_lines_to_terminal(motion_type, false, { args = vim.v.count })
end)
vim.api.nvim_feedkeys("g@_", "n", false)
end)
-- Send whole file
vim.keymap.set("n", [[<leader><leader><c-\>]], function()
set_opfunc(function(motion_type)
require("toggleterm").send_lines_to_terminal(motion_type, false, { args = vim.v.count })
end)
vim.api.nvim_feedkeys("ggg@G''", "n", false)
end)
```
Set `trim_spaces=false` for sending to REPLs for whitespace-sensitive languages like python.
(For python, you probably want to start ipython with `ipython --no-autoindent`.)
<!-- panvimdoc-ignore-start -->
Example:
<!-- panvimdoc-ignore-end -->
<!-- panvimdoc-ignore-start -->
<video src="https://user-images.githubusercontent.com/18753533/159889865-724becab-877b-45a2-898e-820afd6a4ee1.mov" controls="controls" muted="muted" height="640px"></video>
<!-- panvimdoc-ignore-end -->
### ToggleTermSetName
This function allows setting a display name for a terminal. This name is primarily used inside the winbar, and can be a more descriptive way
to remember, which terminal is for what.
You can map this to a key and call it with a count, which will then prompt you a name for the terminal with the matching ID.
Alternatively you can call it with just the name e.g. `:ToggleTermSetName work<CR>` this will the prompt you for which terminal it should apply to.
Lastly you can call it without any arguments, and it will prompt you for which terminal it should apply to then prompt you for the name to use.
### Set terminal shading
This plugin automatically shades terminal filetypes to be darker than other window
you can disable this by setting `shade_terminals = false` in the setup object
```lua
require'toggleterm'.setup {
shade_terminals = false
}
```
alternatively you can set, _which_ filetypes should be shaded by setting
```lua
-- fzf is just an example
require'toggleterm'.setup {
shade_filetypes = { "none", "fzf" }
}
```
setting `"none"` will allow normal terminal buffers to be highlighted.
### Set persistent size
By default, this plugin will persist the size of horizontal and vertical terminals.
Split terminals in the same direction always have the same size.
You can disable this behaviour by setting `persist_size = false` in the setup object.
Disabling this behaviour forces the opening terminal size to the `size` defined in the setup object.
```lua
require'toggleterm'.setup{
persist_size = false
}
```
### Terminal window mappings
It can be helpful to add mappings to make moving in and out of a terminal easier
once toggled, whilst still keeping it open.
```lua
function _G.set_terminal_keymaps()
local opts = {buffer = 0}
vim.keymap.set('t', '<esc>', [[<C-\><C-n>]], opts)
vim.keymap.set('t', 'jk', [[<C-\><C-n>]], opts)
vim.keymap.set('t', '<C-h>', [[<Cmd>wincmd h<CR>]], opts)
vim.keymap.set('t', '<C-j>', [[<Cmd>wincmd j<CR>]], opts)
vim.keymap.set('t', '<C-k>', [[<Cmd>wincmd k<CR>]], opts)
vim.keymap.set('t', '<C-l>', [[<Cmd>wincmd l<CR>]], opts)
vim.keymap.set('t', '<C-w>', [[<C-\><C-n><C-w>]], opts)
end
-- if you only want these mappings for toggle term use term://*toggleterm#* instead
vim.cmd('autocmd! TermOpen term://* lua set_terminal_keymaps()')
```
### Custom Terminals
![lazy git](https://user-images.githubusercontent.com/22454918/116447435-e69f1480-a84f-11eb-86dd-19fa29646aa1.png)
_using [lazygit](https://github.com/jesseduffield/lazygit)_
Toggleterm also exposes the `Terminal` class so that this can be used to create custom terminals
for showing terminal UIs like `lazygit`, `htop` etc.
Each terminal can take the following arguments:
```lua
Terminal:new {
cmd = string -- command to execute when creating the terminal e.g. 'top'
display_name = string -- the name of the terminal
direction = string -- the layout for the terminal, same as the main config options
dir = string -- the directory for the terminal
close_on_exit = bool -- close the terminal window when the process exits
highlights = table -- a table with highlights
env = table -- key:value table with environmental variables passed to jobstart()
clear_env = bool -- use only environmental variables from `env`, passed to jobstart()
on_open = fun(t: Terminal) -- function to run when the terminal opens
on_close = fun(t: Terminal) -- function to run when the terminal closes
auto_scroll = boolean -- automatically scroll to the bottom on terminal output
-- callbacks for processing the output
on_stdout = fun(t: Terminal, job: number, data: string[], name: string) -- callback for processing output on stdout
on_stderr = fun(t: Terminal, job: number, data: string[], name: string) -- callback for processing output on stderr
on_exit = fun(t: Terminal, job: number, exit_code: number, name: string) -- function to run when terminal process exits
}
```
If you want to spawn a custom terminal without running any command, you can omit the `cmd` option.
#### Custom terminal usage
```lua
local Terminal = require('toggleterm.terminal').Terminal
local lazygit = Terminal:new({ cmd = "lazygit", hidden = true })
function _lazygit_toggle()
lazygit:toggle()
end
vim.api.nvim_set_keymap("n", "<leader>g", "<cmd>lua _lazygit_toggle()<CR>", {noremap = true, silent = true})
```
This will create a new terminal, but the specified command is not being run immediately.
The command will run once the terminal is opened. Alternatively `term:spawn()` can be used
to start the command in a background buffer without opening a terminal window yet. If the
`hidden` key is set to true, this terminal will not be toggled by normal toggleterm commands
such as `:ToggleTerm` or the open mapping. It will only open and close by using the returned
terminal object. A mapping for toggling the terminal can be set as in the example above.
Alternatively the terminal can be specified with a count, which is the number that can be used
to trigger this specific terminal. This can then be triggered using the current count e.g.
`:5ToggleTerm<CR>`
```lua
local lazygit = Terminal:new({ cmd = "lazygit", count = 5 })
```
You can also set a custom layout for a terminal.
```lua
local lazygit = Terminal:new({
cmd = "lazygit",
dir = "git_dir",
direction = "float",
float_opts = {
border = "double",
},
-- function to run on opening the terminal
on_open = function(term)
vim.cmd("startinsert!")
vim.api.nvim_buf_set_keymap(term.bufnr, "n", "q", "<cmd>close<CR>", {noremap = true, silent = true})
end,
-- function to run on closing the terminal
on_close = function(term)
vim.cmd("startinsert!")
end,
})
function _lazygit_toggle()
lazygit:toggle()
end
vim.api.nvim_set_keymap("n", "<leader>g", "<cmd>lua _lazygit_toggle()<CR>", {noremap = true, silent = true})
```
**WARNING**: do not use any of the private functionality of the terminal or other non-public parts of the API as these
can change in the future.
### Statusline
To tell each terminal apart you can use the terminal buffer variable `b:toggle_number`
in your statusline
```vim
" this is pseudo code
let statusline .= '%{&ft == "toggleterm" ? "terminal (".b:toggle_number.")" : ""}'
```
### Custom commands
You can create your own commands by using the lua functions this plugin provides directly
```vim
command! -count=1 TermGitPush lua require'toggleterm'.exec("git push", <count>, 12)
command! -count=1 TermGitPushF lua require'toggleterm'.exec("git push -f", <count>, 12)
```
### Open multiple terminals side-by-side
| Direction | Supported |
| ---------- | --------- |
| vertical | ✔️ |
| horizontal | ✔️ |
| tab | ✖️ |
| float | ✖️ |
In your first terminal, you need to leave the `TERMINAL` mode using <kbd>C-\\</kbd><kbd>C-N</kbd> which can be remapped to <kbd>Esc</kbd> for ease of use.
![image](https://user-images.githubusercontent.com/31947091/133395516-22fef1e6-633d-4964-9175-f76fabf66794.png)
Then you type on: `2<C-\>`, and the result:
![image](https://user-images.githubusercontent.com/31947091/133396789-fdf68b30-3a8c-440b-822f-6549f282c4fc.png)
Explain:
- `2`: this is the terminal's number (or ID), your first terminal is `1` (e.g. your 3rd terminal will be `3<C-\>`, so on).
- <kbd>C-\\</kbd>: this is the combined key mapping to the command `:ToggleTerm`.
### FAQ
#### How do I get this plugin to work with Powershell?
Please check out the [Wiki section on this topic](https://github.com/akinsho/toggleterm.nvim/wiki/Tips-and-Tricks#using-toggleterm-with-powershell).

View File

@ -0,0 +1,9 @@
almost toggleterm.txt /*almost*
toggleterm-installation toggleterm.txt /*toggleterm-installation*
toggleterm-links toggleterm.txt /*toggleterm-links*
toggleterm-notices toggleterm.txt /*toggleterm-notices*
toggleterm-requirements toggleterm.txt /*toggleterm-requirements*
toggleterm-roadmap toggleterm.txt /*toggleterm-roadmap*
toggleterm-table-of-contents toggleterm.txt /*toggleterm-table-of-contents*
toggleterm-why? toggleterm.txt /*toggleterm-why?*
toggleterm.txt toggleterm.txt /*toggleterm.txt*

View File

@ -0,0 +1,575 @@
*toggleterm.txt* For Neovim >= 0.8.0 Last change: 2024 May 19
==============================================================================
Table of Contents *toggleterm-table-of-contents*
- Requirements |toggleterm-requirements|
- Installation |toggleterm-installation|
- Notices |toggleterm-notices|
- Why? |toggleterm-why?|
- Roadmap |toggleterm-roadmap|
1. Links |toggleterm-links|
MULTIPLE ORIENTATIONS ~
- **Float**
- **Vertical**
- **Tab**
SEND COMMANDS TO DIFFERENT TERMINALS ~
WINBAR (EXPERIMENTAL/NIGHTLY ONLY) ~
REQUIREMENTS *toggleterm-requirements*
This plugin only works in _Neovim 0.7_ or newer.
INSTALLATION *toggleterm-installation*
Using packer <https://github.com/wbthomason/packer.nvim> in lua
>lua
use {"akinsho/toggleterm.nvim", tag = '*', config = function()
require("toggleterm").setup()
end}
<
Using lazy.nvim <https://github.com/folke/lazy.nvim> in lua
>lua
{
-- amongst your other plugins
{'akinsho/toggleterm.nvim', version = "*", config = true}
-- or
{'akinsho/toggleterm.nvim', version = "*", opts = {--[[ things you want to change go here]]}}
}
<
Using vim-plug <https://github.com/junegunn/vim-plug> in vimscript
>vim
Plug 'akinsho/toggleterm.nvim', {'tag' : '*'}
lua require("toggleterm").setup()
<
You can/should specify a tag for the current major version of the plugin, to
avoid breaking changes as this plugin evolves. To use a version of this plugin
compatible with nvim versions less than 0.7 please use the tag `v1.*`.
NOTICES *toggleterm-notices*
- **28/07/1990** — If using `persist_mode` terminal mappings should be changed to use `wincmd` instead otherwise persist mode will not work correctly. See |toggleterm-here| for details.
WHY? *toggleterm-why?*
Neovims terminal is a very cool, but not super ergonomic tool to use. I find
that I often want to set a process going and leave it to continue to run in the
background. I dont need to see it all the time. I just need to be able to
refer back to it at intervals. I also sometimes want to create a new terminal
and run a few commands.
Sometimes I want these side by side, and I _really_ want these terminals to be
easy to access. I also want my terminal to look different from non-terminal
buffers, so I use `winhighlight` to darken them based on the `Normal`
background colour.
This is the exact use case this was designed for. If thats your use case
this might work for you.
ROADMAP *toggleterm-roadmap*
All I really want this plugin to be is what I described above. A wrapper around
the terminal functionality.
It basically (almost) does all that I need it to.
I wont be turning this into a REPL plugin or doing a bunch of complex stuff.
If you find any issues, _please_ consider a _pull request_ not an issue. Im
also going to be pretty conservative about what I add.
SETUP ~
This plugin must be explicitly enabled by using `require("toggleterm").setup{}`
Setting the `open_mapping` key to use for toggling the terminal(s) will set up
mappings for _normal_ mode. The `open_mapping` can be a key string or an array
of key strings. If you prefix the mapping with a number that particular
terminal will be opened. Otherwise if a prefix is not set, then the last
toggled terminal will be opened. In case there are multiple terminals opened
theyll all be closed, and on the next mapping key theyll be restored.
If you set the `insert_mappings` key to `true`, the mapping will also take
effect in insert mode; similarly setting `terminal_mappings` to `true` will
have the mappings take effect in the opened terminal.
However you will not be able to use a count with the open mapping in terminal
and insert modes. You can create buffer specific mappings to exit terminal mode
and then use a count with the open mapping. Check _Terminal window mappings_
for an example of how to do this.
alternatively you can do this manually (not recommended but, your prerogative)
>vim
" set
autocmd TermEnter term://*toggleterm#*
\ tnoremap <silent><c-t> <Cmd>exe v:count1 . "ToggleTerm"<CR>
" By applying the mappings this way you can pass a count to your
" mapping to open a specific window.
" For example: 2<C-t> will open terminal 2
nnoremap <silent><c-t> <Cmd>exe v:count1 . "ToggleTerm"<CR>
inoremap <silent><c-t> <Esc><Cmd>exe v:count1 . "ToggleTerm"<CR>
<
**NOTE**Please ensure you have set `hidden` in your neovim config, otherwise
the terminals will be discarded when closed.
**WARNING**Please do not copy and paste this configuration! It is here to show
what options are available. It is not written to be used as is.
>lua
require("toggleterm").setup{
-- size can be a number or function which is passed the current terminal
size = 20 | function(term)
if term.direction == "horizontal" then
return 15
elseif term.direction == "vertical" then
return vim.o.columns * 0.4
end
end,
open_mapping = [[<c-\>]], -- or { [[<c-\>]], [[<c-¥>]] } if you also use a Japanese keyboard.
on_create = fun(t: Terminal), -- function to run when the terminal is first created
on_open = fun(t: Terminal), -- function to run when the terminal opens
on_close = fun(t: Terminal), -- function to run when the terminal closes
on_stdout = fun(t: Terminal, job: number, data: string[], name: string) -- callback for processing output on stdout
on_stderr = fun(t: Terminal, job: number, data: string[], name: string) -- callback for processing output on stderr
on_exit = fun(t: Terminal, job: number, exit_code: number, name: string) -- function to run when terminal process exits
hide_numbers = true, -- hide the number column in toggleterm buffers
shade_filetypes = {},
autochdir = false, -- when neovim changes it current directory the terminal will change it's own when next it's opened
highlights = {
-- highlights which map to a highlight group name and a table of it's values
-- NOTE: this is only a subset of values, any group placed here will be set for the terminal window split
Normal = {
guibg = "<VALUE-HERE>",
},
NormalFloat = {
link = 'Normal'
},
FloatBorder = {
guifg = "<VALUE-HERE>",
guibg = "<VALUE-HERE>",
},
},
shade_terminals = true, -- NOTE: this option takes priority over highlights specified so if you specify Normal highlights you should set this to false
shading_factor = '<number>', -- the percentage by which to lighten terminal background, default: -30 (gets multiplied by -3 if background is light)
start_in_insert = true,
insert_mappings = true, -- whether or not the open mapping applies in insert mode
terminal_mappings = true, -- whether or not the open mapping applies in the opened terminals
persist_size = true,
persist_mode = true, -- if set to true (default) the previous terminal mode will be remembered
direction = 'vertical' | 'horizontal' | 'tab' | 'float',
close_on_exit = true, -- close the terminal window when the process exits
-- Change the default shell. Can be a string or a function returning a string
shell = vim.o.shell,
auto_scroll = true, -- automatically scroll to the bottom on terminal output
-- This field is only relevant if direction is set to 'float'
float_opts = {
-- The border key is *almost* the same as 'nvim_open_win'
-- see :h nvim_open_win for details on borders however
-- the 'curved' border is a custom border type
-- not natively supported but implemented in this plugin.
border = 'single' | 'double' | 'shadow' | 'curved' | ... other options supported by win open
-- like `size`, width, height, row, and col can be a number or function which is passed the current terminal
width = <value>,
height = <value>,
row = <value>,
col = <value>,
winblend = 3,
zindex = <value>,
title_pos = 'left' | 'center' | 'right', position of the title of the floating window
},
winbar = {
enabled = false,
name_formatter = function(term) -- term: Terminal
return term.name
end
},
}
<
USAGE ~
TOGGLETERM ~
This is the command the mappings call under the hood. You can use it directly
and prefix it with a count to target a specific terminal. This function also
takes arguments `size`, `dir`, `direction` and `name`. e.g.
>vim
:ToggleTerm size=40 dir=~/Desktop direction=horizontal name=desktop
<
If `dir` is specified on creation toggle term will open at the specified
directory. If the terminal has already been opened at a particular directory it
will remain in that directory.
The directory can also be specified as `git_dir` which toggleterm will then use
to try and derive the git repo directory. _NOTE_This will not work for
`git-worktrees` or other more complex setups.
If `size` is specified, and the command opens a split (horizontal/vertical)
terminal, the height/width of all terminals in the same direction will be
changed to `size`.
If `direction` is specified, and the command opens a terminal, the terminal
will be changed to the specified direction.
If `name` is specified, the display name is set for the toggled terminal. This
name will be visible when using `TermSelect` command to indicate the specific
terminal.
`size` and `direction` are ignored if the command closes a terminal.
CAVEATS
- Having multiple terminals with different directions open at the same time is unsupported.
TOGGLETERMTOGGLEALL ~
This command allows you to open all the previously toggled terminal in one go
or close all the open terminals at once.
TERMEXEC ~
This command allows you to open a terminal with a specific action.
e.g. `2TermExec cmd="git status" dir=~/<my-repo-path>` will run git status in
terminal 2. note that the `cmd` argument **must be quoted**.
_NOTE:_ the `dir` argument can also be _optionally_ quoted if it contains
spaces.
The `cmd` and `dir` arguments can also expand the same special keywords as
|expand| e.g. `TermExec cmd="echo %"` will be expanded to `TermExec cmd="echo
/file/example"`
These special keywords can be escaped using the `\` character, if you want to
print character as is.
The `size`, `direction` and `name` arguments are like the `size`, `direction`
and `name` arguments of `ToggleTerm`.
By default, focus is returned to the original window after executing the
command (except for floating terminals). Use argument `go_back=0` to disable
this behaviour.
You can send commands to a terminal without opening its window by using the
`open=0` argument.
see |expand()| for more details
TERMSELECT ~
This command uses `vim.ui.select` to allow a user to select a terminal to open
or to focus it if its already open. This can be useful if you have a lot of
terminals and want to open a specific one.
SENDING LINES TO THE TERMINAL ~
You can "send lines" to the toggled terminals with the following commands:
- `:ToggleTermSendCurrentLine <T_ID>`sends the whole line where you are standing with your cursor
- `:ToggleTermSendVisualLines <T_ID>`sends all the (whole) lines in your visual selection
- `:ToggleTermSendVisualSelection <T_ID>`sends only the visually selected text (this can be a block of text or a selection in a single line)
(`<T_ID` is an optional terminal ID parameter, which defines where should we
send the lines. If the parameter is not provided, then the default is the
`first terminal`)
Alternatively, for more fine-grained control and use in mappings, in lua:
>lua
local trim_spaces = true
vim.keymap.set("v", "<space>s", function()
require("toggleterm").send_lines_to_terminal("single_line", trim_spaces, { args = vim.v.count })
end)
-- Replace with these for the other two options
-- require("toggleterm").send_lines_to_terminal("visual_lines", trim_spaces, { args = vim.v.count })
-- require("toggleterm").send_lines_to_terminal("visual_selection", trim_spaces, { args = vim.v.count })
-- For use as an operator map:
-- Send motion to terminal
vim.keymap.set("n", [[<leader><c-\>]], function()
set_opfunc(function(motion_type)
require("toggleterm").send_lines_to_terminal(motion_type, false, { args = vim.v.count })
end)
vim.api.nvim_feedkeys("g@", "n", false)
end)
-- Double the command to send line to terminal
vim.keymap.set("n", [[<leader><c-\><c-\>]], function()
set_opfunc(function(motion_type)
require("toggleterm").send_lines_to_terminal(motion_type, false, { args = vim.v.count })
end)
vim.api.nvim_feedkeys("g@_", "n", false)
end)
-- Send whole file
vim.keymap.set("n", [[<leader><leader><c-\>]], function()
set_opfunc(function(motion_type)
require("toggleterm").send_lines_to_terminal(motion_type, false, { args = vim.v.count })
end)
vim.api.nvim_feedkeys("ggg@G''", "n", false)
end)
<
Set `trim_spaces=false` for sending to REPLs for whitespace-sensitive languages
like python. (For python, you probably want to start ipython with `ipython
--no-autoindent`.)
TOGGLETERMSETNAME ~
This function allows setting a display name for a terminal. This name is
primarily used inside the winbar, and can be a more descriptive way to
remember, which terminal is for what.
You can map this to a key and call it with a count, which will then prompt you
a name for the terminal with the matching ID. Alternatively you can call it
with just the name e.g. `:ToggleTermSetName work<CR>` this will the prompt you
for which terminal it should apply to. Lastly you can call it without any
arguments, and it will prompt you for which terminal it should apply to then
prompt you for the name to use.
SET TERMINAL SHADING ~
This plugin automatically shades terminal filetypes to be darker than other
window you can disable this by setting `shade_terminals = false` in the setup
object
>lua
require'toggleterm'.setup {
shade_terminals = false
}
<
alternatively you can set, _which_ filetypes should be shaded by setting
>lua
-- fzf is just an example
require'toggleterm'.setup {
shade_filetypes = { "none", "fzf" }
}
<
setting `"none"` will allow normal terminal buffers to be highlighted.
SET PERSISTENT SIZE ~
By default, this plugin will persist the size of horizontal and vertical
terminals. Split terminals in the same direction always have the same size. You
can disable this behaviour by setting `persist_size = false` in the setup
object. Disabling this behaviour forces the opening terminal size to the `size`
defined in the setup object.
>lua
require'toggleterm'.setup{
persist_size = false
}
<
TERMINAL WINDOW MAPPINGS ~
It can be helpful to add mappings to make moving in and out of a terminal
easier once toggled, whilst still keeping it open.
>lua
function _G.set_terminal_keymaps()
local opts = {buffer = 0}
vim.keymap.set('t', '<esc>', [[<C-\><C-n>]], opts)
vim.keymap.set('t', 'jk', [[<C-\><C-n>]], opts)
vim.keymap.set('t', '<C-h>', [[<Cmd>wincmd h<CR>]], opts)
vim.keymap.set('t', '<C-j>', [[<Cmd>wincmd j<CR>]], opts)
vim.keymap.set('t', '<C-k>', [[<Cmd>wincmd k<CR>]], opts)
vim.keymap.set('t', '<C-l>', [[<Cmd>wincmd l<CR>]], opts)
vim.keymap.set('t', '<C-w>', [[<C-\><C-n><C-w>]], opts)
end
-- if you only want these mappings for toggle term use term://*toggleterm#* instead
vim.cmd('autocmd! TermOpen term://* lua set_terminal_keymaps()')
<
CUSTOM TERMINALS ~
_using lazygit_
Toggleterm also exposes the `Terminal` class so that this can be used to create
custom terminals for showing terminal UIs like `lazygit`, `htop` etc.
Each terminal can take the following arguments:
>lua
Terminal:new {
cmd = string -- command to execute when creating the terminal e.g. 'top'
display_name = string -- the name of the terminal
direction = string -- the layout for the terminal, same as the main config options
dir = string -- the directory for the terminal
close_on_exit = bool -- close the terminal window when the process exits
highlights = table -- a table with highlights
env = table -- key:value table with environmental variables passed to jobstart()
clear_env = bool -- use only environmental variables from `env`, passed to jobstart()
on_open = fun(t: Terminal) -- function to run when the terminal opens
on_close = fun(t: Terminal) -- function to run when the terminal closes
auto_scroll = boolean -- automatically scroll to the bottom on terminal output
-- callbacks for processing the output
on_stdout = fun(t: Terminal, job: number, data: string[], name: string) -- callback for processing output on stdout
on_stderr = fun(t: Terminal, job: number, data: string[], name: string) -- callback for processing output on stderr
on_exit = fun(t: Terminal, job: number, exit_code: number, name: string) -- function to run when terminal process exits
}
<
If you want to spawn a custom terminal without running any command, you can
omit the `cmd` option.
CUSTOM TERMINAL USAGE
>lua
local Terminal = require('toggleterm.terminal').Terminal
local lazygit = Terminal:new({ cmd = "lazygit", hidden = true })
function _lazygit_toggle()
lazygit:toggle()
end
vim.api.nvim_set_keymap("n", "<leader>g", "<cmd>lua _lazygit_toggle()<CR>", {noremap = true, silent = true})
<
This will create a new terminal, but the specified command is not being run
immediately. The command will run once the terminal is opened. Alternatively
`term:spawn()` can be used to start the command in a background buffer without
opening a terminal window yet. If the `hidden` key is set to true, this
terminal will not be toggled by normal toggleterm commands such as
`:ToggleTerm` or the open mapping. It will only open and close by using the
returned terminal object. A mapping for toggling the terminal can be set as in
the example above.
Alternatively the terminal can be specified with a count, which is the number
that can be used to trigger this specific terminal. This can then be triggered
using the current count e.g. `:5ToggleTerm<CR>`
>lua
local lazygit = Terminal:new({ cmd = "lazygit", count = 5 })
<
You can also set a custom layout for a terminal.
>lua
local lazygit = Terminal:new({
cmd = "lazygit",
dir = "git_dir",
direction = "float",
float_opts = {
border = "double",
},
-- function to run on opening the terminal
on_open = function(term)
vim.cmd("startinsert!")
vim.api.nvim_buf_set_keymap(term.bufnr, "n", "q", "<cmd>close<CR>", {noremap = true, silent = true})
end,
-- function to run on closing the terminal
on_close = function(term)
vim.cmd("startinsert!")
end,
})
function _lazygit_toggle()
lazygit:toggle()
end
vim.api.nvim_set_keymap("n", "<leader>g", "<cmd>lua _lazygit_toggle()<CR>", {noremap = true, silent = true})
<
**WARNING**do not use any of the private functionality of the terminal or other
non-public parts of the API as these can change in the future.
STATUSLINE ~
To tell each terminal apart you can use the terminal buffer variable
`b:toggle_number` in your statusline
>vim
" this is pseudo code
let statusline .= '%{&ft == "toggleterm" ? "terminal (".b:toggle_number.")" : ""}'
<
CUSTOM COMMANDS ~
You can create your own commands by using the lua functions this plugin
provides directly
>vim
command! -count=1 TermGitPush lua require'toggleterm'.exec("git push", <count>, 12)
command! -count=1 TermGitPushF lua require'toggleterm'.exec("git push -f", <count>, 12)
<
OPEN MULTIPLE TERMINALS SIDE-BY-SIDE ~
Direction Supported
------------ -----------
vertical
horizontal
tab
float
Inyour first terminal, you need to leave the `TERMINAL` mode using C-\C-N which
can be remapped to Esc for ease of use.
Then you type on: `2<C-\>`, and the result:
Explain:
- `2`this is the terminals number (or ID), your first terminal is `1` (e.g. your 3rd terminal will be `3<C-\>`, so on).
- C-\this is the combined key mapping to the command `:ToggleTerm`.
FAQ ~
HOW DO I GET THIS PLUGIN TO WORK WITH POWERSHELL?
Please check out the Wiki section on this topic
<https://github.com/akinsho/toggleterm.nvim/wiki/Tips-and-Tricks#using-toggleterm-with-powershell>.
==============================================================================
1. Links *toggleterm-links*
1. *lazy git*: https://user-images.githubusercontent.com/22454918/116447435-e69f1480-a84f-11eb-86dd-19fa29646aa1.png
2. *image*: https://user-images.githubusercontent.com/31947091/133395516-22fef1e6-633d-4964-9175-f76fabf66794.png
3. *image*: https://user-images.githubusercontent.com/31947091/133396789-fdf68b30-3a8c-440b-822f-6549f282c4fc.png
Generated by panvimdoc <https://github.com/kdheepak/panvimdoc>
vim:tw=78:ts=8:noet:ft=help:norl:

View File

@ -0,0 +1,475 @@
local api = vim.api
local fn = vim.fn
local lazy = require("toggleterm.lazy")
---@module "toggleterm.utils"
local utils = lazy.require("toggleterm.utils")
---@module "toggleterm.constants"
local constants = require("toggleterm.constants")
---@module "toggleterm.config"
local config = lazy.require("toggleterm.config")
---@module "toggleterm.ui"
local ui = lazy.require("toggleterm.ui")
---@module "toggleterm.commandline"
local commandline = lazy.require("toggleterm.commandline")
local terms = require("toggleterm.terminal")
local AUGROUP = "ToggleTermCommands"
-----------------------------------------------------------
-- Export
-----------------------------------------------------------
local M = {}
--- only shade explicitly specified filetypes
local function apply_colors()
local ft = vim.bo.filetype
ft = (not ft or ft == "") and "none" or ft
local allow_list = config.shade_filetypes or {}
local is_enabled_ft = vim.tbl_contains(allow_list, ft)
if vim.bo.buftype == "terminal" and is_enabled_ft then
local _, term = terms.identify()
ui.hl_term(term)
end
end
local function setup_global_mappings()
local mapping = config.open_mapping
-- v:count defaults the count to 0 but if a count is passed in uses that instead
if mapping then
utils.key_map("n", mapping, '<Cmd>execute v:count . "ToggleTerm"<CR>', {
desc = "Toggle Terminal",
silent = true,
})
if config.insert_mappings then
utils.key_map("i", mapping, "<Esc><Cmd>ToggleTerm<CR>", {
desc = "Toggle Terminal",
silent = true,
})
end
end
end
-- Creates a new terminal if none are present or closes terminals that are
-- currently opened, or opens terminals that were previously closed.
---@param size number?
---@param dir string?
---@param direction string?
---@param name string?
local function smart_toggle(size, dir, direction, name)
local has_open, windows = ui.find_open_windows()
if not has_open then
if not ui.open_terminal_view(size, direction) then
local term_id = terms.get_toggled_id()
terms.get_or_create_term(term_id, dir, direction, name):open(size, direction)
end
else
ui.close_and_save_terminal_view(windows)
end
end
--- @param num number
--- @param size number?
--- @param dir string?
--- @param direction string?
--- @param name string?
local function toggle_nth_term(num, size, dir, direction, name)
local term = terms.get_or_create_term(num, dir, direction, name)
ui.update_origin_window(term.window)
term:toggle(size, direction)
-- Save the terminal in view if it was last closed terminal.
if not ui.find_open_windows() then ui.save_terminal_view({ term.id }, term.id) end
end
---Close the last window if only a terminal *split* is open
---@param term Terminal
---@return boolean
local function close_last_window(term)
local only_one_window = fn.winnr("$") == 1
if only_one_window and vim.bo[term.bufnr].filetype == constants.FILETYPE then
if term:is_split() then
local has_next = pcall(vim.cmd, "keepalt bnext")
return has_next
end
end
return false
end
local function handle_term_enter()
local _, term = terms.identify()
if term then
--- FIXME: we have to reset the filetype here because it is reset by other plugins
--- i.e. telescope.nvim
if vim.bo[term.bufnr] ~= constants.FILETYPE then term:__set_ft_options() end
local closed = close_last_window(term)
if closed then return end
if config.persist_mode then
term:__restore_mode()
elseif config.start_in_insert then
term:set_mode(terms.mode.INSERT)
end
end
end
local function handle_term_leave()
local _, term = terms.identify()
if not term then return end
if config.persist_mode then term:persist_mode() end
if term:is_float() then term:close() end
end
local function on_term_open()
local id, term = terms.identify()
if not term then
local buf = api.nvim_get_current_buf()
terms.Terminal
:new({
id = id,
bufnr = buf,
window = api.nvim_get_current_win(),
highlights = config.highlights,
job_id = vim.b[buf].terminal_job_id,
direction = ui.guess_direction(),
})
:__resurrect()
end
ui.set_winbar(term)
end
function M.exec_command(args, count)
vim.validate({ args = { args, "string" } })
if not args:match("cmd") then
return utils.notify(
"TermExec requires a cmd specified using the syntax cmd='ls -l' e.g. TermExec cmd='ls -l'",
"error"
)
end
local parsed = require("toggleterm.commandline").parse(args)
vim.validate({
cmd = { parsed.cmd, "string" },
size = { parsed.size, "number", true },
dir = { parsed.dir, "string", true },
direction = { parsed.direction, "string", true },
name = { parsed.name, "string", true },
go_back = { parsed.go_back, "boolean", true },
open = { parsed.open, "boolean", true },
})
M.exec(
parsed.cmd,
count,
parsed.size,
parsed.dir,
parsed.direction,
parsed.name,
parsed.go_back,
parsed.open
)
end
--- @param cmd string
--- @param num number?
--- @param size number?
--- @param dir string?
--- @param direction string?
--- @param name string?
--- @param go_back boolean? whether or not to return to original window
--- @param open boolean? whether or not to open terminal window
function M.exec(cmd, num, size, dir, direction, name, go_back, open)
vim.validate({
cmd = { cmd, "string" },
num = { num, "number", true },
size = { size, "number", true },
dir = { dir, "string", true },
direction = { direction, "string", true },
name = { name, "string", true },
go_back = { go_back, "boolean", true },
open = { open, "boolean", true },
})
num = (num and num >= 1) and num or terms.get_toggled_id()
open = open == nil or open
local term = terms.get_or_create_term(num, dir, direction, name)
if not term:is_open() then term:open(size, direction) end
-- going back from floating window closes it
if term:is_float() then go_back = false end
if go_back == nil then go_back = true end
if not open then
term:close()
go_back = false
end
term:send(cmd, go_back)
end
--- @param selection_type string
--- @param trim_spaces boolean
--- @param cmd_data table<string, any>
function M.send_lines_to_terminal(selection_type, trim_spaces, cmd_data)
local id = tonumber(cmd_data.args) or 1
trim_spaces = trim_spaces == nil or trim_spaces
vim.validate({
selection_type = { selection_type, "string", true },
trim_spaces = { trim_spaces, "boolean", true },
terminal_id = { id, "number", true },
})
local current_window = api.nvim_get_current_win() -- save current window
local lines = {}
-- Beginning of the selection: line number, column number
local start_line, start_col
if selection_type == "single_line" then
start_line, start_col = unpack(api.nvim_win_get_cursor(0))
-- nvim_win_get_cursor uses 0-based indexing for columns, while we use 1-based indexing
start_col = start_col + 1
table.insert(lines, fn.getline(start_line))
else
local res = nil
if string.match(selection_type, "visual") then
-- This calls vim.fn.getpos, which uses 1-based indexing for columns
res = utils.get_line_selection("visual")
else
-- This calls vim.fn.getpos, which uses 1-based indexing for columns
res = utils.get_line_selection("motion")
end
start_line, start_col = unpack(res.start_pos)
-- char, line and block are used for motion/operatorfunc. 'block' is ignored
if selection_type == "visual_lines" or selection_type == "line" then
lines = res.selected_lines
elseif selection_type == "visual_selection" or selection_type == "char" then
lines = utils.get_visual_selection(res, true)
end
end
if not lines or not next(lines) then return end
if not trim_spaces then
M.exec(table.concat(lines, "\n"), id)
else
for _, line in ipairs(lines) do
local l = trim_spaces and line:gsub("^%s+", ""):gsub("%s+$", "") or line
M.exec(l, id)
end
end
-- Jump back with the cursor where we were at the beginning of the selection
api.nvim_set_current_win(current_window)
-- nvim_win_set_cursor() uses 0-based indexing for columns, while we use 1-based indexing
api.nvim_win_set_cursor(current_window, { start_line, start_col - 1 })
end
function M.toggle_command(args, count)
local parsed = commandline.parse(args)
vim.validate({
size = { parsed.size, "number", true },
dir = { parsed.dir, "string", true },
direction = { parsed.direction, "string", true },
name = { parsed.name, "string", true },
})
if parsed.size then parsed.size = tonumber(parsed.size) end
M.toggle(count, parsed.size, parsed.dir, parsed.direction, parsed.name)
end
function _G.___toggleterm_winbar_click(id)
if id then
local term = terms.get_or_create_term(id)
if not term then return end
term:toggle()
end
end
--- If a count is provided we operate on the specific terminal buffer
--- i.e. 2ToggleTerm => open or close Term 2
--- if the count is 1 we use a heuristic which is as follows
--- if there is no open terminal window we toggle the first one i.e. assumed
--- to be the primary. However if several are open we close them.
--- this can be used with the count commands to allow specific operations
--- per term or mass actions
--- @param count number?
--- @param size number?
--- @param dir string?
--- @param direction string?
--- @param name string?
function M.toggle(count, size, dir, direction, name)
if count and count >= 1 then
toggle_nth_term(count, size, dir, direction, name)
else
smart_toggle(size, dir, direction, name)
end
end
-- Toggle all terminals
-- If any terminal is open it will be closed
-- If no terminal exists it will do nothing
-- If any terminal exists but is not open it will be open
function M.toggle_all(force)
local terminals = terms.get_all()
if force and ui.find_open_windows() then
for _, term in pairs(terminals) do
term:close()
end
else
if not ui.find_open_windows() then
for _, term in pairs(terminals) do
term:open()
end
else
for _, term in pairs(terminals) do
term:close()
end
end
end
end
---@param _ ToggleTermConfig
local function setup_autocommands(_)
api.nvim_create_augroup(AUGROUP, { clear = true })
local toggleterm_pattern = { "term://*#toggleterm#*", "term://*::toggleterm::*" }
api.nvim_create_autocmd("BufEnter", {
pattern = toggleterm_pattern,
group = AUGROUP,
nested = true, -- this is necessary in case the buffer is the last
callback = handle_term_enter,
})
api.nvim_create_autocmd("WinLeave", {
pattern = toggleterm_pattern,
group = AUGROUP,
callback = handle_term_leave,
})
api.nvim_create_autocmd("TermOpen", {
pattern = toggleterm_pattern,
group = AUGROUP,
callback = on_term_open,
})
api.nvim_create_autocmd("ColorScheme", {
group = AUGROUP,
callback = function()
config.reset_highlights()
for _, term in pairs(terms.get_all()) do
if api.nvim_win_is_valid(term.window) then
api.nvim_win_call(term.window, function() ui.hl_term(term) end)
end
end
end,
})
api.nvim_create_autocmd("TermOpen", {
group = AUGROUP,
pattern = "term://*",
callback = apply_colors,
})
end
---------------------------------------------------------------------------------
-- Commands
---------------------------------------------------------------------------------
---@param callback fun(t: Terminal?)
local function get_subject_terminal(callback)
local items = terms.get_all(true)
if #items == 0 then return utils.notify("No toggleterms are open yet") end
vim.ui.select(items, {
prompt = "Please select a terminal to name: ",
format_item = function(term) return term.id .. ": " .. term:_display_name() end,
}, function(term)
if not term then return end
callback(term)
end)
end
---@param name string
---@param term Terminal
local function set_term_name(name, term) term.display_name = name end
local function request_term_name(term)
vim.ui.input({ prompt = "Please set a name for the terminal" }, function(name)
if name and #name > 0 then set_term_name(name, term) end
end)
end
local function select_terminal(opts)
local terminals = terms.get_all(opts.bang)
if #terminals == 0 then return utils.notify("No toggleterms are open yet", "info") end
vim.ui.select(terminals, {
prompt = "Please select a terminal to open (or focus): ",
format_item = function(term) return term.id .. ": " .. term:_display_name() end,
}, function(_, idx)
local term = terminals[idx]
if not term then return end
if term:is_open() then
term:focus()
else
term:open()
end
end)
end
local function setup_commands()
local command = api.nvim_create_user_command
command("TermSelect", select_terminal, { bang = true })
-- Count is 0 by default
command(
"TermExec",
function(opts) M.exec_command(opts.args, opts.count) end,
{ count = true, complete = commandline.term_exec_complete, nargs = "*" }
)
command(
"ToggleTerm",
function(opts) M.toggle_command(opts.args, opts.count) end,
{ count = true, complete = commandline.toggle_term_complete, nargs = "*" }
)
command("ToggleTermToggleAll", function(opts) M.toggle_all(opts.bang) end, { bang = true })
command(
"ToggleTermSendVisualLines",
function(args) M.send_lines_to_terminal("visual_lines", true, args) end,
{ range = true, nargs = "?" }
)
command(
"ToggleTermSendVisualSelection",
function(args) M.send_lines_to_terminal("visual_selection", true, args) end,
{ range = true, nargs = "?" }
)
command(
"ToggleTermSendCurrentLine",
function(args) M.send_lines_to_terminal("single_line", true, args) end,
{ nargs = "?" }
)
command("ToggleTermSetName", function(opts)
local no_count = not opts.count or opts.count < 1
local no_name = opts.args == ""
if no_count and no_name then
get_subject_terminal(request_term_name)
elseif no_name then
local term = terms.get(opts.count)
if not term then return end
request_term_name(term)
elseif no_count then
get_subject_terminal(function(t) set_term_name(opts.args, t) end)
else
local term = terms.get(opts.count)
if not term then return end
set_term_name(opts.args, term)
end
end, { nargs = "?", count = true })
end
function M.setup(user_prefs)
local conf = config.set(user_prefs)
setup_global_mappings()
setup_autocommands(conf)
setup_commands()
end
return M

View File

@ -0,0 +1,117 @@
local api = vim.api
local bit = require("bit")
-----------------------------------------------------------
-- Export
-----------------------------------------------------------
local M = {}
-----------------------------------------------------------
-- Helpers
-----------------------------------------------------------
---Convert a hex color to an rgb color
---@param color string
---@return number
---@return number
---@return number
local function to_rgb(color)
return tonumber(color:sub(2, 3), 16), tonumber(color:sub(4, 5), 16), tonumber(color:sub(6), 16)
end
-- SOURCE: https://stackoverflow.com/questions/5560248/programmatically-lighten-or-darken-a-hex-color-or-rgb-and-blend-colors
-- @see: https://stackoverflow.com/questions/37796287/convert-decimal-to-hex-in-lua-4
--- Shade Color generate
--- @param color string hex color
--- @param percent number
--- @return string
function M.shade_color(color, percent)
local r, g, b = to_rgb(color)
-- If any of the colors are missing return "NONE" i.e. no highlight
if not r or not g or not b then return "NONE" end
r = math.floor(tonumber(r * (100 + percent) / 100) or 0)
g = math.floor(tonumber(g * (100 + percent) / 100) or 0)
b = math.floor(tonumber(b * (100 + percent) / 100) or 0)
r, g, b = r < 255 and r or 255, g < 255 and g or 255, b < 255 and b or 255
return "#" .. string.format("%02x%02x%02x", r, g, b)
end
--- Determine whether to use black or white text
--- Ref:
--- 1. https://stackoverflow.com/a/1855903/837964
--- 2. https://stackoverflow.com/a/596243
function M.color_is_bright(hex)
if not hex then return false end
local r, g, b = to_rgb(hex)
-- If any of the colors are missing return false
if not r or not g or not b then return false end
-- Counting the perceptive luminance - human eye favors green color
local luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255
-- If luminance is > 0.5 -> Bright colors, black font else Dark colors, white font
return luminance > 0.5
end
--- Get hex color
---@param name string highlight group name
---@param attr string attr name 'bg', 'fg'
---@return string
function M.get_hex(name, attr)
local ok, hl = pcall(api.nvim_get_hl_by_name, name, true)
if not ok then return "NONE" end
hl.foreground = hl.foreground and "#" .. bit.tohex(hl.foreground, 6)
hl.background = hl.background and "#" .. bit.tohex(hl.background, 6)
attr = ({ bg = "background", fg = "foreground" })[attr] or attr
return hl[attr] or "NONE"
end
--- Check if background is bright
--- @return boolean
function M.is_bright_background()
local bg_color = M.get_hex("Normal", "bg")
return M.color_is_bright(bg_color)
end
-----------------------------------------------------------
-- Darken Terminal
-----------------------------------------------------------
local function convert_attributes(result, key, value)
local target = result
if key == "cterm" then
result.cterm = {}
target = result.cterm
end
if value:find(",") then
for _, v in vim.split(value, ",") do
target[v] = true
end
else
target[value] = true
end
end
local function convert_options(opts)
local keys = {
gui = true,
guifg = "foreground",
guibg = "background",
guisp = "sp",
cterm = "cterm",
ctermfg = "ctermfg",
ctermbg = "ctermbg",
link = "link",
}
local result = {}
for key, value in pairs(opts) do
if keys[key] then
if key == "gui" or key == "cterm" then
if value ~= "NONE" then convert_attributes(result, key, value) end
else
result[keys[key]] = value
end
end
end
return result
end
function M.set_hl(name, opts) api.nvim_set_hl(0, name, convert_options(opts)) end
return M

View File

@ -0,0 +1,198 @@
local fn = vim.fn
local u = require("toggleterm.utils")
local M = {}
local p = {
single = "'(.-)'",
double = '"(.-)"',
}
local is_windows = vim.loop.os_uname().version:match("Windows")
---@class ParsedArgs
---@field direction string?
---@field cmd string?
---@field dir string?
---@field size number?
---@field name string?
---@field go_back boolean?
---@field open boolean?
---Take a users command arguments in the format "cmd='git commit' dir=~/dotfiles"
---and parse this into a table of arguments
---{cmd = "git commit", dir = "~/dotfiles"}
---@see https://stackoverflow.com/a/27007701
---@param args string
---@return ParsedArgs
function M.parse(args)
local result = {}
if args then
local quotes = args:match(p.single) and p.single or args:match(p.double) and p.double or nil
if quotes then
-- 1. extract the quoted command
local pattern = "(%S+)=" .. quotes
for key, value in args:gmatch(pattern) do
-- Check if the current OS is Windows so we can determine if +shellslash
-- exists and if it exists, then determine if it is enabled. In that way,
-- we can determine if we should match the value with single or double quotes.
if is_windows then
quotes = not vim.opt.shellslash:get() and quotes or p.single
else
quotes = p.single
end
value = fn.shellescape(value)
result[vim.trim(key)] = fn.expandcmd(value:match(quotes))
end
-- 2. then remove it from the rest of the argument string
args = args:gsub(pattern, "")
end
for _, part in ipairs(vim.split(args, " ")) do
if #part > 1 then
local arg = vim.split(part, "=")
local key, value = arg[1], arg[2]
if key == "size" then
value = tonumber(value)
elseif key == "go_back" or key == "open" then
value = value ~= "0"
end
result[key] = value
end
end
end
return result
end
-- Get a valid base path for a user provided path
-- and an optional search term
---@param typed_path string
---@return string|nil, string|nil
function M.get_path_parts(typed_path)
if vim.fn.isdirectory(typed_path ~= "" and typed_path or ".") == 1 then
-- The string is a valid path, we just need to drop trailing slashes to
-- ease joining the base path with the suggestions
return typed_path:gsub("/$", ""), nil
elseif typed_path:find("/", 2) ~= nil then
-- Maybe the typed path is looking for a nested directory
-- we need to make sure it has at least one slash in it, and that is not
-- from a root path
local base_path = vim.fn.fnamemodify(typed_path, ":h")
local search_term = vim.fn.fnamemodify(typed_path, ":t")
if vim.fn.isdirectory(base_path) then return base_path, search_term end
end
return nil, nil
end
local term_exec_options = {
--- Suggests commands
---@param typed_cmd string|nil
cmd = function(typed_cmd)
local paths = vim.split(vim.env.PATH, ":")
local commands = {}
for _, path in ipairs(paths) do
local glob_str
if string.match(path, "%s*") then
--path with spaces
glob_str = path:gsub(" ", "\\ ") .. "/" .. (typed_cmd or "") .. "*"
else
-- path without spaces
glob_str = path .. "/" .. (typed_cmd or "") .. "*"
end
local dir_cmds = vim.split(vim.fn.glob(glob_str), "\n")
for _, cmd in ipairs(dir_cmds) do
if not u.str_is_empty(cmd) then table.insert(commands, vim.fn.fnamemodify(cmd, ":t")) end
end
end
return commands
end,
--- Suggests paths in the cwd
---@param typed_path string
dir = function(typed_path)
-- Read the typed path as the base for the directory search
local base_path, search_term = M.get_path_parts(typed_path or "")
local safe_path = base_path ~= "" and base_path or "."
local paths = vim.fn.readdir(
safe_path,
function(entry) return vim.fn.isdirectory(safe_path .. "/" .. entry) end
)
if not u.str_is_empty(search_term) then
paths = vim.tbl_filter(
function(path) return path:match("^" .. search_term .. "*") ~= nil end,
paths
)
end
return vim.tbl_map(
function(path) return u.concat_without_empty({ base_path, path }, "/") end,
paths
)
end,
--- Suggests directions for the term
---@param typed_direction string
direction = function(typed_direction)
local directions = {
"float",
"horizontal",
"tab",
"vertical",
}
if u.str_is_empty(typed_direction) then return directions end
return vim.tbl_filter(
function(direction) return direction:match("^" .. typed_direction .. "*") ~= nil end,
directions
)
end,
--- The size param takes in arbitrary numbers, we keep this function only to
--- match the signature of other options
size = function() return {} end,
--- The name param takes in arbitrary strings, we keep this function only to
--- match the signature of other options
name = function() return {} end,
}
local toggle_term_options = {
dir = term_exec_options.dir,
direction = term_exec_options.direction,
size = term_exec_options.size,
name = term_exec_options.name,
}
---@param options table a dictionary of key to function
---@return fun(lead: string, command: string, _: number)
local function complete(options)
---@param lead string the leading portion of the argument currently being completed on
---@param command string the entire command line
---@param _ number the cursor position in it (byte index)
return function(lead, command, _)
local parts = vim.split(lead, "=")
local key = parts[1]
local value = parts[2]
if options[key] then
return vim.tbl_map(function(option) return key .. "=" .. option end, options[key](value))
end
local available_options = vim.tbl_filter(
function(option) return command:match(" " .. option .. "=") == nil end,
vim.tbl_keys(options)
)
table.sort(available_options)
return vim.tbl_map(function(option) return option .. "=" end, available_options)
end
end
--- See :h :command-completion-custom
M.term_exec_complete = complete(term_exec_options)
--- See :h :command-completion-custom
M.toggle_term_complete = complete(toggle_term_options)
return M

View File

@ -0,0 +1,146 @@
local colors = require("toggleterm.colors")
local constants = require("toggleterm.constants")
local utils = require("toggleterm.utils")
local M = {}
local fmt = string.format
local function shade(color, factor) return colors.shade_color(color, factor) end
--- @alias ToggleTermHighlights table<string, table<string, string>>
---@class WinbarOpts
---@field name_formatter fun(term: Terminal):string
---@field enabled boolean
--- @class ToggleTermConfig
--- @field size number
--- @field shade_filetypes string[]
--- @field hide_numbers boolean
--- @field open_mapping string | string[]
--- @field shade_terminals boolean
--- @field insert_mappings boolean
--- @field terminal_mappings boolean
--- @field start_in_insert boolean
--- @field persist_size boolean
--- @field persist_mode boolean
--- @field close_on_exit boolean
--- @field direction '"horizontal"' | '"vertical"' | '"float"'
--- @field shading_factor number
--- @field shell string|fun():string
--- @field auto_scroll boolean
--- @field float_opts table<string, any>
--- @field highlights ToggleTermHighlights
--- @field winbar WinbarOpts
--- @field autochdir boolean
--- @field title_pos '"left"' | '"center"' | '"right"'
---@type ToggleTermConfig
local config = {
size = 12,
shade_filetypes = {},
hide_numbers = true,
shade_terminals = true,
insert_mappings = true,
terminal_mappings = true,
start_in_insert = true,
persist_size = true,
persist_mode = true,
close_on_exit = true,
direction = "horizontal",
shading_factor = constants.shading_amount,
shell = vim.o.shell,
autochdir = false,
auto_scroll = true,
winbar = {
enabled = false,
name_formatter = function(term) return fmt("%d:%s", term.id, term:_display_name()) end,
},
float_opts = {
winblend = 0,
title_pos = "left",
},
}
---Derive the highlights for a toggleterm and merge these with the user's preferences
---A few caveats must be noted. Since I link the normal and float border to the Normal
---highlight this has to be done carefully as if the user has specified any Float highlights
---themselves merging will result in a mix of user highlights and the link key which is invalid
---so I check that they have not attempted to highlight these themselves. Also
---if they have chosen to shade the terminal then this takes priority over their own highlights
---since they can't have it both ways i.e. custom highlighting and shading
---@param conf ToggleTermConfig
---@return ToggleTermHighlights
local function get_highlights(conf)
local user = conf.highlights
local defaults = {
NormalFloat = vim.F.if_nil(user.NormalFloat, { link = "Normal" }),
FloatBorder = vim.F.if_nil(user.FloatBorder, { link = "Normal" }),
StatusLine = { gui = "NONE" },
StatusLineNC = { cterm = "italic", gui = "NONE" },
}
local overrides = {}
local nightly = utils.is_nightly()
local comment_fg = colors.get_hex("Comment", "fg")
local dir_fg = colors.get_hex("Directory", "fg")
local winbar_inactive_opts = { guifg = comment_fg }
local winbar_active_opts = { guifg = dir_fg, gui = "underline" }
if conf.shade_terminals then
local is_bright = colors.is_bright_background()
local degree = is_bright and -3 or 1
local amount = conf.shading_factor * degree
local normal_bg = colors.get_hex("Normal", "bg")
local terminal_bg = conf.shade_terminals and shade(normal_bg, amount) or normal_bg
overrides = {
Normal = { guibg = terminal_bg },
SignColumn = { guibg = terminal_bg },
EndOfBuffer = { guibg = terminal_bg },
StatusLine = { guibg = terminal_bg },
StatusLineNC = { guibg = terminal_bg },
}
-- TODO: Move this to the main overrides block once nvim 0.8 is stable
if nightly then
winbar_inactive_opts.guibg = terminal_bg
winbar_active_opts.guibg = terminal_bg
overrides.WinBarNC = { guibg = terminal_bg }
overrides.WinBar = { guibg = terminal_bg }
end
end
if nightly and conf.winbar.enabled then
colors.set_hl("WinBarActive", winbar_active_opts)
colors.set_hl("WinBarInactive", winbar_inactive_opts)
end
return vim.tbl_deep_extend("force", defaults, conf.highlights, overrides)
end
--- get the full user config or just a specified value
---@param key string?
---@return any
function M.get(key)
if key then return config[key] end
return config
end
function M.reset_highlights() config.highlights = get_highlights(config) end
---@param user_conf ToggleTermConfig
---@return ToggleTermConfig
function M.set(user_conf)
user_conf = user_conf or {}
user_conf.highlights = user_conf.highlights or {}
config = vim.tbl_deep_extend("force", config, user_conf)
config.highlights = get_highlights(config)
return config
end
---@return ToggleTermConfig
return setmetatable(M, {
__index = function(_, k) return config[k] end,
})

View File

@ -0,0 +1,11 @@
local M = {}
-----------------------------------------------------------
-- Constants
-----------------------------------------------------------
M.FILETYPE = "toggleterm"
-- -30 is a magic number based on manual testing of what looks good
M.shading_amount = -30
-- Highlight group name prefix
M.highlight_group_name_prefix = "ToggleTerm"
return M

View File

@ -0,0 +1,17 @@
local lazy = {}
--- Require on index.
---
--- Will only require the module after the first index of a module.
--- Only works for modules that export a table.
---@param require_path string
---@return table
lazy.require = function(require_path)
return setmetatable({}, {
__index = function(_, key) return require(require_path)[key] end,
__newindex = function(_, key, value) require(require_path)[key] = value end,
})
end
return lazy

View File

@ -0,0 +1,595 @@
local M = {}
local lazy = require("toggleterm.lazy")
---@module "toggleterm.ui"
local ui = lazy.require("toggleterm.ui")
---@module "toggleterm.config"
local config = lazy.require("toggleterm.config")
---@module "toggleterm.utils"
local utils = lazy.require("toggleterm.utils")
---@module "toggleterm.constants"
local constants = lazy.require("toggleterm.constants")
local api = vim.api
local fmt = string.format
local fn = vim.fn
local mode = {
INSERT = "i",
NORMAL = "n",
UNSUPPORTED = "?",
}
local AUGROUP = api.nvim_create_augroup("ToggleTermBuffer", { clear = true })
local is_windows = fn.has("win32") == 1
local function is_cmd(shell) return shell:find("cmd") end
local function is_pwsh(shell) return shell:find("pwsh") or shell:find("powershell") end
local function is_nushell(shell) return shell:find("nu") end
local function get_command_sep() return is_windows and is_cmd(vim.o.shell) and "&" or ";" end
local function get_comment_sep() return is_windows and is_cmd(vim.o.shell) and "::" or "#" end
local function get_newline_chr()
local shell = config.get("shell")
if type(shell) == "function" then shell = shell() end
if is_windows then
return is_pwsh(shell) and "\r" or "\r\n"
elseif is_nushell(shell) then
return "\r"
else
return "\n"
end
end
---@alias Mode "n" | "i" | "?"
--- @class TerminalState
--- @field mode Mode
---@type Terminal[]
local terminals = {}
--- @class TermCreateArgs
--- @field newline_chr? string user specified newline chararacter
--- @field cmd? string a custom command to run
--- @field direction? string the layout style for the terminal
--- @field id number?
--- @field highlights table<string, table<string, string>>?
--- @field dir string? the directory for the terminal
--- @field count number? the count that triggers that specific terminal
--- @field display_name string?
--- @field hidden boolean? whether or not to include this terminal in the terminals list
--- @field close_on_exit boolean? whether or not to close the terminal window when the process exits
--- @field auto_scroll boolean? whether or not to scroll down on terminal output
--- @field float_opts table<string, any>?
--- @field on_stdout fun(t: Terminal, job: number, data: string[]?, name: string?)?
--- @field on_stderr fun(t: Terminal, job: number, data: string[], name: string)?
--- @field on_exit fun(t: Terminal, job: number, exit_code: number?, name: string?)?
--- @field on_create fun(term:Terminal)?
--- @field on_open fun(term:Terminal)?
--- @field on_close fun(term:Terminal)?
--- @class Terminal
--- @field newline_chr string
--- @field cmd string
--- @field direction string the layout style for the terminal
--- @field id number
--- @field bufnr number
--- @field window number
--- @field job_id number
--- @field highlights table<string, table<string, string>>
--- @field dir string the directory for the terminal
--- @field name string the name of the terminal
--- @field count number the count that triggers that specific terminal
--- @field hidden boolean whether or not to include this terminal in the terminals list
--- @field close_on_exit boolean? whether or not to close the terminal window when the process exits
--- @field auto_scroll boolean? whether or not to scroll down on terminal output
--- @field float_opts table<string, any>?
--- @field display_name string?
--- @field env table<string, string> environmental variables passed to jobstart()
--- @field clear_env boolean use clean job environment, passed to jobstart()
--- @field on_stdout fun(t: Terminal, job: number, data: string[]?, name: string?)?
--- @field on_stderr fun(t: Terminal, job: number, data: string[], name: string)?
--- @field on_exit fun(t: Terminal, job: number, exit_code: number?, name: string?)?
--- @field on_create fun(term:Terminal)?
--- @field on_open fun(term:Terminal)?
--- @field on_close fun(term:Terminal)?
--- @field _display_name fun(term: Terminal): string
--- @field __state TerminalState
local Terminal = {}
--- Get the next available id based on the next number in the sequence that
--- hasn't already been allocated e.g. in a list of {1,2,5,6} the next id should
--- be 3 then 4 then 7
---@return integer
local function next_id()
local all = M.get_all(true)
for index, term in pairs(all) do
if index ~= term.id then return index end
end
return #all + 1
end
---Get an opened (valid) toggle terminal by id, defaults to the first opened
---@param position number?
---@return number?
function M.get_toggled_id(position)
position = position or 1
local t = M.get_all()
return t[position] and t[position].id or nil
end
---Return currently focused terminal id.
---@return number?
function M.get_focused_id()
for _, term in pairs(terminals) do
if term:is_focused() then return term.id end
end
return nil
end
function M.get_last_focused()
local last_focus = ui.get_terminal_view().focus_term_id
return M.get(last_focus, true)
end
--- @param bufnr number
local function setup_buffer_mappings(bufnr)
local mapping = config.open_mapping
if mapping and config.terminal_mappings then
utils.key_map("t", mapping, "<Cmd>ToggleTerm<CR>", { buffer = bufnr, silent = true })
end
end
---@param id number terminal id
local function on_vim_resized(id)
local term = M.get(id, true)
if not term or not term:is_float() or not term:is_open() then return end
ui.update_float(term)
end
--- Remove the in memory reference to the no longer open terminal
--- @param num number
local function delete(num)
if terminals[num] then terminals[num] = nil end
end
---Terminal buffer autocommands
---@param term Terminal
local function setup_buffer_autocommands(term)
api.nvim_create_autocmd("TermClose", {
buffer = term.bufnr,
group = AUGROUP,
callback = function() delete(term.id) end,
})
if term:is_float() then
api.nvim_create_autocmd("VimResized", {
buffer = term.bufnr,
group = AUGROUP,
callback = function() on_vim_resized(term.id) end,
})
end
if config.start_in_insert then
-- Avoid entering insert mode when spawning terminal in the background
if term.window == api.nvim_get_current_win() then vim.cmd("startinsert") end
end
end
---get the directory for the terminal parsing special arguments
---@param dir string?
---@return string
local function _get_dir(dir)
if dir == "git_dir" then dir = utils.git_dir() end
if dir then
return fn.expand(dir)
else
return vim.loop.cwd()
end
end
---Create a new terminal object
---@param term TermCreateArgs?
---@return Terminal
function Terminal:new(term)
term = term or {}
--- If we try to create a new terminal, but the id is already
--- taken, return the terminal with the containing id
local id = term.count or term.id
if id and terminals[id] then return terminals[id] end
local conf = config.get()
self.__index = self
term.newline_chr = term.newline_chr or get_newline_chr()
term.direction = term.direction or conf.direction
term.id = id or next_id()
term.display_name = term.display_name
term.float_opts = vim.tbl_deep_extend("keep", term.float_opts or {}, conf.float_opts)
term.clear_env = term.clear_env
term.auto_scroll = vim.F.if_nil(term.auto_scroll, conf.auto_scroll)
term.env = vim.F.if_nil(term.env, conf.env)
term.hidden = vim.F.if_nil(term.hidden, false)
term.on_create = vim.F.if_nil(term.on_create, conf.on_create)
term.on_open = vim.F.if_nil(term.on_open, conf.on_open)
term.on_close = vim.F.if_nil(term.on_close, conf.on_close)
term.on_stdout = vim.F.if_nil(term.on_stdout, conf.on_stdout)
term.on_stderr = vim.F.if_nil(term.on_stderr, conf.on_stderr)
term.on_exit = vim.F.if_nil(term.on_exit, conf.on_exit)
term.__state = { mode = "?" }
if term.close_on_exit == nil then term.close_on_exit = conf.close_on_exit end
-- Add the newly created terminal to the list of all terminals
---@diagnostic disable-next-line: return-type-mismatch
return setmetatable(term, self)
end
---@package
---Add a terminal to the list of terminals
function Terminal:__add()
if terminals[self.id] and terminals[self.id] ~= self then self.id = next_id() end
if not terminals[self.id] then terminals[self.id] = self end
return self
end
function Terminal:is_float() return self.direction == "float" and ui.is_float(self.window) end
function Terminal:is_split()
return (self.direction == "vertical" or self.direction == "horizontal")
and not ui.is_float(self.window)
end
function Terminal:is_tab() return self.direction == "tab" and not ui.is_float(self.window) end
function Terminal:resize(size)
if self:is_split() then ui.resize_split(self, size) end
end
function Terminal:is_open()
if not self.window then return false end
local win_type = fn.win_gettype(self.window)
-- empty string window type corresponds to a normal window
local win_open = win_type == "" or win_type == "popup"
return win_open and api.nvim_win_get_buf(self.window) == self.bufnr
end
---@package
function Terminal:__restore_mode() self:set_mode(self.__state.mode) end
--- Set the terminal's mode
---@param m Mode
function Terminal:set_mode(m)
if m == mode.INSERT then
vim.cmd("startinsert")
elseif m == mode.NORMAL then
vim.cmd("stopinsert")
elseif m == mode.UNSUPPORTED and config.get("start_in_insert") then
vim.cmd("startinsert")
end
end
function Terminal:persist_mode()
local raw_mode = api.nvim_get_mode().mode
local m = "?"
if raw_mode:match("nt") then -- nt is normal mode in the terminal
m = mode.NORMAL
elseif raw_mode:match("t") then -- t is insert mode in the terminal
m = mode.INSERT
end
self.__state.mode = m
end
---@package
function Terminal:_display_name() return self.display_name or vim.split(self.name, ";")[1] end
function Terminal:close()
if self.on_close then self:on_close() end
ui.close(self)
ui.stopinsert()
ui.update_origin_window(self.window)
end
function Terminal:shutdown()
if self:is_open() then self:close() end
ui.delete_buf(self)
delete(self.id)
end
---Combine arguments into strings separated by new lines
---@vararg string
---@param newline_chr string
---@return string
local function with_cr(newline_chr, ...)
local result = {}
for _, str in ipairs({ ... }) do
table.insert(result, str .. newline_chr)
end
return table.concat(result, "")
end
function Terminal:scroll_bottom()
if not api.nvim_buf_is_loaded(self.bufnr) or not api.nvim_buf_is_valid(self.bufnr) then return end
if ui.term_has_open_win(self) then api.nvim_buf_call(self.bufnr, ui.scroll_to_bottom) end
end
function Terminal:is_focused() return self.window == api.nvim_get_current_win() end
function Terminal:focus()
if ui.term_has_open_win(self) then api.nvim_set_current_win(self.window) end
end
---Send a command to a running terminal
---@param cmd string|string[]
---@param go_back boolean? whether or not to return to original window
function Terminal:send(cmd, go_back)
cmd = type(cmd) == "table" and with_cr(self.newline_chr, unpack(cmd))
or with_cr(self.newline_chr, cmd --[[@as string]])
fn.chansend(self.job_id, cmd)
self:scroll_bottom()
if go_back and self:is_focused() then
ui.goto_previous()
ui.stopinsert()
elseif not go_back and not self:is_focused() then
self:focus()
end
end
--check for os type and perform os specific clear command
function Terminal:clear()
local clear = is_windows and "cls" or "clear"
self:send(clear)
end
---Update the directory of an already opened terminal
---@param dir string
function Terminal:change_dir(dir, go_back)
dir = _get_dir(dir)
if self.dir == dir then return end
self:send({ fmt("cd %s", dir), self:clear() }, go_back)
self.dir = dir
end
---Update the direction of an already opened terminal
---@param direction string
function Terminal:change_direction(direction)
self.direction = direction
self.window = nil
end
--- Handle when a terminal process exits
---@param term Terminal
local function __handle_exit(term)
return function(...)
if term.on_exit then term:on_exit(...) end
if term.close_on_exit then
term:close()
if api.nvim_buf_is_loaded(term.bufnr) then
api.nvim_buf_delete(term.bufnr, { force = true })
end
end
end
end
---@private
---Prepare callback for terminal output handling
---If `auto_scroll` is active, will create a handler that scrolls on terminal output
---If `handler` is present, will call it passing `self` as the first parameter
---If none of the above is applicable, will not return a handler
---@param handler function? a custom callback function for output handling
function Terminal:__make_output_handler(handler)
if self.auto_scroll or handler then
return function(...)
if self.auto_scroll then self:scroll_bottom() end
if handler then handler(self, ...) end
end
end
end
---@private
function Terminal:__spawn()
local cmd = self.cmd or config.get("shell")
if type(cmd) == "function" then cmd = cmd() end
local command_sep = get_command_sep()
local comment_sep = get_comment_sep()
cmd = table.concat({
cmd,
command_sep,
comment_sep,
constants.FILETYPE,
comment_sep,
self.id,
})
local dir = _get_dir(self.dir)
self.job_id = fn.termopen(cmd, {
detach = 1,
cwd = dir,
on_exit = __handle_exit(self),
on_stdout = self:__make_output_handler(self.on_stdout),
on_stderr = self:__make_output_handler(self.on_stderr),
env = self.env,
clear_env = self.clear_env,
})
self.name = cmd
self.dir = dir
end
---@package
---Add an orphaned terminal to the list of terminal and re-apply settings
function Terminal:__resurrect()
self:__add()
if self:is_split() then ui.resize_split(self) end
-- set the window options including fixing height or width once the window is resized
self:__set_options()
ui.hl_term(self)
end
---@package
function Terminal:__set_ft_options()
local buf = vim.bo[self.bufnr]
buf.filetype = constants.FILETYPE
buf.buflisted = false
end
---@package
function Terminal:__set_win_options()
if self:is_split() then
local field = self.direction == "vertical" and "winfixwidth" or "winfixheight"
utils.wo_setlocal(self.window, field, true)
end
if config.hide_numbers then
utils.wo_setlocal(self.window, "number", false)
utils.wo_setlocal(self.window, "relativenumber", false)
end
end
---@package
function Terminal:__set_options()
self:__set_ft_options()
self:__set_win_options()
vim.b[self.bufnr].toggle_number = self.id
end
---Open a terminal in a type of window i.e. a split,full window or tab
---@param size number
---@param term table
local function opener(size, term)
local direction = term.direction
if term:is_split() then
ui.open_split(size, term)
elseif direction == "tab" then
ui.open_tab(term)
elseif direction == "float" then
ui.open_float(term)
else
error("Invalid terminal direction")
end
end
---Spawn terminal background job in a buffer without a window
function Terminal:spawn()
if not self.bufnr or not api.nvim_buf_is_valid(self.bufnr) then self.bufnr = ui.create_buf() end
self:__add()
if api.nvim_get_current_buf() ~= self.bufnr then
api.nvim_buf_call(self.bufnr, function() self:__spawn() end)
else
self:__spawn()
end
setup_buffer_autocommands(self)
setup_buffer_mappings(self.bufnr)
if self.on_create then self:on_create() end
end
---Open a terminal window
---@param size number?
---@param direction string?
function Terminal:open(size, direction)
local cwd = fn.getcwd()
self.dir = _get_dir(config.autochdir and cwd or self.dir)
ui.set_origin_window()
if direction then self:change_direction(direction) end
if not self.bufnr or not api.nvim_buf_is_valid(self.bufnr) then
local ok, err = pcall(opener, size, self)
if not ok and err then return utils.notify(err, "error") end
self:spawn()
else
local ok, err = pcall(opener, size, self)
if not ok and err then return utils.notify(err, "error") end
ui.switch_buf(self.bufnr)
if config.autochdir and self.dir ~= cwd then self:change_dir(cwd) end
end
ui.hl_term(self)
-- NOTE: it is important that this function is called at this point. i.e. the buffer has been correctly assigned
if self.on_open then self:on_open() end
end
---Open if closed and close if opened
---@param size number?
---@param direction string?
function Terminal:toggle(size, direction)
if self:is_open() then
self:close()
else
self:open(size, direction)
end
return self
end
--- get the toggle term number from
--- the name e.g. term://~/.dotfiles//3371887:/usr/bin/zsh;#toggleterm#1
--- the number in this case is 1
--- @param name string?
--- @return number?
--- @return Terminal?
function M.identify(name)
name = name or api.nvim_buf_get_name(api.nvim_get_current_buf())
local comment_sep = get_comment_sep()
local parts = vim.split(name, comment_sep)
local id = tonumber(parts[#parts])
return id, terminals[id]
end
---get existing terminal or create an empty term table
---@param num number?
---@param dir string?
---@param direction string?
---@param name string?
---@return Terminal
---@return boolean
function M.get_or_create_term(num, dir, direction, name)
local term = M.get(num)
if term then return term, false end
if dir and fn.isdirectory(fn.expand(dir)) == 0 then dir = nil end
return Terminal:new({ id = num, dir = dir, direction = direction, display_name = name }), true
end
---Get a single terminal by id, unless it is hidden
---@param id number?
---@param include_hidden boolean? whether or nor to filter out hidden
---@return Terminal?
function M.get(id, include_hidden)
local term = terminals[id]
return (term and (include_hidden == true or not term.hidden)) and term or nil
end
---Get the first terminal that matches a predicate
---@param predicate fun(term: Terminal): boolean
---@return Terminal?
function M.find(predicate)
if type(predicate) ~= "function" then
utils.notify("terminal.find expects a function, got " .. type(predicate), "error")
return
end
for _, term in pairs(terminals) do
if predicate(term) then return term end
end
return nil
end
---Return the potentially non contiguous map of terminals as a sorted array
---@param include_hidden boolean? whether or nor to filter out hidden
---@return Terminal[]
function M.get_all(include_hidden)
local result = {}
for _, v in pairs(terminals) do
if include_hidden or (not include_hidden and not v.hidden) then table.insert(result, v) end
end
table.sort(result, function(a, b) return a.id < b.id end)
return result
end
if _G.IS_TEST then
function M.__reset()
for _, term in pairs(terminals) do
term:shutdown()
end
end
M.__next_id = next_id
end
M.Terminal = Terminal
M.mode = mode
return M

View File

@ -0,0 +1,472 @@
local M = {}
local lazy = require("toggleterm.lazy")
---@module "toggleterm.constants"
local constants = lazy.require("toggleterm.constants")
---@module "toggleterm.utils"
local utils = lazy.require("toggleterm.utils")
---@module "toggleterm.colors"
local colors = lazy.require("toggleterm.colors")
---@module "toggleterm.config"
local config = lazy.require("toggleterm.config")
---@module "toggleterm.terminal"
local terms = lazy.require("toggleterm.terminal")
local fn = vim.fn
local fmt = string.format
local api = vim.api
local origin_window
local persistent = {}
---@alias TerminalView {terminals: number[], focus_term_id: number}
---@type TerminalView
local terminal_view = {
---@type number[]
-- A list of terminal IDs that are saved from the view on smart toggle.
terminals = {},
---@type number
---Last focused terminal ID in the view.
focus_term_id = nil,
}
--- @class TerminalWindow
--- @field term_id number ID for the terminal in the window
--- @field window number window handle
--
--- Save the size of a split window before it is hidden
--- @param direction string
--- @param window number
function M.save_window_size(direction, window)
if direction == "horizontal" then
persistent.horizontal = api.nvim_win_get_height(window)
elseif direction == "vertical" then
persistent.vertical = api.nvim_win_get_width(window)
end
end
--- Explicitly set the persistent size of a direction
--- @param direction string
--- @param size number
function M.save_direction_size(direction, size) persistent[direction] = size end
--- @param direction string
--- @return boolean
function M.has_saved_size(direction) return persistent[direction] ~= nil end
--- Get the size of the split. Order of priority is as follows:
--- 1. The size argument is a valid number > 0
--- 2. There is persistent width/height information from prev open state
--- 3. Default/base case config size
---
--- If `config.persist_size = false` then option `2` in the
--- list is skipped.
--- @param size number?
--- @param direction string?
function M.get_size(size, direction)
local valid_size = size ~= nil and size > 0
if not config.persist_size then return valid_size and size or config.size end
return valid_size and size or persistent[direction] or config.size
end
local function hl(name) return "%#" .. name .. "#" end
local hl_end = "%*"
--- Create terminal window bar
---@param id number
---@return string
function M.winbar(id)
local terms = require("toggleterm.terminal").get_all()
local str = " "
for _, t in pairs(terms) do
local h = id == t.id and "WinBarActive" or "WinBarInactive"
str = str
.. fmt("%%%d@v:lua.___toggleterm_winbar_click@", t.id)
.. hl(h)
.. config.winbar.name_formatter(t)
.. hl_end
.. " "
end
return str
end
---@param term Terminal?
function M.set_winbar(term)
if
not config.winbar.enabled
or not term
or term:is_float() -- TODO: make this configurable
or fn.exists("+winbar") ~= 1
or not term.window
or not api.nvim_win_is_valid(term.window)
then
return
end
local value = fmt('%%{%%v:lua.require("toggleterm.ui").winbar(%d)%%}', term.id)
utils.wo_setlocal(term.window, "winbar", value)
end
---apply highlights to a terminal
---if no term is passed in we use default values instead
---@param term Terminal?
function M.hl_term(term)
local hls = (term and term.highlights and not vim.tbl_isempty(term.highlights))
and term.highlights
or config.highlights
if not hls or vim.tbl_isempty(hls) then return end
local window = term and term.window or api.nvim_get_current_win()
local id = term and term.id or "Default"
local is_float = M.is_float(window)
-- If the terminal is a floating window we only want to set the background and border
-- not the statusline etc. which are not applicable to floating windows
local hl_names = vim.tbl_filter(
function(name)
return not is_float or (is_float and vim.tbl_contains({ "FloatBorder", "NormalFloat" }, name))
end,
vim.tbl_keys(hls)
)
local highlights = vim.tbl_map(function(hl_group_name)
local name = constants.highlight_group_name_prefix .. id .. hl_group_name
local hi_target = fmt("%s:%s", hl_group_name, name)
local attrs = hls[hl_group_name]
attrs.default = true
colors.set_hl(name, attrs)
return hi_target
end, hl_names)
utils.wo_setlocal(window, "winhighlight", table.concat(highlights, ","))
end
---Create a terminal buffer with the correct buffer/window options
---then set it to current window
---@param term Terminal
local function create_term_buf_if_needed(term)
local valid_win = term.window and api.nvim_win_is_valid(term.window)
local window = valid_win and term.window or api.nvim_get_current_win()
-- If the buffer doesn't exist create a new one
local valid_buf = term.bufnr and api.nvim_buf_is_valid(term.bufnr)
local bufnr = valid_buf and term.bufnr or api.nvim_create_buf(false, false)
-- Assign buf to window to ensure window options are set correctly
api.nvim_win_set_buf(window, bufnr)
term.window, term.bufnr = window, bufnr
term:__set_options()
api.nvim_set_current_buf(bufnr)
end
function M.create_buf() return api.nvim_create_buf(false, false) end
function M.delete_buf(term)
if term.bufnr and api.nvim_buf_is_valid(term.bufnr) then
api.nvim_buf_delete(term.bufnr, { force = true })
end
end
function M.set_origin_window() origin_window = api.nvim_get_current_win() end
function M.get_origin_window() return origin_window end
function M.update_origin_window(term_window)
local curr_win = api.nvim_get_current_win()
if term_window ~= curr_win then origin_window = curr_win end
end
function M.scroll_to_bottom()
local info = vim.api.nvim_get_mode()
if info and (info.mode == "n" or info.mode == "nt") then vim.cmd("normal! G") end
end
function M.goto_previous() vim.cmd("wincmd p") end
function M.stopinsert() vim.cmd("stopinsert!") end
---@param buf integer
---@return boolean
local function default_compare(buf)
return vim.bo[buf].filetype == constants.FILETYPE or vim.b[buf].toggle_number ~= nil
end
--- Find the first open terminal window
--- by iterating all windows and matching the
--- containing buffers filetype with the passed in
--- comparator function or the default which matches
--- the filetype
--- @param comparator function?
--- @return boolean, TerminalWindow[]
function M.find_open_windows(comparator)
comparator = comparator or default_compare
local term_wins, is_open = {}, false
for _, tab in ipairs(api.nvim_list_tabpages()) do
for _, win in pairs(api.nvim_tabpage_list_wins(tab)) do
local buf = api.nvim_win_get_buf(win)
if comparator(buf) then
is_open = true
table.insert(term_wins, { window = win, term_id = vim.b[buf].toggle_number })
end
end
end
return is_open, term_wins
end
---Switch to the given buffer without changing the alternate
---@param buf number
function M.switch_buf(buf)
-- don't change the alternate buffer so that <c-^><c-^> does nothing in the terminal split
local cur_buf = api.nvim_get_current_buf()
if cur_buf ~= buf then vim.cmd(fmt("keepalt buffer %d", buf)) end
end
local split_commands = {
horizontal = {
existing = "rightbelow vsplit",
new = "botright split",
resize = "resize",
},
vertical = {
existing = "rightbelow split",
new = "botright vsplit",
resize = "vertical resize",
},
}
---Guess whether or not the window is a horizontal or vertical split
---this only works if either of the two are full size
---@return string?
function M.guess_direction()
-- current window is full height vertical split
-- NOTE: add one for tabline and one for status
local ui_lines = (vim.o.tabline ~= "" and 1 or 0) + (vim.o.laststatus ~= 0 and 1 or 0)
if api.nvim_win_get_height(0) + vim.o.cmdheight + ui_lines == vim.o.lines then
return "vertical"
end
-- current window is full width horizontal split
if api.nvim_win_get_width(0) == vim.o.columns then return "horizontal" end
return nil
end
--- @private
--- @param size number|function
--- @param term Terminal?
--- @return number?
function M._resolve_size(size, term)
if not size then
return
elseif type(size) == "number" then
return size
elseif term and type(size) == "function" then
return size(term)
end
utils.notify(fmt('The input %s is not of type "number" or "function".', size), "error")
end
local curved = { "", "", "", "", "", "", "", "" }
--- @private
--- @param term Terminal
--- @param opening boolean
function M._get_float_config(term, opening)
local opts = term.float_opts or {}
local border = opts.border == "curved" and curved or opts.border or "single"
local width = math.ceil(math.min(vim.o.columns, math.max(80, vim.o.columns - 20)))
local height = math.ceil(math.min(vim.o.lines, math.max(20, vim.o.lines - 10)))
width = vim.F.if_nil(M._resolve_size(opts.width, term), width)
height = vim.F.if_nil(M._resolve_size(opts.height, term), height)
local row = math.ceil(vim.o.lines - height) * 0.5 - 1
local col = math.ceil(vim.o.columns - width) * 0.5 - 1
row = vim.F.if_nil(M._resolve_size(opts.row, term), row)
col = vim.F.if_nil(M._resolve_size(opts.col, term), col)
local version = vim.version()
local float_config = {
row = row,
col = col,
relative = opts.relative or "editor",
style = opening and "minimal" or nil,
width = width,
height = height,
border = opening and border or nil,
zindex = opts.zindex or nil,
}
if version.major > 0 or version.minor >= 9 then
float_config.title_pos = term.display_name and opts.title_pos or nil
float_config.title = term.display_name
end
return float_config
end
--- @param size number
--- @param term Terminal
function M.open_split(size, term)
local has_open, windows = M.find_open_windows()
local commands = split_commands[term.direction]
if has_open then
-- we need to be in the terminal window most recently opened
-- in order to split it
local split_win = windows[#windows]
if config.persist_size then M.save_window_size(term.direction, split_win.window) end
api.nvim_set_current_win(split_win.window)
vim.cmd(commands.existing)
else
vim.cmd(commands.new)
end
M.resize_split(term, size)
create_term_buf_if_needed(term)
end
--- @param term Terminal
function M.open_tab(term)
-- Open the current buffer in a tab (use tabnew due to issue #95)
vim.cmd("tabedit new")
-- tabnew creates an empty no name buffer so we set it to be wiped once it's replaced
-- by the terminal buffer
vim.bo.bufhidden = "wipe"
-- Replace the current window with a tab
create_term_buf_if_needed(term)
end
---@param term Terminal
local function close_tab(term)
if #vim.api.nvim_list_tabpages() == 1 then
return utils.notify("You cannot close the last tab! This will exit neovim", "error")
end
api.nvim_win_close(term.window, true)
end
---Close terminal window
---@param term Terminal
local function close_split(term)
if term.window and api.nvim_win_is_valid(term.window) then
local persist_size = require("toggleterm.config").get("persist_size")
if persist_size then M.save_window_size(term.direction, term.window) end
api.nvim_win_close(term.window, true)
end
if origin_window and api.nvim_win_is_valid(origin_window) then
api.nvim_set_current_win(origin_window)
else
origin_window = nil
end
end
---Open a floating window
---@param term Terminal
function M.open_float(term)
local opts = term.float_opts or {}
local valid_buf = term.bufnr and api.nvim_buf_is_valid(term.bufnr)
local buf = valid_buf and term.bufnr or api.nvim_create_buf(false, false)
local win = api.nvim_open_win(buf, true, M._get_float_config(term, true))
term.window, term.bufnr = win, buf
-- partial fix for #391
utils.wo_setlocal(win, "sidescrolloff", 0)
if opts.winblend then utils.wo_setlocal(win, "winblend", opts.winblend) end
term:__set_options()
end
---Updates the floating terminal size
---@param term Terminal
function M.update_float(term)
if not vim.api.nvim_win_is_valid(term.window) then return end
vim.api.nvim_win_set_config(term.window, M._get_float_config(term, false))
end
---Close given terminal's ui
---@param term Terminal
function M.close(term)
if term:is_split() then
close_split(term)
elseif term:is_tab() then
close_tab(term)
elseif term.window and api.nvim_win_is_valid(term.window) then
api.nvim_win_close(term.window, true)
end
end
---Resize a split window
---@param term Terminal
---@param size number?
function M.resize_split(term, size)
size = M._resolve_size(M.get_size(size, term.direction), term)
if config.persist_size and size then M.save_direction_size(term.direction, size) end
vim.cmd(split_commands[term.direction].resize .. " " .. size)
end
---Determine if a window is a float
---@param window number
function M.is_float(window) return fn.win_gettype(window) == "popup" end
--- @param bufnr number
function M.find_windows_by_bufnr(bufnr) return fn.win_findbuf(bufnr) end
---Return whether or not the terminal passed in has an open window
---@param term Terminal
---@return boolean
function M.term_has_open_win(term)
if not term.window then return false end
local wins = {}
for _, tab in ipairs(api.nvim_list_tabpages()) do
vim.list_extend(wins, api.nvim_tabpage_list_wins(tab))
end
return vim.tbl_contains(wins, term.window)
end
---Close and save terminals that are currently in view.
---@param windows TerminalWindow[]
function M.close_and_save_terminal_view(windows)
local terminals = {}
local focused_term_id = terms.get_focused_id()
-- NOTE: Use windows to close terminals in order they are being shown on
-- the view.
for _, window in pairs(windows) do
local term = terms.get(window.term_id)
if term then
table.insert(terminals, term.id)
term:close()
end
end
M.save_terminal_view(terminals, focused_term_id)
end
---Open terminals that were saved in the last terminal view.
---@return boolean
function M.open_terminal_view(size, direction)
local opened = false
if not vim.tbl_isempty(terminal_view.terminals) then
for _, term_id in pairs(terminal_view.terminals) do
local term = terms.get(term_id)
if term then
term:open(size, direction)
opened = true
end
end
local focus_term = terms.get(terminal_view.focus_term_id)
if focus_term then focus_term:focus() end
M.save_terminal_view({}, nil)
end
return opened
end
---Save the terminal view with the just closed terminals and the previously
--focused terminal.
---@param terminals number[]
---@param focus_term_id number?
function M.save_terminal_view(terminals, focus_term_id)
terminal_view = { terminals = terminals, focus_term_id = focus_term_id }
end
---@return TerminalView
function M.get_terminal_view() return terminal_view end
return M

View File

@ -0,0 +1,135 @@
local M = {}
local fn, api, opt = vim.fn, vim.api, vim.opt
local fmt = string.format
local levels = vim.log.levels
function M.is_nightly()
local v = vim.version()
return v.minor >= 8
end
---@alias error_types 'error' | 'info' | 'warn'
---Inform a user about something
---@param msg string
---@param level error_types
function M.notify(msg, level)
local err = level:upper()
level = level and levels[err] or levels.INFO
vim.schedule(function() vim.notify(msg, level, { title = "Toggleterm" }) end)
end
---@private
---Helper function to derive the current git directory path
---@return string|nil
function M.git_dir()
local gitdir = fn.system(fmt("git -C %s rev-parse --show-toplevel", fn.expand("%:p:h")))
local isgitdir = fn.matchstr(gitdir, "^fatal:.*") == ""
if not isgitdir then return end
return vim.trim(gitdir)
end
---@param str string|nil
---@return boolean
function M.str_is_empty(str) return str == nil or str == "" end
---@param tbl table
---@return table
function M.tbl_filter_empty(tbl)
return vim.tbl_filter(
---@param str string|nil
function(str) return not M.str_is_empty(str) end,
tbl
)
end
--- Concats a table ignoring empty entries
---@param tbl table
---@param sep string
function M.concat_without_empty(tbl, sep) return table.concat(M.tbl_filter_empty(tbl), sep) end
-- Key mapping function
---@param mod string | string[]
---@param lhs string | string[]
---@param rhs string | function
---@param opts table?
function M.key_map(mod, lhs, rhs, opts)
if type(lhs) == "string" then
vim.keymap.set(mod, lhs, rhs, opts)
elseif type(lhs) == "table" then
for _, key in pairs(lhs) do
vim.keymap.set(mod, key, rhs, opts)
end
end
end
---@param mode "visual" | "motion"
---@return table
function M.get_line_selection(mode)
local start_char, end_char = unpack(({
visual = { "'<", "'>" },
motion = { "'[", "']" },
})[mode])
-- '< marks are only updated when one leaves visual mode.
-- When calling lua functions directly from a mapping, need to
-- explicitly exit visual with the escape key to ensure those marks are
-- accurate.
vim.cmd("normal! ")
-- Get the start and the end of the selection
local start_line, start_col = unpack(fn.getpos(start_char), 2, 3)
local end_line, end_col = unpack(fn.getpos(end_char), 2, 3)
local selected_lines = api.nvim_buf_get_lines(0, start_line - 1, end_line, false)
return {
start_pos = { start_line, start_col },
end_pos = { end_line, end_col },
selected_lines = selected_lines,
}
end
function M.get_visual_selection(res, motion)
motion = motion or false
local mode = fn.visualmode()
if motion then mode = "v" end
-- line-visual
-- return lines encompassed by the selection; already in res object
if mode == "V" then return res.selected_lines end
if mode == "v" then
-- regular-visual
-- return the buffer text encompassed by the selection
local start_line, start_col = unpack(res.start_pos)
local end_line, end_col = unpack(res.end_pos)
-- exclude the last char in text if "selection" is set to "exclusive"
if opt.selection:get() == "exclusive" then end_col = end_col - 1 end
return api.nvim_buf_get_text(0, start_line - 1, start_col - 1, end_line - 1, end_col, {})
end
-- block-visual
-- return the lines encompassed by the selection, each truncated by the start and end columns
if mode == "\x16" then
local _, start_col = unpack(res.start_pos)
local _, end_col = unpack(res.end_pos)
-- exclude the last col of the block if "selection" is set to "exclusive"
if opt.selection:get() == "exclusive" then end_col = end_col - 1 end
-- exchange start and end columns for proper substring indexing if needed
-- e.g. instead of str:sub(10, 5), do str:sub(5, 10)
if start_col > end_col then
start_col, end_col = end_col, start_col
end
-- iterate over lines, truncating each one
return vim.tbl_map(function(line) return line:sub(start_col, end_col) end, res.selected_lines)
end
end
--- Sets a local window option, like `:setlocal`
--- TODO: replace with double-indexing on `vim.wo` when neovim/neovim#20288 (hopefully) merges
---@param win number
---@param option string
---@param value any
function M.wo_setlocal(win, option, value)
api.nvim_set_option_value(option, value, { scope = "local", win = win })
end
return M

View File

@ -0,0 +1,5 @@
column_width = 100
indent_type = "Spaces"
quote_style = "AutoPreferDouble"
indent_width = 2
collapse_simple_statement = 'Always'

View File

@ -0,0 +1,86 @@
describe("command-complete", function()
local command_complete = require("toggleterm.commandline")
it("should return the default options", function()
local results = command_complete.term_exec_complete("", "TermExec ", 9)
assert.is_equal("cmd=, dir=, direction=, name=, size=", table.concat(results, ", "))
end)
describe("helpers", function()
it("should validate relative paths", function()
local cwd, no_search_term = command_complete.get_path_parts("")
assert.is_equal(nil, no_search_term)
assert.is_equal("", cwd)
local partial_path, search_term = command_complete.get_path_parts(".github/work")
assert.is_equal(".github", partial_path)
assert.is_equal("work", search_term)
local path_with_slash, _ = command_complete.get_path_parts(".github/")
assert.is_equal(".github", path_with_slash)
local path_without_slash, _ = command_complete.get_path_parts(".github")
assert.is_equal(".github", path_without_slash)
end)
end)
describe("cmd=", function()
it("should return all the commands in $PATH", function()
local results = command_complete.term_exec_complete("cmd=", "ToggleExec cmd=", 16)
assert.is_not_equal(0, #results)
end)
it("should return matching commands in $PATH", function()
local results = command_complete.term_exec_complete("cmd=m", "ToggleExec cmd=m", 16)
assert.is_not_equal(0, #results)
assert.is_true(vim.tbl_contains(results, "cmd=mv"))
assert.is_true(vim.tbl_contains(results, "cmd=mkdir"))
end)
end)
describe("dir=", function()
it("should return all directories in the cwd", function()
local results = command_complete.term_exec_complete("dir=", "ToggleExec dir=", 16)
assert.is_not_equal(0, #results)
end)
it("should return matching subdirectories", function()
local results =
command_complete.term_exec_complete("dir=.github/wor", "ToggleExec dir=.github/wor", 27)
assert.is_equal("dir=.github/workflows", table.concat(results, ", "))
end)
it("should handle empty dir values", function()
local results = command_complete.term_exec_complete("dir", "ToggleExec dir", 15)
assert.is_not_equal(0, #results)
end)
end)
describe("directions=", function()
it("should return all directions", function()
local results = command_complete.term_exec_complete("direction=", "TermExec direction=", 19)
assert.equal(
table.concat({
"direction=float",
"direction=horizontal",
"direction=tab",
"direction=vertical",
}, ", "),
table.concat(results, ", ")
)
end)
it("should return partiall typed directions", function()
local results =
command_complete.term_exec_complete("direction=ver", "TermExec direction=ver", 22)
assert.equal("direction=vertical", table.concat(results, ", "))
end)
end)
end)

View File

@ -0,0 +1,55 @@
local fmt = string.format
describe("Commandline tests:", function()
local parser = require("toggleterm.commandline")
it("should return a table containg correct arguments", function()
local file = vim.fn.tempname() .. ".txt"
vim.cmd(fmt("e %s", file))
local result = parser.parse("cmd='echo %' dir='/test dir/file.txt'")
assert.is_truthy(result.cmd)
assert.is_truthy(result.dir)
assert.equal(fmt("echo %s", file), result.cmd)
assert.equal("/test dir/file.txt", result.dir)
end)
it("should handle double quotes", function()
local result = parser.parse('cmd="git status"')
assert.truthy(result.cmd)
assert.equal("git status", result.cmd)
end)
it("should handle non-quoted arguments", function()
local result = parser.parse("direction=horizontal dir=/test/file.txt")
assert.is_truthy(result.dir)
assert.is_truthy(result.direction)
assert.equal("/test/file.txt", result.dir)
assert.equal("horizontal", result.direction)
end)
it("should handle size args correctly", function()
local result = parser.parse("size=34")
assert.is_truthy(result.size)
assert.is_true(type(result.size) == "number")
assert.equal(34, result.size)
end)
it("should handle name args correctly", function()
local result = parser.parse("name=sample")
assert.is_truthy(result.name)
assert.is_true(type(result.name) == "string")
assert.equal("sample", result.name)
end)
it("should handle go_back args correctly", function()
local result = parser.parse("go_back=0")
assert.is_true(type(result.go_back) == "boolean")
assert.is_false(result.go_back)
end)
it("should handle open args correctly", function()
local result = parser.parse("open=0")
assert.is_true(type(result.open) == "boolean")
assert.is_false(result.open)
end)
end)

View File

@ -0,0 +1,39 @@
local M = {}
function M.root(root)
local f = debug.getinfo(1, "S").source:sub(2)
return vim.fn.fnamemodify(f, ":p:h:h") .. "/" .. (root or "")
end
---@param plugin string
function M.load(plugin)
local name = plugin:match(".*/(.*)")
local package_root = M.root(".tests/site/pack/deps/start/")
if not vim.loop.fs_stat(package_root .. name) then
print("Installing " .. plugin)
vim.fn.mkdir(package_root, "p")
vim.fn.system({
"git",
"clone",
"--depth=1",
"https://github.com/" .. plugin .. ".git",
package_root .. "/" .. name,
})
end
end
function M.setup()
vim.cmd([[set runtimepath=$VIMRUNTIME]])
vim.opt.runtimepath:append(M.root())
vim.opt.packpath = { M.root(".tests/site") }
M.load("nvim-lua/plenary.nvim")
vim.env.XDG_CONFIG_HOME = M.root(".tests/config")
vim.env.XDG_DATA_HOME = M.root(".tests/data")
vim.env.XDG_STATE_HOME = M.root(".tests/state")
vim.env.XDG_CACHE_HOME = M.root(".tests/cache")
end
vim.o.swapfile = false
_G.__TEST = true
M.setup()

View File

@ -0,0 +1,43 @@
_G.IS_TEST = true
local t = require("toggleterm.terminal")
local Terminal = t.Terminal
describe("Terminal state - ", function()
local toggleterm
vim.o.hidden = true
vim.o.swapfile = false
before_each(function()
package.loaded["toggleterm"] = nil
toggleterm = require("toggleterm")
toggleterm.setup({ start_in_insert = true })
end)
after_each(function() require("toggleterm.terminal").__reset() end)
-- TODO: this test fails because (I think) the shell takes some time to start up and
-- and so the right autocommands haven't fired yet
pending("should persist the terminal state when the window is closed", function()
vim.cmd("edit test.txt")
local term = Terminal:new():toggle()
assert.is_equal(vim.bo.buftype, "terminal")
vim.api.nvim_feedkeys("ils", "x", true)
assert.is.equal("ls", vim.api.nvim_get_current_line())
term:close()
assert.is_not_equal(vim.bo.buftype, "terminal")
assert.equal(t.mode.INSERT, term.__state.mode)
end)
pending("should restore the terminal state when the window is re-opened", function()
local term = Terminal:new():toggle()
term:close()
term:open()
assert.equal(term.__state.mode, t.mode.UNSUPPORTED)
term:set_mode(t.mode.INSERT)
vim.cmd("wincmd p")
vim.cmd("wincmd p")
assert.equal(term.__state.mode, t.mode.INSERT)
end)
end)

View File

@ -0,0 +1,474 @@
_G.IS_TEST = true
local api = vim.api
local fn = vim.fn
local fmt = string.format
local spy = require("luassert.spy")
local match = require("luassert.match")
local toggleterm = require("toggleterm")
local constants = require("toggleterm.constants")
local ui = require("toggleterm.ui")
local t = require("toggleterm.terminal")
---@type Terminal
local Terminal = t.Terminal
---@type fun(): Terminal[]
local get_all = t.get_all
---Return if a terminal has windows
---@param term table
---@return boolean, TerminalWindow[]
local function term_has_windows(term)
return ui.find_open_windows(function(buf) return buf == term.bufnr end)
end
describe("ToggleTerm tests:", function()
-- We must set hidden to use the plugin
vim.o.hidden = true
after_each(function() require("toggleterm.terminal").__reset() end)
describe("toggling terminals - ", function()
it("new terminals are assigned incremental ids", function()
local test1 = Terminal:new():toggle()
local test2 = Terminal:new():toggle()
local test3 = Terminal:new():toggle()
assert.are.same(test1.id, 1)
assert.are.same(test2.id, 2)
assert.are.same(test3.id, 3)
end)
it("should assign the next id filling in any missing gaps", function()
Terminal:new({ id = 2 }):toggle() --2
Terminal:new():toggle() --1
Terminal:new():toggle() --3
Terminal:new():toggle() --4
Terminal:new({ id = 6 }):toggle() --6
local terms = get_all()
terms[3]:shutdown()
terms[1]:shutdown()
local new1 = Terminal:new():toggle()
assert.equal(1, new1.id)
local new3 = Terminal:new():toggle()
assert.equal(3, new3.id)
local new5 = Terminal:new():toggle()
assert.equal(5, new5.id)
local new7 = Terminal:new():toggle()
assert.equal(7, new7.id)
end)
it("should get terminals as a list", function()
Terminal:new({ id = 20 }):toggle()
Terminal:new():toggle()
local terms = get_all()
assert.equal(#terms, 2)
assert.equal(terms[#terms].id, 20)
end)
it("should open a terminal window on toggle", function()
local test1 = Terminal:new()
test1:toggle()
assert.is_true(api.nvim_buf_is_valid(test1.bufnr))
assert.is_true(vim.tbl_contains(api.nvim_list_wins(), test1.window))
end)
it("should close a terminal window if open", function()
local test1 = Terminal:new()
test1:toggle()
assert.is_true(vim.tbl_contains(api.nvim_list_wins(), test1.window))
test1:toggle()
assert.is_not_true(vim.tbl_contains(api.nvim_list_wins(), test1.window))
end)
it("should toggle a specific buffer if a count is passed", function()
toggleterm.toggle(2, 15)
local terminals = get_all()
assert.equals(#terminals, 1)
local term = terminals[1]
assert.is_true(term_has_windows(term))
end)
it("should not list hidden terminals", function()
Terminal:new({ hidden = true }):toggle()
local terminals = get_all()
assert.equal(#terminals, 0)
Terminal:new():toggle()
terminals = get_all()
assert.equal(#terminals, 1)
end)
-- FIXME: this test does not work despite the functionality seeming to work
-- the idea here is that if a custom terminal with hidden = true is created
-- then it shouldn't be toggled open or closed if the general toggleterm command
-- is run so I expect to still see that it's window is open
pending("should not toggle a terminal if hidden", function()
local term = Terminal:new({ cmd = "bash", hidden = true }):toggle()
assert.is_true(term_has_windows(term))
toggleterm.toggle(1)
assert.is_true(term_has_windows(term))
end)
it("should not toggle a terminal if not hidden", function()
local term = Terminal:new():toggle()
assert.is_true(term_has_windows(term))
toggleterm.toggle(1)
assert.is_false(term_has_windows(term))
end)
it("should create a terminal with a custom command", function()
Terminal:new({ cmd = "ls" }):toggle()
assert.truthy(vim.b.term_title:match("ls"))
end)
-- FIXME: Fix flaky test
pending("should spawn in the background", function()
local stdout = {}
local has_spawned = function() return table.concat(stdout, ""):match("SPAWNED") ~= nil end
Terminal:new({
cmd = [[echo SPAWNED]],
on_stdout = function(_, _, lines) vim.list_extend(stdout, lines) end,
}):spawn()
-- Wait some time if job is not ready
vim.wait(1500, has_spawned)
assert.is_true(has_spawned())
end)
-- FIXME: Fix flaky test
pending("should pass environmental variables", function()
local stdout = {}
local expected = "TESTVAR = 0123456789"
local find_end = function() return table.concat(stdout, ""):match(expected) end
Terminal:new({
cmd = [[echo "TESTVAR = $TESTVAR END"]],
env = { TESTVAR = "0123456789" },
on_stdout = function(_, _, lines) vim.list_extend(stdout, lines) end,
}):toggle()
-- Wait some time if job is not ready
vim.wait(500, find_end)
assert.are.equal(expected, table.concat(stdout, " "):match("TESTVAR = %S+"))
end)
it("should open the correct terminal if a user specifies a count", function()
local term = Terminal:new({ count = 5 }):toggle()
term:toggle()
assert.is_false(ui.term_has_open_win(term))
toggleterm.toggle(5)
assert.is_true(ui.term_has_open_win(term))
end)
it("should open the last toggled terminal", function()
-- GIVEN two opened terminals
toggleterm.toggle(1)
toggleterm.toggle(2)
-- AND then closed first terminal
toggleterm.toggle(1)
-- AND then close second terminal via smart toggle
toggleterm.toggle(0)
-- WHEN a smart toggle is hit
toggleterm.toggle(0)
local terms = get_all()
--- THEN only the second terminal should be opened
assert.is_true(ui.term_has_open_win(terms[2]))
assert.is_false(ui.term_has_open_win(terms[1]))
end)
it("should open the last toggled terminal view", function()
-- GIVEN two opened terminals
toggleterm.toggle(1)
toggleterm.toggle(2)
get_all()[1]:focus()
-- AND then closed terminal view via smart toggle
toggleterm.toggle(0)
-- WHEN a smart toggle is hit
toggleterm.toggle(0)
--- THEN both terminals should be opened
local terms = get_all()
local term1 = terms[1]
local term2 = terms[2]
assert.is_true(term1:is_focused())
assert.is_false(term2:is_focused())
assert.is_true(ui.term_has_open_win(term2))
assert.is_true(ui.term_has_open_win(term1))
end)
it("should open the last toggled nth terminal", function()
-- GIVEN two opened terminals
toggleterm.toggle(1)
toggleterm.toggle(2)
-- AND then closed terminal view via smart toggle
toggleterm.toggle(0)
-- AND then open and close 3rd terminal
toggleterm.toggle(3)
toggleterm.toggle(3)
-- WHEN a smart toggle is hit
toggleterm.toggle(0)
local terms = get_all()
--- THEN only 3rd terminal should be opened
assert.is_true(ui.term_has_open_win(terms[3]))
assert.is_false(ui.term_has_open_win(terms[2]))
assert.is_false(ui.term_has_open_win(terms[1]))
end)
it("should open a hidden terminal and a visible one", function()
local hidden = Terminal:new({ hidden = true }):toggle()
local visible = Terminal:new():toggle()
hidden:toggle()
visible:toggle()
end)
it("should close all open terminals using toggle all", function()
local test1 = Terminal:new():toggle()
local test2 = Terminal:new():toggle()
toggleterm.toggle_all()
assert.is_false(ui.term_has_open_win(test1))
assert.is_false(ui.term_has_open_win(test2))
end)
it("should open all open terminals using toggle all", function()
local test1 = Terminal:new():toggle()
local test2 = Terminal:new():toggle()
toggleterm.toggle_all()
assert.is_false(ui.term_has_open_win(test1))
assert.is_false(ui.term_has_open_win(test2))
toggleterm.toggle_all()
assert.is_true(ui.term_has_open_win(test1))
assert.is_true(ui.term_has_open_win(test2))
end)
-- FIXME: broken in CI
-- it("should close on exit", function()
-- local term = Terminal:new():toggle()
-- assert.is_true(ui.term_has_open_win(term))
-- term:send("exit")
-- vim.wait(1000, function() end)
-- assert.is_false(ui.term_has_open_win(term))
-- end)
end)
describe("terminal buffers options - ", function()
before_each(
function()
toggleterm.setup({
open_mapping = [[<c-\>]],
shade_filetypes = { "none" },
direction = "horizontal",
float_opts = {
height = 10,
width = 20,
},
})
end
)
it("should give each terminal a winhighlight", function()
local test1 = Terminal:new({ direction = "horizontal" }):toggle()
assert.is_true(test1:is_split())
local winhighlight = vim.wo[test1.window].winhighlight
assert.is.truthy(winhighlight:match("Normal:ToggleTerm" .. test1.id .. "Normal"))
end)
it("should set the correct filetype", function()
local test1 = Terminal:new():toggle()
local ft = vim.bo[test1.bufnr].filetype
assert.equals(constants.FILETYPE, ft)
end)
end)
describe("executing commands - ", function()
it("should open a terminal to execute commands", function()
toggleterm.exec("ls", 1)
local terminals = get_all()
assert.is_true(#terminals == 1)
assert.is_true(term_has_windows(terminals[1]))
end)
it("should change terminal's directory if specified", function()
toggleterm.exec("ls", 1, 15, fn.expand("~/"))
local terminals = get_all()
assert.is_true(#terminals == 1)
assert.is_true(term_has_windows(terminals[1]))
end)
it("should send commands to a terminal on exec", function()
local test1 = Terminal:new():toggle()
local _ = match._
spy.on(test1, "send")
toggleterm.exec('echo "hello world"', 1)
assert.spy(test1.send).was_called()
assert.spy(test1.send).was_called_with(_, 'echo "hello world"', true)
assert.is_true(vim.tbl_contains(api.nvim_list_wins(), test1.window))
end)
it("should send commands to a terminal without opening its window", function()
local test1 = Terminal:new():toggle()
test1:close()
spy.on(test1, "send")
toggleterm.exec_command("cmd='echo \"hello world\"' open=0", 1)
assert.spy(test1.send).was_called_with(test1, 'echo "hello world"', false)
assert.is_false(vim.tbl_contains(api.nvim_list_wins(), test1.window))
end)
it("should execute the same regardless whether shell is a string or a function", function()
toggleterm.setup({ shell = function() return vim.o.shell end })
local test1 = Terminal:new():toggle()
local _ = match._
spy.on(test1, "send")
toggleterm.exec('echo "hello world"', 1)
assert.spy(test1.send).was_called()
assert.spy(test1.send).was_called_with(_, 'echo "hello world"', true)
assert.is_true(vim.tbl_contains(api.nvim_list_wins(), test1.window))
end)
it("should expand vim wildcards", function()
local file = vim.fn.tempname() .. ".txt"
vim.cmd(fmt("e %s", file))
local test1 = Terminal:new():toggle()
vim.cmd("wincmd w")
spy.on(test1, "send")
toggleterm.exec_command("cmd='echo %'", 1)
assert.spy(test1.send).was_called_with(test1, fmt("echo %s", file), true)
end)
it("should handle nested quotes in cmd args", function()
local file = vim.fn.tempname() .. ".txt"
vim.cmd(fmt("e %s", file))
local test1 = Terminal:new():toggle()
vim.cmd("wincmd w")
spy.on(test1, "send")
toggleterm.exec_command("cmd='g++ -std=c++17 % -o run'", 1)
assert.spy(test1.send).was_called_with(test1, fmt("g++ -std=c++17 %s -o run", file), true)
end)
end)
describe("terminal mappings behaviour", function()
it("should respect terminal_mappings in terminal mode", function()
toggleterm.setup({ open_mapping = [[<space>t]], terminal_mappings = false })
t.Terminal:new():toggle()
local result = vim.fn.mapcheck("<space>t", "t")
assert.equal("", result)
end)
it("should map in terminal mode if terminal_mappings is true", function()
toggleterm.setup({ open_mapping = [[<space>t]], terminal_mappings = true })
t.Terminal:new():toggle()
local result = vim.fn.mapcheck("<space>t", "t")
assert.is_true(#result > 0)
end)
end)
describe("layout options - ", function()
before_each(
function()
toggleterm.setup({
open_mapping = [[<c-\>]],
shade_filetypes = { "none" },
direction = "horizontal",
float_opts = {
height = 10,
width = 20,
},
})
end
)
it("should open with the correct layout", function()
local term = Terminal:new({ direction = "float" }):toggle()
local _, wins = term_has_windows(term)
assert.equal(#wins, 1)
assert.equal("popup", fn.win_gettype(fn.win_id2win(wins[1].window)))
end)
it("should not change numbers when resolving size", function()
local term = Terminal:new()
local size = 20
assert.equal(size, ui._resolve_size(size))
assert.equal(size, ui._resolve_size(size, term))
end)
it("should evaluate custom functions when resolving size", function()
local term = Terminal:new({ direction = "vertical" })
local size1 = 20
local size2 = function(_t)
if _t.direction == "vertical" then return size1 end
return 0
end
assert.equal(ui._resolve_size(size2, term), size1)
end)
it("should correctly merge a users highlights", function()
toggleterm.setup({
shade_terminals = false,
highlights = {
Normal = {
guibg = "Red",
},
},
})
local config = require("toggleterm.config").get("highlights")
assert.equal(config.Normal.guibg, "Red")
assert.truthy(config.StatusLine.guibg)
end)
it("should prefer shading over a users highlights if they opt to shade terminals", function()
toggleterm.setup({
shade_terminals = true,
highlights = {
Normal = {
guibg = "Red",
},
},
})
local config = require("toggleterm.config").get("highlights")
assert.is_not_equal(config.Normal.guibg, "Red")
assert.truthy(config.StatusLine.guibg)
end)
-- FIXME the height is passed in correctly but is returned as 15
-- which seems to be an nvim quirk not the code
it("should open with user configuration if set", function()
local term = Terminal:new({ direction = "float" }):toggle()
local _, wins = term_has_windows(term)
---@type table
local config = api.nvim_win_get_config(wins[1].window)
assert.equal(config.width, 20)
end)
it("should use a user's selected highlights", function()
local normal = "#000000"
local border = "#ffffff"
local term = Terminal:new({
direction = "float",
highlights = {
NormalFloat = {
guibg = normal,
},
FloatBorder = {
guifg = border,
},
},
float_opts = {
winblend = 12,
},
}):toggle()
local winhighlight = vim.wo[term.window].winhighlight
local winblend = vim.wo[term.window].winblend
assert.equal(12, winblend)
assert.is.truthy(winhighlight:match("NormalFloat:ToggleTerm" .. term.id .. "NormalFloat"))
assert.is.truthy(winhighlight:match("FloatBorder:ToggleTerm" .. term.id .. "FloatBorder"))
end)
end)
end)