1
0
mirror of https://github.com/chylex/IntelliJ-IdeaVim.git synced 2026-04-10 15:57:42 +02:00

Compare commits

...

50 Commits

Author SHA1 Message Date
078ddaf3ca Set plugin version to chylex-56 2026-04-09 21:16:06 +02:00
94a7e1d303 Add 'isactionenabled' function 2026-04-09 21:16:06 +02:00
3de7743f56 Fix Ex commands not working 2026-04-09 19:22:04 +02:00
8636717dea Preserve visual mode after executing IDE action 2026-04-09 19:22:04 +02:00
22dfdd8ca6 Make g0/g^/g$ work with soft wraps 2026-04-09 19:22:03 +02:00
49f9f16f0d Make gj/gk jump over soft wraps 2026-04-09 19:22:03 +02:00
9bfc5d72ce Make camelCase motions adjust based on direction of visual selection 2026-04-09 19:22:03 +02:00
84c227122a Make search highlights temporary 2026-04-09 19:22:03 +02:00
1b9ff4c94a Do not switch to normal mode after inserting a live template 2026-04-09 19:22:03 +02:00
bdecbb5ef0 Exit insert mode after refactoring 2026-04-09 19:22:03 +02:00
7dfd8e6cff Add action to run last macro in all opened files 2026-04-09 19:22:03 +02:00
31e76f0fcf Stop macro execution after a failed search 2026-04-09 19:22:03 +02:00
2aadbdc8f0 Revert per-caret registers 2026-04-09 19:22:03 +02:00
627d65e528 Apply scrolloff after executing native IDEA actions 2026-04-09 19:22:03 +02:00
e77871796e Automatically add unambiguous imports after running a macro 2026-04-09 19:22:03 +02:00
c6e993dcbd Fix(VIM-3986): Exception when pasting register contents containing new line 2026-04-09 19:22:03 +02:00
341ba1ba1f Fix(VIM-3179): Respect virtual space below editor (imperfectly) 2026-04-09 19:22:03 +02:00
f3d7ad55f6 Fix(VIM-3178): Workaround to support "Jump to Source" action mapping 2026-04-09 19:22:03 +02:00
5480b99898 Update search register when using f/t 2026-04-09 19:22:03 +02:00
5734a13ea0 Add support for count for visual and line motion surround 2026-04-09 19:22:02 +02:00
582e6bdcd8 Fix vim-surround not working with multiple cursors
Fixes multiple cursors with vim-surround commands `cs, ds, S` (but not `ys`).
2026-04-09 19:22:02 +02:00
7414c3d3ed Fix(VIM-696): Restore visual mode after undo/redo, and disable incompatible actions 2026-04-09 19:22:02 +02:00
8fa5bec363 Respect count with <Action> mappings 2026-04-09 19:22:02 +02:00
aea54bdf81 Change matchit plugin to use HTML patterns in unrecognized files 2026-04-09 19:22:02 +02:00
79aca4497e Fix ex command panel causing Undock tool window to hide 2026-04-09 19:22:02 +02:00
50976ea9da Revert "VIM-4120 display multiple lines in OutputPanel with different styles"
This reverts commit 5e20bbf1
2026-04-09 19:22:02 +02:00
57d0ef1dd5 Reset insert mode when switching active editor 2026-04-06 20:42:59 +02:00
d2f017887f Remove notifications about configuration options 2026-04-06 20:42:59 +02:00
cfe196ed30 Remove AI 2026-04-06 20:42:59 +02:00
536942f514 Set custom plugin version 2026-04-06 20:42:59 +02:00
36e3cd1adb Revert "Fix(VIM-4108): Use default ANTLR output directory for Gradle 9+ compatibility"
This reverts commit a476583ea3.
2026-04-06 19:58:55 +02:00
7c874f834a Revert "Upgrade Gradle wrapper to 9.2.1"
This reverts commit 517bda93
2026-04-06 19:58:52 +02:00
a4e963c98e Revert "Fix(VIM-4109): Configure test source sets for Gradle 9+ compatibility"
This reverts commit 5c0d9569d9.
2026-04-06 19:58:46 +02:00
1grzyb1
46823abcda Fix timing in jump navigation split tests 2026-04-03 12:25:19 +02:00
d85e7dba19 Fix pumvisible returning opposite result
The implementation was broken in ed50fa28f5, which inverted the result but did not invert the condition.
2026-04-03 12:17:47 +02:00
1grzyb1
a9c3277a51 Reset KeyHandler in rider esc lookup 2026-04-03 11:28:24 +02:00
1grzyb1
6e6039c22a Enable lookup listener only in rider/clion 2026-04-03 11:28:24 +02:00
1grzyb1
b49e896b41 Return VimCaret fields back to IjVimCaret
There was compatibility issue with multicursor due to change of return type
2026-04-03 11:14:54 +02:00
1grzyb1
122b066b75 Return KeyGroup from getKey
There was compatibility issue with multicursor due to change of return type
2026-04-03 11:14:54 +02:00
1grzyb1
cb24ac2bfa Restore public fields in IjVimEditor
Some fields where moved to factory and it resulted in compatybility issues with multicursor plugin
2026-04-03 11:14:54 +02:00
1grzyb1
b14324a3e6 Catching initialization exceptions
When external plugin couldn't be initilized and throw exception it resulted in broken ideavim state
2026-04-03 08:37:20 +02:00
1grzyb1
e40a839f52 Fix Escape not exiting insert mode after Ctrl+Space completion in Rider
Octopus is disabled for Rider (VIM-3815), and Rider's LookupSummaryInfo popup causes the popup manager to consume Escape before IdeaVim's action handlers can process it, so we now listen for explicit lookup cancellation via LookupListener to exit insert mode.
2026-04-02 12:27:25 +02:00
1grzyb1
a45cc0891b Don't extend octopus handler in VimEscForRiderHandler
Octopus is disabled for Rider so VimEscForRiderHandler couldn't properly handle esc
2026-04-02 11:02:08 +02:00
1grzyb1
89bad651c0 Add missing frontend module decriptor 2026-04-02 11:02:04 +02:00
dependabot[bot]
5150dc0c9e Bump io.ktor:ktor-client-content-negotiation from 3.4.1 to 3.4.2
Bumps [io.ktor:ktor-client-content-negotiation](https://github.com/ktorio/ktor) from 3.4.1 to 3.4.2.
- [Release notes](https://github.com/ktorio/ktor/releases)
- [Changelog](https://github.com/ktorio/ktor/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ktorio/ktor/compare/3.4.1...3.4.2)

---
updated-dependencies:
- dependency-name: io.ktor:ktor-client-content-negotiation
  dependency-version: 3.4.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-01 19:54:28 +00:00
dependabot[bot]
c6c7d68876 Bump gradle-wrapper from 9.4.0 to 9.4.1
Bumps [gradle-wrapper](https://github.com/gradle/gradle) from 9.4.0 to 9.4.1.
- [Release notes](https://github.com/gradle/gradle/releases)
- [Commits](https://github.com/gradle/gradle/compare/v9.4.0...v9.4.1)

---
updated-dependencies:
- dependency-name: gradle-wrapper
  dependency-version: 9.4.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-01 19:51:49 +00:00
1grzyb1
02130a87c9 Exit search with proper defocus and handle escape 2026-04-01 11:48:43 +02:00
1grzyb1
40ba977e58 Add run configurations for all platforms
To simplify running ideavim with different platforms, this commit introduce run configurations for each platform both in monolith and split mode
2026-04-01 09:43:37 +02:00
1grzyb1
21f304a560 VIM-4135 fix loading rider module 2026-04-01 09:32:32 +02:00
1grzyb1
36e8bd4663 VIM-4016 Fix :edit when project has no source roots
When project couldn't properlly indexed and didn't have source roots it couldn't find file using edit command. So I've modified it to search using absolute paths in project
2026-03-31 09:48:34 +02:00
153 changed files with 1947 additions and 3118 deletions

40
.beads/.gitignore vendored
View File

@@ -1,40 +0,0 @@
# SQLite databases
*.db
*.db?*
*.db-journal
*.db-wal
*.db-shm
# Daemon runtime files
daemon.lock
daemon.log
daemon.pid
bd.sock
sync-state.json
last-touched
.sync.lock
# Local version tracking (prevents upgrade notification spam after git ops)
.local_version
# Legacy database files
db.sqlite
bd.db
# Worktree redirect file (contains relative path to main repo's .beads/)
# Must not be committed as paths would be wrong in other clones
redirect
# Merge artifacts (temporary files from 3-way merge)
beads.base.jsonl
beads.base.meta.json
beads.left.jsonl
beads.left.meta.json
beads.right.jsonl
beads.right.meta.json
# NOTE: Do NOT add negation patterns (e.g., !issues.jsonl) here.
# They would override fork protection in .git/info/exclude, allowing
# contributors to accidentally commit upstream issue databases.
# The JSONL files (issues.jsonl, interactions.jsonl) and config files
# are tracked by git by default since no pattern above ignores them.

View File

@@ -1,81 +0,0 @@
# Beads - AI-Native Issue Tracking
Welcome to Beads! This repository uses **Beads** for issue tracking - a modern, AI-native tool designed to live directly in your codebase alongside your code.
## What is Beads?
Beads is issue tracking that lives in your repo, making it perfect for AI coding agents and developers who want their issues close to their code. No web UI required - everything works through the CLI and integrates seamlessly with git.
**Learn more:** [github.com/steveyegge/beads](https://github.com/steveyegge/beads)
## Quick Start
### Essential Commands
```bash
# Create new issues
bd create "Add user authentication"
# View all issues
bd list
# View issue details
bd show <issue-id>
# Update issue status
bd update <issue-id> --status in_progress
bd update <issue-id> --status done
# Sync with git remote
bd sync
```
### Working with Issues
Issues in Beads are:
- **Git-native**: Stored in `.beads/issues.jsonl` and synced like code
- **AI-friendly**: CLI-first design works perfectly with AI coding agents
- **Branch-aware**: Issues can follow your branch workflow
- **Always in sync**: Auto-syncs with your commits
## Why Beads?
**AI-Native Design**
- Built specifically for AI-assisted development workflows
- CLI-first interface works seamlessly with AI coding agents
- No context switching to web UIs
🚀 **Developer Focused**
- Issues live in your repo, right next to your code
- Works offline, syncs when you push
- Fast, lightweight, and stays out of your way
🔧 **Git Integration**
- Automatic sync with git commits
- Branch-aware issue tracking
- Intelligent JSONL merge resolution
## Get Started with Beads
Try Beads in your own projects:
```bash
# Install Beads
curl -sSL https://raw.githubusercontent.com/steveyegge/beads/main/scripts/install.sh | bash
# Initialize in your repo
bd init
# Create your first issue
bd create "Try out Beads"
```
## Learn More
- **Documentation**: [github.com/steveyegge/beads/docs](https://github.com/steveyegge/beads/tree/main/docs)
- **Quick Start Guide**: Run `bd quickstart`
- **Examples**: [github.com/steveyegge/beads/examples](https://github.com/steveyegge/beads/tree/main/examples)
---
*Beads: Issue tracking that moves at the speed of thought*

View File

@@ -1,62 +0,0 @@
# Beads Configuration File
# This file configures default behavior for all bd commands in this repository
# All settings can also be set via environment variables (BD_* prefix)
# or overridden with command-line flags
# Issue prefix for this repository (used by bd init)
# If not set, bd init will auto-detect from directory name
# Example: issue-prefix: "myproject" creates issues like "myproject-1", "myproject-2", etc.
# issue-prefix: ""
# Use no-db mode: load from JSONL, no SQLite, write back after each command
# When true, bd will use .beads/issues.jsonl as the source of truth
# instead of SQLite database
# no-db: false
# Disable daemon for RPC communication (forces direct database access)
# no-daemon: false
# Disable auto-flush of database to JSONL after mutations
# no-auto-flush: false
# Disable auto-import from JSONL when it's newer than database
# no-auto-import: false
# Enable JSON output by default
# json: false
# Default actor for audit trails (overridden by BD_ACTOR or --actor)
# actor: ""
# Path to database (overridden by BEADS_DB or --db)
# db: ""
# Auto-start daemon if not running (can also use BEADS_AUTO_START_DAEMON)
# auto-start-daemon: true
# Debounce interval for auto-flush (can also use BEADS_FLUSH_DEBOUNCE)
# flush-debounce: "5s"
# Git branch for beads commits (bd sync will commit to this branch)
# IMPORTANT: Set this for team projects so all clones use the same sync branch.
# This setting persists across clones (unlike database config which is gitignored).
# Can also use BEADS_SYNC_BRANCH env var for local override.
# If not set, bd sync will require you to run 'bd config set sync.branch <branch>'.
# sync-branch: "beads-sync"
# Multi-repo configuration (experimental - bd-307)
# Allows hydrating from multiple repositories and routing writes to the correct JSONL
# repos:
# primary: "." # Primary repo (where this database lives)
# additional: # Additional repos to hydrate from (read-only)
# - ~/beads-planning # Personal planning repo
# - ~/work-planning # Work planning repo
# Integration settings (access with 'bd config get/set')
# These are stored in the database, not in this file:
# - jira.url
# - jira.project
# - linear.url
# - linear.api-key
# - github.org
# - github.repo

View File

@@ -1,4 +0,0 @@
{
"database": "beads.db",
"jsonl_export": "issues.jsonl"
}

View File

@@ -1,73 +0,0 @@
---
name: code-reviewer
description: Code reviewer for IdeaVim - focuses on Vim compatibility, Kotlin/Java quality, IntelliJ Platform patterns, and test coverage.
model: inherit
color: pink
---
You are a code reviewer for IdeaVim, an open-source Vim emulator plugin for JetBrains IDEs. Your focus is on Vim compatibility, code quality, and maintainability.
## Project Context
IdeaVim is:
- Written primarily in Kotlin with some Java
- An IntelliJ Platform plugin
- Split into `vim-engine` (platform-independent) and `IdeaVim` (IntelliJ-specific) modules
- Goal: Match Vim functionality and architecture as closely as possible
## When Reviewing Code
### Vim Compatibility
- Does the change match Vim's behavior? Check against `:help` documentation
- Is `@VimBehaviorDiffers` annotation used if behavior intentionally differs from Vim?
- Are motions correctly typed (inclusive, exclusive, or linewise via `MotionType`)?
- Do extensions use the same command names as original Vim plugins?
### Code Quality (Kotlin/Java)
- Kotlin is preferred for new code; Java only where explicitly used
- Check for null safety, proper use of Kotlin idioms
- Resource management (especially with IntelliJ Platform disposables)
- Error handling appropriate for plugin context
### IntelliJ Platform Patterns
- Correct use of Application/Project services
- Proper threading (read/write actions, EDT vs background)
- Disposable lifecycle management
- Action system usage (`<Action>` in mappings, not `:action`)
### Test Coverage
Check that tests cover corner cases from CONTRIBUTING.md:
- **Position-based**: line start/end, file start/end, empty line, single char line
- **Content-based**: whitespace-only lines, trailing spaces, tabs/spaces, Unicode, multi-byte chars
- **Selection-based**: multiple carets, visual modes (char/line/block), empty selection
- **Motion-based**: dollar motion, count with motion (e.g., `3w`, `5j`)
- **Buffer state**: empty file, single line file, long lines
Tests using `doTest` are automatically verified against neovim - this is good.
### Test Quality
- Avoid senseless text like "dhjkwaldjwa" - use Lorem Ipsum or realistic code snippets
- Check if `@TestWithoutNeovim` or `@VimBehaviorDiffers` annotations are appropriate
- Property tests in `propertybased` package are flaky by nature - verify if failures relate to the change
## Review Priorities
1. **Correctness** - Does it work as Vim does?
2. **Safety** - No crashes, proper null handling, thread safety
3. **Tests** - Corner cases covered, meaningful test data
4. **Maintainability** - Clear code, follows project patterns
## What NOT to Focus On
- Generic security issues (this is a local editor plugin, not a web service)
- Database queries (there are none)
- Network security (minimal network usage)
- Arbitrary code metrics like "cyclomatic complexity < 10"
## Output Format
Provide concise, actionable feedback:
- Link to specific lines when pointing out issues
- Reference Vim documentation (`:help <topic>`) when relevant
- Suggest specific fixes, not just problem descriptions
- Acknowledge what's done well (briefly)

View File

@@ -1,206 +0,0 @@
# Codebase Maintenance Instructions
## Goal
Perform routine maintenance on random parts of the IdeaVim codebase to ensure code quality, consistency, and catch potential issues early. This is not about being overly pedantic or making changes for the sake of changes - it's about keeping an eye on the codebase and identifying genuine issues.
## Approach
### 1. Select Random Area
Choose a random part of the codebase to inspect. Use one of these strategies:
```bash
# Get a random Kotlin file
find . -name "*.kt" -not -path "*/build/*" -not -path "*/.gradle/*" | shuf -n 1
# Get a random package/directory
find . -type d -name "*.kt" -not -path "*/build/*" | shuf -n 1 | xargs dirname
# Pick from core areas randomly
# - vim-engine/src/main/kotlin/com/maddyhome/idea/vim/
# - src/main/java/com/maddyhome/idea/vim/
# - tests/
```
**Important**: You're not limited to the file you randomly selected. If investigating reveals related files that need attention, follow the trail. The random selection is just a starting point.
## 2. What to Check
### Code Style & Formatting
- **Kotlin conventions**: Proper use of data classes, sealed classes, when expressions
- **Naming consistency**: Follow existing patterns in the codebase
- **Import organization**: Remove unused imports, prefer explicit imports over wildcards (wildcard imports are generally not welcome)
- **Code structure**: Proper indentation, spacing, line breaks
- **Documentation**: KDoc comments where needed (public APIs, complex logic)
- **Copyright years**: Do NOT update copyright years unless you're making substantive changes to the file. It's perfectly fine for copyright to show an older year. Don't mention copyright year updates in commit messages or change summaries
### Code Quality Issues
- **Null safety**: Proper use of nullable types, safe calls, Elvis operator
- **Error handling**: Appropriate exception handling, meaningful error messages
- **Code duplication**: Identify repeated code that could be extracted
- **Dead code**: Unused functions, parameters, variables
- **TODOs/FIXMEs**: Check if old TODOs are still relevant or can be addressed
- **Magic numbers/strings**: Should be named constants
- **Complex conditionals**: Can they be simplified or extracted?
### Potential Bugs
- **Off-by-one errors**: Especially in loops and range operations
- **Edge cases**: Empty collections, null values, boundary conditions
- **Type safety**: Unnecessary casts, unchecked casts
- **Resource handling**: Proper cleanup, try-with-resources
- **Concurrency issues**: Thread safety if applicable
- **State management**: Proper initialization, mutation patterns
- **IdeaVim enablement checks**: Verify that `injector.enabler.isEnabled()` or `Editor.isIdeaVimDisabledHere` are not missed in places where they should be checked. These functions determine if IdeaVim is active and should be called before performing Vim-specific operations
### Architecture & Design
- **Separation of concerns**: Does the code have a single responsibility?
- **Dependency direction**: Are dependencies pointing the right way?
- **Abstraction level**: Consistent level of abstraction within methods
- **Vim architecture alignment**: Does it match Vim's design philosophy?
- **IntelliJ Platform conventions**: Proper use of platform APIs
### Testing
- **Test coverage**: Are there tests for the code you're reviewing?
- If checking a specific command or function, verify that tests exist for it
- If tests exist, check if they cover the needed cases (edge cases, error conditions, typical usage)
- If tests don't exist or coverage is incomplete, consider creating comprehensive test coverage
- **Test quality**: Do tests cover edge cases?
- **Test naming**: Clear, descriptive test names
- **Flaky tests**: Any potentially unstable tests?
- **Regression tests for bug fixes**: When fixing a bug, always write a test that:
- Would fail with the old (buggy) implementation
- Passes with the fixed implementation
- Clearly documents what bug it's testing (include comments explaining the issue)
- Tests the specific boundary condition or edge case that exposed the bug
- This ensures the bug doesn't resurface in future refactorings
## 3. Investigation Strategy
Don't just look at surface-level issues. Dig deeper:
1. **Read the code**: Understand what it does before suggesting changes
2. **Check related files**: Look at callers, implementations, tests
3. **Look at git history**: `git log --oneline <file>` to understand context
4. **Find related issues**: Search for TODOs, FIXMEs, or commented code
5. **Run tests**: If you make changes, ensure tests pass
6. **Check YouTrack**: Look for related issues if you find bugs
## 4. When to Make Changes
**DO fix**:
- Clear bugs or logic errors
- Obvious code quality issues (unused imports, etc.)
- Misleading or incorrect documentation
- Code that violates established patterns
- Security vulnerabilities
- Performance issues with measurable impact
**DON'T fix**:
- Stylistic preferences if existing code is consistent
- Working code just to use "newer" patterns
- Minor formatting if it's consistent with surrounding code
- Things that are subjective or arguable
- Massive refactorings without clear benefit
**When in doubt**: Document the issue in your report but don't make changes.
## 5. Making Changes
If you decide to make changes:
1. **Make focused commits**: One logical change per commit
- If the change affects many files or is complicated or has multiple logical changes, split it into multiple step-by-step commits
- This makes it easier for reviewers to understand the changes
- Example: First commit renames a function, second commit updates callers, third commit adds new functionality
- This rule is important!
2. **Write clear commit messages**: Explain why, not just what
3. **Run tests**: `./gradlew test -x :tests:property-tests:test -x :tests:long-running-tests:test`
## 6. Examples
### Good Maintenance Examples
**Example 1: Found and fixed null safety issue**
```
Inspected: vim-engine/.../motion/VimMotionHandler.kt
Issues found:
- Several nullable properties accessed without safe checks
- Could cause NPE in edge cases with cursor at document end
Changes:
- Added null checks with Elvis operator
- Added early returns for invalid state
- Added KDoc explaining preconditions
```
**Example 2: No changes needed**
```
Inspected: src/.../action/change/ChangeLineAction.kt
Checked:
- Code style and formatting ✓
- Null safety ✓
- Error handling ✓
- Tests present and comprehensive ✓
Observations:
- Code is well-structured and follows conventions
- Good test coverage including edge cases
- Documentation is clear
- No issues found
```
**Example 3: Found issues but didn't fix**
```
Inspected: tests/.../motion/MotionTests.kt
Issues noted:
- Some test names could be more descriptive
- Potential for extracting common setup code
- Tests are comprehensive but could add edge case for empty file
Recommendation: These are minor quality-of-life improvements.
Not critical, but could be addressed in future cleanup.
```
## IdeaVim-Specific Considerations
- **Vim compatibility**: Changes should maintain compatibility with Vim behavior
- **IntelliJ Platform**: Follow IntelliJ platform conventions and APIs
- **Property tests**: Can be flaky - verify if test failures relate to your changes
- **Action syntax**: Use `<Action>` in mappings, not `:action`
- **Architecture & Guidelines**: Refer to [CONTRIBUTING.md](../CONTRIBUTING.md) for:
- Architecture overview and where to find specific code
- Testing guidelines and corner cases to consider
- Common patterns and conventions
## Commands Reference
```bash
# Run tests (standard suite)
./gradlew test -x :tests:property-tests:test -x :tests:long-running-tests:test
# Run specific test class
./gradlew test --tests "ClassName"
# Check code style
./gradlew ktlintCheck
# Format code
./gradlew ktlintFormat
# Run IdeaVim in dev instance
./gradlew runIde
```
## Final Notes
- **Be thorough but practical**: Don't waste time on nitpicks
- **Context matters**: Understand why code is the way it is before changing
- **Quality over quantity**: One good fix is better than ten trivial changes
- **Document your process**: Help future maintainers understand your thinking
- **Learn from the code**: Use this as an opportunity to understand the codebase better
Remember: The goal is to keep the codebase healthy, not to achieve perfection. Focus on genuine improvements that make the code safer, clearer, or more maintainable.

View File

@@ -1,5 +0,0 @@
{
"enabledPlugins": {
"context7@claude-plugins-official": true
}
}

View File

@@ -1,234 +0,0 @@
---
name: changelog
description: Maintains IdeaVim changelog (CHANGES.md) and build.gradle.kts changeNotes. Use when updating changelog, documenting releases, or reviewing commits/PRs for changelog entries.
---
# Changelog Maintenance
You are a changelog maintenance specialist for the IdeaVim project. Your job is to keep the changelog (CHANGES.md) and build.gradle.kts changeNotes in sync with code changes.
## Historical Context
- The changelog was actively maintained until version 2.9.0
- There's a gap from 2.10.0 through 2.27.0 where changelog wasn't maintained
- We're resuming changelog maintenance from version 2.28.0 onwards
- Between 2.9.0 and 2.28.0, include this note: **"Changelog was not maintained for versions 2.10.0 through 2.27.0"**
## Changelog Structure
### [To Be Released] Section
- All unreleased changes from master branch go here
- When a release is made, this section becomes the new version section
- Create a new empty `[To Be Released]` section after each release
### Version Entry Format
```
## 2.28.0, 2024-MM-DD
### Features:
* Feature description without ticket number
* `CommandName` action can be used... | [VIM-XXXX](https://youtrack.jetbrains.com/issue/VIM-XXXX)
### Fixes:
* [VIM-XXXX](https://youtrack.jetbrains.com/issue/VIM-XXXX) Bug fix description
### Changes:
* Other changes
```
## How to Gather Information
### 1. Check Current State
- Read CHANGES.md to find the last documented version
- **Important**: Only read the top portion of CHANGES.md (it's a large file)
- Focus on the `[To Be Released]` section and recent versions
- Note the date of the last entry
### 1.5. Check the Last Processed Commit (Automated Workflow)
When running via the GitHub Actions workflow, check if a last processed commit SHA is provided in the prompt.
- If a commit SHA is provided, use `git log <SHA>..HEAD --oneline` to see only unprocessed commits
- This is more accurate than date-based filtering
- The last successful workflow run is tracked via GitHub Actions API
### 2. Find Releases
- Use `git tag --list --sort=-version:refname` to see all version tags
- Tags like `2.27.0`, `2.27.1` indicate releases
- Note: Patch releases (x.x.1, x.x.2) might be on separate branches
- Release dates available at: https://plugins.jetbrains.com/plugin/164-ideavim/versions
### 3. Review Changes
```bash
# Get commits since last documented version
git log --oneline --since="YYYY-MM-DD" --first-parent master
# Get merged PRs
gh pr list --state merged --limit 100 --json number,title,author,mergedAt
# Check specific release commits
git log --oneline <previous-tag>..<new-tag>
```
**Important**: Don't just read commit messages - examine the actual changes:
- Use `git show <commit-hash>` to see the full commit content
- Look at modified test files to find specific examples of fixed commands
- Check the actual code changes to understand what was really fixed or added
- Tests often contain the best examples for changelog entries (e.g., exact commands that now work)
### 4. What to Include
- **Features**: New functionality with [VIM-XXXX] ticket numbers if available
- **Bug Fixes**: Fixed issues with [VIM-XXXX] ticket references
- **Breaking Changes**: Any backwards-incompatible changes
- **Deprecations**: Features marked for future removal
- **Merged PRs**: Reference significant PRs like "Implement vim-surround (#123)"
- Note: PRs have their own inclusion rules - see "Merged PRs Special Rules" section below
### 5. What to Exclude
- Dependabot PRs (author: dependabot[bot])
- Claude-generated PRs (check PR author/title)
- Internal refactoring with no user impact
- Documentation-only changes (unless significant)
- Test-only changes
- **API module changes** (while in experimental status) - Do not log changes to the `api` module as it's currently experimental
- Note: This exclusion should be removed once the API status is no longer experimental
- **Vim Everywhere project** (including Hints toggle) - Do not log changes related to the Vim Everywhere project as it's not yet ready
- **Internal code changes** - Do not log coding changes that users cannot see or experience
- Refactoring, code cleanup, internal architecture changes
- Performance optimizations (unless they fix a noticeable user issue)
- Remember: The changelog is for users, not developers
## Writing Style
- **Be concise**: One line per change when possible
- **User-focused**: Describe what changed from user's perspective
- Write for end users, not developers
- Focus on visible behavior changes, new commands, fixed issues users experience
- Avoid technical implementation details
- **Include examples** when helpful:
- For fixes: Show the command/operation that now works correctly
- For features: Demonstrate the new commands or functionality
- Good example: "Fixed `ci"` command in empty strings" or "Added support for `gn` text object"
- Bad examples (too vague, unclear what was broken):
- "Fixed count validation in text objects"
- "Fixed inlay offset calculations"
- Better: Specify the actual case - "Fixed `3daw` deleting wrong number of words" or "Fixed cursor position with inlay hints in `f` motion"
- **If you can't determine the specific case from tests/code, omit the entry rather than leave it unclear**
- **Add helpful links** for context:
- When mentioning IntelliJ features, search for official JetBrains documentation or blog posts
- When referencing Vim commands, link to Vim documentation if helpful
- Example: "Added support for [Next Edit Suggestion](https://blog.jetbrains.com/ai/2025/08/introducing-next-edit-suggestions-in-jetbrains-ai-assistant/)"
- Use web search to find the most relevant official sources
- **Include references**: Add [VIM-XXXX] for YouTrack tickets, (#XXX) for PRs
- **Group logically**: Features, Fixes, Changes, Merged PRs
- **No duplication**: Each change appears in exactly ONE subsection - don't repeat items across categories
- **Use consistent tense**: Past tense for completed work
## Examples of Good Entries
```
### Features:
* Added support for `gn` text object - select next match with `gn`, change with `cgn`
* Implemented `:tabmove` command - use `:tabmove +1` or `:tabmove -1` to reorder tabs
* Support for `z=` to show spelling suggestions
* Added integration with [Next Edit Suggestion](https://blog.jetbrains.com/ai/2025/08/introducing-next-edit-suggestions-in-jetbrains-ai-assistant/) feature
* Support for [multiple cursors](https://www.jetbrains.com/help/idea/multicursor.html) in visual mode
### Fixes:
* [VIM-3456](https://youtrack.jetbrains.com/issue/VIM-3456) Fixed cursor position after undo in visual mode
* [VIM-3458](https://youtrack.jetbrains.com/issue/VIM-3458) Fixed `ci"` command now works correctly in empty strings
* [VIM-3260](https://youtrack.jetbrains.com/issue/VIM-3260) Fixed `G` command at file end with count
* [VIM-3180](https://youtrack.jetbrains.com/issue/VIM-3180) Fixed `vib` and `viB` selection in nested blocks
### Merged PRs:
* [805](https://github.com/JetBrains/ideavim/pull/805) by [chylex](https://github.com/chylex): VIM-3238 Fix recording a macro that replays another macro
```
## IMPORTANT Format Notes
### For Fixes:
Always put the ticket link FIRST, then the description:
```
* [VIM-XXXX](https://youtrack.jetbrains.com/issue/VIM-XXXX) Description of what was fixed
```
### For Features:
- Without ticket: Just the description
- With ticket: Can use either format:
- Description with pipe: `* Feature description | [VIM-XXXX](https://youtrack.jetbrains.com/issue/VIM-XXXX)`
- Link first (like fixes): `* [VIM-XXXX](https://youtrack.jetbrains.com/issue/VIM-XXXX) Feature description`
### Avoid Duplication:
- **Each change should appear in only ONE subsection**
- If a feature is listed in Features, don't repeat it in Fixes
- If a bug fix is in Fixes, don't list it again elsewhere
- Choose the most appropriate category for each change
### Merged PRs Special Rules:
- **Different criteria than other sections**: The exclusion rules for Features/Fixes don't apply here
- **Include PRs from external contributors** even if they're internal changes or refactoring
- **List significant community contributions** regardless of whether they're user-visible
- **Format**: PR number, author, and brief description
- **Use PR title as-is**: Take the description directly from the PR title, don't regenerate or rewrite it
- **Purpose**: Acknowledge community contributions and provide PR tracking
- The "user-visible only" rule does NOT apply to this section
## Process
1. Read the current CHANGES.md (only the top portion - focus on `[To Be Released]` and recent versions)
2. Check previous changelog PRs from GitHub:
- Review the last few changelog update PRs (use `gh pr list --search "Update changelog" --state all --limit 5`)
- **Read the PR comments**: Use `gh pr view <PR_NUMBER> --comments` to check for specific instructions
- Look for any comments or instructions about what NOT to log this time
- Previous PRs may contain specific exclusions or special handling instructions
- Pay attention to review feedback that might indicate what to avoid in future updates
3. Check git tags for any undocumented releases
4. Review commits and PRs since last entry
5. Group changes by release or under [To Be Released]
6. Update CHANGES.md maintaining existing format
7. Update the `changeNotes` section in `build.gradle.kts` (see detailed instructions below)
8. Create a PR only if there are changes to document:
- Title format: "Update changelog: <super short summary>"
- Example: "Update changelog: Add gn text object, fix visual mode issues"
- Body: Brief summary of what was added
## Updating changeNotes in build.gradle.kts
The `changeNotes` section in `build.gradle.kts` displays on the JetBrains Marketplace plugin page. Follow these rules:
### Content Requirements
- **Match CHANGES.md exactly**: Use the same content from the `[To Be Released]` section
- **Don't create a shorter version**: Include all entries as they appear in CHANGES.md
- **Keep the same level of detail**: Don't summarize or condense
### HTML Formatting
Convert Markdown to HTML format:
- Headers: `### Features:` -> `<b>Features:</b>`
- Line breaks: Use `<br>` between items
- Links: Convert markdown links to HTML `<a href="">` tags
- Bullet points: Use `*` or keep `*` with proper spacing
- Code blocks: Use `<code>` tags for commands like `<code>gn</code>`
### Special Notes
- **IMPORTANT**: Keep any existing information about the reward program in changeNotes
- This content appears in the plugin description on JetBrains Marketplace
### Example Conversion
Markdown in CHANGES.md:
```
### Features:
* Added support for `gn` text object
* [VIM-3456](https://youtrack.jetbrains.com/issue/VIM-3456) Fixed cursor position
```
HTML in changeNotes:
```html
<b>Features:</b><br>
* Added support for <code>gn</code> text object<br>
* <a href="https://youtrack.jetbrains.com/issue/VIM-3456">VIM-3456</a> Fixed cursor position<br>
```
## Important Notes
- **Don't create a PR if changelog is already up to date**
- **Preserve existing format and structure**
- **Maintain chronological order (newest first)**
- **Keep the historical gap note between 2.9.0 and 2.28.0**

View File

@@ -1,275 +0,0 @@
---
name: doc-sync
description: Keeps IdeaVim documentation in sync with code changes. Use this skill when you need to verify documentation accuracy after code changes, or when checking if documentation (in doc/, README.md, CONTRIBUTING.md) matches the current codebase. The skill can work bidirectionally - from docs to code verification, or from code changes to documentation updates.
---
# Doc Sync Skill
You are a documentation synchronization specialist for the IdeaVim project. Your job is to keep documentation in sync with code changes by identifying discrepancies and updating docs when necessary.
## Documentation Locations
The IdeaVim project has documentation in these locations:
- `doc/` folder - Detailed documentation files
- `README.md` - Main project README
- `CONTRIBUTING.md` - Contribution guidelines
## Core Mindset
**CRITICAL:** After code changes, documentation is **GUILTY until proven innocent**.
**WRONG APPROACH:** "Be conservative, only update if clearly wrong"
**RIGHT APPROACH:** "Be aggressive finding issues, conservative making fixes"
**Trust Hierarchy:**
1. Working Implementation in codebase (highest truth)
2. API Definition (interface/class)
3. Documentation (assume outdated until verified)
## Phase 0: Pre-Analysis Search (DO THIS FIRST)
Before reading full files, run these quick searches to find red flags:
### 1. Find Working Examples (Ground Truth)
```bash
# Find real implementations
grep -r '@VimPlugin\|@Plugin\|class.*Extension' --include="*.kt" | head -5
# Or search for known implementation patterns
find . -name "*NewApi.kt" -o -name "*Example*.kt"
```
**Read at least ONE working implementation as ground truth.** This shows you what "correct" looks like.
### 2. Check Recent Breaking Changes
```bash
# Check recent commits to the changed files
git log --oneline -10 -- '**/[ChangedFile]*'
# Look for removal commits
git log --grep="remove\|deprecate\|incorrect" --oneline -10
# Check what was actually deleted (more important than additions!)
git show [recent-commit] --stat
```
### 3. Quick Pattern Search in Documentation
```bash
# Find all named parameters in code examples
grep -E '\w+\s*=' doc/*.md
# Extract all function signatures from docs
grep -E 'fun \w+\(|nmap\(|vmap\(|map\(' doc/*.md -B1 -A3
```
Compare each signature/parameter against the actual API.
## Two Modes of Operation
### Mode A: Documentation → Code Verification
Starting with documentation, verify that the code still matches what's documented.
**Steps:**
0. **FIRST:** Find working implementation as ground truth (Phase 0)
1. Read the specified documentation file(s)
2. Extract ALL code examples and function signatures
3. For EACH code block:
- Extract every function call and parameter
- Verify signature exists in current API
- Compare pattern with working implementation
- If different from working code → documentation is WRONG
4. Update documentation if needed
### Mode B: Code Changes → Documentation Update
Starting with code changes (e.g., from git diff), find related documentation and update if needed.
**Steps:**
0. **FIRST:** Understand what was REMOVED (Phase 0 - check git show/diff)
1. Read the changed files and git diff
2. Understand what changed (especially deletions and breaking changes)
3. Find working implementations that use the new API
4. Search for documentation that references these files/features/APIs
5. Extract all code examples from docs
6. Compare each example against working implementation
7. Update documentation to match the correct pattern
## Important Guidelines
### When to Update
**DO update when:**
- API signatures have changed (parameters added/removed/renamed)
- Function/class/file names have been renamed
- Behavior has fundamentally changed
- Features have been removed or added
- File paths in documentation are now incorrect
- Code examples in docs no longer work
**DON'T update when:**
- Only internal implementation changed (not public API)
- Wording could be slightly better but is still accurate
- Minor formatting inconsistencies
- Documentation uses slightly different terminology but conveys the same meaning
- Changes are in test files that don't affect public API
### Update Strategy
1. **Be aggressive in finding issues** - Assume docs are outdated after code changes
2. **Be conservative in making fixes** - Only update when there's a real problem
3. **Preserve style** - Match the existing documentation style
4. **Be specific** - Don't make sweeping changes; target the specific issue
5. **Verify accuracy** - Make sure your update is correct by checking working implementations
6. **Keep context** - Don't remove helpful context or examples unless they're wrong
### Verification Checklist
For EACH code block in documentation, verify:
- [ ] Extract the complete code example
- [ ] Identify every function call with its parameters
- [ ] For each function: Does this signature exist in current API?
- [ ] For each parameter: Does this parameter name/type exist in API?
- [ ] Does this pattern match the working implementation from codebase?
- [ ] If different from working code → **Documentation is WRONG**
- [ ] If parameters don't exist in API → **Documentation is WRONG**
## Workflow
When invoked, you should:
### Step 0: Establish Ground Truth (CRITICAL - DO FIRST)
- **Find working implementations:** Search for @VimPlugin, real examples in codebase
- **Check git history:** Run `git log -10` on changed files, look for "remove" commits
- **Understand deletions:** Run `git show [commit]` to see what was removed
- **Study working code:** Read at least 1-2 real implementations to understand correct patterns
### Step 1: Understand the Task
- If given doc files: Mode A (verify docs match code)
- If given code changes: Mode B (update docs to match code)
- If given both: Check if the code changes affect the mentioned docs
### Step 2: Quick Pattern Search
- Run grep searches from Phase 0 to find obvious red flags
- Extract all function signatures from docs
- Compare against API and working implementations
### Step 3: Detailed Verification
- Read relevant documentation thoroughly
- For EACH code example: Run through Verification Checklist
- Compare every signature and parameter against actual API
- Compare patterns against working implementations
### Step 4: Analyze Discrepancies
- List what's different between docs and code
- Assess severity (critical vs. minor)
- Determine if update is needed
- **Default to updating** when in doubt about code examples
### Step 5: Make Updates if Needed
- Edit documentation files with precise changes
- Explain what was changed and why
- Verify the update matches working implementation
### Step 6: Report Findings
- Summarize what was checked
- List any discrepancies found
- Describe what was updated (if anything)
- Note anything that might need human review
## Example Usage
### Example 1: Check specific documentation
```
User: "Check if doc/ideavim-mappings.md is in sync with the code"
You should:
0. FIRST: Find working implementation (grep for @VimPlugin or similar)
1. Read at least one working example to establish ground truth
2. Read doc/ideavim-mappings.md
3. Extract ALL code examples and function signatures
4. For EACH signature: verify it exists in API and matches working code
5. Compare patterns with working implementation
6. Update docs if any discrepancies found
```
### Example 2: Code changes → docs
```
User: "I changed MappingScope.kt, check if docs need updating"
You should:
0. FIRST: Check git log and recent commits for MappingScope
1. Run: git log --oneline -10 -- '**/MappingScope*'
2. Check for removal commits: git log --grep="remove" --oneline -5
3. If recent commits removed code: git show [commit] to see what was deleted
4. Find working implementation that uses MappingScope correctly
5. Read MappingScope.kt to understand current API
6. Search docs for references to MappingScope, mapping functions, etc.
7. Extract all code examples from docs
8. Compare each example against working implementation
9. Update docs to match the correct pattern
```
### Example 3: Comprehensive check
```
User: "Check if all documentation in doc/ folder is up to date"
You should:
0. FIRST: Find working implementations as ground truth
1. Check recent git history for breaking changes
2. List files in doc/ folder
3. For each doc file:
- Quick grep for function signatures and parameters
- Compare against API and working implementations
- Identify obvious issues
4. For files with issues: run full Mode A verification
5. Update any that need it
```
## Output Format
Always provide a clear report:
```
## Documentation Sync Report
### Files Checked
- [doc file 1]
- [doc file 2]
- [code file 1]
- [code file 2]
### Discrepancies Found
1. **[Doc file]: [Issue description]**
- Current docs say: [quote]
- Actual code: [description]
- Severity: [Critical/Minor]
- Action: [Updated/No action needed]
### Updates Made
- [File]: [Description of change]
### Notes
- [Any observations or recommendations]
```
## Tools Available
You have access to:
- **Read**: Read any file in the project
- **Edit**: Update documentation files
- **Glob**: Find files by pattern
- **Grep**: Search for text in files
- **Bash**: Run git commands to see recent changes
## Key Lessons Learned
**Most Important Insights:**
1. **Start with working code, not documentation.** The working implementation is your ground truth. Documentation is assumed outdated until proven otherwise.
2. **Deletions matter more than additions.** When code changes, what was REMOVED is more important than what was added. Removed functions/parameters will break documentation examples.
3. **Verify every parameter name.** Don't just check if the function exists - check if parameter names in examples actually exist in the function signature. Named parameters in docs that don't exist in code are a critical bug.
4. **Compare patterns, not just signatures.** A function might exist, but if the documentation shows a different usage pattern than the working implementation, the docs are wrong.
5. **Git history tells the story.** Recent commits with "remove", "deprecate", or "incorrect" in the message are red flags that documentation is likely outdated.
Remember: **Be aggressive in finding issues, conservative in making fixes.** Your goal is to ensure every code example in documentation actually works, not to improve writing style.

View File

@@ -1,207 +0,0 @@
---
name: extensions-api-migration
description: Migrates IdeaVim extensions from the old VimExtensionFacade API to the new @VimPlugin annotation-based API. Use when converting existing extensions to use the new API patterns.
---
# Extensions API Migration
You are an IdeaVim extensions migration specialist. Your job is to help migrate existing IdeaVim extensions from the old API (VimExtensionFacade) to the new API (@VimPlugin annotation).
## Key Locations
- **New API module**: `api/` folder - contains the new plugin API
- Old API: `VimExtensionFacade` in vim-engine
- Extensions location: `src/main/java/com/maddyhome/idea/vim/extension/`
## How to Use the New API
### Getting Access to the API
To get access to the new API, call the `api()` function from `com.maddyhome.idea.vim.extension.api`:
```kotlin
val api = api()
```
Obtain the API at the start of the `init()` method - this is the entry point for all further work.
### Registering Text Objects
Use `api.textObjects { }` to register text objects:
```kotlin
// From VimIndentObject.kt
override fun init() {
val api = api()
api.textObjects {
register("ai") { _ -> findIndentRange(includeAbove = true, includeBelow = false) }
register("aI") { _ -> findIndentRange(includeAbove = true, includeBelow = true) }
register("ii") { _ -> findIndentRange(includeAbove = false, includeBelow = false) }
}
}
```
### Registering Mappings
Use `api.mappings { }` to register mappings:
```kotlin
// From ParagraphMotion.kt
override fun init() {
val api = api()
api.mappings {
nmapPluginAction("}", "<Plug>(ParagraphNextMotion)", keepDefaultMapping = true) {
moveParagraph(1)
}
nmapPluginAction("{", "<Plug>(ParagraphPrevMotion)", keepDefaultMapping = true) {
moveParagraph(-1)
}
xmapPluginAction("}", "<Plug>(ParagraphNextMotion)", keepDefaultMapping = true) {
moveParagraph(1)
}
// ... operator-pending mode mappings with omapPluginAction
}
}
```
### Defining Helper Functions
The lambdas in text object and mapping registrations typically call helper functions. Define these functions with `VimApi` as a receiver - this makes the API available inside:
```kotlin
// From VimIndentObject.kt
private fun VimApi.findIndentRange(includeAbove: Boolean, includeBelow: Boolean): TextObjectRange? {
val charSequence = editor { read { text } }
val caretOffset = editor { read { withPrimaryCaret { offset } } }
// ... implementation using API
}
// From ParagraphMotion.kt
internal fun VimApi.moveParagraph(direction: Int) {
val count = getVariable<Int>("v:count1") ?: 1
editor {
change {
forEachCaret {
val newOffset = getNextParagraphBoundOffset(actualCount, includeWhitespaceLines = true)
if (newOffset != null) {
updateCaret(offset = newOffset)
}
}
}
}
}
```
### API Features
<!-- Fill in additional API features here -->
## How to Migrate Existing Extensions
### What Stays the Same
- The extension **still inherits VimExtensionFacade** - this does not change
- The extension **still registers in the XML file** - this does not change
### Migration Steps
#### Step 1: Ensure Test Coverage
Before starting migration, make sure tests exist for the extension:
- Tests should work and have good coverage
- If there aren't enough tests, create more tests first
- Verify tests pass on the existing version of the plugin
#### Step 2: Migrate in Small Steps
- Don't try to handle everything in one run
- Run tests on the plugin (just the single test class to speed up things) after making smaller changes
- This ensures consistency and makes it easier to identify issues
- **Do a separate commit for each small sensible change or migration** unless explicitly told not to
#### Step 3: Migrate Handlers One by One
If the extension has multiple handlers, migrate them one at a time rather than all at once.
#### Step 4: Handler Migration Process
For each handler, follow this approach:
1. **Inject the API**: Add `val api = api()` as the first line inside the `execute` function
2. **Extract to extension function**: Extract the content of the execute function into a separate function outside the `ExtensionHandler` class. The new function should:
- Have `VimApi` as a receiver
- Use the api that was obtained before
- Keep the extraction as-is (no changes to logic yet)
3. **Verify tests pass**: Run tests to ensure the extraction didn't break anything
4. **Migrate function content**: Now start migrating the content of the extracted function to use the new API
5. **Verify tests pass again**: Run tests after each significant change
6. **Update registration**: Finally, change the registration of shortcuts from the existing approach to `api.mappings { }` where you call the newly created function
#### Example Migration Flow
```kotlin
// BEFORE: Old style handler
class MyHandler : ExtensionHandler {
override fun execute(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments) {
// ... implementation
}
}
// STEP 1: Inject API
class MyHandler : ExtensionHandler {
override fun execute(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments) {
val api = api()
// ... implementation
}
}
// STEP 2: Extract to extension function (as-is)
class MyHandler : ExtensionHandler {
override fun execute(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments) {
val api = api()
api.doMyAction(/* pass needed params */)
}
}
private fun VimApi.doMyAction(/* params */) {
// ... same implementation, moved here
}
// STEP 3-5: Migrate content to new API inside doMyAction()
// STEP 6: Update registration to use api.mappings { }
override fun init() {
val api = api()
api.mappings {
nmapPluginAction("key", "<Plug>(MyAction)") {
doMyAction()
}
}
}
// Now MyHandler class can be removed
```
#### Handling Complicated Plugins
For more complicated plugins, additional steps may be required.
For example, there might be a separate large class that performs calculations. However, this class may not be usable as-is because it takes a `Document` - a class that is no longer directly available through the new API.
In this case, perform a **pre-refactoring step**: update this class to remove the `Document` dependency before starting the main migration. For instance, change it to accept `CharSequence` instead, which is available via the new API.
#### Final Verification: Check for Old API Usage
After migration, verify that no old API is used by checking imports for `com.maddyhome`.
**Allowed imports** (these are still required):
- `com.maddyhome.idea.vim.extension.VimExtension`
- `com.maddyhome.idea.vim.extension.api`
Any other `com.maddyhome` imports indicate incomplete migration.

View File

@@ -1,47 +0,0 @@
---
name: git-workflow
description: IdeaVim git workflow conventions covering commits, branches, PRs, and CI. Use when creating commits, managing branches, creating pull requests, reviewing git history, or any git-related activity in the IdeaVim project.
---
# Git Workflow
## Branching
- **Master** is the trunk and MUST always be in a "ready to release" state
- Use **feature branches** for development work
- Naming: `VIM-XXXX/short-description` (e.g., `VIM-3948/editor`)
- Rebase to master frequently to avoid large conflicts
- Small, isolated changes (bug fixes, minor tweaks) MAY go directly to master
- Unfinished changes MAY be committed to master only if they do NOT break functionality
- Use **rebase** for integration, not merge commits (linear history)
## Commits
**Standard format:**
```
VIM-XXXX Description of the change
```
- Start with the YouTrack ticket ID when the change relates to a ticket
- Example: `VIM-3948 Traverse vertical panes in ConfigurableEditor`
**Auto-closing format** (moves YouTrack ticket to "Ready To Release"):
```
fix(VIM-XXXX): Description of the fix
```
**Content rules:**
- Each commit MUST contain a single, focused, meaningful change
- MUST NOT include unrelated changes (formatting, unrelated refactoring)
- Include appropriate tests with behavioral changes
## Pull Requests
- PRs target `master`
- CI runs standard tests automatically (`./gradlew test -x :tests:property-tests:test -x :tests:long-running-tests:test`)
- PRs from external contributors are listed in the changelog under "Merged PRs"
## Issue Tracking
- Use **YouTrack** (not GitHub Issues) - tickets are `VIM-XXXX`
- URL: https://youtrack.jetbrains.com/issues/VIM

View File

@@ -1,125 +0,0 @@
---
name: issues-deduplication
description: Handles deduplication of YouTrack issues. Use when cleaning up duplicate issues, consolidating related bug reports, or organizing issue tracker.
---
# Issues Deduplication
You are an issue tracker specialist for the IdeaVim project. Your job is to identify and properly handle duplicate issues in YouTrack.
## Core Principles
### 1. Choosing Which Issue to Keep Open
**Default rule**: The older issue is typically kept open, and newer issues are marked as duplicates.
**Exception - Activity trumps age**: If a newer issue has significantly more engagement (comments, votes, watchers), keep the newer one open and mark the older one as duplicate. Consider:
- Number of comments
- Number of votes/thumbs-up
- Number of watchers
- Quality of discussion and information
### 2. Never Duplicate Issues with Customer Tags
**IMPORTANT**: Do not mark an issue as duplicate if it has a customer-related tag:
- Tags like `Customer:XXX`
- Company name tags like `Uber`, `Google`, `Meta`, etc.
- Any tag indicating a specific customer reported or is affected by the issue
These issues need individual tracking for customer relationship purposes.
### 3. Closed Issue Warning
**CRITICAL**: Be very careful about duplicating into a closed issue!
Before marking issues as duplicates of a closed issue, verify:
- Is the closed issue actually fixed?
- Does the fix apply to all the duplicate reports?
- Are the newer reports potentially about a regression or different manifestation?
**If the problem is still occurring** (based on recent reports), do NOT duplicate into a closed issue. Instead:
- Reopen the closed issue, OR
- Keep one of the open issues as the primary and duplicate into that
Duplicating active issues into a wrongly-closed issue will mark all related issues as "resolved" and lose track of an unresolved problem.
### 4. Consolidate to a Single Issue
When multiple issues are duplicates of each other (e.g., issues 1, 2, 3, 4, 5):
- **DO**: Mark 2, 3, 4, 5 as duplicates of 1 (star topology)
- **DON'T**: Create chains like 2→1, 3→2, 4→3, 5→4
This makes it easier to track all related reports from a single issue.
### 5. Preserve Unique Information
Before marking an issue as duplicate:
1. Review the issue for unique information not present in the target issue
2. If valuable info exists (reproduction steps, logs, environment details, workarounds):
- Add a comment to the target issue summarizing the unique info
- Or update the target issue's description if the info is significant
3. Then mark as duplicate
## Process
### Step 1: Gather Issue Details
For each candidate issue, collect:
- Issue ID and summary
- Creation date
- Number of comments
- Number of votes
- Tags (especially customer tags)
- Current state (Open, Closed, etc.)
- Key details from description
### Step 2: Group Duplicates
Identify which issues are truly duplicates vs. related-but-different issues.
### Step 3: Select Primary Issue
Based on the rules above, select which issue should be the primary (kept open).
### Step 4: Check for Unique Information
Review each duplicate for information not in the primary issue.
### Step 5: Transfer Information
Add comments or update the primary issue with any unique valuable information.
### Step 6: Mark Duplicates
Use YouTrack to link issues as duplicates:
- Add "duplicates" link from duplicate → primary
- Update the issue state to "Duplicate"
### Step 7: Leave a Courteous Comment
After marking an issue as duplicate, leave a comment on the duplicated issue to:
- Inform the reporter about the merge
- Direct them to the primary issue for updates
- Thank them for their contribution
Example comment:
> This issue has been merged into VIM-XXXX for easier tracking. Please follow that issue for updates. Thank you for your contribution!
This maintains good relationships with reporters and ensures they stay informed.
## YouTrack Operations
### Link as Duplicate
Use `mcp__YouTrack__link_issues` with:
- `issueId`: The duplicate issue
- `targetIssueId`: The primary issue to duplicate into
- `linkName`: "duplicates"
### Add Comment
Use `mcp__YouTrack__add_issue_comment` to transfer unique information.
### Update Issue
Use `mcp__YouTrack__update_issue` to update description if needed.
## Example Decision Matrix
| Scenario | Action |
|----------------------------------------------------------------------------------|------------------------------------------------------------|
| Old issue (2022), new issue (2024) with same problem, similar activity | Duplicate new → old |
| Old issue (2022) with 2 comments, new issue (2024) with 15 comments and 10 votes | Duplicate old → new |
| Issue has `Customer:Acme` tag | Never mark as duplicate |
| Old issue closed as "Fixed", new reports say problem still exists | Keep new issue open, investigate if regression |
| 5 issues about same bug | Pick best one as primary, duplicate all 4 others → primary |

View File

@@ -1,279 +0,0 @@
---
name: tests-maintenance
description: Maintains IdeaVim test suite quality. Reviews disabled tests, ensures Neovim annotations are documented, and improves test readability. Use for periodic test maintenance.
---
# Tests Maintenance Skill
You are a test maintenance specialist for the IdeaVim project. Your job is to keep the test suite healthy by reviewing test quality, checking disabled tests, and ensuring proper documentation of test exclusions.
## Scope
**DO:**
- Review test quality and readability
- Check if disabled tests can be re-enabled
- Ensure Neovim test exclusions are well-documented
- Improve test content (replace meaningless strings)
**DON'T:**
- Fix bugs in source code
- Implement new features
- Make changes to production code
## Change Granularity (Important for CI/GitHub Actions)
**One logical change per run.** This ensures granular, reviewable Pull Requests.
**Rules:**
1. **One test per run**: Focus on a single test file or test method
2. **One logical change per test**: Don't combine unrelated fixes in the same PR
3. **Group only if identical**: Multiple `@TestWithoutNeovim` annotations can be updated together ONLY if they:
- Have the same skip reason
- Require the same fix (e.g., all need the same description added)
- Are part of the same logical issue
**Examples:**
**Good** (pick ONE of these per PR):
- Update one `DIFFERENT``IDEAVIM_API_USED` with description
- Add descriptions to 3 tests that all use `SCROLL` reason (same fix pattern)
- Re-enable one `@Disabled` test that now passes
**Bad** (too many changes):
- Update `DIFFERENT` to `SCROLL` in one test AND `PLUGIN` in another (different reasons)
- Fix test content AND update annotations in the same PR
- Re-enable multiple unrelated disabled tests
**Why this matters:**
- Each PR can be reviewed independently
- Easy to revert if something breaks
- Clear git history of what changed and why
## How to Select Tests
Each run should focus on a small subset. Use one of these strategies:
```bash
# Get a random test file
find . -path "*/test/*" -name "*Test*.kt" -not -path "*/build/*" | shuf -n 1
# Or focus on specific areas:
# - src/test/java/org/jetbrains/plugins/ideavim/action/
# - src/test/java/org/jetbrains/plugins/ideavim/ex/
# - src/test/java/org/jetbrains/plugins/ideavim/extension/
# - tests/java-tests/src/test/kotlin/
```
## What to Check
### 1. Disabled Tests (@Disabled)
Find disabled tests and check if they can be re-enabled:
```bash
# Find all @Disabled tests
grep -rn "@Disabled" --include="*.kt" src/test tests/
```
For each disabled test:
1. **Try running it**: `./gradlew test --tests "ClassName.testMethod"`
2. **If it passes**: Investigate what changed, re-enable with explanation
3. **If it fails**: Ensure reason is documented in @Disabled annotation
4. **If obsolete**: Remove tests for features that no longer exist
### 2. Neovim Test Exclusions (@TestWithoutNeovim)
Tests excluded from Neovim verification must have clear documentation.
```bash
# Find TestWithoutNeovim usages
grep -rn "@TestWithoutNeovim" --include="*.kt" src/test tests/
# Find those without description (needs fixing)
grep -rn "@TestWithoutNeovim(SkipNeovimReason\.[A-Z_]*)" --include="*.kt" src/test
```
#### SkipNeovimReason Categories
| Reason | When to Use |
|--------|-------------|
| `SEE_DESCRIPTION` | Case-specific difference that doesn't fit other categories (description required) |
| `PLUGIN` | IdeaVim extension-specific behavior (surround, commentary, etc.) |
| `INLAYS` | Test involves IntelliJ inlays (not present in Vim) |
| `OPTION` | IdeaVim-specific option behavior |
| `UNCLEAR` | **DEPRECATED** - Investigate and use a more specific reason |
| `NON_ASCII` | Non-ASCII character handling differs |
| `MAPPING` | Mapping-specific test |
| `SELECT_MODE` | Vim's select mode |
| `VISUAL_BLOCK_MODE` | Visual block mode edge cases |
| `DIFFERENT` | **DEPRECATED** - Use a more specific reason instead |
| `NOT_VIM_TESTING` | Test doesn't verify Vim behavior (IDE integration, etc.) |
| `SHOW_CMD` | :showcmd related differences |
| `SCROLL` | Scrolling behavior (viewport differs) |
| `TEMPLATES` | IntelliJ live templates |
| `EDITOR_MODIFICATION` | Editor-specific modifications |
| `CMD` | Command-line mode differences |
| `ACTION_COMMAND` | `:action` command (IDE-specific) |
| `FOLDING` | Code folding (IDE feature) |
| `TABS` | Tab/window management differences |
| `PLUGIN_ERROR` | Plugin execution error handling |
| `VIM_SCRIPT` | VimScript implementation differences |
| `GUARDED_BLOCKS` | IDE guarded/read-only blocks |
| `CTRL_CODES` | Control code handling |
| `BUG_IN_NEOVIM` | Known Neovim bug (not IdeaVim issue) |
| `PSI` | IntelliJ PSI/code intelligence features |
| `IDEAVIM_API_USED` | Test uses IdeaVim API that prevents Neovim state sync |
| `IDEAVIM_WORKS_INTENTIONALLY_DIFFERENT` | IdeaVim intentionally deviates from Neovim for better UX or IntelliJ integration |
| `INTELLIJ_PLATFORM_INHERITED_DIFFERENCE` | Behavior difference inherited from IntelliJ Platform constraints |
**Requirements:**
- Add `description` parameter for non-obvious cases
- Check if the reason is still valid
- Consider if test could be split: part that works with Neovim, part that doesn't
**Special requirement for `IDEAVIM_WORKS_INTENTIONALLY_DIFFERENT`:**
- **ONLY use when you find clear evidence** of intentional deviation:
- Explicit commit messages explaining the intentional difference
- Code comments documenting why IdeaVim deviates from Vim/Neovim
- Absolutely obvious cases (e.g., IntelliJ-specific features not in Neovim)
- **DO NOT use based on guesswork or assumptions**
- If uncertain, use `DIFFERENT` or `UNCLEAR` instead and investigate git history/comments
- The `description` parameter is **mandatory** and must explain what exactly differs and why
**Special requirement for `INTELLIJ_PLATFORM_INHERITED_DIFFERENCE`:**
- Use when behavior difference is due to IntelliJ Platform's underlying implementation
- Common cases include:
- Empty buffer handling (Platform editors can be empty, Neovim buffers always have a newline)
- Position/offset calculations for newline characters
- Line/column indexing differences
- The `description` parameter is **mandatory** and must explain:
- What Platform behavior causes the difference
- How it manifests in the test
- Evidence can be found in Platform API documentation, IdeaVim code comments, or obvious Platform limitations
**Special requirement for `SEE_DESCRIPTION`:**
- Use as a last resort when the difference doesn't fit any standard category
- The `description` parameter is **mandatory** and must provide a clear, specific explanation
- Use sparingly - if multiple tests share similar reasons, consider creating a new dedicated reason
- Always check existing reasons first before using this catch-all
**Handling `DIFFERENT` and `UNCLEAR` (DEPRECATED):**
Both `DIFFERENT` and `UNCLEAR` reasons are deprecated because they're too vague. When you encounter a test with either of these reasons, follow this process:
1. **First, try removing the annotation and running with Neovim:**
```bash
# Comment out or remove @TestWithoutNeovim, then run:
./gradlew test -Dnvim --tests "ClassName.testMethodName"
```
**IMPORTANT:** Verify the output contains `NEOVIM TESTING ENABLED` to confirm Neovim testing is active.
If this message is not present, the test ran without Neovim verification.
2. **If the test passes with Neovim:**
- The annotation is outdated and should be removed
- IdeaVim and Neovim now behave identically for this case
3. **If the test fails with Neovim:**
- Analyze the failure to understand WHY the behavior differs
- Replace `DIFFERENT` with a more specific reason:
- `IDEAVIM_API_USED` - if test uses VimPlugin.* or injector.* APIs directly
- `IDEAVIM_WORKS_INTENTIONALLY_DIFFERENT` - if IdeaVim intentionally deviates (need evidence)
- `INTELLIJ_PLATFORM_INHERITED_DIFFERENCE` - if difference comes from Platform constraints
- `SEE_DESCRIPTION` - for unique cases that don't fit other categories (description required)
- Or another appropriate reason from the table above
- Always add a `description` parameter explaining the specific difference
### 3. Test Quality & Readability
**Meaningful test content**: Avoid senseless text. Look for:
```bash
grep -rn "asdf\|qwerty\|xxxxx\|aaaaa\|dhjkw" --include="*.kt" src/test tests/
```
Replace with:
- Actual code snippets relevant to the test
- Lorem Ipsum template from CONTRIBUTING.md
- Realistic text demonstrating the feature
**Test naming**: Names should explain what's being tested.
### 4. @VimBehaviorDiffers Annotation
Tests marked with this document intentional differences from Vim:
```kotlin
@VimBehaviorDiffers(
originalVimAfter = "expected vim result",
description = "why IdeaVim differs",
shouldBeFixed = true/false
)
```
Check:
- Is the difference still valid?
- If `shouldBeFixed = true`, is there a YouTrack issue?
- Can behavior now be aligned with Vim?
## Making Changes
### When to Change
**DO fix:**
- Unclear or missing test descriptions
- Senseless test content
- Disabled tests that now pass
- Incorrect `@TestWithoutNeovim` reasons
- Missing `description` on annotations
**DON'T:**
- Fix source code bugs
- Implement missing features
- Major refactoring without clear benefit
### Commit Messages
```
tests: Re-enable DeleteMotionTest after fix in #1234
The test was disabled due to a caret positioning bug that was
fixed in commit abc123. Verified the test passes consistently.
```
```
tests: Improve test content readability in ChangeActionTest
Replace meaningless "asdfgh" strings with realistic code snippets
that better demonstrate the change operation behavior.
```
```
tests: Document @TestWithoutNeovim reasons in ScrollTest
Added description parameter to clarify why scroll tests
are excluded from Neovim verification (viewport behavior differs).
```
## Commands Reference
```bash
# Run specific test
./gradlew test --tests "ClassName.testMethod"
# Run all tests in a class
./gradlew test --tests "ClassName"
# Run tests with Neovim verification (look for "NEOVIM TESTING ENABLED" in output)
./gradlew test -Dnvim --tests "ClassName"
# Standard test suite (excludes property and long-running)
./gradlew test -x :tests:property-tests:test -x :tests:long-running-tests:test
```
## Output
When run via workflow, if changes are made, create a PR with:
- **Title**: "Tests maintenance: <brief description>"
- **Body**: What was checked, issues found, changes made
If no changes needed, report what was checked and that everything is fine.

1
.gitattributes vendored Normal file
View File

@@ -0,0 +1 @@
* text=auto eol=lf

4
.gitignore vendored
View File

@@ -26,6 +26,10 @@
.teamcity/target .teamcity/target
.teamcity/*.iml .teamcity/*.iml
# Generated by gradle task "generateGrammarSource"
vim-engine/src/main/java/com/maddyhome/idea/vim/parser/generated
vim-engine/src/main/java/com/maddyhome/idea/vim/regexp/parser/generated
# Created by github automation # Created by github automation
settings.xml settings.xml

2
.idea/misc.xml generated
View File

@@ -18,5 +18,5 @@
</list> </list>
</option> </option>
</component> </component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="corretto-21" project-jdk-type="JavaSDK" /> <component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="jbr-21" project-jdk-type="JavaSDK" />
</project> </project>

View File

@@ -0,0 +1,16 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Split Frontend Debugger" type="Remote" folderName="Split Mode">
<module name="ideavim" />
<option name="USE_SOCKET_TRANSPORT" value="true" />
<option name="SERVER_MODE" value="false" />
<option name="SHMEM_ADDRESS" />
<option name="HOST" value="localhost" />
<option name="PORT" value="5006" />
<option name="AUTO_RESTART" value="false" />
<RunnerSettings RunnerId="Debug">
<option name="DEBUG_PORT" value="5006" />
<option name="LOCAL" value="false" />
</RunnerSettings>
<method v="2" />
</configuration>
</component>

View File

@@ -0,0 +1,24 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Start CLion with IdeaVim" type="GradleRunConfiguration" factoryName="Gradle" folderName="Platforms">
<log_file alias="idea.log" path="$PROJECT_DIR$/build/idea-sandbox/system/log/idea.log" />
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="runClion" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<method v="2" />
</configuration>
</component>

View File

@@ -0,0 +1,25 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Start CLion with IdeaVim (Split Mode)" type="GradleRunConfiguration" factoryName="Gradle" folderName="Platforms (Split)">
<log_file alias="idea.log" path="$PROJECT_DIR$/build/idea-sandbox/system/log/idea.log" />
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="runCLionSplitMode" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>

View File

@@ -1,5 +1,5 @@
<component name="ProjectRunConfigurationManager"> <component name="ProjectRunConfigurationManager">
<configuration default="false" name="Start IJ with IdeaVim (Split Mode)" type="GradleRunConfiguration" factoryName="Gradle"> <configuration default="false" name="Start IJ with IdeaVim (Split Mode)" type="GradleRunConfiguration" factoryName="Gradle" folderName="Split Mode">
<log_file alias="idea.log" path="$PROJECT_DIR$/build/idea-sandbox/system/log/idea.log" /> <log_file alias="idea.log" path="$PROJECT_DIR$/build/idea-sandbox/system/log/idea.log" />
<ExternalSystemSettings> <ExternalSystemSettings>
<option name="executionName" /> <option name="executionName" />

View File

@@ -0,0 +1,25 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Start IJ with IdeaVim (Split Mode Debug Frontend)" type="GradleRunConfiguration" factoryName="Gradle" folderName="Split Mode">
<log_file alias="idea.log" path="$PROJECT_DIR$/build/idea-sandbox/system/log/idea.log" />
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="runIdeSplitModeDebugFrontend" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>

View File

@@ -0,0 +1,24 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Start PyCharm with IdeaVim" type="GradleRunConfiguration" factoryName="Gradle" folderName="Platforms">
<log_file alias="idea.log" path="$PROJECT_DIR$/build/idea-sandbox/system/log/idea.log" />
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="runPycharm" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<method v="2" />
</configuration>
</component>

View File

@@ -0,0 +1,25 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Start PyCharm with IdeaVim (Split Mode)" type="GradleRunConfiguration" factoryName="Gradle" folderName="Platforms (Split)">
<log_file alias="idea.log" path="$PROJECT_DIR$/build/idea-sandbox/system/log/idea.log" />
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="runPycharmSplitMode" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>

View File

@@ -0,0 +1,24 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Start Rider with IdeaVim" type="GradleRunConfiguration" factoryName="Gradle" folderName="Platforms">
<log_file alias="idea.log" path="$PROJECT_DIR$/build/idea-sandbox/system/log/idea.log" />
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="runRider" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<method v="2" />
</configuration>
</component>

View File

@@ -0,0 +1,24 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Start WebStorm with IdeaVim" type="GradleRunConfiguration" factoryName="Gradle" folderName="Platforms">
<log_file alias="idea.log" path="$PROJECT_DIR$/build/idea-sandbox/system/log/idea.log" />
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="runWebstorm" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<method v="2" />
</configuration>
</component>

View File

@@ -0,0 +1,25 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Start WebStorm with IdeaVim (Split Mode)" type="GradleRunConfiguration" factoryName="Gradle" folderName="Platforms (Split)">
<log_file alias="idea.log" path="$PROJECT_DIR$/build/idea-sandbox/system/log/idea.log" />
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value="runWebstormSplitMode" />
</list>
</option>
<option name="vmOptions" value="" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest>
<method v="2" />
</configuration>
</component>

View File

@@ -1,39 +0,0 @@
# CLAUDE.md
Guidance for Claude Code when working with IdeaVim.
## Quick Reference
Essential commands:
- `./gradlew runIde` - Start dev IntelliJ with IdeaVim
- `./gradlew test -x :tests:property-tests:test -x :tests:long-running-tests:test` - Run standard tests
Avoid running all tests, this takes too long. It's preferred to run specific test.
When running gradle tasks, use `--console=plain` for cleaner output without progress bars.
See CONTRIBUTING.md for architecture details and a complete command list.
## IdeaVim-Specific Notes
- Property tests can be flaky - verify if failures relate to your changes
- Use `<Action>` in mappings, not `:action`
- Config file: `~/.ideavimrc` (XDG supported)
- Goal: Match Vim functionality and architecture
## Issue Tracking
This project uses **YouTrack** for issue tracking, NOT GitHub Issues.
- Tickets are prefixed with `VIM-` (e.g., VIM-1234)
- YouTrack URL: https://youtrack.jetbrains.com/issues/VIM
- `gh issue` commands will NOT work
## Additional Documentation
- Changelog maintenance: Handled by the `changelog` skill (auto-detected when updating changelog)
## Active Technologies
- Kotlin (JVM 21) + IntelliJ Platform SDK, IdeaVim vim-engine (001-api-layer)
## Recent Changes
- 001-api-layer: Added Kotlin (JVM 21) + IntelliJ Platform SDK, IdeaVim vim-engine

View File

@@ -6,6 +6,7 @@
* https://opensource.org/licenses/MIT. * https://opensource.org/licenses/MIT.
*/ */
import org.jetbrains.intellij.platform.gradle.IntelliJPlatformType
import org.jetbrains.intellij.platform.gradle.TestFrameworkType import org.jetbrains.intellij.platform.gradle.TestFrameworkType
import org.jetbrains.intellij.platform.gradle.tasks.aware.SplitModeAware import org.jetbrains.intellij.platform.gradle.tasks.aware.SplitModeAware
import org.jetbrains.kotlin.gradle.dsl.JvmTarget import org.jetbrains.kotlin.gradle.dsl.JvmTarget
@@ -26,11 +27,11 @@ buildscript {
classpath("org.eclipse.jgit:org.eclipse.jgit.ssh.apache:7.6.0.202603022253-r") classpath("org.eclipse.jgit:org.eclipse.jgit.ssh.apache:7.6.0.202603022253-r")
classpath("org.kohsuke:github-api:1.305") classpath("org.kohsuke:github-api:1.305")
classpath("io.ktor:ktor-client-core:3.4.1") classpath("io.ktor:ktor-client-core:3.4.2")
classpath("io.ktor:ktor-client-cio:3.4.1") classpath("io.ktor:ktor-client-cio:3.4.2")
classpath("io.ktor:ktor-client-auth:3.4.1") classpath("io.ktor:ktor-client-auth:3.4.2")
classpath("io.ktor:ktor-client-content-negotiation:3.4.1") classpath("io.ktor:ktor-client-content-negotiation:3.4.2")
classpath("io.ktor:ktor-serialization-kotlinx-json:3.4.1") classpath("io.ktor:ktor-serialization-kotlinx-json:3.4.2")
// This comes from the changelog plugin // This comes from the changelog plugin
// classpath("org.jetbrains:markdown:0.3.1") // classpath("org.jetbrains:markdown:0.3.1")
@@ -112,6 +113,8 @@ dependencies {
testFramework(TestFrameworkType.Platform) testFramework(TestFrameworkType.Platform)
testFramework(TestFrameworkType.JUnit5) testFramework(TestFrameworkType.JUnit5)
compatiblePlugin("com.intellij.classic.ui")
pluginModule(runtimeOnly(project(":modules:ideavim-common"))) pluginModule(runtimeOnly(project(":modules:ideavim-common")))
pluginModule(runtimeOnly(project(":modules:ideavim-frontend"))) pluginModule(runtimeOnly(project(":modules:ideavim-frontend")))
pluginModule(runtimeOnly(project(":modules:ideavim-backend"))) pluginModule(runtimeOnly(project(":modules:ideavim-backend")))
@@ -207,6 +210,7 @@ tasks {
// a custom task (see below) // a custom task (see below)
runIde { runIde {
systemProperty("octopus.handler", System.getProperty("octopus.handler") ?: true) systemProperty("octopus.handler", System.getProperty("octopus.handler") ?: true)
systemProperty("idea.trust.all.projects", "true")
} }
// Uncomment to run the plugin in a custom IDE, rather than the IDE specified as a compile target in dependencies // Uncomment to run the plugin in a custom IDE, rather than the IDE specified as a compile target in dependencies
@@ -222,6 +226,30 @@ tasks {
// localPath = file("/Users/{user}/Applications/WebStorm.app") // localPath = file("/Users/{user}/Applications/WebStorm.app")
// } // }
val runPycharm by intellijPlatformTesting.runIde.registering {
type = IntelliJPlatformType.PyCharmProfessional
version = "2025.3.2"
task {
systemProperty("octopus.handler", System.getProperty("octopus.handler") ?: true)
}
}
val runWebstorm by intellijPlatformTesting.runIde.registering {
type = IntelliJPlatformType.WebStorm
version = "2025.3.2"
task {
systemProperty("octopus.handler", System.getProperty("octopus.handler") ?: true)
}
}
val runClion by intellijPlatformTesting.runIde.registering {
type = IntelliJPlatformType.CLion
version = "2025.3.2"
task {
systemProperty("octopus.handler", System.getProperty("octopus.handler") ?: true)
}
}
val runIdeForUiTests by intellijPlatformTesting.runIde.registering { val runIdeForUiTests by intellijPlatformTesting.runIde.registering {
task { task {
jvmArgumentProviders += CommandLineArgumentProvider { jvmArgumentProviders += CommandLineArgumentProvider {
@@ -244,6 +272,55 @@ tasks {
val runIdeSplitMode by intellijPlatformTesting.runIde.registering { val runIdeSplitMode by intellijPlatformTesting.runIde.registering {
splitMode = true splitMode = true
splitModeTarget = SplitModeAware.SplitModeTarget.BOTH splitModeTarget = SplitModeAware.SplitModeTarget.BOTH
plugins {
plugin("AceJump", "3.8.22")
plugin("org.jetbrains.IdeaVim-EasyMotion", "1.16")
}
}
val runWebstormSplitMode by intellijPlatformTesting.runIde.registering {
type = IntelliJPlatformType.WebStorm
version = "2025.3.2"
splitMode = true
splitModeTarget = SplitModeAware.SplitModeTarget.BOTH
plugins {
plugin("AceJump", "3.8.22")
plugin("org.jetbrains.IdeaVim-EasyMotion", "1.16")
}
}
val runRider by intellijPlatformTesting.runIde.registering {
type = IntelliJPlatformType.Rider
version = "2026.1"
task {
systemProperty("idea.log.debug.categories", "com.maddyhome.idea.vim.handler.EditorHandlersChainLogger")
}
plugins {
plugin("AceJump", "3.8.22")
plugin("org.jetbrains.IdeaVim-EasyMotion", "1.16")
}
}
val runCLionSplitMode by intellijPlatformTesting.runIde.registering {
type = IntelliJPlatformType.CLion
version = "2025.3.2"
splitMode = true
splitModeTarget = SplitModeAware.SplitModeTarget.BOTH
plugins {
plugin("AceJump", "3.8.22")
plugin("org.jetbrains.IdeaVim-EasyMotion", "1.16")
}
}
val runPycharmSplitMode by intellijPlatformTesting.runIde.registering {
type = IntelliJPlatformType.PyCharmProfessional
version = "2025.3.2"
splitMode = true
splitModeTarget = SplitModeAware.SplitModeTarget.BOTH
plugins {
plugin("AceJump", "3.8.22")
plugin("org.jetbrains.IdeaVim-EasyMotion", "1.16")
}
} }
// Run split mode with a JDWP debug agent on the frontend (JetBrains Client) process. // Run split mode with a JDWP debug agent on the frontend (JetBrains Client) process.
@@ -252,6 +329,11 @@ tasks {
splitMode = true splitMode = true
splitModeTarget = SplitModeAware.SplitModeTarget.BOTH splitModeTarget = SplitModeAware.SplitModeTarget.BOTH
plugins {
plugin("AceJump", "3.8.22")
plugin("org.jetbrains.IdeaVim-EasyMotion", "1.16")
}
prepareSandboxTask { prepareSandboxTask {
val sandboxDir = project.layout.buildDirectory.dir("idea-sandbox").map { it.asFile } val sandboxDir = project.layout.buildDirectory.dir("idea-sandbox").map { it.asFile }
doLast { doLast {
@@ -283,6 +365,12 @@ tasks {
val testIdeSplitMode by intellijPlatformTesting.testIde.registering { val testIdeSplitMode by intellijPlatformTesting.testIde.registering {
splitMode = true splitMode = true
splitModeTarget = SplitModeAware.SplitModeTarget.BOTH splitModeTarget = SplitModeAware.SplitModeTarget.BOTH
plugins {
plugin("AceJump", "3.8.22")
plugin("org.jetbrains.IdeaVim-EasyMotion", "1.16")
}
task { task {
useJUnitPlatform() useJUnitPlatform()
} }
@@ -300,11 +388,6 @@ tasks {
} }
}) })
} }
buildPlugin {
dependsOn(sourcesJar)
from(sourcesJar) { into("lib/src") }
}
} }
java { java {
@@ -377,13 +460,7 @@ intellijPlatform {
) )
ideaVersion { ideaVersion {
// Let the Gradle plugin set the since-build version. It defaults to the version of the IDE we're building against sinceBuild.set("253")
// specified as two components, `{branch}.{build}` (e.g., "241.15989"). There is no third component specified.
// The until-build version defaults to `{branch}.*`, but we want to support _all_ future versions, so we set it
// with a null provider (the provider is important).
// By letting the Gradle plugin handle this, the Plugin DevKit IntelliJ plugin cannot help us with the "Usage of
// IntelliJ API not available in older IDEs" inspection. However, since our since-build is the version we compile
// against, we can never get an API that's newer - it would be an unresolved symbol.
untilBuild.set(provider { null }) untilBuild.set(provider { null })
} }
} }

View File

@@ -16,11 +16,11 @@
# https://data.services.jetbrains.com/products?code=IU # https://data.services.jetbrains.com/products?code=IU
# Maven releases are here: https://www.jetbrains.com/intellij-repository/releases # Maven releases are here: https://www.jetbrains.com/intellij-repository/releases
# And snapshots: https://www.jetbrains.com/intellij-repository/snapshots # And snapshots: https://www.jetbrains.com/intellij-repository/snapshots
ideaVersion=2025.3 ideaVersion=2026.1
# Values for type: https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#intellij-extension-type # Values for type: https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#intellij-extension-type
ideaType=IU ideaType=IU
instrumentPluginCode=true instrumentPluginCode=true
version=SNAPSHOT version=chylex-56
javaVersion=21 javaVersion=21
remoteRobotVersion=0.11.23 remoteRobotVersion=0.11.23
antlrVersion=4.10.1 antlrVersion=4.10.1
@@ -42,7 +42,6 @@ youtrackToken=
# Gradle settings # Gradle settings
org.gradle.jvmargs='-Dfile.encoding=UTF-8' org.gradle.jvmargs='-Dfile.encoding=UTF-8'
org.gradle.configuration-cache=true
org.gradle.caching=true org.gradle.caching=true
# Disable warning from gradle-intellij-plugin. Kotlin stdlib is included as compileOnly, so the warning is unnecessary # Disable warning from gradle-intellij-plugin. Kotlin stdlib is included as compileOnly, so the warning is unnecessary

View File

@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.0-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
networkTimeout=10000 networkTimeout=10000
validateDistributionUrl=true validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME

2
gradlew vendored
View File

@@ -57,7 +57,7 @@
# Darwin, MinGW, and NonStop. # Darwin, MinGW, and NonStop.
# #
# (3) This script is generated from the Groovy template # (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/b631911858264c0b6e4d6603d677ff5218766cee/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # https://github.com/gradle/gradle/blob/2d6327017519d23b96af35865dc997fcb544fb40/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project. # within the Gradle project.
# #
# You can find Gradle at https://github.com/gradle/gradle/. # You can find Gradle at https://github.com/gradle/gradle/.

View File

@@ -165,25 +165,27 @@ internal class FileRemoteApiImpl : FileRemoteApi {
// ======================== Private helpers ======================== // ======================== Private helpers ========================
private fun findFile(filename: String, project: Project): VirtualFile? { private fun findFile(filename: String, project: Project): VirtualFile? {
var found: VirtualFile?
if (filename.startsWith("~/") || filename.startsWith("~\\")) { if (filename.startsWith("~/") || filename.startsWith("~\\")) {
val relativePath = filename.substring(2) val relativePath = filename.substring(2)
val dir = System.getProperty("user.home") val dir = System.getProperty("user.home")
logger.debug { "home dir file" } logger.debug { "home dir file" }
logger.debug { "looking for $relativePath in $dir" } logger.debug { "looking for $relativePath in $dir" }
found = LocalFileSystem.getInstance().refreshAndFindFileByNioFile(Path(dir, relativePath)) return LocalFileSystem.getInstance().refreshAndFindFileByNioFile(Path(dir, relativePath))
} else {
found = VirtualFileManager.getInstance().findFileByNioPath(Path(filename))
if (found == null) {
found = findByNameInContentRoots(filename, project)
if (found == null) {
found = findByNameInProject(filename, project)
}
}
} }
return found val basePath = project.basePath
if (basePath != null) {
val baseDir = LocalFileSystem.getInstance().refreshAndFindFileByNioFile(Path(basePath))
baseDir?.findFileByRelativePath(filename)?.let { return it }
}
VirtualFileManager.getInstance().findFileByNioPath(Path(filename))?.let { return it }
findByNameInContentRoots(filename, project)?.let { return it }
findByNameInProject(filename, project)?.let { return it }
return null
} }
private fun buildFileInfoMessage(editor: Editor, project: Project, fullPath: Boolean): String { private fun buildFileInfoMessage(editor: Editor, project: Project, fullPath: Boolean): String {

View File

@@ -311,6 +311,7 @@
</group> </group>
<action id="VimFindActionIdAction" class="com.maddyhome.idea.vim.listener.FindActionIdAction"/> <action id="VimFindActionIdAction" class="com.maddyhome.idea.vim.listener.FindActionIdAction"/>
<action id="VimJumpToSource" class="com.intellij.diff.actions.impl.OpenInEditorAction" />
</actions> </actions>
<!-- Frontend vim extensions (editor/text manipulation, no PSI/file-system dependency) --> <!-- Frontend vim extensions (editor/text manipulation, no PSI/file-system dependency) -->

View File

@@ -8,7 +8,7 @@
<idea-plugin> <idea-plugin>
<dependencies> <dependencies>
<module name="com.intellij.modules.rider"/> <plugin id="com.intellij.modules.rider"/>
</dependencies> </dependencies>
<projectListeners> <projectListeners>
<listener class="com.maddyhome.idea.vim.listener.RiderActionListener" <listener class="com.maddyhome.idea.vim.listener.RiderActionListener"

View File

@@ -26,11 +26,11 @@ dependencies {
testImplementation("org.junit.jupiter:junit-jupiter:6.0.3") testImplementation("org.junit.jupiter:junit-jupiter:6.0.3")
testRuntimeOnly("org.junit.platform:junit-platform-launcher") testRuntimeOnly("org.junit.platform:junit-platform-launcher")
implementation("io.ktor:ktor-client-core:3.4.1") implementation("io.ktor:ktor-client-core:3.4.2")
implementation("io.ktor:ktor-client-cio:3.4.1") implementation("io.ktor:ktor-client-cio:3.4.2")
implementation("io.ktor:ktor-client-content-negotiation:3.4.1") implementation("io.ktor:ktor-client-content-negotiation:3.4.2")
implementation("io.ktor:ktor-serialization-kotlinx-json:3.4.1") implementation("io.ktor:ktor-serialization-kotlinx-json:3.4.2")
implementation("io.ktor:ktor-client-auth:3.4.1") implementation("io.ktor:ktor-client-auth:3.4.2")
implementation("org.eclipse.jgit:org.eclipse.jgit:6.6.0.202305301015-r") implementation("org.eclipse.jgit:org.eclipse.jgit:6.6.0.202305301015-r")
// This is needed for jgit to connect to ssh // This is needed for jgit to connect to ssh

View File

@@ -22,6 +22,7 @@ import com.intellij.openapi.util.Disposer;
import com.maddyhome.idea.vim.api.*; import com.maddyhome.idea.vim.api.*;
import com.maddyhome.idea.vim.config.VimState; import com.maddyhome.idea.vim.config.VimState;
import com.maddyhome.idea.vim.config.migration.ApplicationConfigurationMigrator; import com.maddyhome.idea.vim.config.migration.ApplicationConfigurationMigrator;
import com.maddyhome.idea.vim.group.KeyGroup;
import com.maddyhome.idea.vim.group.VimNotifications; import com.maddyhome.idea.vim.group.VimNotifications;
import com.maddyhome.idea.vim.group.VimWindowGroup; import com.maddyhome.idea.vim.group.VimWindowGroup;
import com.maddyhome.idea.vim.history.VimHistory; import com.maddyhome.idea.vim.history.VimHistory;
@@ -130,12 +131,12 @@ public class VimPlugin implements PersistentStateComponent<Element>, Disposable
return VimInjectorKt.getInjector().getHistoryGroup(); return VimInjectorKt.getInjector().getHistoryGroup();
} }
public static @NotNull VimKeyGroup getKey() { public static @NotNull KeyGroup getKey() {
return VimInjectorKt.getInjector().getKeyGroup(); return ((KeyGroup)VimInjectorKt.getInjector().getKeyGroup());
} }
public static @Nullable VimKeyGroup getKeyIfCreated() { public static @Nullable KeyGroup getKeyIfCreated() {
return ApplicationManager.getApplication().getServiceIfCreated(VimKeyGroup.class); return ApplicationManager.getApplication().getServiceIfCreated(KeyGroup.class);
} }
public static @NotNull VimWindowGroup getWindow() { public static @NotNull VimWindowGroup getWindow() {
@@ -337,7 +338,7 @@ public class VimPlugin implements PersistentStateComponent<Element>, Disposable
} }
} }
if (element.getChild("shortcut-conflicts") != null) { if (element.getChild("shortcut-conflicts") != null) {
((VimKeyGroupBase)getKey()).loadShortcutConflictsData(element); getKey().loadShortcutConflictsData(element);
} }
if (element.getChild("editor") != null) { if (element.getChild("editor") != null) {
getEditor().loadEditorStateData(element); getEditor().loadEditorStateData(element);

View File

@@ -0,0 +1,67 @@
package com.maddyhome.idea.vim.action.macro
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.command.UndoConfirmationPolicy
import com.intellij.openapi.command.impl.FinishMarkAction
import com.intellij.openapi.command.impl.StartMarkAction
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.vim.annotations.CommandOrMotion
import com.intellij.vim.annotations.Mode
import com.maddyhome.idea.vim.KeyHandler
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.Argument
import com.maddyhome.idea.vim.command.Command
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.handler.VimActionHandler
import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.newapi.vim
@CommandOrMotion(keys = ["z@"], modes = [Mode.NORMAL])
class PlaybackRegisterInOpenFilesAction : VimActionHandler.SingleExecution() {
override val type: Command.Type = Command.Type.OTHER_SELF_SYNCHRONIZED
override val argumentType: Argument.Type = Argument.Type.CHARACTER
private val playbackRegisterAction = PlaybackRegisterAction()
override fun execute(
editor: VimEditor,
context: ExecutionContext,
cmd: Command,
operatorArguments: OperatorArguments,
): Boolean {
val argument = cmd.argument as? Argument.Character ?: return false
val project = editor.ij.project ?: return false
val fileEditorManager = FileEditorManagerEx.getInstanceExIfCreated(project) ?: return false
val register = argument.character.let { if (it == '@') injector.macro.lastRegister else it }
val commandName = "Execute Macro '$register' in All Open Files"
val action = Runnable {
CommandProcessor.getInstance().markCurrentCommandAsGlobal(project)
for (textEditor in fileEditorManager.allEditors.filterIsInstance<TextEditor>()) {
fileEditorManager.openFile(textEditor.file, true)
val editor = textEditor.editor
val vimEditor = editor.vim
vimEditor.mode = com.maddyhome.idea.vim.state.mode.Mode.NORMAL()
KeyHandler.Companion.getInstance().reset(vimEditor)
val startMarkAction = StartMarkAction.start(editor, project, commandName)
playbackRegisterAction.execute(vimEditor, context, cmd, operatorArguments)
FinishMarkAction.finish(project, editor, startMarkAction)
}
}
CommandProcessor.getInstance()
.executeCommand(project, action, commandName, null, UndoConfirmationPolicy.REQUEST_CONFIRMATION)
return true
}
}

View File

@@ -220,7 +220,7 @@ object VimExtensionFacade {
caret: ImmutableVimCaret, caret: ImmutableVimCaret,
keys: List<KeyStroke?>?, keys: List<KeyStroke?>?,
) { ) {
caret.registerStorage.setKeys(editor, context, register, keys?.filterNotNull() ?: emptyList()) caret.registerStorage.setKeys(register, keys?.filterNotNull() ?: emptyList())
} }
/** Set the current contents of the given register */ /** Set the current contents of the given register */

View File

@@ -11,6 +11,7 @@ import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionPointListener import com.intellij.openapi.extensions.ExtensionPointListener
import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.vim.api.VimInitApi
import com.maddyhome.idea.vim.api.VimExtensionRegistrator import com.maddyhome.idea.vim.api.VimExtensionRegistrator
import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.api.setToggleOption import com.maddyhome.idea.vim.api.setToggleOption
@@ -20,7 +21,6 @@ import com.maddyhome.idea.vim.key.MappingOwner.Plugin.Companion.remove
import com.maddyhome.idea.vim.options.OptionAccessScope import com.maddyhome.idea.vim.options.OptionAccessScope
import com.maddyhome.idea.vim.options.OptionDeclaredScope import com.maddyhome.idea.vim.options.OptionDeclaredScope
import com.maddyhome.idea.vim.options.ToggleOption import com.maddyhome.idea.vim.options.ToggleOption
import com.intellij.vim.api.VimInitApi
import com.maddyhome.idea.vim.statistic.ExtensionTracking import com.maddyhome.idea.vim.statistic.ExtensionTracking
import com.maddyhome.idea.vim.thinapi.VimApiImpl import com.maddyhome.idea.vim.thinapi.VimApiImpl
@@ -106,9 +106,13 @@ class VimExtensionRegistrar : VimExtensionRegistrator {
override fun enableDelayedExtensions() { override fun enableDelayedExtensions() {
delayedExtensionEnabling.forEach { delayedExtensionEnabling.forEach {
val name = it.name ?: it.instance.name val name = it.name ?: it.instance.name
val initApi = createVimApi(name) try {
it.instance.init(initApi) val initApi = createVimApi(name)
logger.info("IdeaVim extension '$name' initialized") it.instance.init(initApi)
logger.info("IdeaVim extension '$name' initialized")
} catch (e: Throwable) {
logger.error("Failed to initialize IdeaVim extension '$name'", e)
}
} }
delayedExtensionEnabling.clear() delayedExtensionEnabling.clear()
} }

View File

@@ -21,9 +21,7 @@ import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Disposer
import com.intellij.util.Alarm import com.intellij.util.Alarm
import com.intellij.util.Alarm.ThreadToUse import com.intellij.util.Alarm.ThreadToUse
import com.jetbrains.rd.util.first
import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.ImmutableVimCaret
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.common.ModeChangeListener import com.maddyhome.idea.vim.common.ModeChangeListener
@@ -123,9 +121,9 @@ internal class VimHighlightedYank : VimExtension, VimYankListener, ModeChangeLis
initialised = false initialised = false
} }
override fun yankPerformed(caretToRange: Map<ImmutableVimCaret, TextRange>) { override fun yankPerformed(editor: VimEditor, range: TextRange) {
ensureInitialised() ensureInitialised()
highlightHandler.highlightYankRange(caretToRange) highlightHandler.highlightYankRange(editor.ij, range)
} }
override fun modeChanged(editor: VimEditor, oldMode: Mode) { override fun modeChanged(editor: VimEditor, oldMode: Mode) {
@@ -146,25 +144,22 @@ internal class VimHighlightedYank : VimExtension, VimYankListener, ModeChangeLis
private var lastEditor: Editor? = null private var lastEditor: Editor? = null
private val highlighters = mutableSetOf<RangeHighlighter>() private val highlighters = mutableSetOf<RangeHighlighter>()
fun highlightYankRange(caretToRange: Map<ImmutableVimCaret, TextRange>) { fun highlightYankRange(editor: Editor, range: TextRange) {
// from vim-highlightedyank docs: When a new text is yanked or user starts editing, the old highlighting would be deleted // from vim-highlightedyank docs: When a new text is yanked or user starts editing, the old highlighting would be deleted
clearYankHighlighters() clearYankHighlighters()
val editor = caretToRange.first().key.editor.ij
lastEditor = editor lastEditor = editor
val attributes = getHighlightTextAttributes(editor) val attributes = getHighlightTextAttributes(editor)
for (range in caretToRange.values) { for (i in 0 until range.size()) {
for (i in 0 until range.size()) { val highlighter = editor.markupModel.addRangeHighlighter(
val highlighter = editor.markupModel.addRangeHighlighter( range.startOffsets[i],
range.startOffsets[i], range.endOffsets[i],
range.endOffsets[i], HighlighterLayer.SELECTION,
HighlighterLayer.SELECTION, attributes,
attributes, HighlighterTargetArea.EXACT_RANGE,
HighlighterTargetArea.EXACT_RANGE, )
) highlighters.add(highlighter)
highlighters.add(highlighter)
}
} }
// from vim-highlightedyank docs: A negative number makes the highlight persistent. // from vim-highlightedyank docs: A negative number makes the highlight persistent.

View File

@@ -268,7 +268,7 @@ private object FileTypePatterns {
} else if (fileTypeName == "CMakeLists.txt" || fileName == "CMakeLists") { } else if (fileTypeName == "CMakeLists.txt" || fileName == "CMakeLists") {
this.cMakePatterns this.cMakePatterns
} else { } else {
return null this.htmlPatterns
} }
} }

View File

@@ -0,0 +1,30 @@
package com.maddyhome.idea.vim.extension.surround
import com.intellij.util.text.CharSequenceSubSequence
internal data class RepeatedCharSequence(val text: CharSequence, val count: Int) : CharSequence {
override val length = text.length * count
override fun get(index: Int): Char {
if (index < 0 || index >= length) throw IndexOutOfBoundsException()
return text[index % text.length]
}
override fun subSequence(startIndex: Int, endIndex: Int): CharSequence {
return CharSequenceSubSequence(this, startIndex, endIndex)
}
override fun toString(): String {
return text.repeat(count)
}
companion object {
fun of(text: CharSequence, count: Int): CharSequence {
return when (count) {
0 -> ""
1 -> text
else -> RepeatedCharSequence(text, count)
}
}
}
}

View File

@@ -15,6 +15,7 @@ import com.maddyhome.idea.vim.KeyHandler
import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimChangeGroup
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.endsWithNewLine import com.maddyhome.idea.vim.api.endsWithNewLine
import com.maddyhome.idea.vim.api.getLeadingCharacterOffset import com.maddyhome.idea.vim.api.getLeadingCharacterOffset
@@ -36,7 +37,10 @@ import com.maddyhome.idea.vim.extension.VimExtensionFacade.setRegisterForCaret
import com.maddyhome.idea.vim.extension.exportOperatorFunction import com.maddyhome.idea.vim.extension.exportOperatorFunction
import com.maddyhome.idea.vim.group.findBlockRange import com.maddyhome.idea.vim.group.findBlockRange
import com.maddyhome.idea.vim.helper.exitVisualMode import com.maddyhome.idea.vim.helper.exitVisualMode
import com.maddyhome.idea.vim.helper.runWithEveryCaretAndRestore
import com.maddyhome.idea.vim.key.OperatorFunction import com.maddyhome.idea.vim.key.OperatorFunction
import com.maddyhome.idea.vim.newapi.IjVimCaret
import com.maddyhome.idea.vim.newapi.IjVimEditor
import com.maddyhome.idea.vim.newapi.ij import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.options.helpers.ClipboardOptionHelper import com.maddyhome.idea.vim.options.helpers.ClipboardOptionHelper
@@ -139,7 +143,7 @@ internal class VimSurroundExtension : VimExtension {
) )
} }
VimExtensionFacade.exportOperatorFunction(OPERATOR_FUNC, Operator()) VimExtensionFacade.exportOperatorFunction(OPERATOR_FUNC, Operator(supportsMultipleCursors = false, count = 1)) // TODO
} }
private class YSurroundHandler : ExtensionHandler { private class YSurroundHandler : ExtensionHandler {
@@ -166,7 +170,7 @@ internal class VimSurroundExtension : VimExtension {
val lastNonWhiteSpaceOffset = getLastNonWhitespaceCharacterOffset(editor.text(), lineStartOffset, lineEndOffset) val lastNonWhiteSpaceOffset = getLastNonWhitespaceCharacterOffset(editor.text(), lineStartOffset, lineEndOffset)
if (lastNonWhiteSpaceOffset != null) { if (lastNonWhiteSpaceOffset != null) {
val range = TextRange(lineStartOffset, lastNonWhiteSpaceOffset + 1) val range = TextRange(lineStartOffset, lastNonWhiteSpaceOffset + 1)
performSurround(pair, range, it) performSurround(pair, range, it, count = operatorArguments.count1)
} }
// it.moveToOffset(lineStartOffset) // it.moveToOffset(lineStartOffset)
} }
@@ -189,15 +193,13 @@ internal class VimSurroundExtension : VimExtension {
private class VSurroundHandler : ExtensionHandler { private class VSurroundHandler : ExtensionHandler {
override fun execute(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments) { override fun execute(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments) {
val selectionStart = editor.ij.caretModel.primaryCaret.selectionStart
// NB: Operator ignores SelectionType anyway // NB: Operator ignores SelectionType anyway
if (!Operator().apply(editor, context, editor.mode.selectionType)) { if (!Operator(supportsMultipleCursors = true, count = operatorArguments.count1).apply(editor, context, editor.mode.selectionType)) {
return return
} }
runWriteAction { runWriteAction {
// Leave visual mode // Leave visual mode
editor.exitVisualMode() editor.exitVisualMode()
editor.ij.caretModel.moveToOffset(selectionStart)
// Reset the key handler so that the command trie is updated for the new mode (Normal) // Reset the key handler so that the command trie is updated for the new mode (Normal)
// TODO: This should probably be handled by ToHandlerMapping.execute // TODO: This should probably be handled by ToHandlerMapping.execute
@@ -220,6 +222,10 @@ internal class VimSurroundExtension : VimExtension {
companion object { companion object {
fun change(editor: VimEditor, context: ExecutionContext, charFrom: Char, newSurround: SurroundPair?) { fun change(editor: VimEditor, context: ExecutionContext, charFrom: Char, newSurround: SurroundPair?) {
editor.ij.runWithEveryCaretAndRestore { changeAtCaret(editor, context, charFrom, newSurround) }
}
fun changeAtCaret(editor: VimEditor, context: ExecutionContext, charFrom: Char, newSurround: SurroundPair?) {
// Save old register values for carets // Save old register values for carets
val surroundings = editor.sortedCarets() val surroundings = editor.sortedCarets()
.map { .map {
@@ -263,7 +269,7 @@ internal class VimSurroundExtension : VimExtension {
it.first + trimmedValue + it.second it.first + trimmedValue + it.second
} ?: innerValue } ?: innerValue
val textData = val textData =
PutData.TextData(null, injector.clipboardManager.dumbCopiedText(text), SelectionType.CHARACTER_WISE) PutData.TextData(text, SelectionType.CHARACTER_WISE, emptyList(), null)
val putData = val putData =
PutData(textData, null, 1, insertTextBeforeCaret = true, rawIndent = true, caretAfterInsertedText = false) PutData(textData, null, 1, insertTextBeforeCaret = true, rawIndent = true, caretAfterInsertedText = false)
@@ -342,20 +348,41 @@ internal class VimSurroundExtension : VimExtension {
} }
} }
private class Operator : OperatorFunction { private class Operator(private val supportsMultipleCursors: Boolean, private val count: Int) : OperatorFunction {
override fun apply(editor: VimEditor, context: ExecutionContext, selectionType: SelectionType?): Boolean { override fun apply(editor: VimEditor, context: ExecutionContext, selectionType: SelectionType?): Boolean {
val ijEditor = editor.ij val ijEditor = editor.ij
val c = injector.keyGroup.getChar(editor) ?: return true val c = injector.keyGroup.getChar(editor) ?: return true
val pair = getOrInputPair(c, ijEditor, context.ij) ?: return false val pair = getOrInputPair(c, ijEditor, context.ij) ?: return false
// XXX: Will it work with line-wise or block-wise selections?
val range = getSurroundRange(editor.currentCaret()) ?: return false runWriteAction {
performSurround(pair, range, editor.currentCaret(), selectionType == SelectionType.LINE_WISE) val change = VimPlugin.getChange()
// Jump back to start if (supportsMultipleCursors) {
executeNormalWithoutMapping(injector.parser.parseKeys("`["), ijEditor) ijEditor.runWithEveryCaretAndRestore {
applyOnce(ijEditor, change, pair, count)
}
}
else {
applyOnce(ijEditor, change, pair, count)
// Jump back to start
executeNormalWithoutMapping(injector.parser.parseKeys("`["), ijEditor)
}
}
return true return true
} }
private fun applyOnce(editor: Editor, change: VimChangeGroup, pair: SurroundPair, count: Int) {
// XXX: Will it work with line-wise or block-wise selections?
val primaryCaret = editor.caretModel.primaryCaret
val range = getSurroundRange(primaryCaret.vim)
if (range != null) {
val start = RepeatedCharSequence.of(pair.first, count)
val end = RepeatedCharSequence.of(pair.second, count)
change.insertText(IjVimEditor(editor), IjVimCaret(primaryCaret), range.startOffset, start)
change.insertText(IjVimEditor(editor), IjVimCaret(primaryCaret), range.endOffset + start.length, end)
}
}
private fun getSurroundRange(caret: VimCaret): TextRange? { private fun getSurroundRange(caret: VimCaret): TextRange? {
val editor = caret.editor val editor = caret.editor
if (editor.mode is Mode.CMD_LINE) { if (editor.mode is Mode.CMD_LINE) {
@@ -444,14 +471,14 @@ private fun getOrInputPair(c: Char, editor: Editor, context: DataContext): Surro
} }
private fun performSurround(pair: SurroundPair, range: TextRange, caret: VimCaret, tagsOnNewLines: Boolean = false) { private fun performSurround(pair: SurroundPair, range: TextRange, caret: VimCaret, count: Int, tagsOnNewLines: Boolean = false) {
val editor = caret.editor val editor = caret.editor
val change = VimPlugin.getChange() val change = VimPlugin.getChange()
val leftSurround = pair.first + if (tagsOnNewLines) "\n" else "" val leftSurround = RepeatedCharSequence.of(pair.first + if (tagsOnNewLines) "\n" else "", count)
val isEOF = range.endOffset == editor.text().length val isEOF = range.endOffset == editor.text().length
val hasNewLine = editor.endsWithNewLine() val hasNewLine = editor.endsWithNewLine()
val rightSurround = if (tagsOnNewLines) { val rightSurround = (if (tagsOnNewLines) {
if (isEOF && !hasNewLine) { if (isEOF && !hasNewLine) {
"\n" + pair.second "\n" + pair.second
} else { } else {
@@ -459,7 +486,7 @@ private fun performSurround(pair: SurroundPair, range: TextRange, caret: VimCare
} }
} else { } else {
pair.second pair.second
} }).let { RepeatedCharSequence.of(it, count) }
change.insertText(editor, caret, range.startOffset, leftSurround) change.insertText(editor, caret, range.startOffset, leftSurround)
change.insertText(editor, caret, range.endOffset + leftSurround.length, rightSurround) change.insertText(editor, caret, range.endOffset + leftSurround.length, rightSurround)

View File

@@ -141,7 +141,7 @@ object IjOptions {
// Temporary feature flags during development, not really intended for external use // Temporary feature flags during development, not really intended for external use
val closenotebooks: ToggleOption = val closenotebooks: ToggleOption =
addOption(ToggleOption("closenotebooks", GLOBAL, "closenotebooks", true, isHidden = true)) addOption(ToggleOption("closenotebooks", GLOBAL, "closenotebooks", true, isHidden = true))
val oldundo: ToggleOption = addOption(ToggleOption("oldundo", GLOBAL, "oldundo", false, isHidden = true)) val oldundo: ToggleOption = addOption(ToggleOption("oldundo", GLOBAL, "oldundo", true, isHidden = true))
val unifyjumps: ToggleOption = addOption(ToggleOption("unifyjumps", GLOBAL, "unifyjumps", true, isHidden = true)) val unifyjumps: ToggleOption = addOption(ToggleOption("unifyjumps", GLOBAL, "unifyjumps", true, isHidden = true))
// This needs to be Option<out VimDataType> so that it can work with derived option types, such as NumberOption, which // This needs to be Option<out VimDataType> so that it can work with derived option types, such as NumberOption, which
// derives from Option<VimInt> // derives from Option<VimInt>

View File

@@ -0,0 +1,68 @@
package com.maddyhome.idea.vim.group
import com.intellij.codeInsight.daemon.ReferenceImporter
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiRecursiveElementWalkingVisitor
import java.util.function.BooleanSupplier
internal object MacroAutoImport {
fun run(editor: Editor, dataContext: DataContext) {
val project = CommonDataKeys.PROJECT.getData(dataContext) ?: return
val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) ?: return
if (!FileDocumentManager.getInstance().requestWriting(editor.document, project)) {
return
}
val importers = ReferenceImporter.EP_NAME.extensionList
if (importers.isEmpty()) {
return
}
ProgressManager.getInstance().run(object : Task.Backgroundable(project, "Auto import", true) {
override fun run(indicator: ProgressIndicator) {
val fixes = ReadAction.nonBlocking<List<BooleanSupplier>> {
val fixes = mutableListOf<BooleanSupplier>()
file.accept(object : PsiRecursiveElementWalkingVisitor() {
override fun visitElement(element: PsiElement) {
for (reference in element.references) {
if (reference.resolve() != null) {
continue
}
for (importer in importers) {
importer.computeAutoImportAtOffset(editor, file, element.textRange.startOffset, true)
?.let(fixes::add)
}
}
super.visitElement(element)
}
})
return@nonBlocking fixes
}.executeSynchronously()
ApplicationManager.getApplication().invokeAndWait {
WriteCommandAction.writeCommandAction(project)
.withName("Auto Import")
.withGroupId("IdeaVimAutoImportAfterMacro")
.shouldRecordActionForActiveDocument(true)
.run<RuntimeException> {
fixes.forEach { it.asBoolean }
}
}
}
})
}
}

View File

@@ -92,6 +92,9 @@ class MacroGroup : VimMacroBase() {
} finally { } finally {
keyStack.removeFirst() keyStack.removeFirst()
} }
if (!isInternalMacro) {
MacroAutoImport.run(editor.ij, context.ij)
}
} }
if (isInternalMacro) { if (isInternalMacro) {

View File

@@ -86,6 +86,9 @@ class MotionGroup : VimMotionGroupBase() {
} }
override fun moveCaretToCurrentDisplayLineStart(editor: VimEditor, caret: ImmutableVimCaret): Motion { override fun moveCaretToCurrentDisplayLineStart(editor: VimEditor, caret: ImmutableVimCaret): Motion {
if (editor.ij.softWrapModel.isSoftWrappingEnabled) {
return AbsoluteOffset(caret.ij.visualLineStart)
}
val col = EditorHelper.getVisualColumnAtLeftOfDisplay(editor.ij, caret.getVisualPosition().line) val col = EditorHelper.getVisualColumnAtLeftOfDisplay(editor.ij, caret.getVisualPosition().line)
return moveCaretToColumn(editor, caret, col, false) return moveCaretToColumn(editor, caret, col, false)
} }
@@ -94,6 +97,15 @@ class MotionGroup : VimMotionGroupBase() {
editor: VimEditor, editor: VimEditor,
caret: ImmutableVimCaret, caret: ImmutableVimCaret,
): @Range(from = 0, to = Int.MAX_VALUE.toLong()) Int { ): @Range(from = 0, to = Int.MAX_VALUE.toLong()) Int {
if (editor.ij.softWrapModel.isSoftWrappingEnabled) {
val offset = caret.ij.visualLineStart
val line = editor.offsetToBufferPosition(offset).line
return if (offset == editor.getLineStartOffset(line)) {
editor.getLeadingCharacterOffset(line, 0)
} else {
offset
}
}
val col = EditorHelper.getVisualColumnAtLeftOfDisplay(editor.ij, caret.getVisualPosition().line) val col = EditorHelper.getVisualColumnAtLeftOfDisplay(editor.ij, caret.getVisualPosition().line)
val bufferLine = caret.getLine() val bufferLine = caret.getLine()
return editor.getLeadingCharacterOffset(bufferLine, col) return editor.getLeadingCharacterOffset(bufferLine, col)
@@ -104,6 +116,9 @@ class MotionGroup : VimMotionGroupBase() {
caret: ImmutableVimCaret, caret: ImmutableVimCaret,
allowEnd: Boolean, allowEnd: Boolean,
): Motion { ): Motion {
if (editor.ij.softWrapModel.isSoftWrappingEnabled) {
return AbsoluteOffset(caret.ij.visualLineEnd - 1)
}
val col = EditorHelper.getVisualColumnAtRightOfDisplay(editor.ij, caret.getVisualPosition().line) val col = EditorHelper.getVisualColumnAtRightOfDisplay(editor.ij, caret.getVisualPosition().line)
return moveCaretToColumn(editor, caret, col, allowEnd) return moveCaretToColumn(editor, caret, col, allowEnd)
} }

View File

@@ -32,7 +32,6 @@ import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.SystemInfo
import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.globalOptions
import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.handler.KeyMapIssue import com.maddyhome.idea.vim.handler.KeyMapIssue
import com.maddyhome.idea.vim.helper.MessageHelper import com.maddyhome.idea.vim.helper.MessageHelper
@@ -40,8 +39,6 @@ import com.maddyhome.idea.vim.icons.VimIcons
import com.maddyhome.idea.vim.key.ShortcutOwner import com.maddyhome.idea.vim.key.ShortcutOwner
import com.maddyhome.idea.vim.key.ShortcutOwnerInfo import com.maddyhome.idea.vim.key.ShortcutOwnerInfo
import com.maddyhome.idea.vim.newapi.globalIjOptions import com.maddyhome.idea.vim.newapi.globalIjOptions
import com.maddyhome.idea.vim.newapi.ijOptions
import com.maddyhome.idea.vim.options.OptionConstants
import com.maddyhome.idea.vim.statistic.ActionTracker import com.maddyhome.idea.vim.statistic.ActionTracker
import com.maddyhome.idea.vim.ui.VimEmulationConfigurable import com.maddyhome.idea.vim.ui.VimEmulationConfigurable
import com.maddyhome.idea.vim.vimscript.services.VimRcService import com.maddyhome.idea.vim.vimscript.services.VimRcService
@@ -64,55 +61,9 @@ internal class NotificationService(private val project: Project?) : VimNotificat
@Suppress("unused") @Suppress("unused")
constructor() : this(null) constructor() : this(null)
override fun notifyAboutIdeaPut() { override fun notifyAboutIdeaPut() {}
val notification = Notification(
IDEAVIM_NOTIFICATION_ID,
IDEAVIM_NOTIFICATION_TITLE,
"""Add <code>ideaput</code> to <code>clipboard</code> option to perform a put via the IDE<br/><b><code>set clipboard+=ideaput</code></b>""",
NotificationType.INFORMATION,
)
notification.addAction(OpenIdeaVimRcAction(notification)) override fun notifyAboutIdeaJoin(editor: VimEditor) {}
notification.addAction(
AppendToIdeaVimRcAction(
notification,
"set clipboard^=ideaput",
"ideaput",
) {
// Technically, we're supposed to prepend values to clipboard so that it's not added to the "exclude" item.
// Since we don't handle exclude, it's safe to append. But let's be clean.
injector.globalOptions().clipboard.prependValue(OptionConstants.clipboard_ideaput)
},
)
notification.notify(project)
}
override fun notifyAboutIdeaJoin(editor: VimEditor) {
val notification = Notification(
IDEAVIM_NOTIFICATION_ID,
IDEAVIM_NOTIFICATION_TITLE,
"""Put <b><code>set ideajoin</code></b> into your <code>~/.ideavimrc</code> to perform a join via the IDE""",
NotificationType.INFORMATION,
)
notification.addAction(OpenIdeaVimRcAction(notification))
notification.addAction(
AppendToIdeaVimRcAction(
notification,
"set ideajoin",
"ideajoin"
) {
// This is a global-local option. Setting it will always set the global value
injector.ijOptions(editor).ideajoin = true
},
)
notification.addAction(HelpLink(ideajoinExamplesUrl))
notification.notify(project)
}
override fun enableRepeatingMode() = Messages.showYesNoDialog( override fun enableRepeatingMode() = Messages.showYesNoDialog(
"Do you want to enable repeating keys in macOS on press and hold?\n\n" + "Do you want to enable repeating keys in macOS on press and hold?\n\n" +

View File

@@ -24,10 +24,9 @@ import org.jetbrains.annotations.Nullable;
import javax.swing.*; import javax.swing.*;
import java.awt.event.KeyEvent; import java.awt.event.KeyEvent;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import static com.maddyhome.idea.vim.api.VimInjectorKt.injector;
/** /**
* This group works with command associated with copying and pasting text * This group works with command associated with copying and pasting text
*/ */
@@ -128,7 +127,7 @@ public class RegisterGroup extends VimRegisterGroupBase
final String text = XMLGroup.getInstance().getSafeXmlText(textElement); final String text = XMLGroup.getInstance().getSafeXmlText(textElement);
if (text != null) { if (text != null) {
logger.trace("Register data parsed"); logger.trace("Register data parsed");
register = new Register(key, injector.getClipboardManager().dumbCopiedText(text), type); register = new Register(key, type, text, Collections.emptyList());
} }
else { else {
logger.trace("Cannot parse register data"); logger.trace("Cannot parse register data");

View File

@@ -37,7 +37,6 @@ import com.maddyhome.idea.vim.ide.isClionNova
import com.maddyhome.idea.vim.ide.isRider import com.maddyhome.idea.vim.ide.isRider
import com.maddyhome.idea.vim.mark.VimMarkConstants.MARK_CHANGE_POS import com.maddyhome.idea.vim.mark.VimMarkConstants.MARK_CHANGE_POS
import com.maddyhome.idea.vim.newapi.IjVimCaret import com.maddyhome.idea.vim.newapi.IjVimCaret
import com.maddyhome.idea.vim.newapi.IjVimCopiedText
import com.maddyhome.idea.vim.newapi.IjVimEditor import com.maddyhome.idea.vim.newapi.IjVimEditor
import com.maddyhome.idea.vim.newapi.ij import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.newapi.vim
@@ -127,7 +126,7 @@ internal class PutGroup : VimPutBase() {
point.dispose() point.dispose()
if (!caret.isValid) return@forEach if (!caret.isValid) return@forEach
val caretPossibleEndOffset = lastPastedRegion?.endOffset ?: (startOffset + text.copiedText.text.length) val caretPossibleEndOffset = lastPastedRegion?.endOffset ?: (startOffset + text.text.length)
val endOffset = if (data.indent) { val endOffset = if (data.indent) {
doIndent( doIndent(
vimEditor, vimEditor,
@@ -179,10 +178,12 @@ internal class PutGroup : VimPutBase() {
val allContentsBefore = CopyPasteManager.getInstance().allContents val allContentsBefore = CopyPasteManager.getInstance().allContents
val sizeBeforeInsert = allContentsBefore.size val sizeBeforeInsert = allContentsBefore.size
val firstItemBefore = allContentsBefore.firstOrNull() val firstItemBefore = allContentsBefore.firstOrNull()
logger.debug { "Copied text: ${text.copiedText}" } logger.debug { "Transferable classes: ${text.transferableData.joinToString { it.javaClass.name }}" }
val (textContent, transferableData) = text.copiedText as IjVimCopiedText
val origContent: TextBlockTransferable = val origContent: TextBlockTransferable =
injector.clipboardManager.setClipboardText(textContent, textContent, transferableData) as TextBlockTransferable injector.clipboardManager.setClipboardText(
text.text,
transferableData = text.transferableData,
) as TextBlockTransferable
val allContentsAfter = CopyPasteManager.getInstance().allContents val allContentsAfter = CopyPasteManager.getInstance().allContents
val sizeAfterInsert = allContentsAfter.size val sizeAfterInsert = allContentsAfter.size
try { try {
@@ -190,7 +191,7 @@ internal class PutGroup : VimPutBase() {
} finally { } finally {
val textInClipboard = (firstItemBefore as? TextBlockTransferable) val textInClipboard = (firstItemBefore as? TextBlockTransferable)
?.getTransferData(DataFlavor.stringFlavor) as? String ?.getTransferData(DataFlavor.stringFlavor) as? String
val textOnTop = textInClipboard != null && textInClipboard != text.copiedText.text val textOnTop = textInClipboard != null && textInClipboard != text.text
if (sizeBeforeInsert != sizeAfterInsert || textOnTop) { if (sizeBeforeInsert != sizeAfterInsert || textOnTop) {
// Sometimes an inserted text replaces an existing one. E.g. on insert with + or * register // Sometimes an inserted text replaces an existing one. E.g. on insert with + or * register
(CopyPasteManager.getInstance() as? CopyPasteManagerEx)?.run { removeContent(origContent) } (CopyPasteManager.getInstance() as? CopyPasteManagerEx)?.run { removeContent(origContent) }

View File

@@ -241,13 +241,17 @@ internal class VimEscHandler(nextHandler: EditorActionHandler) : VimKeyHandler(n
/** /**
* Rider (and CLion Nova) uses a separate handler for esc to close the completion. IdeaOnlyEscapeHandlerAction is especially * Rider (and CLion Nova) uses a separate handler for esc to close the completion. IdeaOnlyEscapeHandlerAction is especially
* designer to get all the esc presses, and if there is a completion close it and do not pass the execution further. * designed to get all the esc presses, and if there is a completion close it and do not pass the execution further.
* This doesn't work the same as in IJ. * This doesn't work the same as in IJ.
* In IdeaVim, we'd like to exit insert mode on closing completion. This is a requirement as the change of this * In IdeaVim, we'd like to exit insert mode on closing completion. This is a requirement as the change of this
* behaviour causes a lot of complaining from users. Since the rider handler gets execution control, we don't * behaviour causes a lot of complaining from users. Since the rider handler gets execution control, we don't
* receive an event and don't exit the insert mode. * receive an event and don't exit the insert mode.
* To fix it, this special handler exists only for rider and stands before the rider's handler. We don't execute the * To fix it, this special handler exists only for rider and stands before the rider's handler. We don't execute the
* handler from rider because the autocompletion is closed automatically anyway. * handler from rider because the autocompletion is closed automatically anyway.
*
* NOTE: This handler only works when octopus is enabled (non-Rider IDEs). For Rider, where octopus is disabled
* (VIM-3815) and Escape is consumed by the popup manager before the EditorEscape chain fires, the fix is in
* [com.maddyhome.idea.vim.listener.IdeaSpecifics.LookupTopicListener] via a LookupListener.
*/ */
internal class VimEscForRiderHandler(nextHandler: EditorActionHandler) : VimKeyHandler(nextHandler) { internal class VimEscForRiderHandler(nextHandler: EditorActionHandler) : VimKeyHandler(nextHandler) {
override val key: String = "<Esc>" override val key: String = "<Esc>"

View File

@@ -351,7 +351,7 @@ public class EditorHelper {
final int offset = y - ((screenHeight - lineHeight) / lineHeight / 2 * lineHeight); final int offset = y - ((screenHeight - lineHeight) / lineHeight / 2 * lineHeight);
final @NotNull VimEditor editor1 = new IjVimEditor(editor); final @NotNull VimEditor editor1 = new IjVimEditor(editor);
final int lastVisualLine = EngineEditorHelperKt.getVisualLineCount(editor1) - 1; final int lastVisualLine = EngineEditorHelperKt.getVisualLineCount(editor1) + editor.getSettings().getAdditionalLinesCount();
final int offsetForLastLineAtBottom = getOffsetToScrollVisualLineToBottomOfScreen(editor, lastVisualLine); final int offsetForLastLineAtBottom = getOffsetToScrollVisualLineToBottomOfScreen(editor, lastVisualLine);
// For `zz`, we want to use virtual space and move any line, including the last one, to the middle of the screen. // For `zz`, we want to use virtual space and move any line, including the last one, to the middle of the screen.

View File

@@ -12,7 +12,9 @@ package com.maddyhome.idea.vim.helper
import com.intellij.codeWithMe.ClientId import com.intellij.codeWithMe.ClientId
import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.CaretState
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorKind
import com.intellij.openapi.editor.ex.util.EditorUtil import com.intellij.openapi.editor.ex.util.EditorUtil
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.util.ui.table.JBTableRowEditor import com.intellij.util.ui.table.JBTableRowEditor
@@ -22,6 +24,8 @@ import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.group.IjOptionConstants import com.maddyhome.idea.vim.group.IjOptionConstants
import com.maddyhome.idea.vim.key.IdeaVimDisablerExtensionPoint import com.maddyhome.idea.vim.key.IdeaVimDisablerExtensionPoint
import com.maddyhome.idea.vim.newapi.globalIjOptions import com.maddyhome.idea.vim.newapi.globalIjOptions
import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.state.mode.inBlockSelection
import java.awt.Component import java.awt.Component
import javax.swing.JComponent import javax.swing.JComponent
import javax.swing.JTable import javax.swing.JTable
@@ -111,8 +115,7 @@ internal fun Editor.isPrimaryEditor(): Boolean {
internal fun Editor.isTerminalEditor(): Boolean { internal fun Editor.isTerminalEditor(): Boolean {
return !isViewer return !isViewer
&& document.isWritable && document.isWritable
&& !EditorHelper.isFileEditor(this) && this.editorKind == EditorKind.CONSOLE
&& !EditorHelper.isDiffEditor(this)
} }
// Optimized clone of com.intellij.ide.ui.laf.darcula.DarculaUIUtil.isTableCellEditor // Optimized clone of com.intellij.ide.ui.laf.darcula.DarculaUIUtil.isTableCellEditor
@@ -141,3 +144,41 @@ private fun vimEnabled(editor: Editor?): Boolean {
if (editor != null && editor.isIdeaVimDisabledHere) return false if (editor != null && editor.isIdeaVimDisabledHere) return false
return true return true
} }
internal inline fun Editor.runWithEveryCaretAndRestore(action: () -> Unit) {
val caretModel = this.caretModel
val carets = if (this.vim.inBlockSelection) null else caretModel.allCarets
if (carets == null || carets.size == 1) {
action()
}
else {
var initialDocumentSize = this.document.textLength
var documentSizeDifference = 0
val caretOffsets = carets.map { it.selectionStart to it.selectionEnd }
val restoredCarets = mutableListOf<CaretState>()
caretModel.removeSecondaryCarets()
for ((selectionStart, selectionEnd) in caretOffsets) {
if (selectionStart == selectionEnd) {
caretModel.primaryCaret.moveToOffset(selectionStart + documentSizeDifference)
}
else {
caretModel.primaryCaret.setSelection(
selectionStart + documentSizeDifference,
selectionEnd + documentSizeDifference
)
}
action()
restoredCarets.add(caretModel.caretsAndSelections.single())
val documentLength = this.document.textLength
documentSizeDifference += documentLength - initialDocumentSize
initialDocumentSize = documentLength
}
caretModel.caretsAndSelections = restoredCarets
}
}

View File

@@ -24,15 +24,19 @@ import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.editor.actionSystem.DocCommandGroupId import com.intellij.openapi.editor.actionSystem.DocCommandGroupId
import com.intellij.openapi.progress.util.ProgressIndicatorUtils import com.intellij.openapi.progress.util.ProgressIndicatorUtils
import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsContexts
import com.intellij.refactoring.actions.BaseRefactoringAction
import com.maddyhome.idea.vim.RegisterActions import com.maddyhome.idea.vim.RegisterActions
import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.NativeAction import com.maddyhome.idea.vim.api.NativeAction
import com.maddyhome.idea.vim.api.VimActionExecutor import com.maddyhome.idea.vim.api.VimActionExecutor
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.handler.EditorActionHandlerBase import com.maddyhome.idea.vim.handler.EditorActionHandlerBase
import com.maddyhome.idea.vim.newapi.IjNativeAction import com.maddyhome.idea.vim.newapi.IjNativeAction
import com.maddyhome.idea.vim.newapi.ij import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.state.mode.Mode
import com.maddyhome.idea.vim.state.mode.inVisualMode
import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.NonNls
import java.awt.Component import java.awt.Component
import javax.swing.JComponent import javax.swing.JComponent
@@ -68,6 +72,12 @@ class IjActionExecutor : VimActionExecutor {
thisLogger().error("Actions cannot be updated when write-action is running or pending") thisLogger().error("Actions cannot be updated when write-action is running or pending")
} }
val startVisualModeType = (editor?.mode as? Mode.VISUAL)?.selectionType
val startVisualCaretSelection = if (editor != null && startVisualModeType != null && action.action !is BaseRefactoringAction)
editor.primaryCaret().let { Triple(it.offset, it.selectionStart, it.selectionEnd) }
else
null
val ijAction = (action as IjNativeAction).action val ijAction = (action as IjNativeAction).action
try { try {
isRunningActionFromVim = true isRunningActionFromVim = true
@@ -77,6 +87,20 @@ class IjActionExecutor : VimActionExecutor {
val place = ijAction.choosePlace() val place = ijAction.choosePlace()
val res = ActionManager.getInstance().tryToExecute(ijAction, null, contextComponent, place, true) val res = ActionManager.getInstance().tryToExecute(ijAction, null, contextComponent, place, true)
res.waitFor(5_000) res.waitFor(5_000)
if (startVisualModeType != null && startVisualCaretSelection != null) {
val primaryCaret = editor.primaryCaret()
val endVisualCaretOffset = primaryCaret.offset
if (startVisualCaretSelection.first != endVisualCaretOffset) {
if (!editor.inVisualMode || (editor.mode as Mode.VISUAL).selectionType != startVisualModeType) {
injector.visualMotionGroup.toggleVisual(editor, 1, 0, startVisualModeType)
}
primaryCaret.moveToOffset(startVisualCaretSelection.first)
primaryCaret.setSelection(startVisualCaretSelection.second, startVisualCaretSelection.third)
primaryCaret.moveToOffset(endVisualCaretOffset)
}
}
return res.isDone return res.isDone
} finally { } finally {
isRunningActionFromVim = false isRunningActionFromVim = false

View File

@@ -58,7 +58,7 @@ internal object ScrollViewHelper {
// that this needs to be replaced as a more or less dumb line for line rewrite. // that this needs to be replaced as a more or less dumb line for line rewrite.
val topLine = getVisualLineAtTopOfScreen(editor) val topLine = getVisualLineAtTopOfScreen(editor)
val bottomLine = getVisualLineAtBottomOfScreen(editor) val bottomLine = getVisualLineAtBottomOfScreen(editor)
val lastLine = vimEditor.getVisualLineCount() - 1 val lastLine = vimEditor.getVisualLineCount() + editor.settings.additionalLinesCount
// We need the non-normalised value here, so we can handle cases such as so=999 to keep the current line centred // We need the non-normalised value here, so we can handle cases such as so=999 to keep the current line centred
val scrollOffset = injector.options(vimEditor).scrolloff val scrollOffset = injector.options(vimEditor).scrolloff

View File

@@ -17,6 +17,7 @@ import com.intellij.openapi.editor.markup.HighlighterLayer
import com.intellij.openapi.editor.markup.HighlighterTargetArea import com.intellij.openapi.editor.markup.HighlighterTargetArea
import com.intellij.openapi.editor.markup.RangeHighlighter import com.intellij.openapi.editor.markup.RangeHighlighter
import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.util.application
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.globalOptions import com.maddyhome.idea.vim.api.globalOptions
import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.injector
@@ -30,6 +31,7 @@ import com.maddyhome.idea.vim.state.mode.inVisualMode
import org.jetbrains.annotations.Contract import org.jetbrains.annotations.Contract
import java.awt.Font import java.awt.Font
import java.util.* import java.util.*
import javax.swing.Timer
fun updateSearchHighlights( fun updateSearchHighlights(
pattern: String?, pattern: String?,
@@ -84,6 +86,12 @@ fun addSubstitutionConfirmationHighlight(editor: Editor, start: Int, end: Int):
) )
} }
val removeHighlightsEditors = mutableListOf<Editor>()
val removeHighlightsTimer = Timer(400) {
removeHighlightsEditors.forEach(::removeSearchHighlights)
removeHighlightsEditors.clear()
}
/** /**
* Refreshes current search highlights for all visible editors * Refreshes current search highlights for all visible editors
*/ */
@@ -125,27 +133,43 @@ private fun updateSearchHighlights(
// hlsearch (+ incsearch/noincsearch) // hlsearch (+ incsearch/noincsearch)
// Make sure the range fits this editor. Note that Vim will use the same range for all windows. E.g., given // Make sure the range fits this editor. Note that Vim will use the same range for all windows. E.g., given
// `:1,5s/foo`, Vim will highlight all occurrences of `foo` in the first five lines of all visible windows // `:1,5s/foo`, Vim will highlight all occurrences of `foo` in the first five lines of all visible windows
val vimEditor = editor.vim val isSearching = injector.commandLine.getActiveCommandLine() != null
val editorLastLine = vimEditor.lineCount() - 1 application.invokeLater {
val searchStartLine = searchRange?.startLine ?: 0 val vimEditor = editor.vim
val searchEndLine = (searchRange?.endLine ?: -1).coerceAtMost(editorLastLine) val editorLastLine = vimEditor.lineCount() - 1
if (searchStartLine <= editorLastLine) { val searchStartLine = searchRange?.startLine ?: 0
val results = val searchEndLine = (searchRange?.endLine ?: -1).coerceAtMost(editorLastLine)
injector.searchHelper.findAll( if (searchStartLine <= editorLastLine) {
vimEditor, val visibleArea = editor.scrollingModel.visibleAreaOnScrollingFinished
pattern, val visibleTopLeft = visibleArea.location
searchStartLine, val visibleBottomRight = visibleArea.location.apply { translate(visibleArea.width, visibleArea.height) }
searchEndLine, val visibleStartOffset = editor.logicalPositionToOffset(editor.xyToLogicalPosition(visibleTopLeft))
shouldIgnoreCase(pattern, shouldIgnoreSmartCase) val visibleEndOffset = editor.logicalPositionToOffset(editor.xyToLogicalPosition(visibleBottomRight))
) val visibleStartLine = editor.document.getLineNumber(visibleStartOffset)
if (results.isNotEmpty()) { val visibleEndLine = editor.document.getLineNumber(visibleEndOffset)
if (editor === currentEditor?.ij) { removeSearchHighlights(editor)
currentMatchOffset = findClosestMatch(results, initialOffset, count1, forwards)
val results =
injector.searchHelper.findAll(
vimEditor,
pattern,
searchStartLine.coerceAtLeast(visibleStartLine),
searchEndLine.coerceAtMost(visibleEndLine),
shouldIgnoreCase(pattern, shouldIgnoreSmartCase)
)
if (results.isNotEmpty()) {
if (editor === currentEditor?.ij) {
currentMatchOffset = findClosestMatch(results, initialOffset, count1, forwards)
}
highlightSearchResults(editor, pattern, results, currentMatchOffset)
if (!isSearching) {
removeHighlightsEditors.add(editor)
removeHighlightsTimer.restart()
}
} }
highlightSearchResults(editor, pattern, results, currentMatchOffset)
} }
editor.vimLastSearch = pattern
} }
editor.vimLastSearch = pattern
} else if (shouldAddCurrentMatchSearchHighlight(pattern, showHighlights, initialOffset)) { } else if (shouldAddCurrentMatchSearchHighlight(pattern, showHighlights, initialOffset)) {
// nohlsearch + incsearch. Even though search highlights are disabled, we still show a highlight (current editor // nohlsearch + incsearch. Even though search highlights are disabled, we still show a highlight (current editor
// only), because 'incsearch' is active. But we don't show a search if Visual is active (behind Command-line of // only), because 'incsearch' is active. But we don't show a search if Visual is active (behind Command-line of
@@ -179,6 +203,7 @@ private fun updateSearchHighlights(
} }
} }
removeHighlightsTimer.restart()
return currentEditorCurrentMatchOffset return currentEditorCurrentMatchOffset
} }
@@ -204,7 +229,7 @@ private fun removeSearchHighlights(editor: Editor) {
*/ */
@Contract("_, _, false -> false; _, null, true -> false") @Contract("_, _, false -> false; _, null, true -> false")
private fun shouldAddAllSearchHighlights(editor: Editor, newPattern: String?, hlSearch: Boolean): Boolean { private fun shouldAddAllSearchHighlights(editor: Editor, newPattern: String?, hlSearch: Boolean): Boolean {
return hlSearch && newPattern != null && newPattern != editor.vimLastSearch && newPattern != "" return hlSearch && newPattern != null && newPattern != ""
} }
private fun findClosestMatch( private fun findClosestMatch(

View File

@@ -19,6 +19,7 @@ import com.intellij.openapi.fileEditor.TextEditorWithPreview
import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider
import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.registry.Registry
import com.intellij.util.PlatformUtils import com.intellij.util.PlatformUtils
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
@@ -28,6 +29,8 @@ import com.maddyhome.idea.vim.common.InsertSequence
import com.maddyhome.idea.vim.newapi.IjVimCaret import com.maddyhome.idea.vim.newapi.IjVimCaret
import com.maddyhome.idea.vim.newapi.globalIjOptions import com.maddyhome.idea.vim.newapi.globalIjOptions
import com.maddyhome.idea.vim.newapi.ij import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.state.mode.SelectionType
import com.maddyhome.idea.vim.state.mode.inVisualMode
import com.maddyhome.idea.vim.undo.VimTimestampBasedUndoService import com.maddyhome.idea.vim.undo.VimTimestampBasedUndoService
/** /**
@@ -81,15 +84,7 @@ class UndoRedoHelper : VimTimestampBasedUndoService {
// TODO refactor me after VIM-308 when restoring selection and caret movement will be ignored by undo // TODO refactor me after VIM-308 when restoring selection and caret movement will be ignored by undo
editor.runWithChangeTracking { editor.runWithChangeTracking {
undoManager.undo(fileEditor) undoManager.undo(fileEditor)
restoreVisualMode(editor)
// We execute undo one more time if the previous one just restored selection
if (!hasChanges && hasSelection(editor) && undoManager.isUndoAvailable(fileEditor)) {
undoManager.undo(fileEditor)
}
}
CommandProcessor.getInstance().runUndoTransparentAction {
removeSelections(editor)
} }
} else { } else {
runWithBooleanRegistryOption("ide.undo.transparent.caret.movement", true) { runWithBooleanRegistryOption("ide.undo.transparent.caret.movement", true) {
@@ -240,4 +235,21 @@ class UndoRedoHelper : VimTimestampBasedUndoService {
val hasChanges: Boolean val hasChanges: Boolean
get() = changeListener.hasChanged || initialPath != editor.getPath() get() = changeListener.hasChanged || initialPath != editor.getPath()
} }
private fun restoreVisualMode(editor: VimEditor) {
if (!editor.inVisualMode && editor.ij.selectionModel.hasSelection()) {
val detectedMode = VimPlugin.getVisualMotion().detectSelectionType(editor)
// Visual block selection is restored into multiple carets, so multi-carets that form a block are always
// identified as visual block mode, leading to false positives.
// Since I use visual block mode much less often than multi-carets, this is a judgment call to never restore
// visual block mode.
val wantedMode = if (detectedMode == SelectionType.BLOCK_WISE)
SelectionType.CHARACTER_WISE
else
detectedMode
VimPlugin.getVisualMotion().enterVisualMode(editor, wantedMode)
}
}
} }

View File

@@ -18,7 +18,6 @@ import com.intellij.openapi.editor.VisualPosition
import com.intellij.openapi.editor.markup.RangeHighlighter import com.intellij.openapi.editor.markup.RangeHighlighter
import com.intellij.openapi.util.Key import com.intellij.openapi.util.Key
import com.intellij.openapi.util.UserDataHolder import com.intellij.openapi.util.UserDataHolder
import com.maddyhome.idea.vim.api.CaretRegisterStorageBase
import com.maddyhome.idea.vim.api.LocalMarkStorage import com.maddyhome.idea.vim.api.LocalMarkStorage
import com.maddyhome.idea.vim.api.SelectionInfo import com.maddyhome.idea.vim.api.SelectionInfo
import com.maddyhome.idea.vim.api.VimOutputPanel import com.maddyhome.idea.vim.api.VimOutputPanel
@@ -97,9 +96,8 @@ var Caret.vimInsertStart: RangeMarker by userDataOr {
} }
// TODO: Data could be lost during visual block motion // TODO: Data could be lost during visual block motion
var Caret.registerStorage: CaretRegisterStorageBase? by userDataCaretToEditor() internal var Caret.markStorage: LocalMarkStorage? by userDataCaretToEditor()
var Caret.markStorage: LocalMarkStorage? by userDataCaretToEditor() internal var Caret.lastSelectionInfo: SelectionInfo? by userDataCaretToEditor()
var Caret.lastSelectionInfo: SelectionInfo? by userDataCaretToEditor()
var Editor.vimInitialised: Boolean by userDataOr { false } var Editor.vimInitialised: Boolean by userDataOr { false }

View File

@@ -64,8 +64,10 @@ class IJEditorFocusListener : EditorListener {
VimPlugin.getChange().insertBeforeCaret(editor, context) VimPlugin.getChange().insertBeforeCaret(editor, context)
KeyHandler.getInstance().lastUsedEditorInfo = LastUsedEditorInfo(currentEditorHashCode, true) KeyHandler.getInstance().lastUsedEditorInfo = LastUsedEditorInfo(currentEditorHashCode, true)
} }
if (isCurrentEditorTerminal && !ijEditor.inInsertMode) { if (isCurrentEditorTerminal) {
switchToInsertMode.run() if (!ijEditor.inInsertMode) {
switchToInsertMode.run()
}
} else if (ijEditor.isInsertMode && (oldEditorInfo.isInsertModeForced || !ijEditor.document.isWritable)) { } else if (ijEditor.isInsertMode && (oldEditorInfo.isInsertModeForced || !ijEditor.document.isWritable)) {
val context: ExecutionContext = injector.executionContextManager.getEditorExecutionContext(editor) val context: ExecutionContext = injector.executionContextManager.getEditorExecutionContext(editor)
val mode = injector.vimState.mode val mode = injector.vimState.mode

View File

@@ -17,7 +17,9 @@ import com.intellij.codeInsight.template.Template
import com.intellij.codeInsight.template.TemplateEditingAdapter import com.intellij.codeInsight.template.TemplateEditingAdapter
import com.intellij.codeInsight.template.TemplateManagerListener import com.intellij.codeInsight.template.TemplateManagerListener
import com.intellij.codeInsight.template.impl.TemplateImpl import com.intellij.codeInsight.template.impl.TemplateImpl
import com.intellij.codeInsight.template.impl.TemplateManagerImpl
import com.intellij.codeInsight.template.impl.TemplateState import com.intellij.codeInsight.template.impl.TemplateState
import com.intellij.codeInsight.template.impl.actions.NextVariableAction
import com.intellij.find.FindModelListener import com.intellij.find.FindModelListener
import com.intellij.ide.actions.ApplyIntentionAction import com.intellij.ide.actions.ApplyIntentionAction
import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.ActionManager
@@ -32,6 +34,7 @@ import com.intellij.openapi.actionSystem.impl.ProxyShortcutSet
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.editor.actions.EnterAction import com.intellij.openapi.editor.actions.EnterAction
import com.intellij.openapi.editor.impl.ScrollingModelImpl
import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.project.DumbAwareToggleAction import com.intellij.openapi.project.DumbAwareToggleAction
import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.TextRange
@@ -46,8 +49,9 @@ import com.maddyhome.idea.vim.group.NotificationService
import com.maddyhome.idea.vim.group.visual.IdeaSelectionControl import com.maddyhome.idea.vim.group.visual.IdeaSelectionControl
import com.maddyhome.idea.vim.helper.exitSelectMode import com.maddyhome.idea.vim.helper.exitSelectMode
import com.maddyhome.idea.vim.helper.exitVisualMode import com.maddyhome.idea.vim.helper.exitVisualMode
import com.maddyhome.idea.vim.helper.hasVisualSelection
import com.maddyhome.idea.vim.helper.isIdeaVimDisabledHere import com.maddyhome.idea.vim.helper.isIdeaVimDisabledHere
import com.maddyhome.idea.vim.ide.isClionNova
import com.maddyhome.idea.vim.ide.isRider
import com.maddyhome.idea.vim.newapi.globalIjOptions import com.maddyhome.idea.vim.newapi.globalIjOptions
import com.maddyhome.idea.vim.newapi.initInjector import com.maddyhome.idea.vim.newapi.initInjector
import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.newapi.vim
@@ -71,6 +75,7 @@ internal object IdeaSpecifics {
private val surrounderAction = private val surrounderAction =
"com.intellij.codeInsight.generation.surroundWith.SurroundWithHandler\$InvokeSurrounderAction" "com.intellij.codeInsight.generation.surroundWith.SurroundWithHandler\$InvokeSurrounderAction"
private var editor: Editor? = null private var editor: Editor? = null
private var caretOffset = -1
private var completionData: CompletionData? = null private var completionData: CompletionData? = null
override fun beforeActionPerformed(action: AnAction, event: AnActionEvent) { override fun beforeActionPerformed(action: AnAction, event: AnActionEvent) {
@@ -79,6 +84,7 @@ internal object IdeaSpecifics {
val hostEditor = event.dataContext.getData(CommonDataKeys.HOST_EDITOR) val hostEditor = event.dataContext.getData(CommonDataKeys.HOST_EDITOR)
if (hostEditor != null) { if (hostEditor != null) {
editor = hostEditor editor = hostEditor
caretOffset = hostEditor.caretModel.offset
} }
val isVimAction = (action as? AnActionWrapper)?.delegate is VimShortcutKeyAction val isVimAction = (action as? AnActionWrapper)?.delegate is VimShortcutKeyAction
@@ -155,26 +161,46 @@ internal object IdeaSpecifics {
if (VimPlugin.isNotEnabled()) return if (VimPlugin.isNotEnabled()) return
val editor = editor val editor = editor
if (editor != null && action is ChooseItemAction && injector.registerGroup.isRecording) { if (editor != null) {
completionData?.recordCompletion(editor, VimPlugin.getRegister()) if (action is ChooseItemAction && injector.registerGroup.isRecording) {
} completionData?.recordCompletion(editor, VimPlugin.getRegister()
)
}
//region Enter insert mode after surround with if //region Enter insert mode after surround with if
if (surrounderAction == action.javaClass.name && surrounderItems.any { if (surrounderAction == action.javaClass.name && surrounderItems.any {
action.templatePresentation.text.endsWith( action.templatePresentation.text.endsWith(
it, it,
) )
}
) {
editor?.let {
it.vim.mode = Mode.NORMAL()
VimPlugin.getChange().insertBeforeCaret(it.vim, event.dataContext.vim)
KeyHandler.getInstance().reset(it.vim)
}
} }
) { else if (action is NextVariableAction && TemplateManagerImpl.getTemplateState(editor) == null) {
editor?.let { editor.vim.exitInsertMode(event.dataContext.vim)
it.vim.mode = Mode.NORMAL() KeyHandler.getInstance().reset(editor.vim)
VimPlugin.getChange().insertBeforeCaret(it.vim, event.dataContext.vim) }
KeyHandler.getInstance().reset(it.vim) //endregion
if (caretOffset != -1 && caretOffset != editor.caretModel.offset) {
val scrollModel = editor.scrollingModel as ScrollingModelImpl
if (scrollModel.isScrollingNow) {
val v = scrollModel.verticalScrollOffset
val h = scrollModel.horizontalScrollOffset
scrollModel.finishAnimation()
scrollModel.scroll(h, v)
scrollModel.finishAnimation()
}
injector.scroll.scrollCaretIntoView(editor.vim)
} }
} }
//endregion
this.editor = null this.editor = null
this.caretOffset = -1
this.completionData?.dispose() this.completionData?.dispose()
this.completionData = null this.completionData = null
@@ -308,23 +334,6 @@ internal object IdeaSpecifics {
vimEditor.exitMode() vimEditor.exitMode()
vimEditor.mode = Mode.NORMAL() vimEditor.mode = Mode.NORMAL()
} }
} else {
// IdeaSelectionControl will not be called if we're moving to a new variable with no change in selection.
// And if we're moving to the end of the template, the change in selection will reset us to Normal because
// IdeaSelectionControl will be called when the template is no longer active.
if ((!editor.selectionModel.hasSelection() && !vimEditor.mode.hasVisualSelection) || newIndex == -1) {
if (vimEditor.isIdeaRefactorModeSelect) {
if (vimEditor.mode !is Mode.INSERT) {
vimEditor.exitMode()
injector.application.runReadAction {
val context = injector.executionContextManager.getEditorExecutionContext(editor.vim)
VimPlugin.getChange().insertBeforeCaret(editor.vim, context)
}
}
} else {
vimEditor.mode = Mode.NORMAL()
}
}
} }
} }
} }
@@ -343,6 +352,16 @@ internal object IdeaSpecifics {
if (newLookup.editor.isIdeaVimDisabledHere) return if (newLookup.editor.isIdeaVimDisabledHere) return
(VimPlugin.getKey() as VimKeyGroupBase).registerShortcutsForLookup(newLookup) (VimPlugin.getKey() as VimKeyGroupBase).registerShortcutsForLookup(newLookup)
// In Rider/CLion Nova, octopus is disabled (VIM-3815) and Escape is consumed by the popup manager
// (due to LookupSummaryInfo popup) before the action system runs, so IdeaVim never sees it.
// Listen for explicit lookup cancellation (Escape) to exit insert mode.
// Note: we check isRider/isClionNova specifically, not !isOctopusEnabled(), because
// JetBrains Client (split mode) also has octopus disabled but doesn't need this workaround,
// and isCanceledExplicitly can be true for non-Escape keys (e.g. space) in that environment.
if (isRider() || isClionNova()) {
newLookup.addLookupListener(RiderEscLookupListener(newLookup.editor))
}
} }
// Lookup closed // Lookup closed
@@ -354,6 +373,20 @@ internal object IdeaSpecifics {
} }
} }
} }
/**
* In Rider/CLion Nova, octopus is disabled (VIM-3815) and Escape is consumed by the popup manager
* (due to LookupSummaryInfo parameter info popup) before the action system runs, so IdeaVim never sees it.
* This listener exits insert mode when the lookup is explicitly cancelled (Escape).
*/
private class RiderEscLookupListener(private val editor: Editor) : com.intellij.codeInsight.lookup.LookupListener {
override fun lookupCanceled(event: com.intellij.codeInsight.lookup.LookupEvent) {
if (event.isCanceledExplicitly && editor.vim.mode is Mode.INSERT) {
editor.vim.exitInsertMode(injector.executionContextManager.getEditorExecutionContext(editor.vim))
KeyHandler.getInstance().reset(editor.vim)
}
}
}
//endregion //endregion
//region Hide Vim search highlights when showing IntelliJ search results //region Hide Vim search highlights when showing IntelliJ search results

View File

@@ -98,6 +98,7 @@ import com.maddyhome.idea.vim.newapi.IjVimSearchGroup
import com.maddyhome.idea.vim.newapi.InsertTimeRecorder import com.maddyhome.idea.vim.newapi.InsertTimeRecorder
import com.maddyhome.idea.vim.newapi.ij import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.state.mode.Mode
import com.maddyhome.idea.vim.state.mode.inSelectMode import com.maddyhome.idea.vim.state.mode.inSelectMode
import com.maddyhome.idea.vim.state.mode.selectionType import com.maddyhome.idea.vim.state.mode.selectionType
import com.maddyhome.idea.vim.ui.ShowCmdOptionChangeListener import com.maddyhome.idea.vim.ui.ShowCmdOptionChangeListener
@@ -412,10 +413,21 @@ object VimListenerManager {
// We can't rely on being passed a non-null editor, so check for Code With Me scenarios explicitly // We can't rely on being passed a non-null editor, so check for Code With Me scenarios explicitly
if (VimPlugin.isNotEnabled() || !ClientId.isCurrentlyUnderLocalId) return if (VimPlugin.isNotEnabled() || !ClientId.isCurrentlyUnderLocalId) return
val newEditor = event.newEditor
if (newEditor is TextEditor) {
val editor = newEditor.editor
if (editor.isInsertMode) {
editor.vim.mode = Mode.NORMAL()
KeyHandler.getInstance().reset(editor.vim)
}
// Breaks relativenumber for some reason
// injector.scroll.scrollCaretIntoView(editor.vim)
}
injector.outputPanel.getCurrentOutputPanel()?.close() injector.outputPanel.getCurrentOutputPanel()?.close()
MotionGroup.fileEditorManagerSelectionChangedCallback(event) MotionGroup.fileEditorManagerSelectionChangedCallback(event)
FileGroupHelper.fileEditorManagerSelectionChangedCallback(event) FileGroupHelper.fileEditorManagerSelectionChangedCallback(event)
(VimPlugin.getSearch() as IjVimSearchGroup).fileEditorManagerSelectionChangedCallback(event) // (VimPlugin.getSearch() as IjVimSearchGroup).fileEditorManagerSelectionChangedCallback(event)
IjVimRedrawService.fileEditorManagerSelectionChangedCallback(event) IjVimRedrawService.fileEditorManagerSelectionChangedCallback(event)
VimLastSelectedEditorTracker.setLastSelectedEditor(event.newEditor) VimLastSelectedEditorTracker.setLastSelectedEditor(event.newEditor)
} }

View File

@@ -38,7 +38,7 @@ import java.io.IOException
internal class IjClipboardManager : VimClipboardManager { internal class IjClipboardManager : VimClipboardManager {
override fun getPrimaryContent(editor: VimEditor, context: ExecutionContext): IjVimCopiedText? { override fun getPrimaryContent(): IjVimCopiedText? {
val clipboard = Toolkit.getDefaultToolkit()?.systemSelection ?: return null val clipboard = Toolkit.getDefaultToolkit()?.systemSelection ?: return null
val contents = clipboard.getContents(null) ?: return null val contents = clipboard.getContents(null) ?: return null
val (text, transferableData) = getTextAndTransferableData(contents) ?: return null val (text, transferableData) = getTextAndTransferableData(contents) ?: return null
@@ -241,6 +241,6 @@ internal class IjClipboardManager : VimClipboardManager {
} }
} }
data class IjVimCopiedText(override val text: String, val transferableData: List<Any>) : VimCopiedText { data class IjVimCopiedText(override val text: String, override val transferableData: List<Any>) : VimCopiedText {
override fun updateText(newText: String): VimCopiedText = IjVimCopiedText(newText, transferableData) override fun updateText(newText: String): VimCopiedText = IjVimCopiedText(newText, transferableData)
} }

View File

@@ -12,14 +12,14 @@ import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.editor.LogicalPosition
import com.intellij.openapi.editor.VisualPosition import com.intellij.openapi.editor.VisualPosition
import com.maddyhome.idea.vim.api.BufferPosition import com.maddyhome.idea.vim.api.BufferPosition
import com.maddyhome.idea.vim.api.CaretRegisterStorage import com.maddyhome.idea.vim.api.ImmutableVimCaret
import com.maddyhome.idea.vim.api.CaretRegisterStorageBase
import com.maddyhome.idea.vim.api.LocalMarkStorage import com.maddyhome.idea.vim.api.LocalMarkStorage
import com.maddyhome.idea.vim.api.SelectionInfo import com.maddyhome.idea.vim.api.SelectionInfo
import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimCaretBase import com.maddyhome.idea.vim.api.VimCaretBase
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.VimVisualPosition import com.maddyhome.idea.vim.api.VimVisualPosition
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.common.InsertSequence import com.maddyhome.idea.vim.common.InsertSequence
import com.maddyhome.idea.vim.common.LiveRange import com.maddyhome.idea.vim.common.LiveRange
import com.maddyhome.idea.vim.group.visual.VisualChange import com.maddyhome.idea.vim.group.visual.VisualChange
@@ -28,7 +28,6 @@ import com.maddyhome.idea.vim.helper.insertHistory
import com.maddyhome.idea.vim.helper.lastSelectionInfo import com.maddyhome.idea.vim.helper.lastSelectionInfo
import com.maddyhome.idea.vim.helper.markStorage import com.maddyhome.idea.vim.helper.markStorage
import com.maddyhome.idea.vim.helper.moveToInlayAwareOffset import com.maddyhome.idea.vim.helper.moveToInlayAwareOffset
import com.maddyhome.idea.vim.helper.registerStorage
import com.maddyhome.idea.vim.helper.resetVimLastColumn import com.maddyhome.idea.vim.helper.resetVimLastColumn
import com.maddyhome.idea.vim.helper.vimInsertStart import com.maddyhome.idea.vim.helper.vimInsertStart
import com.maddyhome.idea.vim.helper.vimLastColumn import com.maddyhome.idea.vim.helper.vimLastColumn
@@ -36,22 +35,14 @@ import com.maddyhome.idea.vim.helper.vimLastVisualOperatorRange
import com.maddyhome.idea.vim.helper.vimLine import com.maddyhome.idea.vim.helper.vimLine
import com.maddyhome.idea.vim.helper.vimSelectionStart import com.maddyhome.idea.vim.helper.vimSelectionStart
import com.maddyhome.idea.vim.helper.vimSelectionStartClear import com.maddyhome.idea.vim.helper.vimSelectionStartClear
import com.maddyhome.idea.vim.register.VimRegisterGroup
import com.maddyhome.idea.vim.state.mode.SelectionType import com.maddyhome.idea.vim.state.mode.SelectionType
class IjVimCaret(val caret: Caret) : VimCaretBase() { class IjVimCaret(val caret: Caret) : VimCaretBase() {
override val registerStorage: CaretRegisterStorage override val registerStorage: VimRegisterGroup
get() { get() = injector.registerGroup
var storage = this.caret.registerStorage
if (storage == null) {
initInjector() // To initialize injector used in CaretRegisterStorageBase
storage = CaretRegisterStorageBase(this)
this.caret.registerStorage = storage
} else if (storage.caret != this) {
storage.caret = this
}
return storage
}
override val markStorage: LocalMarkStorage override val markStorage: LocalMarkStorage
get() { get() {
var storage = this.caret.markStorage var storage = this.caret.markStorage
@@ -208,3 +199,12 @@ class IjVimCaret(val caret: Caret) : VimCaretBase() {
override fun hashCode(): Int = this.caret.hashCode() override fun hashCode(): Int = this.caret.hashCode()
} }
val Caret.vim: VimCaret
get() = VimEditorFactory.getInstance().createVimCaret(this)
val VimCaret.ij: Caret
get() = VimEditorFactory.getInstance().extractCaret(this)
val ImmutableVimCaret.ij: Caret
get() = VimEditorFactory.getInstance().extractCaret(this)

View File

@@ -22,6 +22,7 @@ import com.intellij.openapi.editor.ex.ScrollingModelEx
import com.intellij.openapi.editor.ex.util.EditorUtil import com.intellij.openapi.editor.ex.util.EditorUtil
import com.intellij.openapi.editor.impl.CaretModelImpl import com.intellij.openapi.editor.impl.CaretModelImpl
import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.platform.project.projectId import com.intellij.platform.project.projectId
import com.maddyhome.idea.vim.api.BufferPosition import com.maddyhome.idea.vim.api.BufferPosition
@@ -150,7 +151,7 @@ class IjVimEditor(editor: Editor) : MutableLinearEditor, VimEditorBase() {
} }
} }
if (!isWritable()) return if (!isWritable()) return
editor.document.insertString(atPosition, text) editor.document.insertString(atPosition, StringUtil.convertLineSeparators(text, "\n"))
} }
override fun replaceString(start: Int, end: Int, newString: String) { override fun replaceString(start: Int, end: Int, newString: String) {
@@ -179,21 +180,38 @@ class IjVimEditor(editor: Editor) : MutableLinearEditor, VimEditorBase() {
return editor.caretModel.allCarets.map { IjVimCaret(it) } return editor.caretModel.allCarets.map { IjVimCaret(it) }
} }
override var isFirstCaret = true
override var isReversingCarets = false
@Suppress("ideavimRunForEachCaret") @Suppress("ideavimRunForEachCaret")
override fun forEachCaret(action: (VimCaret) -> Unit) { override fun forEachCaret(action: (VimCaret) -> Unit) {
if (editor.vim.inBlockSelection) { if (editor.vim.inBlockSelection) {
action(IjVimCaret(editor.caretModel.primaryCaret)) action(IjVimCaret(editor.caretModel.primaryCaret))
} else { } else {
editor.caretModel.runForEachCaret({ try {
if (it.isValid) { editor.caretModel.runForEachCaret({
action(IjVimCaret(it)) if (it.isValid) {
} action(IjVimCaret(it))
}, false) isFirstCaret = false
}
}, false)
} finally {
isFirstCaret = true
}
} }
} }
override fun forEachNativeCaret(action: (VimCaret) -> Unit, reverse: Boolean) { override fun forEachNativeCaret(action: (VimCaret) -> Unit, reverse: Boolean) {
editor.caretModel.runForEachCaret({ action(IjVimCaret(it)) }, reverse) isReversingCarets = reverse
try {
editor.caretModel.runForEachCaret({
action(IjVimCaret(it))
isFirstCaret = false
}, reverse)
} finally {
isFirstCaret = true
isReversingCarets = false
}
} }
override fun isInForEachCaretScope(): Boolean { override fun isInForEachCaretScope(): Boolean {
@@ -613,6 +631,10 @@ class IjVimEditor(editor: Editor) : MutableLinearEditor, VimEditorBase() {
get() = ijFoldRegion.endOffset get() = ijFoldRegion.endOffset
} }
override fun getSoftWrapStartAtOffset(offset: Int): Int? {
return editor.softWrapModel.getSoftWrap(offset)?.start
}
override fun <T : ImmutableVimCaret> findLastVersionOfCaret(caret: T): T { override fun <T : ImmutableVimCaret> findLastVersionOfCaret(caret: T): T {
return caret return caret
} }
@@ -649,3 +671,12 @@ class IjVimEditor(editor: Editor) : MutableLinearEditor, VimEditorBase() {
} }
} }
val Editor.vim: VimEditor
get() = VimEditorFactory.getInstance().createVimEditor(this)
val VimEditor.ij: Editor
get() = VimEditorFactory.getInstance().extractEditor(this)
val com.intellij.openapi.util.TextRange.vim: TextRange
get() = TextRange(this.startOffset, this.endOffset)

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2003-2026 The IdeaVim authors * Copyright 2003-2023 The IdeaVim authors
* *
* Use of this source code is governed by an MIT-style * Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at * license that can be found in the LICENSE.txt file or at
@@ -9,7 +9,9 @@
package com.maddyhome.idea.vim.newapi package com.maddyhome.idea.vim.newapi
import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationManager
import com.maddyhome.idea.vim.api.MessageType import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.wm.WindowManager
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.VimMessagesBase import com.maddyhome.idea.vim.api.VimMessagesBase
import com.maddyhome.idea.vim.api.globalOptions import com.maddyhome.idea.vim.api.globalOptions
@@ -23,43 +25,56 @@ internal class IjVimMessages : VimMessagesBase() {
private var message: String? = null private var message: String? = null
private var error = false private var error = false
private var lastBeepTimeMillis = 0L private var lastBeepTimeMillis = 0L
private var allowClearStatusBarMessage = true
override fun showMessage(editor: VimEditor, message: String?) { override fun showStatusBarMessage(editor: VimEditor?, message: String?) {
showMessageInternal(editor, message, MessageType.STANDARD) fun setStatusBarMessage(project: Project, message: String?) {
} WindowManager.getInstance().getStatusBar(project)?.let {
it.info = if (message.isNullOrBlank()) "" else "Vim - $message"
override fun showErrorMessage(editor: VimEditor, message: String?) { }
showMessageInternal(editor, message, MessageType.ERROR)
indicateError()
}
private fun showMessageInternal(editor: VimEditor, message: String?, messageType: MessageType) {
this.message = message
if (message.isNullOrBlank()) {
clearStatusBarMessage()
return
} }
val context = injector.executionContextManager.getEditorExecutionContext(editor) this.message = message
injector.outputPanel.output(editor, context, message, messageType)
}
@Suppress("DEPRECATION") val project = editor?.ij?.project
override fun showStatusBarMessage(editor: VimEditor?, message: String?) { if (project != null) {
if (editor != null) { setStatusBarMessage(project, message)
showMessage(editor, message)
} else { } else {
// Legacy path for when editor is null - just store the message // TODO: We really shouldn't set the status bar text for other projects. That's rude.
this.message = message ProjectManager.getInstance().openProjects.forEach {
setStatusBarMessage(it, message)
}
}
// Redraw happens automatically based on changes or scrolling. If we've just set the message (e.g., searching for a
// string, hitting the bottom and scrolling to the top), make sure we don't immediately clear it when scrolling.
allowClearStatusBarMessage = false
ApplicationManager.getApplication().invokeLater {
allowClearStatusBarMessage = true
} }
} }
override fun getStatusBarMessage(): String? = message override fun getStatusBarMessage(): String? = message
// Vim doesn't appear to have a policy about clearing the status bar, other than on "redraw". This can be forced with
// <C-L> or the `:redraw` command, but also happens as the screen changes, e.g., when inserting or deleting lines,
// scrolling, entering Command-line mode and probably lots more. We should manually clear the status bar when these
// things happen.
override fun clearStatusBarMessage() { override fun clearStatusBarMessage() {
if (message.isNullOrEmpty()) return val currentMessage = message
injector.outputPanel.getCurrentOutputPanel()?.close() if (currentMessage.isNullOrEmpty()) return
// Don't clear the status bar message if we've only just set it
if (!allowClearStatusBarMessage) return
ProjectManager.getInstance().openProjects.forEach { project ->
WindowManager.getInstance().getStatusBar(project)?.let { statusBar ->
// Only clear the status bar if it's showing our last message
if (statusBar.info?.contains(currentMessage) == true) {
statusBar.info = ""
}
}
}
message = null message = null
} }

View File

@@ -14,7 +14,6 @@ import com.intellij.openapi.editor.Editor
import com.maddyhome.idea.vim.api.ImmutableVimCaret import com.maddyhome.idea.vim.api.ImmutableVimCaret
import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.common.TextRange
interface VimEditorFactory { interface VimEditorFactory {
fun createVimEditor(editor: Editor): VimEditor fun createVimEditor(editor: Editor): VimEditor
@@ -27,21 +26,3 @@ interface VimEditorFactory {
fun getInstance(): VimEditorFactory = service() fun getInstance(): VimEditorFactory = service()
} }
} }
val Editor.vim: VimEditor
get() = VimEditorFactory.getInstance().createVimEditor(this)
val VimEditor.ij: Editor
get() = VimEditorFactory.getInstance().extractEditor(this)
val Caret.vim: VimCaret
get() = VimEditorFactory.getInstance().createVimCaret(this)
val VimCaret.ij: Caret
get() = VimEditorFactory.getInstance().extractCaret(this)
val ImmutableVimCaret.ij: Caret
get() = VimEditorFactory.getInstance().extractCaret(this)
val com.intellij.openapi.util.TextRange.vim: TextRange
get() = TextRange(this.startOffset, this.endOffset)

View File

@@ -12,8 +12,8 @@ import com.intellij.ide.ui.LafManagerListener
import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import com.intellij.openapi.wm.impl.IdeBackgroundUtil import com.intellij.openapi.wm.impl.IdeBackgroundUtil
import com.intellij.openapi.wm.impl.ToolWindowManagerImpl
import com.intellij.ui.ClientProperty import com.intellij.ui.ClientProperty
import com.intellij.ui.JBColor
import com.intellij.ui.components.JBPanel import com.intellij.ui.components.JBPanel
import com.intellij.ui.components.JBScrollPane import com.intellij.ui.components.JBScrollPane
import com.intellij.util.IJSwingUtilities import com.intellij.util.IJSwingUtilities
@@ -24,6 +24,7 @@ import com.maddyhome.idea.vim.api.MessageType
import com.maddyhome.idea.vim.api.VimOutputPanel import com.maddyhome.idea.vim.api.VimOutputPanel
import com.maddyhome.idea.vim.api.globalOptions import com.maddyhome.idea.vim.api.globalOptions
import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.diagnostic.VimLogger
import com.maddyhome.idea.vim.helper.requestFocus import com.maddyhome.idea.vim.helper.requestFocus
import com.maddyhome.idea.vim.helper.selectEditorFont import com.maddyhome.idea.vim.helper.selectEditorFont
import com.maddyhome.idea.vim.helper.vimMorePanel import com.maddyhome.idea.vim.helper.vimMorePanel
@@ -35,165 +36,121 @@ import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent import java.awt.event.ComponentEvent
import java.awt.event.KeyAdapter import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent import java.awt.event.KeyEvent
import java.lang.ref.WeakReference
import javax.swing.JComponent import javax.swing.JComponent
import javax.swing.JLabel import javax.swing.JLabel
import javax.swing.JRootPane
import javax.swing.JScrollPane import javax.swing.JScrollPane
import javax.swing.JTextPane import javax.swing.JTextArea
import javax.swing.KeyStroke import javax.swing.KeyStroke
import javax.swing.SwingUtilities import javax.swing.SwingUtilities
import javax.swing.text.DefaultCaret
import javax.swing.text.SimpleAttributeSet
import javax.swing.text.StyleConstants
import javax.swing.text.StyledDocument
import kotlin.math.ceil import kotlin.math.ceil
import kotlin.math.min import kotlin.math.min
/** /**
* Panel that displays text in a `more` like window overlaid on the editor. * This panel displays text in a `more` like window and implements [VimOutputPanel].
*/ */
class OutputPanel private constructor( class OutputPanel(editorRef: WeakReference<Editor>) : JBPanel<OutputPanel?>(), VimOutputPanel {
private val editor: Editor, private val myEditorRef: WeakReference<Editor> = editorRef
) : JBPanel<OutputPanel>(), VimOutputPanel { val editor: Editor? get() = myEditorRef.get()
private val textPane = JTextPane() val myLabel: JLabel = JLabel("more")
private val resizeAdapter: ComponentAdapter private val myText = JTextArea()
private var defaultForeground: Color? = null private val myScrollPane: JScrollPane =
JBScrollPane(myText, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER)
private val myAdapter: ComponentAdapter
private var myLineHeight = 0
private var glassPane: JComponent? = null private var myOldGlass: JComponent? = null
private var originalLayout: LayoutManager? = null private var myOldLayout: LayoutManager? = null
private var wasOpaque = false private var myWasOpaque = false
var active: Boolean = false var myActive: Boolean = false
private val segments = mutableListOf<TextLine>()
private val labelComponent: JLabel = JLabel("more") val isActive: Boolean
private val scrollPane: JScrollPane = get() = myActive
JBScrollPane(textPane, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER)
private var cachedLineHeight = 0
private var isSingleLine = false
init { init {
textPane.isEditable = false // Create a text editor for the text and a label for the prompt
textPane.caret = object : DefaultCaret() { val layout = BorderLayout(0, 0)
override fun setVisible(v: Boolean) { setLayout(layout)
super.setVisible(false) add(myScrollPane, BorderLayout.CENTER)
} add(myLabel, BorderLayout.SOUTH)
}
textPane.highlighter = null
resizeAdapter = object : ComponentAdapter() { // Set the text area read only, and support wrap
myText.isEditable = false
myText.setLineWrap(true)
myAdapter = object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) { override fun componentResized(e: ComponentEvent?) {
positionPanel() positionPanel()
} }
} }
// Suppress the fancy frame background used in the Islands theme // Setup some listeners to handle keystrokes
ClientProperty.putRecursive(this, IdeBackgroundUtil.NO_BACKGROUND, true) val moreKeyListener = MoreKeyListener()
addKeyListener(moreKeyListener)
myText.addKeyListener(moreKeyListener)
// Initialize panel // Suppress the fancy frame background used in the Islands theme, which comes from a custom Graphics implementation
setLayout(BorderLayout(0, 0)) // applied to the IdeRoot, and used to paint all children, including this panel. This client property is checked by
add(scrollPane, BorderLayout.CENTER) // JBPanel.getComponentGraphics to give us the original Graphics, opting out of the fancy painting.
add(labelComponent, BorderLayout.SOUTH) ClientProperty.putRecursive<Boolean?>(this, IdeBackgroundUtil.NO_BACKGROUND, true)
editor?.let { putClientProperty(ToolWindowManagerImpl.PARENT_COMPONENT, it.component) }
val keyListener = OutputPanelKeyListener()
addKeyListener(keyListener)
textPane.addKeyListener(keyListener)
updateUI() updateUI()
} }
// Called automatically when the LAF is changed and the component is visible, and manually by the LAF listener handler
override fun updateUI() { override fun updateUI() {
super.updateUI() super.updateUI()
setBorder(ExPanelBorder()) setBorder(ExPanelBorder())
// Swing uses a bad pattern of calling updateUI() from the constructor. At this moment, all these variables are null
@Suppress("SENSELESS_COMPARISON") @Suppress("SENSELESS_COMPARISON")
if (textPane != null && labelComponent != null && scrollPane != null) { if (myText != null && myLabel != null && myScrollPane != null) {
setFontForElements() setFontForElements()
textPane.setBorder(null) myText.setBorder(null)
scrollPane.setBorder(null) myScrollPane.setBorder(null)
labelComponent.setForeground(textPane.getForeground()) myLabel.setForeground(myText.getForeground())
// Make sure the panel is positioned correctly in case we're changing font size
positionPanel() positionPanel()
} }
} }
override var text: String override var text: String
get() = textPane.getText() ?: "" get() = myText.text
set(value) { set(value) {
// ExOutputPanel will strip a trailing newline. We'll do it now so that tests have the same behaviour.
val newValue = value.removeSuffix("\n") val newValue = value.removeSuffix("\n")
segments.clear() myText.text = newValue
if (newValue.isEmpty()) return val ed = editor
segments.add(TextLine(newValue, null)) if (ed != null) {
myText.setFont(selectEditorFont(ed, newValue))
}
myText.setCaretPosition(0)
if (newValue.isNotEmpty()) {
activate()
}
} }
override var label: String override var label: String
get() = labelComponent.text get() = myLabel.text ?: ""
set(value) { set(value) {
labelComponent.text = value myLabel.text = value
val ed = editor
if (ed != null) {
myLabel.setFont(selectEditorFont(ed, value))
}
} }
/**
* Sets styled text with multiple segments, each potentially having a different color.
*/
fun setStyledText(lines: List<TextLine>) {
val doc = textPane.styledDocument
doc.remove(0, doc.length)
if (defaultForeground == null) {
defaultForeground = textPane.foreground
}
if (lines.size > 1) {
setMultiLineText(lines, doc)
} else {
doc.insertString(doc.length, lines[0].text.removeSuffix("\n"), getLineColor(lines[0]))
}
val fullText = doc.getText(0, doc.length)
textPane.setFont(selectEditorFont(editor, fullText))
textPane.setCaretPosition(0)
if (fullText.isNotEmpty()) {
activate()
}
}
private fun setMultiLineText(
lines: List<TextLine>,
doc: StyledDocument,
) {
for ((index, line) in lines.withIndex()) {
val text = line.text.removeSuffix("\n")
val attrs = getLineColor(line)
val separator = if (index < lines.size - 1) "\n" else ""
doc.insertString(doc.length, text + separator, attrs)
}
}
private fun getLineColor(segment: TextLine): SimpleAttributeSet {
val attrs = SimpleAttributeSet()
val color = segment.color ?: defaultForeground
if (color != null) {
StyleConstants.setForeground(attrs, color)
}
return attrs
}
override fun addText(text: String, isNewLine: Boolean, messageType: MessageType) { override fun addText(text: String, isNewLine: Boolean, messageType: MessageType) {
val color = when (messageType) { if (this.text.isNotEmpty() && isNewLine) {
MessageType.ERROR -> JBColor.RED this.text += "\n$text"
MessageType.STANDARD -> null } else {
} this.text += text
segments.add(TextLine(text, color))
}
override fun show() {
val currentPanel = injector.outputPanel.getCurrentOutputPanel()
if (currentPanel != null && currentPanel != this) currentPanel.close()
setStyledText(segments)
if (!active) {
activate()
} }
} }
@@ -202,15 +159,20 @@ class OutputPanel private constructor(
} }
override fun clearText() { override fun clearText() {
segments.clear()
}
fun clear() {
text = "" text = ""
} }
override fun handleKey(key: KeyStroke) { override fun show() {
editor ?: return
val currentPanel = injector.outputPanel.getCurrentOutputPanel()
if (currentPanel != null && currentPanel != this) currentPanel.close()
if (!myActive) {
activate()
}
}
override fun handleKey(key: KeyStroke) {
if (isAtEnd) { if (isAtEnd) {
close(key) close(key)
return return
@@ -235,262 +197,214 @@ class OutputPanel private constructor(
override fun getForeground(): Color? { override fun getForeground(): Color? {
@Suppress("SENSELESS_COMPARISON") @Suppress("SENSELESS_COMPARISON")
if (textPane == null) { if (myText == null) {
// Swing uses a bad pattern of calling getForeground() from the constructor. At this moment, `myText` is null.
return super.getForeground() return super.getForeground()
} }
return textPane.getForeground() return myText.getForeground()
} }
override fun getBackground(): Color? { override fun getBackground(): Color? {
@Suppress("SENSELESS_COMPARISON") @Suppress("SENSELESS_COMPARISON")
if (textPane == null) { if (myText == null) {
// Swing uses a bad pattern of calling getBackground() from the constructor. At this moment, `myText` is null.
return super.getBackground() return super.getBackground()
} }
return textPane.getBackground() return myText.getBackground()
} }
/** /**
* Turns off the output panel and optionally puts the focus back to the original component. * Turns off the ex entry field and optionally puts the focus back to the original component
*/ */
fun deactivate(refocusOwningEditor: Boolean) { fun deactivate(refocusOwningEditor: Boolean) {
if (!active) return if (!myActive) return
active = false myActive = false
clearText() myText.text = ""
textPane.text = "" val ed = editor
if (refocusOwningEditor) { if (refocusOwningEditor && ed != null) {
requestFocus(editor.contentComponent) requestFocus(ed.contentComponent)
} }
if (glassPane != null) { if (myOldGlass != null) {
glassPane!!.removeComponentListener(resizeAdapter) myOldGlass!!.removeComponentListener(myAdapter)
glassPane!!.isVisible = false myOldGlass!!.isVisible = false
glassPane!!.remove(this) myOldGlass!!.remove(this)
glassPane!!.setOpaque(wasOpaque) myOldGlass!!.setOpaque(myWasOpaque)
glassPane!!.setLayout(originalLayout) myOldGlass!!.setLayout(myOldLayout)
} }
} }
/** /**
* Turns on the output panel for the given editor. * Turns on the more window for the given editor
*/ */
fun activate() { fun activate() {
disableOldGlass() val ed = editor ?: return
val root = SwingUtilities.getRootPane(ed.contentComponent)
deactivateOldGlass(root)
setFontForElements() setFontForElements()
positionPanel() positionPanel()
if (glassPane != null) { if (myOldGlass != null) {
glassPane!!.isVisible = true myOldGlass!!.isVisible = true
} }
active = true myActive = true
requestFocus(textPane) requestFocus(myText)
} }
private fun disableOldGlass() { private fun deactivateOldGlass(root: JRootPane?) {
val root = SwingUtilities.getRootPane(editor.contentComponent) ?: return if (root == null) return
glassPane = root.getGlassPane() as JComponent? myOldGlass = root.getGlassPane() as JComponent?
if (glassPane == null) { if (myOldGlass != null) {
myOldLayout = myOldGlass!!.layout
myWasOpaque = myOldGlass!!.isOpaque
myOldGlass!!.setLayout(null)
myOldGlass!!.setOpaque(false)
myOldGlass!!.add(this)
myOldGlass!!.addComponentListener(myAdapter)
}
}
private fun setFontForElements() {
val ed = editor ?: return
myText.setFont(selectEditorFont(ed, myText.getText()))
myLabel.setFont(selectEditorFont(ed, myLabel.text))
}
override fun scrollLine() {
scrollOffset(myLineHeight)
}
override fun scrollPage() {
scrollOffset(myScrollPane.getVerticalScrollBar().visibleAmount)
}
override fun scrollHalfPage() {
val sa = myScrollPane.getVerticalScrollBar().visibleAmount / 2.0
val offset = ceil(sa / myLineHeight) * myLineHeight
scrollOffset(offset.toInt())
}
fun onBadKey() {
val ed = editor ?: return
myLabel.setText(injector.messages.message("message.ex.output.more.prompt.full"))
myLabel.setFont(selectEditorFont(ed, myLabel.text))
}
private fun scrollOffset(more: Int) {
val ed = editor ?: return
val `val` = myScrollPane.getVerticalScrollBar().value
myScrollPane.getVerticalScrollBar().setValue(`val` + more)
myScrollPane.getHorizontalScrollBar().setValue(0)
if (isAtEnd) {
myLabel.setText(injector.messages.message("message.ex.output.end.prompt"))
} else {
myLabel.setText(injector.messages.message("message.ex.output.more.prompt"))
}
myLabel.setFont(selectEditorFont(ed, myLabel.text))
}
val isAtEnd: Boolean
get() {
val isSingleLine = myText.getLineCount() == 1
if (isSingleLine) return true
val scrollBar = myScrollPane.getVerticalScrollBar()
val value = scrollBar.value
if (!scrollBar.isVisible) {
return true
}
return value >= scrollBar.maximum - scrollBar.visibleAmount ||
scrollBar.maximum <= scrollBar.visibleAmount
}
private fun positionPanel() {
val ed = editor ?: return
val contentComponent = ed.contentComponent
val scroll = SwingUtilities.getAncestorOfClass(JScrollPane::class.java, contentComponent)
val rootPane = SwingUtilities.getRootPane(contentComponent)
if (scroll == null || rootPane == null) {
// These might be null if we're invoked during component initialisation and before it's been added to the tree
return return
} }
originalLayout = glassPane!!.layout
wasOpaque = glassPane!!.isOpaque size = scroll.size
glassPane!!.setLayout(null)
glassPane!!.setOpaque(false) myLineHeight = myText.getFontMetrics(myText.getFont()).height
glassPane!!.add(this) val count: Int = countLines(myText.getText())
glassPane!!.addComponentListener(resizeAdapter) val visLines = size.height / myLineHeight - 1
val lines = min(count, visLines)
setSize(
size.width,
lines * myLineHeight + myLabel.getPreferredSize().height + border.getBorderInsets(this).top * 2
)
val height = size.height
val bounds = scroll.bounds
bounds.translate(0, scroll.getHeight() - height)
bounds.height = height
val pos = SwingUtilities.convertPoint(scroll.getParent(), bounds.location, rootPane.getGlassPane())
bounds.location = pos
setBounds(bounds)
myScrollPane.getVerticalScrollBar().setValue(0)
if (!injector.globalOptions().more) {
// FIX
scrollOffset(100000)
} else {
scrollOffset(0)
}
}
fun close(key: KeyStroke? = null) {
val ed = editor ?: return
ApplicationManager.getApplication().invokeLater {
deactivate(true)
val project = ed.project
if (project != null && key != null && key.keyChar != '\n') {
val keys: MutableList<KeyStroke> = ArrayList(1)
keys.add(key)
if (LOG.isTrace()) {
LOG.trace(
"Adding new keys to keyStack as part of playback. State before adding keys: " +
getInstance().keyStack.dump()
)
}
getInstance().keyStack.addKeys(keys)
val context: ExecutionContext =
injector.executionContextManager.getEditorExecutionContext(IjVimEditor(ed))
VimPlugin.getMacro().playbackKeys(IjVimEditor(ed), context, 1)
}
}
} }
override fun close() { override fun close() {
close(null) close(null)
} }
fun close(key: KeyStroke?) { private class MoreKeyListener : KeyAdapter() {
val passKeyBack = isSingleLine /**
ApplicationManager.getApplication().invokeLater { * Invoked when a key has been pressed.
deactivate(true) */
val project = editor.project
// For single line messages, pass any key back to the editor (including Enter)
// For multi-line messages, don't pass Enter back (it was used to dismiss)
if (project != null && key != null && (passKeyBack || key.keyChar != '\n')) {
val keys: MutableList<KeyStroke> = ArrayList(1)
keys.add(key)
getInstance().keyStack.addKeys(keys)
val context: ExecutionContext =
injector.executionContextManager.getEditorExecutionContext(IjVimEditor(editor))
VimPlugin.getMacro().playbackKeys(IjVimEditor(editor), context, 1)
}
}
}
private fun setFontForElements() {
textPane.setFont(selectEditorFont(editor, textPane.getText()))
labelComponent.setFont(selectEditorFont(editor, labelComponent.text))
}
private fun positionPanel() {
val scroll = positionPanelStart() ?: return
val lineHeight = textPane.getFontMetrics(textPane.getFont()).height
val count = countLines(textPane.getText())
val visLines = size.height / lineHeight - 1
val lines = min(count, visLines)
// Simple output: single line that fits entirely - no label needed
isSingleLine = count == 1 && count <= visLines
labelComponent.isVisible = !isSingleLine
val extraHeight = if (isSingleLine) 0 else labelComponent.getPreferredSize().height
setSize(
size.width,
lines * lineHeight + extraHeight + border.getBorderInsets(this).top * 2
)
finishPositioning(scroll)
// Force layout so that viewport sizes are valid before checking scroll state
validate()
// onPositioned
cachedLineHeight = lineHeight
scrollPane.getVerticalScrollBar().setValue(0)
if (!isSingleLine) {
if (!injector.globalOptions().more) {
scrollOffset(100000)
} else {
scrollOffset(0)
}
}
}
private fun positionPanelStart(): JScrollPane? {
val contentComponent = editor.contentComponent
val scroll = SwingUtilities.getAncestorOfClass(JScrollPane::class.java, contentComponent) as? JScrollPane
val rootPane = SwingUtilities.getRootPane(contentComponent)
if (scroll == null || rootPane == null) {
return null
}
size = scroll.size
return scroll
}
private fun finishPositioning(scroll: JScrollPane) {
val rootPane = SwingUtilities.getRootPane(editor.contentComponent)
val bounds = scroll.bounds
bounds.translate(0, scroll.getHeight() - size.height)
bounds.height = size.height
val pos = SwingUtilities.convertPoint(scroll.getParent(), bounds.location, rootPane.getGlassPane())
bounds.location = pos
setBounds(bounds)
}
private fun countLines(text: String): Int {
if (text.isEmpty()) {
return 1
}
var count = 0
var pos = -1
while ((text.indexOf('\n', pos + 1).also { pos = it }) != -1) {
count++
}
if (text[text.length - 1] != '\n') {
count++
}
return count
}
override fun scrollLine() {
scrollOffset(cachedLineHeight)
}
override fun scrollPage() {
scrollOffset(scrollPane.getVerticalScrollBar().visibleAmount)
}
override fun scrollHalfPage() {
val sa = scrollPane.getVerticalScrollBar().visibleAmount / 2.0
val offset = ceil(sa / cachedLineHeight) * cachedLineHeight
scrollOffset(offset.toInt())
}
fun onBadKey() {
labelComponent.setText(injector.messages.message("message.ex.output.more.prompt.full"))
labelComponent.setFont(selectEditorFont(editor, labelComponent.text))
}
private fun scrollOffset(more: Int) {
scrollPane.validate()
val scrollBar = scrollPane.getVerticalScrollBar()
val value = scrollBar.value
scrollBar.setValue(value + more)
scrollPane.getHorizontalScrollBar().setValue(0)
// Check if we're at the end or if content fits entirely (nothing to scroll)
if (isAtEnd) {
labelComponent.setText(injector.messages.message("message.ex.output.end.prompt"))
} else {
labelComponent.setText(injector.messages.message("message.ex.output.more.prompt"))
}
labelComponent.setFont(selectEditorFont(editor, labelComponent.text))
}
val isAtEnd: Boolean
get() {
if (isSingleLine) return true
val contentHeight = textPane.preferredSize.height
val viewportHeight = scrollPane.viewport.height
if (contentHeight <= viewportHeight) return true
val scrollBar = scrollPane.getVerticalScrollBar()
return scrollBar.value >= scrollBar.maximum - scrollBar.visibleAmount
}
private inner class OutputPanelKeyListener : KeyAdapter() {
override fun keyTyped(e: KeyEvent) { override fun keyTyped(e: KeyEvent) {
val currentPanel: VimOutputPanel = injector.outputPanel.getCurrentOutputPanel() ?: return val currentPanel: VimOutputPanel = injector.outputPanel.getCurrentOutputPanel() ?: return
val keyChar = e.keyChar val keyCode = e.getKeyCode()
val keyChar = e.getKeyChar()
val modifiers = e.modifiersEx val modifiers = e.modifiersEx
val keyStroke = KeyStroke.getKeyStroke(keyChar, modifiers) val keyStroke = if (keyChar == KeyEvent.CHAR_UNDEFINED)
KeyStroke.getKeyStroke(keyCode, modifiers)
else
KeyStroke.getKeyStroke(keyChar, modifiers)
currentPanel.handleKey(keyStroke) currentPanel.handleKey(keyStroke)
} }
override fun keyPressed(e: KeyEvent) {
if (!e.isActionKey && e.keyCode != KeyEvent.VK_ENTER) return
val currentPanel = injector.outputPanel.getCurrentOutputPanel() as? OutputPanel ?: return
val keyCode = e.keyCode
val modifiers = e.modifiersEx
val keyStroke = KeyStroke.getKeyStroke(keyCode, modifiers)
if (isSingleLine) {
currentPanel.close(keyStroke)
e.consume()
return
}
// Multi-line mode: arrow keys scroll, down/right at end closes
when (keyCode) {
KeyEvent.VK_ENTER -> {
if (currentPanel.isAtEnd) currentPanel.close() else currentPanel.scrollLine()
e.consume()
}
KeyEvent.VK_DOWN -> if (currentPanel.isAtEnd) currentPanel.close(keyStroke) else currentPanel.scrollLine()
KeyEvent.VK_RIGHT -> if (currentPanel.isAtEnd) currentPanel.close(keyStroke) else currentPanel.scrollLine()
KeyEvent.VK_UP -> currentPanel.scrollOffset(-cachedLineHeight)
KeyEvent.VK_LEFT -> currentPanel.scrollOffset(-cachedLineHeight)
KeyEvent.VK_PAGE_DOWN -> if (currentPanel.isAtEnd) currentPanel.close(keyStroke) else currentPanel.scrollPage()
KeyEvent.VK_PAGE_UP -> currentPanel.scrollOffset(-scrollPane.verticalScrollBar.visibleAmount)
}
}
} }
class LafListener : LafManagerListener { class LafListener : LafManagerListener {
override fun lookAndFeelChanged(source: LafManager) { override fun lookAndFeelChanged(source: LafManager) {
if (VimPlugin.isNotEnabled()) return if (VimPlugin.isNotEnabled()) return
// This listener is only invoked for local scenarios, and we only need to update local editor UI. This will invoke
// updateUI on the output pane and it's child components
for (vimEditor in injector.editorGroup.getEditors()) { for (vimEditor in injector.editorGroup.getEditors()) {
val editor = (vimEditor as IjVimEditor).editor val editor = (vimEditor as IjVimEditor).editor
if (!isPanelActive(editor)) continue if (!isPanelActive(editor)) continue
@@ -500,24 +414,41 @@ class OutputPanel private constructor(
} }
companion object { companion object {
private val LOG: VimLogger = injector.getLogger<OutputPanel>(OutputPanel::class.java)
fun getNullablePanel(editor: Editor): OutputPanel? { fun getNullablePanel(editor: Editor): OutputPanel? {
return editor.vimMorePanel as OutputPanel? return editor.vimMorePanel as? OutputPanel
} }
fun isPanelActive(editor: Editor): Boolean { fun isPanelActive(editor: Editor): Boolean {
return getNullablePanel(editor) != null return getNullablePanel(editor)?.myActive ?: false
} }
fun getInstance(editor: Editor): OutputPanel { fun getInstance(editor: Editor): OutputPanel {
var panel: OutputPanel? = getNullablePanel(editor) var panel: OutputPanel? = getNullablePanel(editor)
if (panel == null) { if (panel == null) {
panel = OutputPanel(editor) panel = OutputPanel(WeakReference(editor))
editor.vimMorePanel = panel editor.vimMorePanel = panel
} }
return panel return panel
} }
private fun countLines(text: String): Int {
if (text.isEmpty()) {
return 0
}
var count = 0
var pos = -1
while ((text.indexOf('\n', pos + 1).also { pos = it }) != -1) {
count++
}
if (text[text.length - 1] != '\n') {
count++
}
return count
}
} }
} }
data class TextLine(val text: String, val color: Color?)

View File

@@ -15,6 +15,7 @@ import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.wm.IdeFocusManager import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.openapi.wm.impl.ToolWindowManagerImpl
import com.intellij.ui.DocumentAdapter import com.intellij.ui.DocumentAdapter
import com.intellij.util.IJSwingUtilities import com.intellij.util.IJSwingUtilities
import com.maddyhome.idea.vim.EventFacade import com.maddyhome.idea.vim.EventFacade
@@ -144,6 +145,7 @@ class ExEntryPanel private constructor() : JPanel(), VimCommandLine {
glassPane.addComponentListener(resizePanelListener) glassPane.addComponentListener(resizePanelListener)
positionPanel() positionPanel()
glassPane.isVisible = true glassPane.isVisible = true
putClientProperty(ToolWindowManagerImpl.PARENT_COMPONENT, parent)
entry.requestFocusInWindow() entry.requestFocusInWindow()
} }
this.isActive = true this.isActive = true
@@ -191,6 +193,7 @@ class ExEntryPanel private constructor() : JPanel(), VimCommandLine {
requestFocus(parent!!) requestFocus(parent!!)
} }
putClientProperty(ToolWindowManagerImpl.PARENT_COMPONENT, null)
oldGlass!!.removeComponentListener(resizePanelListener) oldGlass!!.removeComponentListener(resizePanelListener)
oldGlass!!.isVisible = false oldGlass!!.isVisible = false
oldGlass!!.remove(this) oldGlass!!.remove(this)
@@ -284,7 +287,7 @@ class ExEntryPanel private constructor() : JPanel(), VimCommandLine {
.calculateCount0Snapshot() .calculateCount0Snapshot()
) )
if (labelText == "/" || labelText == "?" || searchCommand) { if ((labelText == "/" || labelText == "?" || searchCommand) && !injector.macro.isExecutingMacro) {
val forwards = labelText != "?" // :s, :g, :v are treated as forwards val forwards = labelText != "?" // :s, :g, :v are treated as forwards
val patternEnd: Int = injector.searchGroup.findEndOfPattern(searchText, separator, 0) val patternEnd: Int = injector.searchGroup.findEndOfPattern(searchText, separator, 0)
val pattern = searchText.take(patternEnd) val pattern = searchText.take(patternEnd)

View File

@@ -194,7 +194,7 @@ class ExTextField internal constructor(private val myParentPanel: ExEntryPanel)
// handler adds all non-control characters to the text field. We want to add all characters, so if we have an // handler adds all non-control characters to the text field. We want to add all characters, so if we have an
// actual character, just add it. Anything else, we'll pass to the super class like before (even though it's unclear // actual character, just add it. Anything else, we'll pass to the super class like before (even though it's unclear
// what it will do with the keystroke) // what it will do with the keystroke)
if (stroke.keyChar != KeyEvent.CHAR_UNDEFINED) { if (stroke.keyChar != KeyEvent.CHAR_UNDEFINED && !isKeyCharEnterOrEscape(stroke.keyChar)) {
replaceSelection(stroke.keyChar.toString()) replaceSelection(stroke.keyChar.toString())
} else { } else {
val event = KeyEvent( val event = KeyEvent(

View File

@@ -22,11 +22,11 @@ class IjOutputPanelService : VimOutputPanelServiceBase() {
private var activeOutputPanel: WeakReference<VimOutputPanel>? = null private var activeOutputPanel: WeakReference<VimOutputPanel>? = null
override fun getCurrentOutputPanel(): VimOutputPanel? { override fun getCurrentOutputPanel(): VimOutputPanel? {
return activeOutputPanel?.get()?.takeIf { (it as OutputPanel).active } return activeOutputPanel?.get()?.takeIf { (it as OutputPanel).isActive }
} }
override fun create(editor: VimEditor, context: ExecutionContext): VimOutputPanel { override fun create(editor: VimEditor, context: ExecutionContext): VimOutputPanel {
val panel = OutputPanel.getInstance(editor.ij) val panel = OutputPanel(WeakReference(editor.ij))
activeOutputPanel = WeakReference(panel) activeOutputPanel = WeakReference(panel)
return panel return panel
} }

View File

@@ -96,7 +96,7 @@ data class ReadCommand(val range: Range, val modifier: CommandModifier, val argu
val copiedText = injector.clipboardManager.dumbCopiedText(content) val copiedText = injector.clipboardManager.dumbCopiedText(content)
val caret = editor.currentCaret() val caret = editor.currentCaret()
val address = if (range.addresses.isEmpty()) -1 else range.addresses.last().getLine1(editor, caret) val address = if (range.addresses.isEmpty()) -1 else range.addresses.last().getLine1(editor, caret)
val textData = PutData.TextData(null, copiedText, SelectionType.LINE_WISE) val textData = PutData.TextData(null, SelectionType.LINE_WISE, copiedText.transferableData, null)
return PutData( return PutData(
textData, textData,
null, null,

View File

@@ -0,0 +1,43 @@
package com.maddyhome.idea.vim.vimscript.model.functions.handlers
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.impl.PresentationFactory
import com.intellij.openapi.actionSystem.impl.Utils
import com.intellij.openapi.keymap.impl.ActionProcessor
import com.intellij.vim.annotations.VimscriptFunction
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.vimscript.model.VimLContext
import com.maddyhome.idea.vim.vimscript.model.datatypes.VimInt
import com.maddyhome.idea.vim.vimscript.model.datatypes.asVimInt
import com.maddyhome.idea.vim.vimscript.model.functions.BuiltinFunctionHandler
import java.awt.event.KeyEvent
@VimscriptFunction(name = "isactionenabled")
internal class IsActionEnabled : BuiltinFunctionHandler<VimInt>() {
override fun doFunction(
arguments: Arguments,
editor: VimEditor,
context: ExecutionContext,
vimContext: VimLContext,
): VimInt {
val action = ActionManager.getInstance().getAction(arguments.getString(0).value)
if (action == null) {
return false.asVimInt()
}
val presentationFactory = PresentationFactory()
val wrappedContext = Utils.createAsyncDataContext(context.ij)
val actionProcessor = object : ActionProcessor() {}
val inputEventAdjusted = KeyEvent(editor.ij.contentComponent, KeyEvent.KEY_PRESSED, 0L, 0, KeyEvent.VK_UNDEFINED, '\u0000')
val updateEvent = Utils.runUpdateSessionForInputEvent(listOf(action), inputEventAdjusted, wrappedContext, "IdeaVim", actionProcessor, presentationFactory) { _, updater, events ->
val presentation = updater(action)
events[presentation]
}
val result = updateEvent != null && updateEvent.presentation.isEnabled
return result.asVimInt()
}
}

View File

@@ -20,5 +20,5 @@ import com.maddyhome.idea.vim.vimscript.model.functions.BuiltinFunctionHandler
@VimscriptFunction(name = "pumvisible") @VimscriptFunction(name = "pumvisible")
internal class PopupMenuVisibleFunctionHandler : BuiltinFunctionHandler<VimInt>() { internal class PopupMenuVisibleFunctionHandler : BuiltinFunctionHandler<VimInt>() {
override fun doFunction(arguments: Arguments, editor: VimEditor, context: ExecutionContext, vimContext: VimLContext) = override fun doFunction(arguments: Arguments, editor: VimEditor, context: ExecutionContext, vimContext: VimLContext) =
(CompletionService.getCompletionService().currentCompletion == null).asVimInt() (CompletionService.getCompletionService().currentCompletion != null).asVimInt()
} }

View File

@@ -0,0 +1,17 @@
<!--
~ Copyright 2003-2026 The IdeaVim authors
~
~ Use of this source code is governed by an MIT-style
~ license that can be found in the LICENSE.txt file or at
~ https://opensource.org/licenses/MIT.
-->
<!-- Split-mode (Remote Dev) specific registrations.
This module only loads when intellij.platform.frontend.split is available,
which provides access to intellij.rd.client and its extension points. -->
<idea-plugin package="com.maddyhome.idea.vim">
<dependencies>
<module name="intellij.platform.frontend.split"/>
<module name="IdeaVIM.ideavim-frontend"/>
</dependencies>
</idea-plugin>

View File

@@ -1,12 +1,4 @@
<!-- <idea-plugin>
~ Copyright 2003-2026 The IdeaVim authors
~
~ Use of this source code is governed by an MIT-style
~ license that can be found in the LICENSE.txt file or at
~ https://opensource.org/licenses/MIT.
-->
<idea-plugin url="https://plugins.jetbrains.com/plugin/164">
<name>IdeaVim</name> <name>IdeaVim</name>
<id>IdeaVIM</id> <id>IdeaVIM</id>
<description><![CDATA[ <description><![CDATA[
@@ -40,7 +32,7 @@
<li><a href="https://youtrack.jetbrains.com/issues/VIM">Issue tracker</a> — feature requests and bug reports</li> <li><a href="https://youtrack.jetbrains.com/issues/VIM">Issue tracker</a> — feature requests and bug reports</li>
</ul> </ul>
]]></description> ]]></description>
<version>SNAPSHOT</version> <version>chylex</version>
<vendor>JetBrains</vendor> <vendor>JetBrains</vendor>
<!-- Mark the plugin as compatible with RubyMine and other products based on the IntelliJ platform (including CWM) --> <!-- Mark the plugin as compatible with RubyMine and other products based on the IntelliJ platform (including CWM) -->

View File

@@ -78,5 +78,10 @@
"keys": "gJ", "keys": "gJ",
"class": "com.maddyhome.idea.vim.action.change.delete.DeleteJoinVisualLinesAction", "class": "com.maddyhome.idea.vim.action.change.delete.DeleteJoinVisualLinesAction",
"modes": "X" "modes": "X"
},
{
"keys": "z@",
"class": "com.maddyhome.idea.vim.action.macro.PlaybackRegisterInOpenFilesAction",
"modes": "N"
} }
] ]

View File

@@ -1,4 +1,5 @@
{ {
"has": "com.maddyhome.idea.vim.vimscript.model.functions.handlers.HasFunctionHandler", "has": "com.maddyhome.idea.vim.vimscript.model.functions.handlers.HasFunctionHandler",
"isactionenabled": "com.maddyhome.idea.vim.vimscript.model.functions.handlers.IsActionEnabled",
"pumvisible": "com.maddyhome.idea.vim.vimscript.model.functions.handlers.PopupMenuVisibleFunctionHandler" "pumvisible": "com.maddyhome.idea.vim.vimscript.model.functions.handlers.PopupMenuVisibleFunctionHandler"
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2003-2023 The IdeaVim authors * Copyright 2003-2026 The IdeaVim authors
* *
* Use of this source code is governed by an MIT-style * Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at * license that can be found in the LICENSE.txt file or at
@@ -10,9 +10,12 @@ package org.jetbrains.plugins.ideavim.action.motion.search
import com.maddyhome.idea.vim.state.mode.Mode import com.maddyhome.idea.vim.state.mode.Mode
import com.maddyhome.idea.vim.state.mode.SelectionType import com.maddyhome.idea.vim.state.mode.SelectionType
import com.maddyhome.idea.vim.ui.ex.ExEntryPanel
import org.jetbrains.plugins.ideavim.VimTestCase import org.jetbrains.plugins.ideavim.VimTestCase
import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test import org.junit.jupiter.api.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class SearchEntryFwdActionTest : VimTestCase() { class SearchEntryFwdActionTest : VimTestCase() {
@Test @Test
@@ -110,6 +113,23 @@ class SearchEntryFwdActionTest : VimTestCase() {
) )
} }
@Test
fun `test escape after search not found closes panel without inserting escape char`() {
configureByText("lorem ipsum dolor sit amet")
typeText("/notfound")
val panel = ExEntryPanel.getOrCreatePanelInstance()
assertTrue(panel.isActive)
typeText("<Esc>")
assertFalse(panel.isActive)
assertMode(Mode.NORMAL())
// The panel text should not contain ^[ (escape character written as text)
assertFalse(panel.text.contains("\u001B"), "Panel text should not contain escape character")
assertFalse(panel.text.contains("^["), "Panel text should not contain ^[ literal")
}
@Disabled("Ctrl-o doesn't work yet in select mode") @Disabled("Ctrl-o doesn't work yet in select mode")
@Test @Test
fun `search in one time from select mode`() { fun `search in one time from select mode`() {

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2003-2026 The IdeaVim authors * Copyright 2003-2023 The IdeaVim authors
* *
* Use of this source code is governed by an MIT-style * Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at * license that can be found in the LICENSE.txt file or at
@@ -134,7 +134,7 @@ class CmdCommandTest : VimTestCase() {
VimPlugin.getCommand().resetAliases() VimPlugin.getCommand().resetAliases()
configureByText("\n") configureByText("\n")
typeText(commandToKeys("command! -range Error echo <args>")) typeText(commandToKeys("command! -range Error echo <args>"))
assertPluginError(true) assertPluginError(false)
kotlin.test.assertEquals("'-range' is not supported by `command`", injector.messages.getStatusBarMessage()) kotlin.test.assertEquals("'-range' is not supported by `command`", injector.messages.getStatusBarMessage())
} }
@@ -143,7 +143,7 @@ class CmdCommandTest : VimTestCase() {
VimPlugin.getCommand().resetAliases() VimPlugin.getCommand().resetAliases()
configureByText("\n") configureByText("\n")
typeText(commandToKeys("command! -complete=color Error echo <args>")) typeText(commandToKeys("command! -complete=color Error echo <args>"))
assertPluginError(true) assertPluginError(false)
kotlin.test.assertEquals("'-complete' is not supported by `command`", injector.messages.getStatusBarMessage()) kotlin.test.assertEquals("'-complete' is not supported by `command`", injector.messages.getStatusBarMessage())
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2003-2026 The IdeaVim authors * Copyright 2003-2023 The IdeaVim authors
* *
* Use of this source code is governed by an MIT-style * Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at * license that can be found in the LICENSE.txt file or at
@@ -24,6 +24,7 @@ class ExecuteCommandTest : VimTestCase() {
fun `test execute with range`() { fun `test execute with range`() {
configureByText("\n") configureByText("\n")
typeText(commandToKeys("1,2execute 'echo 42'")) typeText(commandToKeys("1,2execute 'echo 42'"))
assertNoExOutput()
assertPluginError(true) assertPluginError(true)
} }

View File

@@ -72,6 +72,7 @@ class HistoryCommandTest : VimTestCase() {
fun `test history with 'history' option set to 0 shows nothing`() { fun `test history with 'history' option set to 0 shows nothing`() {
enterCommand("set history=0") enterCommand("set history=0")
enterCommand("history") enterCommand("history")
assertNoExOutput()
assertPluginError(false) assertPluginError(false)
assertPluginErrorMessage("'history' option is zero") assertPluginErrorMessage("'history' option is zero")
} }

View File

@@ -241,12 +241,7 @@ class RegistersCommandTest : VimTestCase() {
val vimEditor = fixture.editor.vim val vimEditor = fixture.editor.vim
val context = injector.executionContextManager.getEditorExecutionContext(vimEditor) val context = injector.executionContextManager.getEditorExecutionContext(vimEditor)
injector.registerGroup.saveRegister( injector.registerGroup.saveRegister(vimEditor, context, '+', Register('+', SelectionType.LINE_WISE, "Lorem ipsum dolor", mutableListOf()))
vimEditor,
context,
'+',
Register('+', injector.clipboardManager.dumbCopiedText("Lorem ipsum dolor"), SelectionType.LINE_WISE)
)
val clipboardContent = injector.clipboardManager.dumbCopiedText("clipboard content") val clipboardContent = injector.clipboardManager.dumbCopiedText("clipboard content")
injector.clipboardManager.setClipboardContent(vimEditor, context, clipboardContent) injector.clipboardManager.setClipboardContent(vimEditor, context, clipboardContent)
typeText("V<Esc>") typeText("V<Esc>")
@@ -453,12 +448,7 @@ class RegistersCommandTest : VimTestCase() {
val vimEditor = fixture.editor.vim val vimEditor = fixture.editor.vim
val context = injector.executionContextManager.getEditorExecutionContext(vimEditor) val context = injector.executionContextManager.getEditorExecutionContext(vimEditor)
val clipboardContent = injector.clipboardManager.dumbCopiedText("clipboard content") val clipboardContent = injector.clipboardManager.dumbCopiedText("clipboard content")
injector.registerGroup.saveRegister( injector.registerGroup.saveRegister(vimEditor, context, '+', Register('+', SelectionType.LINE_WISE, "Lorem ipsum dolor", mutableListOf()))
vimEditor,
context,
'+',
Register('+', injector.clipboardManager.dumbCopiedText("Lorem ipsum dolor"), SelectionType.LINE_WISE)
)
injector.clipboardManager.setClipboardContent(vimEditor, context, clipboardContent) injector.clipboardManager.setClipboardContent(vimEditor, context, clipboardContent)
typeText("V<Esc>") typeText("V<Esc>")

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2003-2026 The IdeaVim authors * Copyright 2003-2025 The IdeaVim authors
* *
* Use of this source code is governed by an MIT-style * Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at * license that can be found in the LICENSE.txt file or at
@@ -43,6 +43,7 @@ class AndFunctionTest : VimTestCase() {
@Test @Test
fun `test and function with list causes error`() { fun `test and function with list causes error`() {
enterCommand("echo and([1, 2, 3], [2, 3, 4])") enterCommand("echo and([1, 2, 3], [2, 3, 4])")
assertNoExOutput()
assertPluginError(true) assertPluginError(true)
assertPluginErrorMessage("E745: Using a List as a Number") assertPluginErrorMessage("E745: Using a List as a Number")
} }
@@ -50,6 +51,7 @@ class AndFunctionTest : VimTestCase() {
@Test @Test
fun `test and function with dict causes error`() { fun `test and function with dict causes error`() {
enterCommand("echo and({1: 2, 3: 4}, {3: 4, 5: 6})") enterCommand("echo and({1: 2, 3: 4}, {3: 4, 5: 6})")
assertNoExOutput()
assertPluginError(true) assertPluginError(true)
assertPluginErrorMessage("E728: Using a Dictionary as a Number") assertPluginErrorMessage("E728: Using a Dictionary as a Number")
} }
@@ -57,6 +59,7 @@ class AndFunctionTest : VimTestCase() {
@Test @Test
fun `test and function with float causes error`() { fun `test and function with float causes error`() {
enterCommand("echo and(1.5, 2.5)") enterCommand("echo and(1.5, 2.5)")
assertNoExOutput()
assertPluginError(true) assertPluginError(true)
assertPluginErrorMessage("E805: Using a Float as a Number") assertPluginErrorMessage("E805: Using a Float as a Number")
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2003-2026 The IdeaVim authors * Copyright 2003-2025 The IdeaVim authors
* *
* Use of this source code is governed by an MIT-style * Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at * license that can be found in the LICENSE.txt file or at
@@ -28,6 +28,7 @@ class InvertFunctionTest : VimTestCase() {
@Test @Test
fun `test invert function with list causes error`() { fun `test invert function with list causes error`() {
enterCommand("echo invert([1, 2, 3])") enterCommand("echo invert([1, 2, 3])")
assertNoExOutput()
assertPluginError(true) assertPluginError(true)
assertPluginErrorMessage("E745: Using a List as a Number") assertPluginErrorMessage("E745: Using a List as a Number")
} }
@@ -35,6 +36,7 @@ class InvertFunctionTest : VimTestCase() {
@Test @Test
fun `test invert function with dict causes error`() { fun `test invert function with dict causes error`() {
enterCommand("echo invert({1: 2, 3: 4})") enterCommand("echo invert({1: 2, 3: 4})")
assertNoExOutput()
assertPluginError(true) assertPluginError(true)
assertPluginErrorMessage("E728: Using a Dictionary as a Number") assertPluginErrorMessage("E728: Using a Dictionary as a Number")
} }
@@ -42,6 +44,7 @@ class InvertFunctionTest : VimTestCase() {
@Test @Test
fun `test invert function with float causes error`() { fun `test invert function with float causes error`() {
enterCommand("echo invert(1.5)") enterCommand("echo invert(1.5)")
assertNoExOutput()
assertPluginError(true) assertPluginError(true)
assertPluginErrorMessage("E805: Using a Float as a Number") assertPluginErrorMessage("E805: Using a Float as a Number")
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2003-2026 The IdeaVim authors * Copyright 2003-2025 The IdeaVim authors
* *
* Use of this source code is governed by an MIT-style * Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at * license that can be found in the LICENSE.txt file or at
@@ -43,6 +43,7 @@ class OrFunctionTest : VimTestCase() {
@Test @Test
fun `test or function with list causes error`() { fun `test or function with list causes error`() {
enterCommand("echo or([1, 2, 3], [2, 3, 4])") enterCommand("echo or([1, 2, 3], [2, 3, 4])")
assertNoExOutput()
assertPluginError(true) assertPluginError(true)
assertPluginErrorMessage("E745: Using a List as a Number") assertPluginErrorMessage("E745: Using a List as a Number")
} }
@@ -50,6 +51,7 @@ class OrFunctionTest : VimTestCase() {
@Test @Test
fun `test or function with dict causes error`() { fun `test or function with dict causes error`() {
enterCommand("echo or({1: 2, 3: 4}, {3: 4, 5: 6})") enterCommand("echo or({1: 2, 3: 4}, {3: 4, 5: 6})")
assertNoExOutput()
assertPluginError(true) assertPluginError(true)
assertPluginErrorMessage("E728: Using a Dictionary as a Number") assertPluginErrorMessage("E728: Using a Dictionary as a Number")
} }
@@ -57,6 +59,7 @@ class OrFunctionTest : VimTestCase() {
@Test @Test
fun `test or function with float causes error`() { fun `test or function with float causes error`() {
enterCommand("echo or(1.5, 2.5)") enterCommand("echo or(1.5, 2.5)")
assertNoExOutput()
assertPluginError(true) assertPluginError(true)
assertPluginErrorMessage("E805: Using a Float as a Number") assertPluginErrorMessage("E805: Using a Float as a Number")
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2003-2026 The IdeaVim authors * Copyright 2003-2025 The IdeaVim authors
* *
* Use of this source code is governed by an MIT-style * Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at * license that can be found in the LICENSE.txt file or at
@@ -43,6 +43,7 @@ class XorFunctionTest : VimTestCase() {
@Test @Test
fun `test xor function with list causes error`() { fun `test xor function with list causes error`() {
enterCommand("echo xor([1, 2, 3], [2, 3, 4])") enterCommand("echo xor([1, 2, 3], [2, 3, 4])")
assertNoExOutput()
assertPluginError(true) assertPluginError(true)
assertPluginErrorMessage("E745: Using a List as a Number") assertPluginErrorMessage("E745: Using a List as a Number")
} }
@@ -50,6 +51,7 @@ class XorFunctionTest : VimTestCase() {
@Test @Test
fun `test xor function with dict causes error`() { fun `test xor function with dict causes error`() {
enterCommand("echo xor({1: 2, 3: 4}, {3: 4, 5: 6})") enterCommand("echo xor({1: 2, 3: 4}, {3: 4, 5: 6})")
assertNoExOutput()
assertPluginError(true) assertPluginError(true)
assertPluginErrorMessage("E728: Using a Dictionary as a Number") assertPluginErrorMessage("E728: Using a Dictionary as a Number")
} }
@@ -57,6 +59,7 @@ class XorFunctionTest : VimTestCase() {
@Test @Test
fun `test xor function with float causes error`() { fun `test xor function with float causes error`() {
enterCommand("echo xor(1.5, 2.5)") enterCommand("echo xor(1.5, 2.5)")
assertNoExOutput()
assertPluginError(true) assertPluginError(true)
assertPluginErrorMessage("E805: Using a Float as a Number") assertPluginErrorMessage("E805: Using a Float as a Number")
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2003-2026 The IdeaVim authors * Copyright 2003-2025 The IdeaVim authors
* *
* Use of this source code is governed by an MIT-style * Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at * license that can be found in the LICENSE.txt file or at
@@ -33,6 +33,7 @@ class ToLowerFunctionTest : VimTestCase() {
@Test @Test
fun `test tolower with list causes error`() { fun `test tolower with list causes error`() {
enterCommand("echo tolower([1, 2, 3])") enterCommand("echo tolower([1, 2, 3])")
assertNoExOutput()
assertPluginError(true) assertPluginError(true)
assertPluginErrorMessage("E730: Using a List as a String") assertPluginErrorMessage("E730: Using a List as a String")
} }
@@ -40,6 +41,7 @@ class ToLowerFunctionTest : VimTestCase() {
@Test @Test
fun `test tolower with dict causes error`() { fun `test tolower with dict causes error`() {
enterCommand("echo tolower({1: 2, 3: 4})") enterCommand("echo tolower({1: 2, 3: 4})")
assertNoExOutput()
assertPluginError(true) assertPluginError(true)
assertPluginErrorMessage("E731: Using a Dictionary as a String") assertPluginErrorMessage("E731: Using a Dictionary as a String")
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2003-2026 The IdeaVim authors * Copyright 2003-2025 The IdeaVim authors
* *
* Use of this source code is governed by an MIT-style * Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at * license that can be found in the LICENSE.txt file or at
@@ -33,6 +33,7 @@ class ToUpperFunctionTest : VimTestCase() {
@Test @Test
fun `test toupper with list causes error`() { fun `test toupper with list causes error`() {
enterCommand("echo toupper([1, 2, 3])") enterCommand("echo toupper([1, 2, 3])")
assertNoExOutput()
assertPluginError(true) assertPluginError(true)
assertPluginErrorMessage("E730: Using a List as a String") assertPluginErrorMessage("E730: Using a List as a String")
} }
@@ -40,6 +41,7 @@ class ToUpperFunctionTest : VimTestCase() {
@Test @Test
fun `test toupper with dict causes error`() { fun `test toupper with dict causes error`() {
enterCommand("echo toupper({1: 2, 3: 4})") enterCommand("echo toupper({1: 2, 3: 4})")
assertNoExOutput()
assertPluginError(true) assertPluginError(true)
assertPluginErrorMessage("E731: Using a Dictionary as a String") assertPluginErrorMessage("E731: Using a Dictionary as a String")
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2003-2026 The IdeaVim authors * Copyright 2003-2023 The IdeaVim authors
* *
* Use of this source code is governed by an MIT-style * Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at * license that can be found in the LICENSE.txt file or at
@@ -207,12 +207,7 @@ class FunctionDeclarationTest : VimTestCase() {
typeText(commandToKeys("echo F1()")) typeText(commandToKeys("echo F1()"))
assertPluginError(true) assertPluginError(true)
assertPluginErrorMessage("E121: Undefined variable: x") assertPluginErrorMessage("E121: Undefined variable: x")
assertExOutput( assertExOutput("0")
"""
E121: Undefined variable: x
0
""".trimIndent()
)
typeText(commandToKeys("delf! F1")) typeText(commandToKeys("delf! F1"))
typeText(commandToKeys("delf! F2")) typeText(commandToKeys("delf! F2"))

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2003-2026 The IdeaVim authors * Copyright 2003-2023 The IdeaVim authors
* *
* Use of this source code is governed by an MIT-style * Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at * license that can be found in the LICENSE.txt file or at
@@ -154,12 +154,7 @@ class TryCatchTest : VimTestCase() {
), ),
) )
assertPluginError(true) assertPluginError(true)
assertExOutput( assertExOutput("finally block")
"""
finally block
my exception
""".trimIndent()
)
} }
@Test @Test

View File

@@ -50,4 +50,4 @@ class RegisterVariableTest : VimTestCase() {
assertEquals("ab", register.text) assertEquals("ab", register.text)
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2003-2026 The IdeaVim authors * Copyright 2003-2023 The IdeaVim authors
* *
* Use of this source code is governed by an MIT-style * Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at * license that can be found in the LICENSE.txt file or at
@@ -223,7 +223,7 @@ class SearchGroupTest : VimTestCase() {
) { ) {
enterCommand("set nowrapscan") enterCommand("set nowrapscan")
} }
assertPluginError(true) assertPluginError(false)
assertPluginErrorMessage("E385: Search hit BOTTOM without match for: one") assertPluginErrorMessage("E385: Search hit BOTTOM without match for: one")
} }
@@ -242,7 +242,7 @@ class SearchGroupTest : VimTestCase() {
three three
""".trimIndent() """.trimIndent()
) )
assertPluginError(true) assertPluginError(false)
assertPluginErrorMessage("E486: Pattern not found: banana") assertPluginErrorMessage("E486: Pattern not found: banana")
} }
@@ -282,7 +282,7 @@ class SearchGroupTest : VimTestCase() {
) { ) {
enterCommand("set nowrapscan") enterCommand("set nowrapscan")
} }
assertPluginError(true) assertPluginError(false)
assertPluginErrorMessage("E384: Search hit TOP without match for: three") assertPluginErrorMessage("E384: Search hit TOP without match for: three")
} }
@@ -301,7 +301,7 @@ class SearchGroupTest : VimTestCase() {
three three
""".trimIndent() """.trimIndent()
) )
assertPluginError(true) assertPluginError(false)
assertPluginErrorMessage("E486: Pattern not found: banana") assertPluginErrorMessage("E486: Pattern not found: banana")
} }
@@ -615,7 +615,7 @@ class SearchGroupTest : VimTestCase() {
) )
enterCommand("set nowrapscan") enterCommand("set nowrapscan")
typeText("10", "/", searchCommand("one")) typeText("10", "/", searchCommand("one"))
assertPluginError(true) assertPluginError(false)
assertPluginErrorMessage("E385: Search hit BOTTOM without match for: one") assertPluginErrorMessage("E385: Search hit BOTTOM without match for: one")
assertPosition(2, 0) assertPosition(2, 0)
} }
@@ -679,7 +679,7 @@ class SearchGroupTest : VimTestCase() {
) )
enterCommand("set nowrapscan") enterCommand("set nowrapscan")
typeText("12", "?one<CR>") typeText("12", "?one<CR>")
assertPluginError(true) assertPluginError(false)
assertPluginErrorMessage("E384: Search hit TOP without match for: one") assertPluginErrorMessage("E384: Search hit TOP without match for: one")
assertPosition(8, 0) assertPosition(8, 0)
} }

View File

@@ -608,7 +608,7 @@ class NavigateBetweenFoldsTest : FoldActionTestBase() {
typeText("yzj") typeText("yzj")
val context = injector.executionContextManager.getEditorExecutionContext(fixture.editor.vim) val context = injector.executionContextManager.getEditorExecutionContext(fixture.editor.vim)
val regText = injector.registerGroup.getRegister(fixture.editor.vim, context, '0')!!.text val regText = injector.registerGroup.getRegister(fixture.editor.vim, context, '0')!!.text!!
// Linewise yank includes all lines from cursor to fold start (inclusive) // Linewise yank includes all lines from cursor to fold start (inclusive)
assertEquals(true, regText.contains("int x = 5")) assertEquals(true, regText.contains("int x = 5"))
assertEquals(true, regText.contains("int y = 10")) assertEquals(true, regText.contains("int y = 10"))

View File

@@ -22,11 +22,11 @@ class JumpNavigationSplitTest : IdeaVimStarterTestBase() {
openFile(longFile("Jump1")) openFile(longFile("Jump1"))
typeVim("G") typeVim("G")
pause(300) pause(500)
assertCaretAfter(40, "G should go to end of file") assertCaretAfter(40, "G should go to end of file")
ctrlO() ctrlO()
pause(300) pause(500)
assertCaretBefore(10, "Ctrl-O should jump back to start") assertCaretBefore(10, "Ctrl-O should jump back to start")
} }
@@ -35,7 +35,7 @@ class JumpNavigationSplitTest : IdeaVimStarterTestBase() {
openFile(longFile("Jump2")) openFile(longFile("Jump2"))
typeVim("gg") typeVim("gg")
pause(300) pause(500)
typeVim("/Line 30\n") typeVim("/Line 30\n")
pause() pause()

View File

@@ -36,10 +36,6 @@ tasks {
group = "verification" group = "verification"
useJUnitPlatform() useJUnitPlatform()
// Gradle 9+ requires explicit test source set configuration for custom Test tasks
testClassesDirs = sourceSets["test"].output.classesDirs
classpath = sourceSets["test"].runtimeClasspath
// This is needed for the robot to access the message of the exception // This is needed for the robot to access the message of the exception
// Usually these opens are provided by the intellij gradle plugin // Usually these opens are provided by the intellij gradle plugin
// https://github.com/JetBrains/gradle-intellij-plugin/blob/b21e3f382e9885948a6427001d5e64234c602613/src/main/kotlin/org/jetbrains/intellij/utils/OpenedPackages.kt#L26 // https://github.com/JetBrains/gradle-intellij-plugin/blob/b21e3f382e9885948a6427001d5e64234c602613/src/main/kotlin/org/jetbrains/intellij/utils/OpenedPackages.kt#L26

View File

@@ -37,10 +37,6 @@ tasks {
group = "verification" group = "verification"
useJUnitPlatform() useJUnitPlatform()
// Gradle 9+ requires explicit test source set configuration for custom Test tasks
testClassesDirs = sourceSets["test"].output.classesDirs
classpath = sourceSets["test"].runtimeClasspath
// This is needed for the robot to access the message of the exception // This is needed for the robot to access the message of the exception
// Usually these opens are provided by the intellij gradle plugin // Usually these opens are provided by the intellij gradle plugin
// https://github.com/JetBrains/gradle-intellij-plugin/blob/b21e3f382e9885948a6427001d5e64234c602613/src/main/kotlin/org/jetbrains/intellij/utils/OpenedPackages.kt#L26 // https://github.com/JetBrains/gradle-intellij-plugin/blob/b21e3f382e9885948a6427001d5e64234c602613/src/main/kotlin/org/jetbrains/intellij/utils/OpenedPackages.kt#L26

View File

@@ -37,10 +37,6 @@ tasks {
group = "verification" group = "verification"
useJUnitPlatform() useJUnitPlatform()
// Gradle 9+ requires explicit test source set configuration for custom Test tasks
testClassesDirs = sourceSets["test"].output.classesDirs
classpath = sourceSets["test"].runtimeClasspath
// This is needed for the robot to access the message of the exception // This is needed for the robot to access the message of the exception
// Usually these opens are provided by the intellij gradle plugin // Usually these opens are provided by the intellij gradle plugin
// https://github.com/JetBrains/gradle-intellij-plugin/blob/b21e3f382e9885948a6427001d5e64234c602613/src/main/kotlin/org/jetbrains/intellij/utils/OpenedPackages.kt#L26 // https://github.com/JetBrains/gradle-intellij-plugin/blob/b21e3f382e9885948a6427001d5e64234c602613/src/main/kotlin/org/jetbrains/intellij/utils/OpenedPackages.kt#L26

View File

@@ -82,6 +82,7 @@ tasks {
generateGrammarSource { generateGrammarSource {
maxHeapSize = "128m" maxHeapSize = "128m"
arguments.addAll(listOf("-package", "com.maddyhome.idea.vim.parser.generated", "-visitor")) arguments.addAll(listOf("-package", "com.maddyhome.idea.vim.parser.generated", "-visitor"))
outputDirectory = file("src/main/java/com/maddyhome/idea/vim/parser/generated")
} }
named("compileKotlin") { named("compileKotlin") {

View File

@@ -16,7 +16,7 @@ import com.maddyhome.idea.vim.command.Command
import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.handler.VimActionHandler import com.maddyhome.idea.vim.handler.VimActionHandler
@CommandOrMotion(keys = ["<C-R>"], modes = [Mode.NORMAL]) @CommandOrMotion(keys = ["U", "<C-R>"], modes = [Mode.NORMAL, Mode.VISUAL])
class RedoAction : VimActionHandler.SingleExecution() { class RedoAction : VimActionHandler.SingleExecution() {
override val type: Command.Type = Command.Type.OTHER_SELF_SYNCHRONIZED override val type: Command.Type = Command.Type.OTHER_SELF_SYNCHRONIZED

Some files were not shown because too many files have changed in this diff Show More