1
0
mirror of https://github.com/chylex/IntelliJ-IdeaVim.git synced 2025-08-18 19:24:55 +02:00

Compare commits

..

16 Commits

Author SHA1 Message Date
1afd0d3c37 Set plugin version to chylex-18 2023-10-20 00:58:13 +02:00
547bd08c7e Set minimum IDEA version to 2023.2 2023-10-20 00:58:13 +02:00
0c4154547f Reset insert mode when switching active editor 2023-10-20 00:58:12 +02:00
92d8be1ba4 Revert "Add VimScript 'renaming()' function"
This reverts commit a8a822b58e.
2023-10-20 00:58:12 +02:00
080dbe9c0e Prevent IdeaVIM from stealing key binding that confirms in-place refactoring 2023-10-20 00:58:12 +02:00
ff7e6bf053 Set plugin version to chylex-17 2023-10-19 06:13:47 +02:00
f19ce34311 Add operating system type to has() function 2023-10-18 22:14:42 +02:00
8bcb0d116d Set plugin version to chylex-16 2023-09-29 01:39:49 +02:00
d9ae9fa40d Remove update checker 2023-09-29 01:39:48 +02:00
c19f88e5c0 [VIM-696] Restore visual mode after undo/redo, and disable incompatible actions 2023-09-29 01:39:48 +02:00
03f4fb288d Change matchit plugin to use HTML patterns in unrecognized files 2023-09-29 01:39:48 +02:00
ef27579277 Fix vim-surround not working with multiple cursors
Fixes multiple cursors with vim-surround commands `cs, ds, S` (but not `ys`).
2023-09-29 01:39:48 +02:00
a8a822b58e Add VimScript 'renaming()' function 2023-09-29 01:39:48 +02:00
9752bd5bbb Add support for repeatable actions with ':raction' 2023-09-29 01:39:48 +02:00
240d9e0be4 Disable taking over arrow keys and Home/End 2023-09-29 01:39:48 +02:00
328442544d Set custom plugin version 2023-09-29 01:39:48 +02:00
811 changed files with 63528 additions and 108271 deletions

View File

@@ -14,7 +14,6 @@ jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: github.repository == 'JetBrains/ideavim'
steps: steps:
- name: Fetch origin repo - name: Fetch origin repo

View File

@@ -12,7 +12,6 @@ jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: github.repository == 'JetBrains/ideavim'
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3

View File

@@ -12,7 +12,6 @@ jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: github.repository == 'JetBrains/ideavim'
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2

View File

@@ -12,7 +12,6 @@ jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: github.repository == 'JetBrains/ideavim'
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2

View File

@@ -8,7 +8,7 @@ permissions:
jobs: jobs:
dependabot: dependabot:
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: ${{ github.actor == 'dependabot[bot]' && github.repository == 'JetBrains/ideavim' }} if: ${{ github.actor == 'dependabot[bot]' }}
steps: steps:
- name: Auto-merge Dependabot PR - name: Auto-merge Dependabot PR
run: gh pr merge --auto --rebase "$PR_URL" run: gh pr merge --auto --rebase "$PR_URL"

View File

@@ -11,7 +11,7 @@ on:
jobs: jobs:
build: build:
if: false if: github.event.pull_request.merged == true
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:

View File

@@ -1,81 +0,0 @@
name: Run Non Octopus UI Tests
on:
workflow_dispatch:
schedule:
- cron: '0 12 * * *'
jobs:
build-for-ui-test-mac-os:
if: github.repository == 'JetBrains/ideavim'
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
- name: Setup Java
uses: actions/setup-java@v4
with:
distribution: zulu
java-version: 17
- name: Setup FFmpeg
run: brew install ffmpeg
- name: Setup Gradle
uses: gradle/gradle-build-action@v2.4.2
- name: Build Plugin
run: gradle :buildPlugin
- name: Run Idea
run: |
mkdir -p build/reports
gradle runIdeForUiTests -Doctopus.handler=false > build/reports/idea.log &
- name: Wait for Idea started
uses: jtalk/url-health-check-action@v3
with:
url: http://127.0.0.1:8082
max-attempts: 20
retry-delay: 10s
- name: Tests
run: gradle :tests:ui-ij-tests:testUi
- name: Move video
if: always()
run: mv tests/ui-ij-tests/video build/reports
- name: Move sandbox logs
if: always()
run: mv build/idea-sandbox/system/log sandbox-idea-log
- name: Save report
if: always()
uses: actions/upload-artifact@v4
with:
name: ui-test-fails-report-mac
path: |
build/reports
tests/ui-ij-tests/build/reports
sandbox-idea-log
# build-for-ui-test-linux:
# runs-on: ubuntu-latest
# steps:
# - uses: actions/checkout@v2
# - name: Setup Java
# uses: actions/setup-java@v2.1.0
# with:
# distribution: zulu
# java-version: 11
# - name: Build Plugin
# run: gradle :buildPlugin
# - name: Run Idea
# run: |
# export DISPLAY=:99.0
# Xvfb -ac :99 -screen 0 1920x1080x16 &
# mkdir -p build/reports
# gradle :runIdeForUiTests #> build/reports/idea.log
# - name: Wait for Idea started
# uses: jtalk/url-health-check-action@1.5
# with:
# url: http://127.0.0.1:8082
# max-attempts: 15
# retry-delay: 30s
# - name: Tests
# run: gradle :testUi
# - name: Save fails report
# if: ${{ failure() }}
# uses: actions/upload-artifact@v2
# with:
# name: ui-test-fails-report-linux
# path: |
# ui-test-example/build/reports

View File

@@ -1,52 +0,0 @@
name: Run UI PyCharm Tests
on:
workflow_dispatch:
schedule:
- cron: '0 12 * * *'
jobs:
build-for-ui-test-mac-os:
if: github.repository == 'JetBrains/ideavim'
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
- name: Setup Java
uses: actions/setup-java@v4
with:
distribution: zulu
java-version: 17
- uses: actions/setup-python@v5
with:
python-version: '3.10'
- name: Setup FFmpeg
run: brew install ffmpeg
- name: Setup Gradle
uses: gradle/gradle-build-action@v2.4.2
- name: Build Plugin
run: gradle :buildPlugin
- name: Run Idea
run: |
mkdir -p build/reports
gradle :runIdeForUiTests -PideaType=PC > build/reports/idea.log &
- name: Wait for Idea started
uses: jtalk/url-health-check-action@v3
with:
url: http://127.0.0.1:8082
max-attempts: 20
retry-delay: 10s
- name: Tests
run: gradle :tests:ui-py-tests:testUi
- name: Move video
if: always()
run: mv tests/ui-py-tests/video build/reports
- name: Move sandbox logs
if: always()
run: mv build/idea-sandbox/system/log sandbox-idea-log
- name: Save report
if: always()
uses: actions/upload-artifact@v4
with:
name: ui-test-fails-report-mac
path: |
build/reports
tests/ui-py-tests/build/reports
sandbox-idea-log

View File

@@ -5,48 +5,44 @@ on:
- cron: '0 12 * * *' - cron: '0 12 * * *'
jobs: jobs:
build-for-ui-test-mac-os: build-for-ui-test-mac-os:
if: github.repository == 'JetBrains/ideavim'
runs-on: macos-latest runs-on: macos-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v2
- name: Setup Java - name: Setup Java
uses: actions/setup-java@v4 uses: actions/setup-java@v2.1.0
with: with:
distribution: zulu distribution: zulu
java-version: 17 java-version: 11
- name: Setup FFmpeg - name: Setup FFmpeg
run: brew install ffmpeg uses: FedericoCarboni/setup-ffmpeg@v1
- name: Setup Gradle with:
uses: gradle/gradle-build-action@v2.4.2 # Not strictly necessary, but it may prevent rate limit
# errors especially on GitHub-hosted macos machines.
token: ${{ secrets.GITHUB_TOKEN }}
- name: Build Plugin - name: Build Plugin
run: gradle :buildPlugin run: gradle :buildPlugin
- name: Run Idea - name: Run Idea
run: | run: |
mkdir -p build/reports mkdir -p build/reports
gradle runIdeForUiTests > build/reports/idea.log & gradle :runIdeForUiTests > build/reports/idea.log &
- name: Wait for Idea started - name: Wait for Idea started
uses: jtalk/url-health-check-action@v3 uses: jtalk/url-health-check-action@1.5
with: with:
url: http://127.0.0.1:8082 url: http://127.0.0.1:8082
max-attempts: 20 max-attempts: 20
retry-delay: 10s retry-delay: 10s
- name: Tests - name: Tests
run: gradle :tests:ui-ij-tests:testUi run: gradle :testUi
- name: Move video - name: Move video
if: always() if: ${{ failure() }}
run: mv tests/ui-ij-tests/video build/reports run: mv video build/reports
- name: Move sandbox logs - name: Save fails report
if: always() if: ${{ failure() }}
run: mv build/idea-sandbox/system/log sandbox-idea-log uses: actions/upload-artifact@v2
- name: Save report
if: always()
uses: actions/upload-artifact@v4
with: with:
name: ui-test-fails-report-mac name: ui-test-fails-report-mac
path: | path: |
build/reports build/reports
tests/ui-ij-tests/build/reports
sandbox-idea-log
# build-for-ui-test-linux: # build-for-ui-test-linux:
# runs-on: ubuntu-latest # runs-on: ubuntu-latest
# steps: # steps:

View File

@@ -14,7 +14,6 @@ jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: github.repository == 'JetBrains/ideavim'
steps: steps:
- name: Fetch origin repo - name: Fetch origin repo

View File

@@ -0,0 +1,33 @@
# This workflow will build a package using Gradle and then publish it to GitHub packages when a release is created
# For more information see: https://github.com/actions/setup-java/blob/main/docs/advanced-usage.md#Publishing-using-gradle
# This workflow syncs changes from the docs folder of IdeaVim to the IdeaVim.wiki repository
name: Update Affected Rate field on YouTrack
on:
workflow_dispatch:
schedule:
- cron: '0 8 * * *'
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Fetch origin repo
uses: actions/checkout@v3
- name: Set up JDK 17
uses: actions/setup-java@v2
with:
java-version: '17'
distribution: 'adopt'
server-id: github # Value of the distributionManagement/repository/id field of the pom.xml
settings-path: ${{ github.workspace }} # location for the settings.xml file
- name: Update YouTrack
run: ./gradlew scripts:updateAffectedRates
env:
YOUTRACK_TOKEN: ${{ secrets.YOUTRACK_TOKEN }}

View File

@@ -15,7 +15,6 @@ jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: github.repository == 'JetBrains/ideavim'
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3

View File

@@ -7,12 +7,14 @@ on:
workflow_dispatch: workflow_dispatch:
schedule: schedule:
- cron: '0 10 * * *' - cron: '0 10 * * *'
# Workflow run on push is disabled to avoid conflicts when merging PR
# push:
# branches: [ master ]
jobs: jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: false
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3

View File

@@ -12,7 +12,6 @@ jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: github.repository == 'JetBrains/ideavim'
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2

4
.gitignore vendored
View File

@@ -23,10 +23,6 @@
# Generated by gradle task "generateGrammarSource" # Generated by gradle task "generateGrammarSource"
src/main/java/com/maddyhome/idea/vim/vimscript/parser/generated src/main/java/com/maddyhome/idea/vim/vimscript/parser/generated
vim-engine/src/main/java/com/maddyhome/idea/vim/regexp/parser/generated
# Generated JSONs for lazy classloading
/vim-engine/src/main/resources/ksp-generated
/src/main/resources/ksp-generated
# Created by github automation # Created by github automation
settings.xml settings.xml

View File

@@ -1,6 +1,6 @@
<component name="CopyrightManager"> <component name="CopyrightManager">
<copyright> <copyright>
<option name="notice" value="Copyright 2003-&amp;#36;today.year The IdeaVim authors&#10;&#10;Use of this source code is governed by an MIT-style&#10;license that can be found in the LICENSE.txt file or at&#10;https://opensource.org/licenses/MIT." /> <option name="notice" value="Copyright 2003-2023 The IdeaVim authors&#10;&#10;Use of this source code is governed by an MIT-style&#10;license that can be found in the LICENSE.txt file or at&#10;https://opensource.org/licenses/MIT." />
<option name="myName" value="IdeaVim" /> <option name="myName" value="IdeaVim" />
</copyright> </copyright>
</component> </component>

View File

@@ -5,13 +5,15 @@ object Constants {
const val EAP_CHANNEL = "eap" const val EAP_CHANNEL = "eap"
const val DEV_CHANNEL = "Dev" const val DEV_CHANNEL = "Dev"
const val GITHUB_TESTS = "2023.3.2" const val VERSION = "2.4.0"
const val NVIM_TESTS = "2023.3.2"
const val PROPERTY_TESTS = "2023.3.2"
const val LONG_RUNNING_TESTS = "2023.3.2"
const val QODANA_TESTS = "2023.3.2"
const val RELEASE = "2023.3.2"
const val RELEASE_DEV = "2023.3.2" const val GITHUB_TESTS = "LATEST-EAP-SNAPSHOT"
const val RELEASE_EAP = "2023.3.2" const val NVIM_TESTS = "LATEST-EAP-SNAPSHOT"
const val PROPERTY_TESTS = "LATEST-EAP-SNAPSHOT"
const val LONG_RUNNING_TESTS = "LATEST-EAP-SNAPSHOT"
const val QODANA_TESTS = "LATEST-EAP-SNAPSHOT"
const val RELEASE = "2023.1.2"
const val RELEASE_DEV = "2023.1.2"
const val RELEASE_EAP = "2023.1.2"
} }

View File

@@ -15,7 +15,7 @@ import jetbrains.buildServer.configs.kotlin.v2019_2.BuildType
import jetbrains.buildServer.configs.kotlin.v2019_2.Project import jetbrains.buildServer.configs.kotlin.v2019_2.Project
object Project : Project({ object Project : Project({
description = "Vim engine for JetBrains IDEs" description = "Vim engine for IDEs based on the IntelliJ platform"
subProjects(Releases, OldTests, GitHub) subProjects(Releases, OldTests, GitHub)
@@ -24,8 +24,6 @@ object Project : Project({
// Active tests // Active tests
buildType(TestingBuildType("Latest EAP", "<default>", version = "LATEST-EAP-SNAPSHOT")) buildType(TestingBuildType("Latest EAP", "<default>", version = "LATEST-EAP-SNAPSHOT"))
buildType(TestingBuildType("2023.3", "<default>", version = "2023.3"))
buildType(TestingBuildType("2024.1", "<default>"))
buildType(TestingBuildType("Latest EAP With Xorg", "<default>", version = "LATEST-EAP-SNAPSHOT")) buildType(TestingBuildType("Latest EAP With Xorg", "<default>", version = "LATEST-EAP-SNAPSHOT"))
buildType(PropertyBased) buildType(PropertyBased)
@@ -40,11 +38,6 @@ object Project : Project({
// Common build type for all configurations // Common build type for all configurations
abstract class IdeaVimBuildType(init: BuildType.() -> Unit) : BuildType({ abstract class IdeaVimBuildType(init: BuildType.() -> Unit) : BuildType({
artifactRules = """
+:build/reports => build/reports
+:/mnt/agent/temp/buildTmp/ => /mnt/agent/temp/buildTmp/
""".trimIndent()
init() init()
requirements { requirements {

View File

@@ -34,6 +34,7 @@ object Compatibility : IdeaVimBuildType({
java --version java --version
java -jar verifier1/verifier-cli-dev-all-1.jar check-plugin '${'$'}org.jetbrains.IdeaVim-EasyMotion' [latest-IU] -team-city java -jar verifier1/verifier-cli-dev-all-1.jar check-plugin '${'$'}org.jetbrains.IdeaVim-EasyMotion' [latest-IU] -team-city
java -jar verifier1/verifier-cli-dev-all-1.jar check-plugin '${'$'}io.github.mishkun.ideavimsneak' [latest-IU] -team-city
java -jar verifier1/verifier-cli-dev-all-1.jar check-plugin '${'$'}eu.theblob42.idea.whichkey' [latest-IU] -team-city java -jar verifier1/verifier-cli-dev-all-1.jar check-plugin '${'$'}eu.theblob42.idea.whichkey' [latest-IU] -team-city
java -jar verifier1/verifier-cli-dev-all-1.jar check-plugin '${'$'}IdeaVimExtension' [latest-IU] -team-city java -jar verifier1/verifier-cli-dev-all-1.jar check-plugin '${'$'}IdeaVimExtension' [latest-IU] -team-city
# Outdated java -jar verifier/verifier-cli-dev-all.jar check-plugin '${'$'}github.zgqq.intellij-enhance' [latest-IU] -team-city # Outdated java -jar verifier/verifier-cli-dev-all.jar check-plugin '${'$'}github.zgqq.intellij-enhance' [latest-IU] -team-city

View File

@@ -25,7 +25,7 @@ object LongRunning : IdeaVimBuildType({
steps { steps {
gradle { gradle {
tasks = "clean :tests:long-running-tests:testLongRunning" tasks = "clean testLongRunning"
buildFile = "" buildFile = ""
enableStacktrace = true enableStacktrace = true
} }

View File

@@ -39,7 +39,7 @@ object Nvim : IdeaVimBuildType({
""".trimIndent() """.trimIndent()
} }
gradle { gradle {
tasks = "clean test -Dnvim" tasks = "clean testWithNeovim"
buildFile = "" buildFile = ""
enableStacktrace = true enableStacktrace = true
} }

View File

@@ -24,7 +24,7 @@ object PropertyBased : IdeaVimBuildType({
steps { steps {
gradle { gradle {
tasks = "clean :tests:property-tests:testPropertyBased" tasks = "clean testPropertyBased"
buildFile = "" buildFile = ""
enableStacktrace = true enableStacktrace = true
} }

View File

@@ -20,8 +20,8 @@ object PublishVimEngine : IdeaVimBuildType({
params { params {
param("env.ORG_GRADLE_PROJECT_engineVersion", "%build.number%") param("env.ORG_GRADLE_PROJECT_engineVersion", "%build.number%")
param("env.ORG_GRADLE_PROJECT_uploadUrl", "https://packages.jetbrains.team/maven/p/ij/intellij-dependencies") param("env.ORG_GRADLE_PROJECT_uploadUrl", "https://packages.jetbrains.team/maven/p/ij/intellij-dependencies")
password("env.ORG_GRADLE_PROJECT_spacePassword", "credentialsJSON:5ea56f8c-efe7-4e1e-83de-0c02bcc39d0b", display = ParameterDisplay.HIDDEN) password("env.ORG_GRADLE_PROJECT_spacePassword", "credentialsJSON:790b4e43-ee83-4184-b81b-678afab60409", display = ParameterDisplay.HIDDEN)
param("env.ORG_GRADLE_PROJECT_spaceUsername", "a121c67e-39ac-40e6-bf82-649855ec27b6") param("env.ORG_GRADLE_PROJECT_spaceUsername", "Aleksei.Plate")
} }
vcs { vcs {

View File

@@ -46,8 +46,8 @@ object Qodana : IdeaVimBuildType({
version = Qodana.JVMVersion.LATEST version = Qodana.JVMVersion.LATEST
} }
reportAsTests = true reportAsTests = true
additionalDockerArguments = "-e QODANA_TOKEN=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJvcmdhbml6YXRpb24iOiIzUFZrQSIsInByb2plY3QiOiIzN1FlQSIsInRva2VuIjoiM0t2bXoifQ.uohp81tM7iAfvvB6k8faarfpV-OjusAaEbWQ8iNrOgs"
additionalQodanaArguments = "--baseline qodana.sarif.json" additionalQodanaArguments = "--baseline qodana.sarif.json"
cloudToken = "credentialsJSON:6b79412e-9198-4862-9223-c5019488f903"
} }
} }
@@ -63,6 +63,7 @@ object Qodana : IdeaVimBuildType({
timezone = "SERVER" timezone = "SERVER"
} }
param("dayOfWeek", "Sunday") param("dayOfWeek", "Sunday")
enabled = false
} }
} }

View File

@@ -5,7 +5,6 @@ import _Self.Constants.RELEASE_EAP
import _Self.IdeaVimBuildType import _Self.IdeaVimBuildType
import jetbrains.buildServer.configs.kotlin.v2019_2.CheckoutMode import jetbrains.buildServer.configs.kotlin.v2019_2.CheckoutMode
import jetbrains.buildServer.configs.kotlin.v2019_2.DslContext import jetbrains.buildServer.configs.kotlin.v2019_2.DslContext
import jetbrains.buildServer.configs.kotlin.v2019_2.ParameterDisplay
import jetbrains.buildServer.configs.kotlin.v2019_2.buildFeatures.sshAgent import jetbrains.buildServer.configs.kotlin.v2019_2.buildFeatures.sshAgent
import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.gradle import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.gradle
import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.script import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.script
@@ -31,11 +30,6 @@ object ReleaseEap : IdeaVimBuildType({
"credentialsJSON:a8ab8150-e6f8-4eaf-987c-bcd65eac50b5", "credentialsJSON:a8ab8150-e6f8-4eaf-987c-bcd65eac50b5",
label = "Slack Token" label = "Slack Token"
) )
password(
"env.YOUTRACK_TOKEN",
"credentialsJSON:2479995b-7b60-4fbb-b095-f0bafae7f622",
display = ParameterDisplay.HIDDEN
)
} }
vcs { vcs {
@@ -67,9 +61,13 @@ object ReleaseEap : IdeaVimBuildType({
tasks = "scripts:addReleaseTag" tasks = "scripts:addReleaseTag"
} }
gradle { gradle {
name = "Publish plugin"
tasks = "publishPlugin" tasks = "publishPlugin"
} }
// Same as the script below. However, jgit can't find ssh keys on TeamCity
// gradle {
// name = "Push changes to the repo"
// tasks = "scripts:pushChanges"
// }
script { script {
name = "Push changes to the repo" name = "Push changes to the repo"
scriptContent = """ scriptContent = """
@@ -83,10 +81,6 @@ object ReleaseEap : IdeaVimBuildType({
git push origin %build.number% git push origin %build.number%
""".trimIndent() """.trimIndent()
} }
gradle {
name = "YouTrack post release actions"
tasks = "scripts:eapReleaseActions"
}
} }
features { features {

View File

@@ -45,11 +45,7 @@ sealed class ReleasePlugin(private val releaseType: String) : IdeaVimBuildType({
"credentialsJSON:a8ab8150-e6f8-4eaf-987c-bcd65eac50b5", "credentialsJSON:a8ab8150-e6f8-4eaf-987c-bcd65eac50b5",
label = "Slack Token" label = "Slack Token"
) )
password( password("env.ORG_GRADLE_PROJECT_youtrackToken", "credentialsJSON:3cd3e867-282c-451f-b958-bc95d56a8450", display = ParameterDisplay.HIDDEN)
"env.ORG_GRADLE_PROJECT_youtrackToken",
"credentialsJSON:7bc0eb3a-b86a-4ebd-b622-d4ef12d7e1d3",
display = ParameterDisplay.HIDDEN
)
param("env.ORG_GRADLE_PROJECT_releaseType", releaseType) param("env.ORG_GRADLE_PROJECT_releaseType", releaseType)
} }
@@ -69,25 +65,9 @@ sealed class ReleasePlugin(private val releaseType: String) : IdeaVimBuildType({
name = "Pull git history" name = "Pull git history"
scriptContent = "git fetch --unshallow" scriptContent = "git fetch --unshallow"
} }
script { gradle {
name = "Reset release branch" name = "Select branch"
scriptContent = """ tasks = "scripts:selectBranch"
if [ "major" = "$releaseType" ] || [ "minor" = "$releaseType" ]
then
echo Resetting the release branch because the release type is $releaseType
git checkout master
latest_eap=${'$'}(git describe --tags --match="[0-9].[0-9]*.[0-9]-eap.[0-9]*" --abbrev=0 HEAD)
echo Latest EAP: ${'$'}latest_eap
commit_of_latest_eap=${'$'}(git rev-list -n 1 ${'$'}latest_eap)
echo Commit of latest EAP: ${'$'}commit_of_latest_eap
git checkout release
git reset --hard ${'$'}commit_of_latest_eap
else
git checkout release
echo Do not reset the release branch because the release type is $releaseType
fi
echo Checked out release branch
""".trimIndent()
} }
gradle { gradle {
name = "Calculate new version" name = "Calculate new version"
@@ -97,50 +77,52 @@ sealed class ReleasePlugin(private val releaseType: String) : IdeaVimBuildType({
name = "Set TeamCity build number" name = "Set TeamCity build number"
tasks = "scripts:setTeamCityBuildNumber" tasks = "scripts:setTeamCityBuildNumber"
} }
// gradle { gradle {
// name = "Update change log" name = "Update change log"
// tasks = "scripts:changelogUpdateUnreleased" tasks = "scripts:changelogUpdateUnreleased"
// } }
// gradle { gradle {
// name = "Commit preparation changes" name = "Commit preparation changes"
// tasks = "scripts:commitChanges" tasks = "scripts:commitChanges"
// } }
gradle { gradle {
name = "Add release tag" name = "Add release tag"
tasks = "scripts:addReleaseTag" tasks = "scripts:addReleaseTag"
} }
script { gradle {
name = "Run tests" name = "Reset release branch"
scriptContent = "./gradlew test" tasks = "scripts:resetReleaseBranch"
} }
gradle { gradle {
name = "Publish release" name = "Publish release"
tasks = "publishPlugin" tasks = "publishPlugin"
} }
// script {
// name = "Checkout master branch"
// scriptContent = """
// echo Checkout master
// git checkout master
// """.trimIndent()
// }
// gradle { // gradle {
// name = "Update change log in master" // name = "Push changes to the repo"
// tasks = "scripts:changelogUpdateUnreleased" // tasks = "scripts:pushChangesWithReleaseBranch"
// }
// gradle {
// name = "Commit preparation changes in master"
// tasks = "scripts:commitChanges"
// } // }
script { script {
name = "Push changes to the repo" name = "Push changes to the repo"
scriptContent = """ scriptContent = """
git checkout release branch=$(git branch --show-current)
echo checkout release branch echo current branch is ${'$'}branch
git branch --set-upstream-to=origin/release release if [ "master" != "${'$'}branch" ];
git push origin --force then
# Push tag git checkout master
git push origin %build.number% fi
git push origin --tags
git push origin
if [ "patch" != $releaseType ];
then
git checkout release
echo checkout release branch
git push --tags
git push origin --force
fi
git checkout ${'$'}branch
""".trimIndent() """.trimIndent()
} }
gradle { gradle {

View File

@@ -20,6 +20,4 @@ object OldTests : Project({
buildType(TestingBuildType("IC-2021.2.2", "203-212", javaVersion = "1.8", javaPlugin = false)) buildType(TestingBuildType("IC-2021.2.2", "203-212", javaVersion = "1.8", javaPlugin = false))
buildType(TestingBuildType("IC-2021.3.2", "213-221", javaVersion = "1.8", javaPlugin = false)) buildType(TestingBuildType("IC-2021.3.2", "213-221", javaVersion = "1.8", javaPlugin = false))
buildType(TestingBuildType("IC-2022.2.3", branch = "222", javaPlugin = false)) buildType(TestingBuildType("IC-2022.2.3", branch = "222", javaPlugin = false))
buildType(TestingBuildType("IC-2023.1", "231-232", javaPlugin = false))
buildType(TestingBuildType("IC-2023.2", "231-232", javaPlugin = false))
}) })

View File

@@ -1,39 +0,0 @@
package patches.buildTypes
import jetbrains.buildServer.configs.kotlin.v2019_2.*
import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.GradleBuildStep
import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.gradle
import jetbrains.buildServer.configs.kotlin.v2019_2.ui.*
/*
This patch script was generated by TeamCity on settings change in UI.
To apply the patch, change the buildType with id = 'IdeaVimTests_Latest_EAP'
accordingly, and delete the patch script.
*/
changeBuildType(RelativeId("IdeaVimTests_Latest_EAP")) {
check(artifactRules == """
+:build/reports => build/reports
+:/mnt/agent/temp/buildTmp/ => /mnt/agent/temp/buildTmp/
""".trimIndent()) {
"Unexpected option value: artifactRules = $artifactRules"
}
artifactRules = """
+:build/reports => build/reports
+:/mnt/agent/temp/buildTmp/ => /mnt/agent/temp/buildTmp/
+:tests/java-tests/build/reports => tests/java-tests/build/reports
""".trimIndent()
expectSteps {
gradle {
tasks = "clean test"
buildFile = ""
enableStacktrace = true
}
}
steps {
update<GradleBuildStep>(0) {
clearConditions()
jdkHome = "/usr/lib/jvm/java-17-amazon-corretto"
}
}
}

View File

@@ -1,19 +0,0 @@
package patches.buildTypes
import jetbrains.buildServer.configs.kotlin.v2019_2.*
import jetbrains.buildServer.configs.kotlin.v2019_2.ui.*
/*
This patch script was generated by TeamCity on settings change in UI.
To apply the patch, change the buildType with id = 'PublishVimEngine'
accordingly, and delete the patch script.
*/
changeBuildType(RelativeId("PublishVimEngine")) {
vcs {
check(branchFilter == "+:<default>") {
"Unexpected option value: branchFilter = $branchFilter"
}
branchFilter = "+:fleet"
}
}

View File

@@ -0,0 +1,20 @@
package patches.buildTypes
import jetbrains.buildServer.configs.kotlin.v2019_2.*
import jetbrains.buildServer.configs.kotlin.v2019_2.ui.*
/*
This patch script was generated by TeamCity on settings change in UI.
To apply the patch, change the buildType with id = 'ReleasePatch'
accordingly, and delete the patch script.
*/
changeBuildType(RelativeId("ReleasePatch")) {
params {
expect {
password("env.ORG_GRADLE_PROJECT_youtrackToken", "credentialsJSON:3cd3e867-282c-451f-b958-bc95d56a8450", display = ParameterDisplay.HIDDEN)
}
update {
password("env.ORG_GRADLE_PROJECT_youtrackToken", "credentialsJSON:7bc0eb3a-b86a-4ebd-b622-d4ef12d7e1d3", display = ParameterDisplay.HIDDEN)
}
}
}

View File

@@ -30,5 +30,5 @@ node (Plugins -> teamcity-configs -> teamcity-configs:generate),
the 'Debug' option is available in the context menu for the task. the 'Debug' option is available in the context menu for the task.
*/ */
version = "2023.11" version = "2023.05"
project(_Self.Project) project(_Self.Project)

View File

@@ -483,26 +483,6 @@ Contributors:
[![icon][github]](https://github.com/ludwig-jb) [![icon][github]](https://github.com/ludwig-jb)
&nbsp; &nbsp;
ludwig-jb ludwig-jb
* [![icon][mail]](mailto:pvydmuch@gmail.com)
[![icon][github]](https://github.com/pWydmuch)
&nbsp;
pWydmuch
* [![icon][mail]](mailto:leonid989@gmail.com)
[![icon][github]](https://github.com/Infonautica)
&nbsp;
Leonid Danilov
* [![icon][mail]](mailto:emanuel-367@hotmail.com)
[![icon][github]](https://github.com/emanuelgestosa)
&nbsp;
Emanuel Gestosa
* [![icon][mail]](mailto:81118900+lippfi@users.noreply.github.com)
[![icon][github]](https://github.com/lippfi)
&nbsp;
lippfi,
* [![icon][mail]](mailto:fillipser143@gmail.com)
[![icon][github]](https://github.com/Parker7123)
&nbsp;
FilipParker
Previous contributors: Previous contributors:

View File

@@ -23,92 +23,13 @@ It is important to distinguish EAP from traditional pre-release software.
Please note that the quality of EAP versions may at times be way below even Please note that the quality of EAP versions may at times be way below even
usual beta standards. usual beta standards.
## End of changelog file maintenance ## To Be Released
Since version 2.9.0, the changelog can be found on YouTrack
To Be Released: https://youtrack.jetbrains.com/issues/VIM?q=%23%7BReady%20To%20Release%7D%20
Latest Fixes: https://youtrack.jetbrains.com/issues/VIM?q=State:%20Fixed%20sort%20by:%20updated%20
## 2.9.0, 2024-02-20
### Fixes:
* [VIM-3055](https://youtrack.jetbrains.com/issue/VIM-3055) Fix the issue with double deleting after dot
### 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
## 2.8.0, 2024-01-30
### Fixes:
* [VIM-3130](https://youtrack.jetbrains.com/issue/VIM-3130) Change the build version to 2023.1.2
* [VIM-3168](https://youtrack.jetbrains.com/issue/VIM-3168) Do not switch to block caret after enter if the IdeaVim is disabled
* [VIM-3165](https://youtrack.jetbrains.com/issue/VIM-3165) Do not process enter key as IdeaVim shortcut if it's not an actual keypress
* [VIM-3159](https://youtrack.jetbrains.com/issue/VIM-3159) Shift-enter now works in normal mode again
* [VIM-3157](https://youtrack.jetbrains.com/issue/VIM-3157) Do not invoke enter in invokeLater for python console
* [VIM-3195](https://youtrack.jetbrains.com/issue/VIM-3195) Fix escape in injected editor
* [VIM-3190](https://youtrack.jetbrains.com/issue/VIM-3190) Do not use octopus handler if the enter key is used with modifiers like shift or control
* [VIM-3203](https://youtrack.jetbrains.com/issue/VIM-3203) Split action not works in normal mode
* [VIM-3184](https://youtrack.jetbrains.com/issue/VIM-3184) Revert "VIM-3184: Temporally disable new handlers for the thin client"
* [VIM-3186](https://youtrack.jetbrains.com/issue/VIM-3186) Do not multiply the enter action by the amount of carets
* [VIM-3177](https://youtrack.jetbrains.com/issue/VIM-3177) Formatting of commit message works again
* [VIM-1611](https://youtrack.jetbrains.com/issue/VIM-1611) actions related to resolving conflicts doesn't seem to work
* [VIM-3204](https://youtrack.jetbrains.com/issue/VIM-3204) Add checker that verifies the configuratin of the keymap
* [VIM-3084](https://youtrack.jetbrains.com/issue/VIM-3084) Double update for the status bar icon
* [VIM-3176](https://youtrack.jetbrains.com/issue/VIM-3176) Reselecting visual selection after pasting above it select wrong lines
* [VIM-3206](https://youtrack.jetbrains.com/issue/VIM-3206) Disable both copilot suggestion and insert mode on a single escape
* [VIM-3090](https://youtrack.jetbrains.com/issue/VIM-3090) Cmd line mode saves the visual mode
* [VIM-3085](https://youtrack.jetbrains.com/issue/VIM-3085) Open access to VimTypedActionHandler and VimShortcutKeyAction
* [VIM-3260](https://youtrack.jetbrains.com/issue/VIM-3260) Processing the offsets at the file end
* [VIM-3183](https://youtrack.jetbrains.com/issue/VIM-3183) Execute .ideavimrc on pooled thread
### Merged PRs:
* [763](https://github.com/JetBrains/ideavim/pull/763) by [Sam Ng](https://github.com/samabcde): Fix(VIM-3176) add test for restore selection after pasting in/below s…
* [772](https://github.com/JetBrains/ideavim/pull/772) by [chylex](https://github.com/chylex): Prevent code completion popup from appearing after running a macro
* [787](https://github.com/JetBrains/ideavim/pull/787) by [Leonid Danilov](https://github.com/Infonautica): Added "Which-Key" to Plugins
* [778](https://github.com/JetBrains/ideavim/pull/778) by [lippfi](https://github.com/lippfi): Showmode
* [788](https://github.com/JetBrains/ideavim/pull/788) by [Matt Ellis](https://github.com/citizenmatt): Refactor VimOptionGroupBase
## 2.7.0, 2023-11-07
### Fixes:
* [VIM-2933](https://youtrack.jetbrains.com/issue/VIM-2933) Reloading/sourcing .ideavimrc does not initialize new plugins
* [VIM-3138](https://youtrack.jetbrains.com/issue/VIM-3138) Do not try to register disposer if the caret is already disposed
### Merged PRs:
* [734](https://github.com/JetBrains/ideavim/pull/734) by [Matt Ellis](https://github.com/citizenmatt): Support `~/` on Windows
* [736](https://github.com/JetBrains/ideavim/pull/736) by [chylex](https://github.com/chylex): Fix(VIM-2933): Reloading/sourcing .ideavimrc does not initialize new plugins
## 2.6.3, 2023-10-30
### Changes:
- 2.6.0 and 2.6.1 releases are broken. Version 2.6.3 reverts IdeaVim plugin to the working state as for 2.5.1.
## 2.6.0, 2023-10-27
This version of IdeaVim contains a lot of issues. Version 2.6.3 reverts these changes.
### Features:
* `ShowHoverInfo` action can be used in mappings to open a tooltip that is shown by
mouse hovering | [VIM-2106](https://youtrack.jetbrains.com/issue/VIM-2106)
* `has` Vim Script function supports the most common OS checks: win32, win64, linux, mac, macunix, osx, osxdarwin, bsd, sun, unix
* See https://github.com/JetBrains/ideavim#vim-script for details about Vim Script
### Fixes: ### Fixes:
* [VIM-3060](https://youtrack.jetbrains.com/issue/VIM-3060) Clipboard interaction stopped working * [VIM-3060](https://youtrack.jetbrains.com/issue/VIM-3060) Clipboard interaction stopped working
* [VIM-3095](https://youtrack.jetbrains.com/issue/VIM-3095) Fix missing ellipsis digraph
* [VIM-2562](https://youtrack.jetbrains.com/issue/VIM-2562) Fix hang with multi-width chars in command line
* [VIM-696](https://youtrack.jetbrains.com/issue/VIM-696) Vim selection issue after undo
* [VIM-1639](https://youtrack.jetbrains.com/issue/VIM-1639) Ctrl-o and Ctrl-i jumping in files of different projects
### Merged PRs: ### Merged PRs:
* [697](https://github.com/JetBrains/ideavim/pull/697) by [Matt Ellis](https://github.com/citizenmatt): Support per-window "global" values for local-to-window options * [697](https://github.com/JetBrains/ideavim/pull/697) by [Matt Ellis](https://github.com/citizenmatt): Support per-window "global" values for local-to-window options
* [717](https://github.com/JetBrains/ideavim/pull/717) by [Matt Ellis](https://github.com/citizenmatt): Fix(VIM-2562): Fix hang with multi-width chars in command line
* [732](https://github.com/JetBrains/ideavim/pull/732) by [pWydmuch](https://github.com/pWydmuch): Fix md links in doc
* [733](https://github.com/JetBrains/ideavim/pull/733) by [Matt Ellis](https://github.com/citizenmatt): Add support for ShowHoverInfo action to 2023.1 and 2023.2
* [729](https://github.com/JetBrains/ideavim/pull/729) by [chylex](https://github.com/chylex): Add operating system type to `has()` function
* [726](https://github.com/JetBrains/ideavim/pull/726) by [Matt Ellis](https://github.com/citizenmatt): Fix range for fall back comment mode
## 2.5.0, 2023-09-01 ## 2.5.0, 2023-09-01

View File

@@ -255,7 +255,8 @@ Ex commands or via `:map` command mappings:
##### Some popular actions: ##### Some popular actions:
``` ```
ShowHoverInfo - Quick Documentation and Error Description QuickJavaDoc - Quick Documentation (not only for java, all languages)
ShowErrorDescription - Show description of the error under the caret (cursor hovering)
QuickImplementations - Quick Definition QuickImplementations - Quick Definition
``` ```
@@ -324,7 +325,7 @@ IdeaVim tips and tricks
- Use the power of IJ and Vim: - Use the power of IJ and Vim:
- `set ideajoin` to enable join via the IDE. See the [examples](https://jb.gg/f9zji9). - `set ideajoin` to enable join via the IDE. See the [examples](https://jb.gg/f9zji9).
- Make sure `ideaput` is enabled for `clipboard` to enable native IJ insertion in Vim. - Make sure `ideaput` is enabled for `clipboard` to enable native IJ insertion in Vim.
- Sync IJ bookmarks and IdeaVim global marks: `set ideamarks` (works for marks with capital letters only) - Sync IJ bookmarks and Vim marks: `set ideamarks`
- Check out more [ex commands](https://github.com/JetBrains/ideavim/wiki/%22set%22-commands). - Check out more [ex commands](https://github.com/JetBrains/ideavim/wiki/%22set%22-commands).
- Use your vim settings with IdeaVim. Put `source ~/.vimrc` in `~/.ideavimrc`. - Use your vim settings with IdeaVim. Put `source ~/.vimrc` in `~/.ideavimrc`.

View File

@@ -84,8 +84,3 @@ IV) It is not allowed to remove this license from the distribution of the Vim
license for previous Vim releases instead of the license that they came license for previous Vim releases instead of the license that they came
with, at your option. with, at your option.
``` ```
---
File [sneakIcon.png](doc/images/sneakIcon.svg), which is originally an icon of the ideavim-sneak plugin,
is merged icons of IdeaVim plugin and a random sneaker by FreePic from flaticon.com.

View File

@@ -8,11 +8,8 @@
plugins { plugins {
kotlin("jvm") kotlin("jvm")
kotlin("plugin.serialization") version "1.9.22"
} }
val kotlinxSerializationVersion: String by project
group = "com.intellij" group = "com.intellij"
version = "SNAPSHOT" version = "SNAPSHOT"
@@ -21,10 +18,6 @@ repositories {
} }
dependencies { dependencies {
compileOnly("com.google.devtools.ksp:symbol-processing-api:1.9.23-1.0.20") compileOnly("com.google.devtools.ksp:symbol-processing-api:1.9.10-1.0.13")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json-jvm:$kotlinxSerializationVersion") { implementation("org.jetbrains.kotlinx:kotlinx-serialization-json-jvm:1.6.0")
// kotlin stdlib is provided by IJ, so there is no need to include it into the distribution
exclude("org.jetbrains.kotlin", "kotlin-stdlib")
exclude("org.jetbrains.kotlin", "kotlin-stdlib-common")
}
} }

View File

@@ -1,55 +0,0 @@
/*
* Copyright 2003-2023 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.
*/
package com.intellij.vim.annotations
// TODO support numpad keys parsing, see :keycodes
/**
* It's not necessary a Vim command
* This annotation may be used for:
* - commands
* - motions
*/
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.SOURCE)
annotation class CommandOrMotion(val keys: Array<String>, vararg val modes: Mode)
annotation class TextObject(val keys: String)
enum class Mode(val abbrev: Char) {
/**
* Indicates this key mapping applies to Normal mode
*/
NORMAL('N'),
/**
* Indicates this key mapping applies to Visual mode
*/
VISUAL('X'),
/**
* Indicates this key mapping applies to Select mode
*/
SELECT('S'),
/**
* Indicates this key mapping applies to Operator Pending mode
*/
OP_PENDING('O'),
/**
* Indicates this key mapping applies to Insert or Replace modes
*/
INSERT('I'),
/**
* Indicates this key mapping applies to Command Line mode
*/
CMD_LINE('C'),
}

View File

@@ -1,62 +0,0 @@
/*
* Copyright 2003-2023 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.
*/
package com.intellij.vim.processors
import com.google.devtools.ksp.KspExperimental
import com.google.devtools.ksp.getAnnotationsByType
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.processing.SymbolProcessor
import com.google.devtools.ksp.processing.SymbolProcessorEnvironment
import com.google.devtools.ksp.symbol.KSAnnotated
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.google.devtools.ksp.symbol.KSFile
import com.google.devtools.ksp.symbol.KSVisitorVoid
import com.intellij.vim.annotations.CommandOrMotion
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.nio.file.Files
import kotlin.io.path.Path
import kotlin.io.path.writeText
class CommandOrMotionProcessor(private val environment: SymbolProcessorEnvironment): SymbolProcessor {
private val visitor = CommandOrMotionVisitor()
private val commands = mutableListOf<CommandBean>()
private val json = Json { prettyPrint = true }
override fun process(resolver: Resolver): List<KSAnnotated> {
resolver.getAllFiles().forEach { it.accept(visitor, Unit) }
val generatedDirPath = Path(environment.options["generated_directory"]!!)
Files.createDirectories(generatedDirPath)
val filePath = generatedDirPath.resolve(environment.options["commands_file"]!!)
val fileContent = json.encodeToString(commands)
filePath.writeText(fileContent)
return emptyList()
}
private inner class CommandOrMotionVisitor : KSVisitorVoid() {
@OptIn(KspExperimental::class)
override fun visitClassDeclaration(classDeclaration: KSClassDeclaration, data: Unit) {
val commandAnnotation = classDeclaration.getAnnotationsByType(CommandOrMotion::class).firstOrNull() ?: return
for (key in commandAnnotation.keys) {
commands.add(
CommandBean(key, classDeclaration.qualifiedName!!.asString(), commandAnnotation.modes.map { it.abbrev }.joinToString(separator = ""))
)
}
}
override fun visitFile(file: KSFile, data: Unit) {
file.declarations.forEach { it.accept(this, Unit) }
}
}
}

View File

@@ -20,7 +20,6 @@ import com.google.devtools.ksp.symbol.KSVisitorVoid
import com.intellij.vim.annotations.ExCommand import com.intellij.vim.annotations.ExCommand
import kotlinx.serialization.encodeToString import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
import java.nio.file.Files
import kotlin.io.path.Path import kotlin.io.path.Path
import kotlin.io.path.writeText import kotlin.io.path.writeText
@@ -32,11 +31,7 @@ class ExCommandProcessor(private val environment: SymbolProcessorEnvironment): S
override fun process(resolver: Resolver): List<KSAnnotated> { override fun process(resolver: Resolver): List<KSAnnotated> {
resolver.getAllFiles().forEach { it.accept(visitor, Unit) } resolver.getAllFiles().forEach { it.accept(visitor, Unit) }
val filePath = Path(environment.options["generated_directory"]!!, environment.options["ex_commands_file"]!!)
val generatedDirPath = Path(environment.options["generated_directory"]!!)
Files.createDirectories(generatedDirPath)
val filePath = generatedDirPath.resolve(environment.options["ex_commands_file"]!!)
val fileContent = json.encodeToString(commandToClass) val fileContent = json.encodeToString(commandToClass)
filePath.writeText(fileContent) filePath.writeText(fileContent)

View File

@@ -20,7 +20,6 @@ import com.google.devtools.ksp.symbol.KSVisitorVoid
import com.intellij.vim.annotations.VimscriptFunction import com.intellij.vim.annotations.VimscriptFunction
import kotlinx.serialization.encodeToString import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
import java.nio.file.Files
import kotlin.io.path.Path import kotlin.io.path.Path
import kotlin.io.path.writeText import kotlin.io.path.writeText
@@ -32,11 +31,7 @@ class VimscriptFunctionProcessor(private val environment: SymbolProcessorEnviron
override fun process(resolver: Resolver): List<KSAnnotated> { override fun process(resolver: Resolver): List<KSAnnotated> {
resolver.getAllFiles().forEach { it.accept(visitor, Unit) } resolver.getAllFiles().forEach { it.accept(visitor, Unit) }
val filePath = Path(environment.options["generated_directory"]!!, environment.options["vimscript_functions_file"]!!)
val generatedDirPath = Path(environment.options["generated_directory"]!!)
Files.createDirectories(generatedDirPath)
val filePath = generatedDirPath.resolve(environment.options["vimscript_functions_file"]!!)
val fileContent = json.encodeToString(nameToClass) val fileContent = json.encodeToString(nameToClass)
filePath.writeText(fileContent) filePath.writeText(fileContent)

View File

@@ -1,20 +0,0 @@
/*
* Copyright 2003-2023 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.
*/
package com.intellij.vim.providers
import com.google.devtools.ksp.processing.SymbolProcessor
import com.google.devtools.ksp.processing.SymbolProcessorEnvironment
import com.google.devtools.ksp.processing.SymbolProcessorProvider
import com.intellij.vim.processors.CommandOrMotionProcessor
class CommandOrMotionProcessorProvider : SymbolProcessorProvider {
override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor {
return CommandOrMotionProcessor(environment)
}
}

View File

@@ -1,3 +1,2 @@
com.intellij.vim.providers.CommandOrMotionProcessorProvider
com.intellij.vim.providers.ExCommandProcessorProvider
com.intellij.vim.providers.VimscriptFunctionProcessorProvider com.intellij.vim.providers.VimscriptFunctionProcessorProvider
com.intellij.vim.providers.ExCommandProcessorProvider

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
Welcome to the IdeaVim wiki! Welcome to the IdeaVim wiki!
- List of IdeaVim plugins: [plugins](IdeaVim%20Plugins.md) - List of IdeaVim plugins: [[plugins|IdeaVim Plugins]]
- Examples of `ideajoin` option (also known as "smart join"): ["ideajoin" examples](ideajoin-examples.md) - Examples of `ideajoin` option (also known as "smart join"): [["ideajoin" examples|ideajoin-examples]]
- List of "set" commands: ["set" commands](set-commands.md) - List of "set" commands: [["set" commands|set-commands]]
- Docs about "select" mode in vim: [select mode](Select-mode.md) - Docs about "select" mode in vim: [[select mode|Select-mode]]

View File

@@ -45,20 +45,15 @@ All commands with the mappings are supported. See the [full list of supported co
<details> <details>
<summary><h2>sneak</h2></summary> <summary><h2>sneak</h2></summary>
<img src="images/sneakIcon.svg" width="80" height="80" alt="icon"/>
By [Mikhail Levchenko](https://github.com/Mishkun)
Original repository with the plugin: https://github.com/Mishkun/ideavim-sneak
Original plugin: [vim-sneak](https://github.com/justinmk/vim-sneak). Original plugin: [vim-sneak](https://github.com/justinmk/vim-sneak).
### Setup: ### Setup:
- Add the following command to `~/.ideavimrc`: `Plug 'justinmk/vim-sneak'` - Install [IdeaVim-sneak](https://plugins.jetbrains.com/plugin/15348-ideavim-sneak) plugin.
- Add the following command to `~/.ideavimrc`: `set sneak`
### Instructions ### Instructions
* Type `s` and two chars to start sneaking in forward direction See the [docs](https://github.com/Mishkun/ideavim-sneak#usage)
* Type `S` and two chars to start sneaking in backward direction
* Type `;` or `,` to proceed with sneaking just as if you were using `f` or `t` commands
</details> </details>
@@ -82,7 +77,7 @@ Original plugin: [NERDTree](https://github.com/preservim/nerdtree).
### Instructions ### Instructions
[See here](NERDTree-support.md). [[See here|NERDTree-support]].
</details> </details>
@@ -401,19 +396,3 @@ Original plugin: [quick-scope](https://github.com/unblevable/quick-scope).
https://plugins.jetbrains.com/plugin/19417-ideavim-quickscope https://plugins.jetbrains.com/plugin/19417-ideavim-quickscope
</details> </details>
<details>
<summary><h2>Which-Key</h2></summary>
Original plugin: [vim-which-key](https://github.com/liuchengxu/vim-which-key).
### Setup:
- Install [Which-Key](https://plugins.jetbrains.com/plugin/15976-which-key) plugin.
- Add the following command to `~/.ideavimrc`: `set which-key`
### Instructions
https://github.com/TheBlob42/idea-which-key?tab=readme-ov-file#installation
</details>

View File

@@ -3,11 +3,6 @@ Put `set ideajoin` to your `~/.ideavimrc` to enable this functionality.
Now, you can press `J` (`shift+j`) on a line or a selected block of text to join the lines together. Now, you can press `J` (`shift+j`) on a line or a selected block of text to join the lines together.
:warning: This feature is language-specific. This means that the IDE should implement this feature for a particular
language in order for the IDE to work as described below. If any of the examples provided below don't match your case,
please file an issue in the project related to your IDE: https://youtrack.jetbrains.com/.
Here is a list of known requests: https://youtrack.jetbrains.com/issues?q=links:VIM-3214.
* Automatic join concatenated lines: * Automatic join concatenated lines:
``` ```

View File

@@ -1,28 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<svg viewBox="386.498 234 32 32" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="ideavim_plugin-a" x1="-6.748%" x2="47.286%" y1="33.61%" y2="85.907%">
<stop offset="0" stop-color="#3BEA62"/>
<stop offset="1" stop-color="#087CFA"/>
</linearGradient>
</defs>
<g transform="matrix(1.238978, 0.90017, -0.90017, 1.238978, 131.776901, -422.953003)" style="">
<path d="M 399.962 247.648 C 399.207 246.894 399.147 246.318 399.692 245.453 C 400.237 244.588 401.955 245.886 401.955 245.886 L 401.955 250.737" style="fill: rgb(248, 245, 231);"/>
<path d="M 413.846 253.602 C 413.846 255.077 411.827 256.134 409.392 256.134 L 396.381 256.134 C 395.211 256.134 394.232 256.003 393.433 255.817 C 391.496 255.367 390.613 254.596 390.613 254.596 L 391.478 252.513 L 393.607 252.617 Z M 413.846 253.602" fill="#cce6f6" style=""/>
<path d="M 413.846 253.602 C 413.846 253.602 411.475 254.468 408.27 254.468 C 405.94 254.468 398.116 253.433 394.023 252.869 C 392.488 252.658 391.478 252.512 391.478 252.512 C 390.864 251.662 392.078 248.741 392.758 247.263 C 393.118 246.484 393.85 245.929 394.703 245.83 C 394.782 245.82 394.861 245.815 394.939 245.815 C 395.369 245.815 395.645 246.532 396.059 247.225 C 396.446 247.877 396.955 248.507 397.823 248.507 C 399.617 248.507 401.955 245.886 401.955 245.886 C 406.544 249.03 410.097 250.43 410.097 250.43 C 410.097 250.43 413.061 250.446 413.782 251.167 C 414.503 251.888 414.422 253.218 413.846 253.602 Z M 413.846 253.602" style="fill: rgb(8, 124, 250);"/>
<path d="M 394.023 252.869 L 393.433 255.817 C 391.496 255.367 390.613 254.596 390.613 254.596 L 391.478 252.513 L 393.607 252.617 Z M 394.023 252.869" fill="#9dcae0" style=""/>
<path d="M 396.059 247.225 C 395.073 245.986 393.193 250.255 394.023 252.869 C 392.488 252.658 391.478 252.513 391.478 252.513 C 390.864 251.662 392.078 248.741 392.758 247.263 C 393.118 246.484 393.85 245.929 394.703 245.83 C 394.782 245.82 394.861 245.815 394.939 245.815 C 395.369 245.815 395.645 246.532 396.059 247.225 Z M 396.059 247.225" style="fill: rgb(14, 112, 142);"/>
<path d="M 403.527 246.924 L 399.174 251.768 C 397.7 250.892 395.578 250.174 394.016 249.717 C 392.843 249.372 391.985 249.174 391.959 249.168 C 392.108 248.769 392.268 248.379 392.421 248.022 L 394.341 248.65 L 394.884 248.827 C 395.509 249.031 396.192 248.95 396.753 248.608 L 397.153 248.363 C 397.35 248.454 397.572 248.507 397.823 248.507 C 399.617 248.507 401.955 245.886 401.955 245.886 C 402.494 246.256 403.02 246.601 403.527 246.924 Z M 403.527 246.924" style="fill: rgb(59, 234, 98);"/>
<path d="M 413.847 253.602 C 413.847 253.602 411.475 254.468 408.27 254.468 C 407.586 254.468 406.426 254.378 405.025 254.238 L 405.025 254.237 C 405.025 253.495 406.924 251.743 408.366 251.616 C 408.623 252.865 410.097 252.512 411.219 252.128 C 412.341 251.743 413.783 251.167 413.783 251.167 C 414.503 251.888 414.422 253.218 413.847 253.602 Z M 413.847 253.602" style="fill: rgb(8, 124, 250);"/>
<path d="M 394.341 248.65 C 394.214 248.978 394.103 249.339 394.016 249.717 C 392.843 249.372 391.985 249.174 391.959 249.168 C 392.108 248.769 392.268 248.379 392.421 248.022 Z M 394.341 248.65" style="fill: rgb(37, 187, 163);"/>
<path d="M 408.366 251.616 C 406.924 251.743 405.025 253.495 405.025 254.237 L 405.025 254.238 C 403.784 254.113 402.355 253.948 400.899 253.77 C 400.899 253.051 400.191 252.372 399.174 251.768 L 399.174 251.768 L 403.528 246.924 C 407.331 249.34 410.097 250.43 410.097 250.43 C 410.77 251.102 409.809 251.487 408.366 251.616 Z M 408.366 251.616" style="fill: rgb(248, 245, 231);"/>
<polygon fill="url(#ideavim_plugin-a)" fill-rule="evenodd" points="406.356 248.463 403.261 252.616 402.183 248.212 400.984 249.899 401.999 254.236 403.927 254.176 407.639 249.062" style="" transform="matrix(0.994522, 0.104529, -0.104529, 0.994522, 28.475005, -40.88594)"/>
<g fill="#fb6572" transform="matrix(0.046265, 0, 0, 0.046265, 390.612823, 245.155533)" style="">
<path d="m288.839844 72.65625c-2.007813 0-4.011719-.761719-5.542969-2.292969-3.058594-3.0625-3.058594-8.023437 0-11.082031l20.089844-20.089844c3.0625-3.058594 8.023437-3.058594 11.082031 0 3.058594 3.0625 3.0625 8.023438 0 11.082032l-20.089844 20.089843c-1.527344 1.53125-3.535156 2.292969-5.539062 2.292969zm0 0" style="fill: rgb(56, 228, 105);"/>
<path d="m314.589844 87.082031c-2.007813 0-4.011719-.765625-5.542969-2.296875-3.0625-3.058594-3.0625-8.019531 0-11.082031l20.089844-20.085937c3.0625-3.058594 8.023437-3.058594 11.082031 0 3.058594 3.0625 3.058594 8.023437 0 11.082031l-20.089844 20.085937c-1.527344 1.53125-3.535156 2.296875-5.539062 2.296875zm0 0" style="fill: rgb(59, 233, 100);"/>
<path d="m340.339844 101.507812c-2.007813 0-4.011719-.765624-5.542969-2.296874-3.058594-3.058594-3.058594-8.023438 0-11.082032l20.089844-20.085937c3.0625-3.0625 8.023437-3.0625 11.082031 0 3.058594 3.058593 3.0625 8.023437 0 11.082031l-20.089844 20.085938c-1.527344 1.53125-3.535156 2.296874-5.539062 2.296874zm0 0" style="fill: rgb(59, 233, 100);"/>
<path d="m366.089844 115.929688c-2.003906 0-4.011719-.761719-5.539063-2.292969-3.0625-3.0625-3.0625-8.023438 0-11.082031l20.085938-20.089844c3.0625-3.058594 8.023437-3.058594 11.082031 0 3.0625 3.0625 3.0625 8.023437 0 11.082031l-20.085938 20.089844c-1.53125 1.53125-3.535156 2.292969-5.542968 2.292969zm0 0" style="fill: rgb(59, 233, 100);"/>
</g>
<path d="M 401.925 247.748 C 401.761 247.748 401.611 247.629 401.573 247.469 C 401.536 247.312 401.611 247.144 401.753 247.067 C 402 246.933 402.318 247.147 402.286 247.426 C 402.265 247.606 402.107 247.748 401.925 247.748 Z M 401.925 247.748" fill="#1e2628" style=""/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 5.6 KiB

View File

@@ -8,29 +8,21 @@
# suppress inspection "UnusedProperty" for whole file # suppress inspection "UnusedProperty" for whole file
#ideaVersion=LATEST-EAP-SNAPSHOT ideaVersion=2023.2
ideaVersion=2024.1
# Values for type: https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#intellij-extension-type
ideaType=IC
downloadIdeaSources=true downloadIdeaSources=true
instrumentPluginCode=true instrumentPluginCode=true
version=chylex-33 version=chylex-18
javaVersion=17 javaVersion=17
remoteRobotVersion=0.11.22 remoteRobotVersion=0.11.17
antlrVersion=4.10.1 antlrVersion=4.10.1
kotlin.incremental.useClasspathSnapshot=false kotlin.incremental.useClasspathSnapshot=false
# Please don't forget to update kotlin version in buildscript section # Please don't forget to update kotlin version in buildscript section
# Also update kotlinxSerializationVersion version kotlinVersion=1.8.21
kotlinVersion=1.9.22
publishToken=token publishToken=token
publishChannels=eap publishChannels=eap
# Kotlinx serialization also uses some version of kotlin stdlib under the hood. However,
# we exclude this version from the dependency and use our own version of kotlin that is specified above
kotlinxSerializationVersion=1.6.2
slackUrl= slackUrl=
youtrackToken= youtrackToken=

Binary file not shown.

View File

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

5
gradlew vendored
View File

@@ -130,13 +130,10 @@ location of your Java installation."
fi fi
else else
JAVACMD=java JAVACMD=java
if ! command -v java >/dev/null 2>&1 which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi
fi fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.

File diff suppressed because one or more lines are too long

View File

@@ -21,9 +21,6 @@ exclude:
- src/test/java/org/jetbrains/plugins/ideavim/propertybased/samples/SimpleText.kt - src/test/java/org/jetbrains/plugins/ideavim/propertybased/samples/SimpleText.kt
- src/main/java/com/maddyhome/idea/vim/vimscript/parser/generated - src/main/java/com/maddyhome/idea/vim/vimscript/parser/generated
- src/main/java/com/maddyhome/idea/vim/package-info.java - src/main/java/com/maddyhome/idea/vim/package-info.java
- vim-engine/src/main/java/com/maddyhome/idea/vim/regexp/parser/generated
- src/main/java/com/maddyhome/idea/vim/group/SearchGroup.java
- tests/ui-fixtures
dependencyIgnores: dependencyIgnores:
- name: "acejump" - name: "acejump"
- name: "icu4j" - name: "icu4j"

View File

@@ -20,17 +20,17 @@ repositories {
} }
dependencies { dependencies {
compileOnly("org.jetbrains.kotlin:kotlin-stdlib:1.9.23") compileOnly("org.jetbrains.kotlin:kotlin-stdlib:1.9.10")
implementation("io.ktor:ktor-client-core:2.3.10") implementation("io.ktor:ktor-client-core:2.3.4")
implementation("io.ktor:ktor-client-cio:2.3.10") implementation("io.ktor:ktor-client-cio:2.3.4")
implementation("io.ktor:ktor-client-content-negotiation:2.3.10") implementation("io.ktor:ktor-client-content-negotiation:2.3.4")
implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.10") implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.4")
implementation("io.ktor:ktor-client-auth:2.3.10") implementation("io.ktor:ktor-client-auth:2.3.4")
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
implementation("org.eclipse.jgit:org.eclipse.jgit.ssh.apache:6.9.0.202403050737-r") implementation("org.eclipse.jgit:org.eclipse.jgit.ssh.apache:6.7.0.202309050840-r")
implementation("com.vdurmont:semver4j:3.1.0") implementation("com.vdurmont:semver4j:3.1.0")
} }
@@ -58,6 +58,13 @@ tasks.register("checkNewPluginDependencies", JavaExec::class) {
classpath = sourceSets["main"].runtimeClasspath classpath = sourceSets["main"].runtimeClasspath
} }
tasks.register("updateAffectedRates", JavaExec::class) {
group = "verification"
description = "This job updates Affected Rate field on YouTrack"
mainClass.set("scripts.YouTrackUsersAffectedKt")
classpath = sourceSets["main"].runtimeClasspath
}
tasks.register("calculateNewVersion", JavaExec::class) { tasks.register("calculateNewVersion", JavaExec::class) {
group = "release" group = "release"
mainClass.set("scripts.release.CalculateNewVersionKt") mainClass.set("scripts.release.CalculateNewVersionKt")
@@ -86,16 +93,28 @@ tasks.register("addReleaseTag", JavaExec::class) {
args = listOf(project.version.toString(), rootProject.rootDir.toString(), releaseType ?: "") args = listOf(project.version.toString(), rootProject.rootDir.toString(), releaseType ?: "")
} }
tasks.register("selectBranch", JavaExec::class) { tasks.register("resetReleaseBranch", JavaExec::class) {
group = "release" group = "release"
mainClass.set("scripts.release.SelectBranchKt") mainClass.set("scripts.release.ResetReleaseBranchKt")
classpath = sourceSets["main"].runtimeClasspath classpath = sourceSets["main"].runtimeClasspath
args = listOf(project.version.toString(), rootProject.rootDir.toString(), releaseType ?: "") args = listOf(project.version.toString(), rootProject.rootDir.toString(), releaseType ?: "")
} }
tasks.register("eapReleaseActions", JavaExec::class) { tasks.register("pushChanges", JavaExec::class) {
mainClass.set("scripts.PushChangesKt")
classpath = sourceSets["main"].runtimeClasspath
args = listOf(rootProject.rootDir.toString())
}
tasks.register("pushChangesWithReleaseBranch", JavaExec::class) {
mainClass.set("scripts.PushChangesWithReleaseBranchKt")
classpath = sourceSets["main"].runtimeClasspath
args = listOf(rootProject.rootDir.toString(), releaseType ?: "")
}
tasks.register("selectBranch", JavaExec::class) {
group = "release" group = "release"
mainClass.set("scripts.releaseEap.EapReleaseActionsKt") mainClass.set("scripts.release.SelectBranchKt")
classpath = sourceSets["main"].runtimeClasspath classpath = sourceSets["main"].runtimeClasspath
args = listOf(project.version.toString(), rootProject.rootDir.toString(), releaseType ?: "") args = listOf(project.version.toString(), rootProject.rootDir.toString(), releaseType ?: "")
} }

View File

@@ -22,7 +22,7 @@ import kotlinx.serialization.json.jsonPrimitive
*/ */
@Suppress("SpellCheckingInspection") @Suppress("SpellCheckingInspection")
val knownPlugins = setOf( val knownPlugins = listOf(
"IdeaVimExtension", "IdeaVimExtension",
"github.zgqq.intellij-enhance", "github.zgqq.intellij-enhance",
"org.jetbrains.IdeaVim-EasyMotion", "org.jetbrains.IdeaVim-EasyMotion",
@@ -31,13 +31,7 @@ val knownPlugins = setOf(
"com.github.copilot", "com.github.copilot",
"com.github.dankinsoid.multicursor", "com.github.dankinsoid.multicursor",
"com.joshestein.ideavim-quickscope", "com.joshestein.ideavim-quickscope",
"ca.alexgirard.HarpoonIJ", "ca.alexgirard.HarpoonIJ",
"me.kyren223.harpoonforjb", // https://plugins.jetbrains.com/plugin/23771-harpoonforjb
"com.github.erotourtes.harpoon", // https://plugins.jetbrains.com/plugin/21796-harpooner
"me.kyren223.trident", // https://plugins.jetbrains.com/plugin/23818-trident
"com.protoseo.input-source-auto-converter",
// "cc.implicated.intellij.plugins.bunny", // I don't want to include this plugin in the list of IdeaVim plugins as I don't understand what this is for // "cc.implicated.intellij.plugins.bunny", // I don't want to include this plugin in the list of IdeaVim plugins as I don't understand what this is for
) )
@@ -47,15 +41,19 @@ suspend fun main() {
parameter("dependency", "IdeaVIM") parameter("dependency", "IdeaVIM")
parameter("includeOptional", true) parameter("includeOptional", true)
} }
val output = response.body<List<String>>().toSet() val output = response.body<List<String>>()
println(output) println(output)
val newPlugins = (output - knownPlugins).map { it to (getPluginLinkByXmlId(it) ?: "Can't find plugin link") } if (knownPlugins != output) {
if (newPlugins.isNotEmpty()) { val newPlugins = (output - knownPlugins).map { it to (getPluginLinkByXmlId(it) ?: "Can't find plugin link") }
// val removedPlugins = (knownPlugins - output.toSet()).map { it to (getPluginLinkByXmlId(it) ?: "Can't find plugin link") } val removedPlugins = (knownPlugins - output.toSet()).map { it to (getPluginLinkByXmlId(it) ?: "Can't find plugin link") }
error( error(
""" """
Unregistered plugins: Unregistered plugins:
${newPlugins.joinToString(separator = "\n") { it.first + "(" + it.second + ")" }} ${if (newPlugins.isNotEmpty()) newPlugins.joinToString(separator = "\n") { it.first + "(" + it.second + ")" } else "No unregistered plugins"}
Removed plugins:
${if (removedPlugins.isNotEmpty()) removedPlugins.joinToString(separator = "\n") { it.first + "(" + it.second + ")" } else "No removed plugins"}
""".trimIndent() """.trimIndent()
) )
} }

View File

@@ -32,7 +32,7 @@ fun httpClient(): HttpClient {
install(Auth) { install(Auth) {
bearer { bearer {
loadTokens { loadTokens {
val accessToken = System.getenv("YOUTRACK_TOKEN") ?: error("Missing YOUTRACK_TOKEN") val accessToken = System.getenv("YOUTRACK_TOKEN")!!
BearerTokens(accessToken, "") BearerTokens(accessToken, "")
} }
} }

View File

@@ -0,0 +1,37 @@
/*
* Copyright 2003-2023 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.
*/
package scripts
import scripts.release.checkoutBranch
import scripts.release.withGit
import scripts.release.withRepo
fun main(args: Array<String>) {
val rootDir = args[0]
println("root dir: $rootDir")
val currentBranch = withRepo(rootDir) { it.branch }
println("Current branch is $currentBranch")
withGit(rootDir) { git ->
if (currentBranch != "master") {
git.checkoutBranch("master")
println("Check out master branch")
}
git.push()
.setPushTags()
.call()
println("Master pushed with tags")
git.checkoutBranch(currentBranch)
println("Checked out $currentBranch branch")
}
}

View File

@@ -0,0 +1,54 @@
/*
* Copyright 2003-2023 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.
*/
package scripts
import scripts.release.checkoutBranch
import scripts.release.withGit
import scripts.release.withRepo
fun main(args: Array<String>) {
val rootDir = args[0]
val releaseType = args[1]
println("root dir: $rootDir")
println("releaseType: $releaseType")
val currentBranch = withRepo(rootDir) { it.branch }
println("Current branch is $currentBranch")
withGit(rootDir) { git ->
if (currentBranch != "master") {
git.checkoutBranch("master")
println("Check out master branch")
}
git.push()
.setPushTags()
.call()
println("Master pushed with tags")
if (releaseType != "patch") {
git.checkoutBranch("release")
println("Checked out release")
git
.push()
.setForce(true)
.setPushTags()
.call()
println("Pushed release branch with tags")
}
else {
println("Do not push release branch because type of release is $releaseType")
}
git.checkoutBranch(currentBranch)
println("Checked out $currentBranch branch")
}
}

View File

@@ -8,29 +8,21 @@
package scripts.release package scripts.release
import org.eclipse.jgit.lib.ObjectId
import org.eclipse.jgit.revwalk.RevCommit
import org.eclipse.jgit.revwalk.RevWalk
import org.eclipse.jgit.revwalk.filter.RevFilter
fun main(args: Array<String>) { fun main(args: Array<String>) {
println("HI!") println("HI!")
val projectDir = args[0] val projectDir = args[0]
println("Working directory: $projectDir") println("Working directory: $projectDir")
val (lastVersion, objectId) = getVersion(projectDir, ReleaseType.STABLE_NO_PATCH) val (lastVersion, objectId) = getVersion(projectDir, onlyStable = true)
println("Last version: $lastVersion, hash: ${objectId.name}") println("Last version: $lastVersion, hash: ${objectId.name}")
val branch = withRepo(projectDir) { it.branch } val branch = withRepo(projectDir) { it.branch }
check(branch == "master") { check(branch == "master") {
"We should be on master branch" "We should be on master branch"
} }
val mergeBaseCommit = getMergeBaseWithMaster(projectDir, objectId)
println("Base commit $mergeBaseCommit")
withGit(projectDir) { git -> withGit(projectDir) { git ->
val log = git.log().setMaxCount(500).call().toList() val log = git.log().setMaxCount(500).call().toList()
println("First commit hash in log: " + log.first().name + " log size: ${log.size}") println("First commit hash in log: " + log.first().name + " log size: ${log.size}")
val logDiff = log.takeWhile { it.id.name != mergeBaseCommit } val logDiff = log.takeWhile { it.id.name != objectId.name }
val numCommits = logDiff.size val numCommits = logDiff.size
println("Log diff size is $numCommits") println("Log diff size is $numCommits")
check(numCommits < 450) { check(numCommits < 450) {
@@ -43,18 +35,3 @@ fun main(args: Array<String>) {
println("##teamcity[setParameter name='env.ORG_GRADLE_PROJECT_version' value='$nextVersion']") println("##teamcity[setParameter name='env.ORG_GRADLE_PROJECT_version' value='$nextVersion']")
} }
} }
private fun getMergeBaseWithMaster(projectDir: String, tag: ObjectId): String {
withRepo(projectDir) { repo ->
val master = repo.resolve("master")
RevWalk(repo).use { walk ->
val tagRevCommit = walk.parseCommit(tag)
val masterRevCommit = walk.parseCommit(master)
walk.setRevFilter(RevFilter.MERGE_BASE)
walk.markStart(tagRevCommit)
walk.markStart(masterRevCommit)
val mergeBase: RevCommit = walk.next()
return mergeBase.name
}
}
}

View File

@@ -12,7 +12,7 @@ fun main(args: Array<String>) {
println("HI!") println("HI!")
val projectDir = args[0] val projectDir = args[0]
println("Working directory: $projectDir") println("Working directory: $projectDir")
val (lastVersion, _) = getVersion(projectDir, ReleaseType.ANY) val (lastVersion, _) = getVersion(projectDir, onlyStable = false)
val nextVersion = if (lastVersion.suffixTokens.isEmpty()) { val nextVersion = if (lastVersion.suffixTokens.isEmpty()) {
lastVersion.nextMinor().withSuffix("eap.1").value lastVersion.nextMinor().withSuffix("eap.1").value

View File

@@ -14,7 +14,7 @@ fun main(args: Array<String>) {
val releaseType = args[1] val releaseType = args[1]
println("Working directory: $projectDir") println("Working directory: $projectDir")
println("Release type: $releaseType") println("Release type: $releaseType")
val (lastVersion, _) = getVersion(projectDir, ReleaseType.ONLY_STABLE) val (lastVersion, _) = getVersion(projectDir, onlyStable = true)
val nextVersion = when (releaseType) { val nextVersion = when (releaseType) {
"major" -> lastVersion.nextMajor() "major" -> lastVersion.nextMajor()

View File

@@ -8,45 +8,28 @@
package scripts.release package scripts.release
import com.vdurmont.semver4j.Semver
import java.time.LocalDate import java.time.LocalDate
import java.time.format.DateTimeFormatter import java.time.format.DateTimeFormatter
import kotlin.io.path.Path import kotlin.io.path.Path
import kotlin.io.path.readText import kotlin.io.path.readText
import kotlin.io.path.writeText import kotlin.io.path.writeText
private const val toBeReleased = "## To Be Released"
fun main(args: Array<String>) { fun main(args: Array<String>) {
println("Start updating unreleased section") println("Start updating unreleased section")
val (newVersion, rootDir, releaseType) = readArgs(args) val (newVersion, rootDir, releaseType) = readArgs(args)
checkReleaseType(releaseType) checkReleaseType(releaseType)
if (releaseType == "patch") {
println("Skip updating the changelog because release type is 'patch'")
return
}
val currentDate = LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE) val currentDate = LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE)
val newItem = "## $newVersion, $currentDate" val newItem = "## $newVersion, $currentDate"
val changelogPath = Path("$rootDir/CHANGES.md") val changelogPath = Path("$rootDir/CHANGES.md")
val changelog = changelogPath.readText() val changelog = changelogPath.readText()
val newChangelog = if (releaseType == "patch") { val newChangelog = changelog.replace("## To Be Released", newItem)
val decreasedVersion = Semver(newVersion).withIncPatch(-1)
val firstEntry = changelog.indexOf("## $decreasedVersion")
if (firstEntry != -1) {
val newLog = StringBuilder(changelog)
newLog.insert(firstEntry, newItem + "\n")
newLog.toString()
} else {
changelog
}
} else {
if (toBeReleased in changelog) {
changelog.replace(toBeReleased, newItem)
} else {
val firstEntry = changelog.indexOf("##")
val newLog = StringBuilder(changelog)
newLog.insert(firstEntry, newItem + "\n")
newLog.toString()
}
}
changelogPath.writeText(newChangelog) changelogPath.writeText(newChangelog)
} }

View File

@@ -13,20 +13,21 @@ fun main(args: Array<String>) {
checkReleaseType(releaseType) checkReleaseType(releaseType)
withGit(rootDir) { git -> if (releaseType == "patch") {
if (git.diff().call().isNotEmpty()) { println("Skip committing changes because release type is 'patch'")
git return
.commit() }
.setAll(true)
.setAuthor("IdeaVim Bot", "maintainers@ideavim.dev")
.setMessage("Preparation to $newVersion release")
.setSign(false)
.call()
val lastGitMessage = git.log().call().first().shortMessage withGit(rootDir) { git ->
println("Changes committed. Last gitlog message: $lastGitMessage") git
} else { .commit()
println("No Changes") .setAll(true)
} .setAuthor("IdeaVim Bot", "maintainers@ideavim.dev")
.setMessage("Preparation to $newVersion release")
.setSign(false)
.call()
val lastGitMessage = git.log().call().first().shortMessage
println("Changes committed. Last gitlog message: $lastGitMessage")
} }
} }

View File

@@ -0,0 +1,38 @@
/*
* Copyright 2003-2023 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.
*/
package scripts.release
fun main(args: Array<String>) {
val (_, rootDir, releaseType) = readArgs(args)
checkReleaseType(releaseType)
checkBranch(rootDir, releaseType)
if (releaseType == "patch") {
println("Skip release branch reset because release type is 'patch'")
return
}
withGit(rootDir) { git ->
val currentCommit = git.log().setMaxCount(1).call().first()
println("Current commit id: ${currentCommit.id.name}")
git.checkoutBranch("release")
println("Checked out release branch")
git.reset()
.setRef(currentCommit.id.name)
.call()
println("release branch reset")
git.checkoutBranch("master")
println("Checked out master branch")
}
}

View File

@@ -15,7 +15,8 @@ fun main(args: Array<String>) {
withGit(rootDir) { git -> withGit(rootDir) { git ->
val branchName = when (releaseType) { val branchName = when (releaseType) {
"major", "minor", "patch" -> "release" "major", "minor" -> "master"
"patch" -> "release"
else -> error("Unsupported release type: $releaseType") else -> error("Unsupported release type: $releaseType")
} }

View File

@@ -9,7 +9,6 @@
package scripts.release package scripts.release
import com.vdurmont.semver4j.Semver import com.vdurmont.semver4j.Semver
import org.eclipse.jgit.api.CreateBranchCommand
import org.eclipse.jgit.api.Git import org.eclipse.jgit.api.Git
import org.eclipse.jgit.lib.ObjectId import org.eclipse.jgit.lib.ObjectId
import org.eclipse.jgit.lib.Repository import org.eclipse.jgit.lib.Repository
@@ -58,13 +57,7 @@ internal fun checkBranch(rootDir: String, releaseType: String) {
} }
} }
enum class ReleaseType { internal fun getVersion(projectDir: String, onlyStable: Boolean): Pair<Semver, ObjectId> {
ANY,
ONLY_STABLE,
STABLE_NO_PATCH, // Version that ends on 0. Like 2.5.0
}
internal fun getVersion(projectDir: String, releaseType: ReleaseType): Pair<Semver, ObjectId> {
val repository = RepositoryBuilder().setGitDir(File("$projectDir/.git")).build() val repository = RepositoryBuilder().setGitDir(File("$projectDir/.git")).build()
val git = Git(repository) val git = Git(repository)
println(git.log().call().first()) println(git.log().call().first())
@@ -81,24 +74,19 @@ internal fun getVersion(projectDir: String, releaseType: ReleaseType): Pair<Semv
} }
.sortedBy { it.first } .sortedBy { it.first }
val version = when (releaseType) { val version = if (onlyStable) {
ReleaseType.ANY -> versions.last() versions.last { it.first.isStable }
ReleaseType.ONLY_STABLE -> versions.last { it.first.isStable } } else {
ReleaseType.STABLE_NO_PATCH -> versions.last { it.first.isStable && it.first.patch == 0 } versions.last()
} }
return version return version
} }
internal fun Git.checkoutBranch(name: String) { internal fun Git.checkoutBranch(name: String) {
println("Checking out $name")
val shouldCreateBranch = this.branchList().call().any { it.name == "refs/heads/$name" }.not() val shouldCreateBranch = this.branchList().call().any { it.name == "refs/heads/$name" }.not()
val checkoutCommand = checkout() checkout()
.setCreateBranch(shouldCreateBranch) .setCreateBranch(shouldCreateBranch)
.setName(name) .setName(name)
if (shouldCreateBranch) { .call()
// Without starting point the branch will be created on HEAD.
checkoutCommand.setStartPoint("origin/$name").setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
}
checkoutCommand.call()
} }

View File

@@ -1,36 +0,0 @@
/*
* Copyright 2003-2024 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.
*/
package scripts.releaseEap
import kotlinx.coroutines.runBlocking
import scripts.addComment
import scripts.getYoutrackTicketsByQuery
import scripts.release.readArgs
import scripts.releasedInEapTagId
import scripts.setTag
fun main(args: Array<String>) {
runBlocking {
val (newVersion, _, _) = readArgs(args)
// Search for Ready to release, but without "IdeaVim Released In EAP" tag
val ticketsToUpdate =
getYoutrackTicketsByQuery("%23%7BReady%20To%20Release%7D%20tag:%20-%7BIdeaVim%20Released%20In%20EAP%7D%20")
println("Have to update the following tickets: $ticketsToUpdate")
ticketsToUpdate.forEach { ticketId ->
setTag(ticketId, releasedInEapTagId)
addComment(
ticketId, """
The fix is available in the IdeaVim $newVersion. See https://jb.gg/ideavim-eap for the instructions on how to get EAP builds as updates within the IDE. You can also wait till the next stable release with this fix, youll get it automatically.
""".trimIndent()
)
}
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2003-2023 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.
*/
package scripts
import io.ktor.client.call.*
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put
val areaWeights = setOf(
Triple("118-53212", "Plugins", 50),
Triple("118-53220", "Vim Script", 30),
Triple("118-54084", "Esc", 100),
)
suspend fun updateRates() {
println("Updating rates of the issues")
areaWeights.forEach { (id, name, weight) ->
val unmappedIssues = unmappedIssues(name)
println("Got ${unmappedIssues.size} for $name area")
unmappedIssues.forEach { issueId ->
print("Trying to update issue $issueId: ")
val response = updateCustomField(issueId) {
put("name", "Affected Rate")
put("\$type", "SimpleIssueCustomField")
put("value", weight)
}
println(response)
}
}
}
private suspend fun unmappedIssues(area: String): List<String> {
val areaProcessed = if (" " in area) "{$area}" else area
val res = issuesQuery(
query = "project: VIM Affected Rate: {No affected rate} Area: $areaProcessed #Unresolved",
fields = "id,idReadable"
)
return res.body<JsonArray>().map { it.jsonObject }.map { it["idReadable"]!!.jsonPrimitive.content }
}
suspend fun getAreasWithoutWeight(): Set<Pair<String, String>> {
val allAreas = getAreaValues()
return allAreas
.filterNot { it.key in areaWeights.map { it.first }.toSet() }
.entries
.map { it.key to it.value }
.toSet()
}
suspend fun main() {
updateRates()
}

View File

@@ -11,8 +11,6 @@ package scripts
import io.ktor.client.call.* import io.ktor.client.call.*
import io.ktor.client.request.* import io.ktor.client.request.*
import io.ktor.http.* import io.ktor.http.*
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.addJsonObject import kotlinx.serialization.json.addJsonObject
import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.buildJsonObject
@@ -23,10 +21,6 @@ import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonArray import kotlinx.serialization.json.putJsonArray
import kotlinx.serialization.json.putJsonObject import kotlinx.serialization.json.putJsonObject
// YouTrack tag "IdeaVim Released In EAP"
const val releasedInEapTagId = "68-385032"
suspend fun setYoutrackStatus(tickets: Collection<String>, status: String) { suspend fun setYoutrackStatus(tickets: Collection<String>, status: String) {
val client = httpClient() val client = httpClient()
@@ -65,59 +59,3 @@ suspend fun setYoutrackStatus(tickets: Collection<String>, status: String) {
} }
} }
} }
fun getYoutrackTicketsByQuery(query: String): Set<String> {
val client = httpClient()
return runBlocking {
val response = client.get("https://youtrack.jetbrains.com/api/issues/?fields=idReadable&query=project:VIM+$query")
response.body<JsonArray>().mapTo(HashSet()) { it.jsonObject.getValue("idReadable").jsonPrimitive.content }
}
}
/**
* 68-385032
* [issueHumanId] is like VIM-123
* [tagId] is like "145-23"
*/
suspend fun setTag(issueHumanId: String, tagId: String) {
val client = httpClient()
println("Try to add tag $tagId to $issueHumanId")
val response =
// I've updated default url in client, so this may be broken now
client.post("https://youtrack.jetbrains.com/api/issues/$issueHumanId/tags?fields=customFields(id,name,value(id,name))") {
contentType(ContentType.Application.Json)
accept(ContentType.Application.Json)
val request = buildJsonObject {
put("id", tagId)
}
setBody(request)
}
println(response)
println(response.body<String>())
if (!response.status.isSuccess()) {
error("Request failed. $issueHumanId, ${response.body<String>()}")
}
}
suspend fun addComment(issueHumanId: String, text: String) {
val client = httpClient()
println("Try to add comment to $issueHumanId")
val response =
// I've updated default url in client, so this may be broken now
client.post("https://youtrack.jetbrains.com/api/issues/$issueHumanId/comments?fields=customFields(id,name,value(id,name))") {
contentType(ContentType.Application.Json)
accept(ContentType.Application.Json)
val request = buildJsonObject {
put("text", text)
}
setBody(request)
}
println(response)
println(response.body<String>())
if (!response.status.isSuccess()) {
error("Request failed. $issueHumanId, ${response.body<String>()}")
}
}

View File

@@ -12,9 +12,4 @@ rootProject.name = 'IdeaVIM'
include 'vim-engine' include 'vim-engine'
include 'scripts' include 'scripts'
include 'annotation-processors' include 'annotation-processors'
include 'tests:java-tests'
include 'tests:property-tests'
include 'tests:long-running-tests'
include 'tests:ui-ij-tests'
include 'tests:ui-py-tests'
include 'tests:ui-fixtures'

View File

@@ -11,6 +11,7 @@ package com.maddyhome.idea.vim;
import com.intellij.openapi.Disposable; import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.ShortcutSet; import com.intellij.openapi.actionSystem.ShortcutSet;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.actionSystem.TypedAction; import com.intellij.openapi.editor.actionSystem.TypedAction;
@@ -79,6 +80,14 @@ public class EventFacade {
action.unregisterCustomShortcutSet(component); action.unregisterCustomShortcutSet(component);
} }
public void addDocumentListener(@NotNull Document document, @NotNull DocumentListener listener) {
document.addDocumentListener(listener);
}
public void removeDocumentListener(@NotNull Document document, @NotNull DocumentListener listener) {
document.removeDocumentListener(listener);
}
public void addEditorFactoryListener(@NotNull EditorFactoryListener listener, @NotNull Disposable parentDisposable) { public void addEditorFactoryListener(@NotNull EditorFactoryListener listener, @NotNull Disposable parentDisposable) {
EditorFactory.getInstance().addEditorFactoryListener(listener, parentDisposable); EditorFactory.getInstance().addEditorFactoryListener(listener, parentDisposable);
} }
@@ -89,12 +98,20 @@ public class EventFacade {
editor.getCaretModel().addCaretListener(listener, disposable); editor.getCaretModel().addCaretListener(listener, disposable);
} }
public void removeCaretListener(@NotNull Editor editor, @NotNull CaretListener listener) {
editor.getCaretModel().removeCaretListener(listener);
}
public void addEditorMouseListener(@NotNull Editor editor, public void addEditorMouseListener(@NotNull Editor editor,
@NotNull EditorMouseListener listener, @NotNull EditorMouseListener listener,
@NotNull Disposable disposable) { @NotNull Disposable disposable) {
editor.addEditorMouseListener(listener, disposable); editor.addEditorMouseListener(listener, disposable);
} }
public void removeEditorMouseListener(@NotNull Editor editor, @NotNull EditorMouseListener listener) {
editor.removeEditorMouseListener(listener);
}
public void addComponentMouseListener(@NotNull Component component, public void addComponentMouseListener(@NotNull Component component,
@NotNull MouseListener mouseListener, @NotNull MouseListener mouseListener,
@NotNull Disposable disposable) { @NotNull Disposable disposable) {
@@ -102,18 +119,30 @@ public class EventFacade {
Disposer.register(disposable, () -> component.removeMouseListener(mouseListener)); Disposer.register(disposable, () -> component.removeMouseListener(mouseListener));
} }
public void removeComponentMouseListener(@NotNull Component component, @NotNull MouseListener mouseListener) {
component.removeMouseListener(mouseListener);
}
public void addEditorMouseMotionListener(@NotNull Editor editor, public void addEditorMouseMotionListener(@NotNull Editor editor,
@NotNull EditorMouseMotionListener listener, @NotNull EditorMouseMotionListener listener,
@NotNull Disposable disposable) { @NotNull Disposable disposable) {
editor.addEditorMouseMotionListener(listener, disposable); editor.addEditorMouseMotionListener(listener, disposable);
} }
public void removeEditorMouseMotionListener(@NotNull Editor editor, @NotNull EditorMouseMotionListener listener) {
editor.removeEditorMouseMotionListener(listener);
}
public void addEditorSelectionListener(@NotNull Editor editor, public void addEditorSelectionListener(@NotNull Editor editor,
@NotNull SelectionListener listener, @NotNull SelectionListener listener,
@NotNull Disposable disposable) { @NotNull Disposable disposable) {
editor.getSelectionModel().addSelectionListener(listener, disposable); editor.getSelectionModel().addSelectionListener(listener, disposable);
} }
public void removeEditorSelectionListener(@NotNull Editor editor, @NotNull SelectionListener listener) {
editor.getSelectionModel().removeSelectionListener(listener);
}
private @NotNull TypedAction getTypedAction() { private @NotNull TypedAction getTypedAction() {
return TypedAction.getInstance(); return TypedAction.getInstance();
} }

View File

@@ -11,20 +11,25 @@ package com.maddyhome.idea.vim
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.project.Project import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManagerListener import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.startup.ProjectActivity import com.intellij.openapi.startup.StartupActivity
import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.helper.EditorHelper import com.maddyhome.idea.vim.helper.EditorHelper
import com.maddyhome.idea.vim.newapi.IjVimEditor import com.maddyhome.idea.vim.helper.localEditors
import com.maddyhome.idea.vim.newapi.globalIjOptions import com.maddyhome.idea.vim.newapi.globalIjOptions
/** /**
* @author Alex Plate * @author Alex Plate
*/ */
internal class PluginStartup : ProjectActivity/*, LightEditCompatible*/ { // This service should be migrated to ProjectActivity. But we should cariful because simple replacement
// leads to deadlock in tests. I'm not sure about the exact reasons, but "invokeAndWait" inside "initialize" function
// causes this deadlock. Good new: it's easy reproducible in tests.
// Previous migration: fc7efd5484a13b40ba9bf86a1d5429e215d973f3
// Revert: 24dd84b31cffb99eb6114524859a46d02717d33f
internal class PluginStartup : StartupActivity.DumbAware/*, LightEditCompatible*/ {
private var firstInitializationOccurred = false private var firstInitializationOccurred = false
override suspend fun execute(project: Project) { override fun runActivity(project: Project) {
if (firstInitializationOccurred) return if (firstInitializationOccurred) return
firstInitializationOccurred = true firstInitializationOccurred = true
@@ -36,10 +41,8 @@ internal class PluginStartup : ProjectActivity/*, LightEditCompatible*/ {
// This is a temporal workaround for VIM-2487 // This is a temporal workaround for VIM-2487
internal class PyNotebooksCloseWorkaround : ProjectManagerListener { internal class PyNotebooksCloseWorkaround : ProjectManagerListener {
override fun projectClosingBeforeSave(project: Project) { override fun projectClosingBeforeSave(project: Project) {
// TODO: Confirm context in CWM scenario
if (injector.globalIjOptions().closenotebooks) { if (injector.globalIjOptions().closenotebooks) {
injector.editorGroup.getEditors().forEach { vimEditor -> localEditors().forEach { editor ->
val editor = (vimEditor as IjVimEditor).editor
val virtualFile = EditorHelper.getVirtualFile(editor) val virtualFile = EditorHelper.getVirtualFile(editor)
if (virtualFile?.extension == "ipynb") { if (virtualFile?.extension == "ipynb") {
val fileEditorManager = FileEditorManagerEx.getInstanceEx(project) val fileEditorManager = FileEditorManagerEx.getInstanceEx(project)

View File

@@ -0,0 +1,79 @@
/*
* Copyright 2003-2023 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.
*/
package com.maddyhome.idea.vim;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.maddyhome.idea.vim.group.KeyGroup;
import com.maddyhome.idea.vim.handler.ActionBeanClass;
import com.maddyhome.idea.vim.handler.EditorActionHandlerBase;
import com.maddyhome.idea.vim.key.MappingOwner;
import com.maddyhome.idea.vim.newapi.IjVimActionsInitiator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.event.KeyEvent;
public class RegisterActions {
public static final ExtensionPointName<ActionBeanClass> VIM_ACTIONS_EP =
ExtensionPointName.create("IdeaVIM.vimAction");
/**
* Register all the key/action mappings for the plugin.
*/
public static void registerActions() {
registerVimCommandActions();
registerEmptyShortcuts();
registerEpListener();
}
private static void registerEpListener() {
// IdeaVim doesn't support contribution to VIM_ACTIONS_EP extension point, so technically we can skip this update,
// but let's support dynamic plugins in a more classic way and reload actions on every EP change.
VIM_ACTIONS_EP.addChangeListener(() -> {
unregisterActions();
registerActions();
}, VimPlugin.getInstance());
}
public static @Nullable EditorActionHandlerBase findAction(@NotNull String id) {
return VIM_ACTIONS_EP.getExtensionList(ApplicationManager.getApplication()).stream()
.filter(vimActionBean -> vimActionBean.getActionId().equals(id)).findFirst().map(ActionBeanClass::getInstance)
.orElse(null);
}
public static @NotNull EditorActionHandlerBase findActionOrDie(@NotNull String id) {
EditorActionHandlerBase action = findAction(id);
if (action == null) throw new RuntimeException("Action " + id + " is not registered");
return action;
}
public static void unregisterActions() {
KeyGroup keyGroup = VimPlugin.getKeyIfCreated();
if (keyGroup != null) {
keyGroup.unregisterCommandActions();
}
}
private static void registerVimCommandActions() {
KeyGroup parser = VimPlugin.getKey();
VIM_ACTIONS_EP.getExtensionList(ApplicationManager.getApplication()).stream().map(IjVimActionsInitiator::new)
.forEach(parser::registerCommandAction);
}
private static void registerEmptyShortcuts() {
final KeyGroup parser = VimPlugin.getKey();
// The {char1} <BS> {char2} shortcut is handled directly by KeyHandler#handleKey, so doesn't have an action. But we
// still need to register the shortcut, to make sure the editor doesn't swallow it.
parser
.registerShortcutWithoutAction(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), MappingOwner.IdeaVim.System.INSTANCE);
}
}

View File

@@ -1,56 +0,0 @@
/*
* Copyright 2003-2023 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.
*/
package com.maddyhome.idea.vim
import com.maddyhome.idea.vim.action.EngineCommandProvider
import com.maddyhome.idea.vim.action.IntellijCommandProvider
import com.maddyhome.idea.vim.handler.EditorActionHandlerBase
import com.maddyhome.idea.vim.key.MappingOwner
import java.awt.event.KeyEvent
import javax.swing.KeyStroke
public object RegisterActions {
/**
* Register all the key/action mappings for the plugin.
*/
@JvmStatic
public fun registerActions() {
registerVimCommandActions()
registerShortcutsWithoutActions()
}
public fun findAction(id: String): EditorActionHandlerBase? {
val commandBean = EngineCommandProvider.getCommands().firstOrNull { it.actionId == id }
?: IntellijCommandProvider.getCommands().firstOrNull { it.actionId == id } ?: return null
return commandBean.instance
}
public fun findActionOrDie(id: String): EditorActionHandlerBase {
return findAction(id) ?: throw RuntimeException("Action $id is not registered")
}
@JvmStatic
public fun unregisterActions() {
val keyGroup = VimPlugin.getKeyIfCreated()
keyGroup?.unregisterCommandActions()
}
private fun registerVimCommandActions() {
val parser = VimPlugin.getKey()
EngineCommandProvider.getCommands().forEach { parser.registerCommandAction(it) }
IntellijCommandProvider.getCommands().forEach { parser.registerCommandAction(it) }
}
private fun registerShortcutsWithoutActions() {
val parser = VimPlugin.getKey()
// The {char1} <BS> {char2} shortcut is handled directly by KeyHandler#handleKey, so doesn't have an action. But we
// still need to register the shortcut, to make sure the editor doesn't swallow it.
parser.registerShortcutWithoutAction(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), MappingOwner.IdeaVim.System)
}
}

View File

@@ -39,9 +39,11 @@ import com.maddyhome.idea.vim.listener.VimListenerManager;
import com.maddyhome.idea.vim.newapi.IjVimInjector; import com.maddyhome.idea.vim.newapi.IjVimInjector;
import com.maddyhome.idea.vim.ui.StatusBarIconFactory; import com.maddyhome.idea.vim.ui.StatusBarIconFactory;
import com.maddyhome.idea.vim.ui.ex.ExEntryPanel; import com.maddyhome.idea.vim.ui.ex.ExEntryPanel;
import com.maddyhome.idea.vim.vimscript.services.OptionService;
import com.maddyhome.idea.vim.vimscript.services.VariableService; import com.maddyhome.idea.vim.vimscript.services.VariableService;
import com.maddyhome.idea.vim.yank.YankGroupBase; import com.maddyhome.idea.vim.yank.YankGroupBase;
import org.jdom.Element; import org.jdom.Element;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -115,6 +117,12 @@ public class VimPlugin implements PersistentStateComponent<Element>, Disposable
return ApplicationManager.getApplication().getService(CommandGroup.class); return ApplicationManager.getApplication().getService(CommandGroup.class);
} }
@Deprecated // "Please use `injector.markService` instead"
@ApiStatus.ScheduledForRemoval(inVersion = "2.3")
public static @NotNull MarkGroup getMark() {
return ApplicationManager.getApplication().getService(MarkGroup.class);
}
public static @NotNull RegisterGroup getRegister() { public static @NotNull RegisterGroup getRegister() {
return ((RegisterGroup)VimInjectorKt.getInjector().getRegisterGroup()); return ((RegisterGroup)VimInjectorKt.getInjector().getRegisterGroup());
} }
@@ -187,6 +195,13 @@ public class VimPlugin implements PersistentStateComponent<Element>, Disposable
return VimInjectorKt.getInjector().getOptionGroup(); return VimInjectorKt.getInjector().getOptionGroup();
} }
/** Deprecated: Use getOptionGroup */
@Deprecated
// Used by which-key 0.8.0, IdeaVimExtension 1.6.5 + 1.6.8
public static @NotNull OptionService getOptionService() {
return VimInjectorKt.getInjector().getOptionService();
}
private static @NotNull NotificationService getNotifications() { private static @NotNull NotificationService getNotifications() {
return getNotifications(null); return getNotifications(null);
} }
@@ -204,30 +219,20 @@ public class VimPlugin implements PersistentStateComponent<Element>, Disposable
return getInstance().enabled; return getInstance().enabled;
} }
public static boolean isNotEnabled() {
return !isEnabled();
}
public static void setEnabled(final boolean enabled) { public static void setEnabled(final boolean enabled) {
if (isEnabled() == enabled) return; if (isEnabled() == enabled) return;
getInstance().enabled = enabled;
if (enabled) {
VimInjectorKt.getInjector().getListenersNotifier().notifyPluginTurnedOn();
} else {
VimInjectorKt.getInjector().getListenersNotifier().notifyPluginTurnedOff();
}
if (!enabled) { if (!enabled) {
getInstance().turnOffPlugin(true); getInstance().turnOffPlugin(true);
} }
getInstance().enabled = enabled;
if (enabled) { if (enabled) {
getInstance().turnOnPlugin(); getInstance().turnOnPlugin();
} }
StatusBarIconFactory.Util.INSTANCE.updateIcon(); StatusBarIconFactory.Companion.updateIcon();
} }
public static String getMessage() { public static String getMessage() {
@@ -259,8 +264,7 @@ public class VimPlugin implements PersistentStateComponent<Element>, Disposable
if (enabled) { if (enabled) {
Application application = ApplicationManager.getApplication(); Application application = ApplicationManager.getApplication();
if (application.isUnitTestMode()) { if (application.isUnitTestMode()) {
turnOnPlugin(); application.invokeAndWait(this::turnOnPlugin);
//application.invokeAndWait(this::turnOnPlugin);
} }
else { else {
application.invokeLater(this::turnOnPlugin); application.invokeLater(this::turnOnPlugin);
@@ -302,6 +306,11 @@ public class VimPlugin implements PersistentStateComponent<Element>, Disposable
* This is required to ensure that all options are correctly initialised and registered. Must be before any commands * This is required to ensure that all options are correctly initialised and registered. Must be before any commands
* are executed.</li> * are executed.</li>
* <li>~/.ideavimrc execution<br> * <li>~/.ideavimrc execution<br>
* <ul>
* <li>4.1 executes commands from the .ideavimrc file and 4.2 initializes extensions.</li>
* <li>4.1 MUST BE BEFORE 4.2. This is a flow of vim/IdeaVim initialization, firstly .ideavimrc is executed and then
* the extensions are initialized.</li>
* </ul>
* </li> * </li>
* <li>Components initialization<br> * <li>Components initialization<br>
* This should happen after ideavimrc execution because VimListenerManager accesses `number` option * This should happen after ideavimrc execution because VimListenerManager accesses `number` option
@@ -330,9 +339,13 @@ public class VimPlugin implements PersistentStateComponent<Element>, Disposable
VimInjectorKt.getInjector().getOptionGroup().initialiseOptions(); VimInjectorKt.getInjector().getOptionGroup().initialiseOptions();
// 4) ~/.ideavimrc execution // 4) ~/.ideavimrc execution
// 4.1) Execute ~/.ideavimrc
// Evaluate in the context of the fallback window, to capture local option state, to copy to the first editor window // Evaluate in the context of the fallback window, to capture local option state, to copy to the first editor window
registerIdeavimrc(VimInjectorKt.getInjector().getFallbackWindow()); registerIdeavimrc(VimInjectorKt.getInjector().getFallbackWindow());
// 4.2) Initialize extensions. Always after 4.1
VimExtensionRegistrar.enableDelayedExtensions();
// Turing on should be performed after all commands registration // Turing on should be performed after all commands registration
getSearch().turnOn(); getSearch().turnOn();
VimListenerManager.INSTANCE.turnOn(); VimListenerManager.INSTANCE.turnOn();
@@ -353,7 +366,6 @@ public class VimPlugin implements PersistentStateComponent<Element>, Disposable
if (onOffDisposable != null) { if (onOffDisposable != null) {
Disposer.dispose(onOffDisposable); Disposer.dispose(onOffDisposable);
onOffDisposable = null;
} }
} }

View File

@@ -14,7 +14,7 @@ import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project import com.intellij.openapi.project.Project
import com.maddyhome.idea.vim.group.EditorHolderService import com.maddyhome.idea.vim.group.EditorHolderService
@Service(Service.Level.PROJECT) @Service
internal class VimProjectService(val project: Project) : Disposable { internal class VimProjectService(val project: Project) : Disposable {
override fun dispose() { override fun dispose() {
// Not sure if this is a best solution // Not sure if this is a best solution

View File

@@ -28,11 +28,8 @@ import javax.swing.KeyStroke
* Accepts all regular keystrokes and passes them on to the Vim key handler. * Accepts all regular keystrokes and passes them on to the Vim key handler.
* *
* IDE shortcut keys used by Vim commands are handled by [com.maddyhome.idea.vim.action.VimShortcutKeyAction]. * IDE shortcut keys used by Vim commands are handled by [com.maddyhome.idea.vim.action.VimShortcutKeyAction].
*
* This class is used in Which-Key plugin, so don't make it internal. Generally, we should provide a proper
* way to get ideavim keys for this plugin. See VIM-3085
*/ */
public class VimTypedActionHandler(origHandler: TypedActionHandler) : TypedActionHandlerEx { internal class VimTypedActionHandler(origHandler: TypedActionHandler) : TypedActionHandlerEx {
private val handler = KeyHandler.getInstance() private val handler = KeyHandler.getInstance()
private val traceTime = injector.globalOptions().ideatracetime private val traceTime = injector.globalOptions().ideatracetime
@@ -77,7 +74,7 @@ public class VimTypedActionHandler(origHandler: TypedActionHandler) : TypedActio
val modifiers = if (charTyped == ' ' && VimKeyListener.isSpaceShift) KeyEvent.SHIFT_DOWN_MASK else 0 val modifiers = if (charTyped == ' ' && VimKeyListener.isSpaceShift) KeyEvent.SHIFT_DOWN_MASK else 0
val keyStroke = KeyStroke.getKeyStroke(charTyped, modifiers) val keyStroke = KeyStroke.getKeyStroke(charTyped, modifiers)
val startTime = if (traceTime) System.currentTimeMillis() else null val startTime = if (traceTime) System.currentTimeMillis() else null
handler.handleKey(editor.vim, keyStroke, context.vim, handler.keyHandlerState) handler.handleKey(editor.vim, keyStroke, injector.executionContextManager.onEditor(editor.vim, context.vim))
if (startTime != null) { if (startTime != null) {
val duration = System.currentTimeMillis() - startTime val duration = System.currentTimeMillis() - startTime
LOG.info("VimTypedAction '$charTyped': $duration ms") LOG.info("VimTypedAction '$charTyped': $duration ms")
@@ -89,7 +86,7 @@ public class VimTypedActionHandler(origHandler: TypedActionHandler) : TypedActio
} }
} }
internal companion object { companion object {
private val LOG = logger<VimTypedActionHandler>() private val LOG = logger<VimTypedActionHandler>()
} }
} }

View File

@@ -7,8 +7,6 @@
*/ */
package com.maddyhome.idea.vim.action package com.maddyhome.idea.vim.action
import com.intellij.vim.annotations.CommandOrMotion
import com.intellij.vim.annotations.Mode
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.VimEditor import com.maddyhome.idea.vim.api.VimEditor
@@ -16,7 +14,6 @@ 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 = [":"], modes = [Mode.NORMAL, Mode.VISUAL, Mode.OP_PENDING])
internal class ExEntryAction : VimActionHandler.SingleExecution() { internal class ExEntryAction : VimActionHandler.SingleExecution() {
override val type: Command.Type = Command.Type.OTHER_READONLY override val type: Command.Type = Command.Type.OTHER_READONLY

View File

@@ -1,13 +0,0 @@
/*
* Copyright 2003-2023 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.
*/
package com.maddyhome.idea.vim.action
public object IntellijCommandProvider : CommandProvider {
override val commandListFileName: String = "intellij_commands.json"
}

View File

@@ -14,10 +14,14 @@ import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.AnActionWrapper import com.intellij.openapi.actionSystem.AnActionWrapper
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.actionSystem.KeyboardShortcut
import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.application.invokeLater import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.actionSystem.EditorActionManager
import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.util.Key import com.intellij.openapi.util.Key
@@ -44,6 +48,7 @@ import com.maddyhome.idea.vim.listener.AceJumpService
import com.maddyhome.idea.vim.listener.AppCodeTemplates.appCodeTemplateCaptured import com.maddyhome.idea.vim.listener.AppCodeTemplates.appCodeTemplateCaptured
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.newapi.vim
import com.maddyhome.idea.vim.state.mode.mode
import com.maddyhome.idea.vim.vimscript.model.datatypes.VimString import com.maddyhome.idea.vim.vimscript.model.datatypes.VimString
import java.awt.event.InputEvent import java.awt.event.InputEvent
import java.awt.event.KeyEvent import java.awt.event.KeyEvent
@@ -54,17 +59,9 @@ import javax.swing.KeyStroke
* *
* *
* These keys are not passed to [com.maddyhome.idea.vim.VimTypedActionHandler] and should be handled by actions. * These keys are not passed to [com.maddyhome.idea.vim.VimTypedActionHandler] and should be handled by actions.
*
* This class is used in Which-Key plugin, so don't make it internal. Generally, we should provide a proper
* way to get ideavim keys for this plugin. See VIM-3085
*/ */
public class VimShortcutKeyAction : AnAction(), DumbAware/*, LightEditCompatible*/ { internal class VimShortcutKeyAction : AnAction(), DumbAware/*, LightEditCompatible*/ {
private val traceTime: Boolean private val traceTime = injector.globalOptions().ideatracetime
get() {
// Make sure the injector is initialized
VimPlugin.getInstance()
return injector.globalOptions().ideatracetime
}
override fun actionPerformed(e: AnActionEvent) { override fun actionPerformed(e: AnActionEvent) {
LOG.trace("Executing shortcut key action") LOG.trace("Executing shortcut key action")
@@ -78,8 +75,11 @@ public class VimShortcutKeyAction : AnAction(), DumbAware/*, LightEditCompatible
// Should we use HelperKt.getTopLevelEditor(editor) here, as we did in former EditorKeyHandler? // Should we use HelperKt.getTopLevelEditor(editor) here, as we did in former EditorKeyHandler?
try { try {
val start = if (traceTime) System.currentTimeMillis() else null val start = if (traceTime) System.currentTimeMillis() else null
val keyHandler = KeyHandler.getInstance() KeyHandler.getInstance().handleKey(
keyHandler.handleKey(editor.vim, keyStroke, e.dataContext.vim, keyHandler.keyHandlerState) editor.vim,
keyStroke,
injector.executionContextManager.onEditor(editor.vim, e.dataContext.vim),
)
if (start != null) { if (start != null) {
val duration = System.currentTimeMillis() - start val duration = System.currentTimeMillis() - start
LOG.info("VimShortcut update '$keyStroke': $duration ms") LOG.info("VimShortcut update '$keyStroke': $duration ms")
@@ -95,30 +95,28 @@ public class VimShortcutKeyAction : AnAction(), DumbAware/*, LightEditCompatible
// There is a chance that we can use BGT, but we call for isCell inside the update. // There is a chance that we can use BGT, but we call for isCell inside the update.
// Not sure if can can use BGT with this call. Let's use EDT for now. // Not sure if can can use BGT with this call. Let's use EDT for now.
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT override fun getActionUpdateThread() = ActionUpdateThread.EDT
override fun update(e: AnActionEvent) { override fun update(e: AnActionEvent) {
val start = if (traceTime) System.currentTimeMillis() else null val start = if (traceTime) System.currentTimeMillis() else null
val keyStroke = getKeyStroke(e) val actionEnableStatus = isEnabled(e)
val actionEnableStatus = isEnabled(e, keyStroke)
e.presentation.isEnabled = actionEnableStatus.isEnabled e.presentation.isEnabled = actionEnableStatus.isEnabled
actionEnableStatus.printLog(keyStroke) actionEnableStatus.printLog()
if (start != null) { if (start != null) {
val keyStroke = getKeyStroke(e)
val duration = System.currentTimeMillis() - start val duration = System.currentTimeMillis() - start
LOG.info("VimShortcut update '$keyStroke': $duration ms") LOG.info("VimShortcut update '$keyStroke': $duration ms")
} }
} }
private fun isEnabled(e: AnActionEvent, keyStroke: KeyStroke?): ActionEnableStatus { private fun isEnabled(e: AnActionEvent): ActionEnableStatus {
if (VimPlugin.isNotEnabled()) return ActionEnableStatus.no("IdeaVim is disabled", LogLevel.DEBUG) if (!VimPlugin.isEnabled()) return ActionEnableStatus.no("IdeaVim is disabled", LogLevel.DEBUG)
val editor = getEditor(e) val editor = getEditor(e)
val keyStroke = getKeyStroke(e)
if (editor != null && keyStroke != null) { if (editor != null && keyStroke != null) {
if (enableOctopus) { if (enableOctopus) {
if (isOctopusEnabled(keyStroke, editor)) { if (isOctopusEnabled(keyStroke, editor)) {
return ActionEnableStatus.no( return ActionEnableStatus.no("Octopus handler is enabled", LogLevel.DEBUG)
"Processing VimShortcutKeyAction for the key that is used in the octopus handler",
LogLevel.ERROR
)
} }
} }
if (editor.isIdeaVimDisabledHere) { if (editor.isIdeaVimDisabledHere) {
@@ -166,6 +164,18 @@ public class VimShortcutKeyAction : AnAction(), DumbAware/*, LightEditCompatible
return ActionEnableStatus.no("App code template is active", LogLevel.INFO) return ActionEnableStatus.no("App code template is active", LogLevel.INFO)
} }
if (keyCode == KeyEvent.VK_LEFT || keyCode == KeyEvent.VK_RIGHT || keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_DOWN || keyCode == KeyEvent.VK_HOME || keyCode == KeyEvent.VK_END) {
return ActionEnableStatus.no("Special keys", LogLevel.INFO)
}
val nextTemplateVariableShortcuts = KeymapManager.getInstance().activeKeymap.getShortcuts(IdeActions.ACTION_EDITOR_NEXT_TEMPLATE_VARIABLE)
if (nextTemplateVariableShortcuts.any { it is KeyboardShortcut && it.firstKeyStroke == keyStroke }) {
val handler = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_NEXT_TEMPLATE_VARIABLE)
if (handler.isEnabled(editor, null, e.dataContext)) {
return ActionEnableStatus.no("Next template variable or finish in-place refactoring", LogLevel.INFO)
}
}
if (editor.inInsertMode) { if (editor.inInsertMode) {
if (keyCode == KeyEvent.VK_TAB) { if (keyCode == KeyEvent.VK_TAB) {
// TODO: This stops VimEditorTab seeing <Tab> in insert mode and correctly scrolling the view // TODO: This stops VimEditorTab seeing <Tab> in insert mode and correctly scrolling the view
@@ -231,9 +241,9 @@ public class VimShortcutKeyAction : AnAction(), DumbAware/*, LightEditCompatible
/** /**
* getDefaultKeyStroke is needed for NEO layout keyboard VIM-987 * getDefaultKeyStroke is needed for NEO layout keyboard VIM-987
* but we should cache the value because on the second call (isEnabled -> actionPerformed) * but we should cache the value because on the second call (isEnabled -> actionPerformed)
* the event is already consumed and getDefaultKeyStroke returns null * the event is already consumed
*/ */
private var keyStrokeCache: Pair<Long?, KeyStroke?> = null to null private var keyStrokeCache: Pair<KeyEvent?, KeyStroke?> = null to null
private fun getKeyStroke(e: AnActionEvent): KeyStroke? { private fun getKeyStroke(e: AnActionEvent): KeyStroke? {
val inputEvent = e.inputEvent val inputEvent = e.inputEvent
@@ -241,9 +251,9 @@ public class VimShortcutKeyAction : AnAction(), DumbAware/*, LightEditCompatible
val defaultKeyStroke = KeyStrokeAdapter.getDefaultKeyStroke(inputEvent) val defaultKeyStroke = KeyStrokeAdapter.getDefaultKeyStroke(inputEvent)
val strokeCache = keyStrokeCache val strokeCache = keyStrokeCache
if (defaultKeyStroke != null) { if (defaultKeyStroke != null) {
keyStrokeCache = inputEvent.`when` to defaultKeyStroke keyStrokeCache = inputEvent to defaultKeyStroke
return defaultKeyStroke return defaultKeyStroke
} else if (strokeCache.first == inputEvent.`when`) { } else if (strokeCache.first === inputEvent) {
keyStrokeCache = null to null keyStrokeCache = null to null
return strokeCache.second return strokeCache.second
} }
@@ -276,7 +286,7 @@ public class VimShortcutKeyAction : AnAction(), DumbAware/*, LightEditCompatible
.toSet() .toSet()
} }
internal companion object { companion object {
@JvmField @JvmField
val VIM_ONLY_EDITOR_KEYS: Set<KeyStroke> = val VIM_ONLY_EDITOR_KEYS: Set<KeyStroke> =
ImmutableSet.builder<KeyStroke>().addAll(getKeyStrokes(KeyEvent.VK_ENTER, 0)) ImmutableSet.builder<KeyStroke>().addAll(getKeyStrokes(KeyEvent.VK_ENTER, 0))
@@ -367,19 +377,13 @@ private class ActionEnableStatus(
val message: String, val message: String,
val logLevel: LogLevel, val logLevel: LogLevel,
) { ) {
fun printLog(keyStroke: KeyStroke?) { fun printLog() {
val message = "IdeaVim keys are enabled = $isEnabled for key '$keyStroke': $message"
when (logLevel) { when (logLevel) {
LogLevel.INFO -> LOG.info(message) LogLevel.INFO -> LOG.info("IdeaVim keys are enabled = $isEnabled: $message")
LogLevel.DEBUG -> LOG.debug(message) LogLevel.DEBUG -> LOG.debug("IdeaVim keys are enabled = $isEnabled: $message")
LogLevel.ERROR -> LOG.error(message)
} }
} }
override fun toString(): String {
return "ActionEnableStatus(isEnabled=$isEnabled, message='$message', logLevel=$logLevel)"
}
companion object { companion object {
private val LOG = logger<ActionEnableStatus>() private val LOG = logger<ActionEnableStatus>()
@@ -389,5 +393,5 @@ private class ActionEnableStatus(
} }
private enum class LogLevel { private enum class LogLevel {
DEBUG, INFO, ERROR, DEBUG, INFO,
} }

View File

@@ -7,94 +7,46 @@
*/ */
package com.maddyhome.idea.vim.action.change package com.maddyhome.idea.vim.action.change
import com.intellij.vim.annotations.CommandOrMotion
import com.intellij.vim.annotations.Mode
import com.maddyhome.idea.vim.KeyHandler 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.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.api.setChangeMarks import com.maddyhome.idea.vim.api.setChangeMarks
import com.maddyhome.idea.vim.command.Argument import com.maddyhome.idea.vim.command.Argument
import com.maddyhome.idea.vim.command.Command import com.maddyhome.idea.vim.command.Command
import com.maddyhome.idea.vim.command.CommandFlags
import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.state.mode.SelectionType
import com.maddyhome.idea.vim.common.TextRange import com.maddyhome.idea.vim.common.TextRange
import com.maddyhome.idea.vim.common.argumentCaptured import com.maddyhome.idea.vim.common.argumentCaptured
import com.maddyhome.idea.vim.ex.ExException
import com.maddyhome.idea.vim.group.MotionGroup import com.maddyhome.idea.vim.group.MotionGroup
import com.maddyhome.idea.vim.group.visual.VimSelection import com.maddyhome.idea.vim.group.visual.VimSelection
import com.maddyhome.idea.vim.handler.VimActionHandler import com.maddyhome.idea.vim.handler.VimActionHandler
import com.maddyhome.idea.vim.handler.VisualOperatorActionHandler import com.maddyhome.idea.vim.handler.VisualOperatorActionHandler
import com.maddyhome.idea.vim.helper.MessageHelper import com.maddyhome.idea.vim.helper.MessageHelper
import com.maddyhome.idea.vim.helper.enumSetOf
import com.maddyhome.idea.vim.helper.vimStateMachine import com.maddyhome.idea.vim.helper.vimStateMachine
import com.maddyhome.idea.vim.newapi.ij import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.state.mode.SelectionType import java.util.*
import com.maddyhome.idea.vim.vimscript.model.CommandLineVimLContext
import com.maddyhome.idea.vim.vimscript.model.datatypes.VimFuncref
import com.maddyhome.idea.vim.vimscript.model.expressions.FunctionCallExpression
import com.maddyhome.idea.vim.vimscript.model.expressions.SimpleExpression
// todo make it multicaret // todo make it multicaret
private fun doOperatorAction(editor: VimEditor, context: ExecutionContext, textRange: TextRange, selectionType: SelectionType): Boolean { private fun doOperatorAction(editor: VimEditor, context: ExecutionContext, textRange: TextRange, selectionType: SelectionType): Boolean {
val func = injector.globalOptions().operatorfunc val operatorFunction = injector.keyGroup.operatorFunction
if (func.isEmpty()) { if (operatorFunction == null) {
VimPlugin.showMessage(MessageHelper.message("E774")) VimPlugin.showMessage(MessageHelper.message("E774"))
return false return false
} }
val scriptContext = CommandLineVimLContext
// The option value is either a function name, which should have a handler, or it might be a lambda expression, or a
// `function` or `funcref` call expression, all of which will return a funcref (with a handler)
var handler = injector.functionService.getFunctionHandlerOrNull(null, func, scriptContext)
if (handler == null) {
val expression = injector.vimscriptParser.parseExpression(func)
if (expression != null) {
try {
val value = expression.evaluate(editor, context, scriptContext)
if (value is VimFuncref) {
handler = value.handler
}
} catch (ex: ExException) {
// Get the argument for function('...') or funcref('...') for the error message
val functionName = if (expression is FunctionCallExpression && expression.arguments.size > 0) {
expression.arguments[0].evaluate(editor, context, scriptContext).toString()
}
else {
func
}
VimPlugin.showMessage("E117: Unknown function: $functionName")
return false
}
}
}
if (handler == null) {
VimPlugin.showMessage("E117: Unknown function: $func")
return false
}
val arg = when (selectionType) {
SelectionType.LINE_WISE -> "line"
SelectionType.CHARACTER_WISE -> "char"
SelectionType.BLOCK_WISE -> "block"
}
val saveRepeatHandler = VimRepeater.repeatHandler val saveRepeatHandler = VimRepeater.repeatHandler
injector.markService.setChangeMarks(editor.primaryCaret(), textRange) injector.markService.setChangeMarks(editor.primaryCaret(), textRange)
KeyHandler.getInstance().reset(editor) KeyHandler.getInstance().reset(editor)
val result = operatorFunction.apply(editor, context, selectionType)
val arguments = listOf(SimpleExpression(arg))
handler.executeFunction(arguments, editor, context, scriptContext)
VimRepeater.repeatHandler = saveRepeatHandler VimRepeater.repeatHandler = saveRepeatHandler
return true return result
} }
@CommandOrMotion(keys = ["g@"], modes = [Mode.NORMAL])
internal class OperatorAction : VimActionHandler.SingleExecution() { internal class OperatorAction : VimActionHandler.SingleExecution() {
override val type: Command.Type = Command.Type.OTHER_SELF_SYNCHRONIZED override val type: Command.Type = Command.Type.OTHER_SELF_SYNCHRONIZED
@@ -145,10 +97,11 @@ internal class OperatorAction : VimActionHandler.SingleExecution() {
} }
} }
@CommandOrMotion(keys = ["g@"], modes = [Mode.VISUAL])
internal class VisualOperatorAction : VisualOperatorActionHandler.ForEachCaret() { internal class VisualOperatorAction : VisualOperatorActionHandler.ForEachCaret() {
override val type: Command.Type = Command.Type.OTHER_SELF_SYNCHRONIZED override val type: Command.Type = Command.Type.OTHER_SELF_SYNCHRONIZED
override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_EXIT_VISUAL)
override fun executeAction( override fun executeAction(
editor: VimEditor, editor: VimEditor,
caret: VimCaret, caret: VimCaret,

View File

@@ -8,8 +8,6 @@
package com.maddyhome.idea.vim.action.change package com.maddyhome.idea.vim.action.change
import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.command.CommandProcessor
import com.intellij.vim.annotations.CommandOrMotion
import com.intellij.vim.annotations.Mode
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.VimEditor import com.maddyhome.idea.vim.api.VimEditor
@@ -20,7 +18,6 @@ import com.maddyhome.idea.vim.handler.VimActionHandler
import com.maddyhome.idea.vim.helper.vimStateMachine import com.maddyhome.idea.vim.helper.vimStateMachine
import com.maddyhome.idea.vim.newapi.ij import com.maddyhome.idea.vim.newapi.ij
@CommandOrMotion(keys = ["."], modes = [Mode.NORMAL])
internal class RepeatChangeAction : VimActionHandler.SingleExecution() { internal class RepeatChangeAction : VimActionHandler.SingleExecution() {
override val type: Command.Type = Command.Type.OTHER_WRITABLE override val type: Command.Type = Command.Type.OTHER_WRITABLE

View File

@@ -7,8 +7,6 @@
*/ */
package com.maddyhome.idea.vim.action.change.delete package com.maddyhome.idea.vim.action.change.delete
import com.intellij.vim.annotations.CommandOrMotion
import com.intellij.vim.annotations.Mode
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
@@ -19,7 +17,6 @@ import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.handler.ChangeEditorActionHandler import com.maddyhome.idea.vim.handler.ChangeEditorActionHandler
import com.maddyhome.idea.vim.newapi.ijOptions import com.maddyhome.idea.vim.newapi.ijOptions
@CommandOrMotion(keys = ["gJ"], modes = [Mode.NORMAL])
public class DeleteJoinLinesAction : ChangeEditorActionHandler.ConditionalSingleExecution() { public class DeleteJoinLinesAction : ChangeEditorActionHandler.ConditionalSingleExecution() {
override val type: Command.Type = Command.Type.DELETE override val type: Command.Type = Command.Type.DELETE
override fun runAsMulticaret( override fun runAsMulticaret(

View File

@@ -7,8 +7,6 @@
*/ */
package com.maddyhome.idea.vim.action.change.delete package com.maddyhome.idea.vim.action.change.delete
import com.intellij.vim.annotations.CommandOrMotion
import com.intellij.vim.annotations.Mode
import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.ExecutionContext
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
@@ -18,7 +16,6 @@ import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.handler.ChangeEditorActionHandler import com.maddyhome.idea.vim.handler.ChangeEditorActionHandler
import com.maddyhome.idea.vim.newapi.ijOptions import com.maddyhome.idea.vim.newapi.ijOptions
@CommandOrMotion(keys = ["J"], modes = [Mode.NORMAL])
public class DeleteJoinLinesSpacesAction : ChangeEditorActionHandler.SingleExecution() { public class DeleteJoinLinesSpacesAction : ChangeEditorActionHandler.SingleExecution() {
override val type: Command.Type = Command.Type.DELETE override val type: Command.Type = Command.Type.DELETE
@@ -34,7 +31,7 @@ public class DeleteJoinLinesSpacesAction : ChangeEditorActionHandler.SingleExecu
} }
injector.editorGroup.notifyIdeaJoin(editor) injector.editorGroup.notifyIdeaJoin(editor)
var res = true var res = true
editor.nativeCarets().sortedByDescending { it.offset }.forEach { caret -> editor.nativeCarets().sortedByDescending { it.offset.point }.forEach { caret ->
if (!injector.changeGroup.deleteJoinLines(editor, caret, operatorArguments.count1, true, operatorArguments)) { if (!injector.changeGroup.deleteJoinLines(editor, caret, operatorArguments.count1, true, operatorArguments)) {
res = false res = false
} }

View File

@@ -7,25 +7,27 @@
*/ */
package com.maddyhome.idea.vim.action.change.delete package com.maddyhome.idea.vim.action.change.delete
import com.intellij.vim.annotations.CommandOrMotion
import com.intellij.vim.annotations.Mode
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
import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.Command import com.maddyhome.idea.vim.command.Command
import com.maddyhome.idea.vim.command.CommandFlags
import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.group.visual.VimSelection import com.maddyhome.idea.vim.group.visual.VimSelection
import com.maddyhome.idea.vim.handler.VisualOperatorActionHandler import com.maddyhome.idea.vim.handler.VisualOperatorActionHandler
import com.maddyhome.idea.vim.helper.enumSetOf
import com.maddyhome.idea.vim.newapi.ijOptions import com.maddyhome.idea.vim.newapi.ijOptions
import java.util.*
/** /**
* @author vlan * @author vlan
*/ */
@CommandOrMotion(keys = ["gJ"], modes = [Mode.VISUAL])
public class DeleteJoinVisualLinesAction : VisualOperatorActionHandler.SingleExecution() { public class DeleteJoinVisualLinesAction : VisualOperatorActionHandler.SingleExecution() {
override val type: Command.Type = Command.Type.DELETE override val type: Command.Type = Command.Type.DELETE
override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_EXIT_VISUAL)
override fun executeForAllCarets( override fun executeForAllCarets(
editor: VimEditor, editor: VimEditor,
context: ExecutionContext, context: ExecutionContext,
@@ -39,7 +41,7 @@ public class DeleteJoinVisualLinesAction : VisualOperatorActionHandler.SingleExe
return true return true
} }
var res = true var res = true
editor.nativeCarets().sortedByDescending { it.offset }.forEach { caret -> editor.nativeCarets().sortedByDescending { it.offset.point }.forEach { caret ->
if (!caret.isValid) return@forEach if (!caret.isValid) return@forEach
val range = caretsAndSelections[caret] ?: return@forEach val range = caretsAndSelections[caret] ?: return@forEach
if (!injector.changeGroup.deleteJoinRange( if (!injector.changeGroup.deleteJoinRange(

View File

@@ -7,25 +7,27 @@
*/ */
package com.maddyhome.idea.vim.action.change.delete package com.maddyhome.idea.vim.action.change.delete
import com.intellij.vim.annotations.CommandOrMotion
import com.intellij.vim.annotations.Mode
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
import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.Command import com.maddyhome.idea.vim.command.Command
import com.maddyhome.idea.vim.command.CommandFlags
import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.group.visual.VimSelection import com.maddyhome.idea.vim.group.visual.VimSelection
import com.maddyhome.idea.vim.handler.VisualOperatorActionHandler import com.maddyhome.idea.vim.handler.VisualOperatorActionHandler
import com.maddyhome.idea.vim.helper.enumSetOf
import com.maddyhome.idea.vim.newapi.ijOptions import com.maddyhome.idea.vim.newapi.ijOptions
import java.util.*
/** /**
* @author vlan * @author vlan
*/ */
@CommandOrMotion(keys = ["J"], modes = [Mode.VISUAL])
public class DeleteJoinVisualLinesSpacesAction : VisualOperatorActionHandler.SingleExecution() { public class DeleteJoinVisualLinesSpacesAction : VisualOperatorActionHandler.SingleExecution() {
override val type: Command.Type = Command.Type.DELETE override val type: Command.Type = Command.Type.DELETE
override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_EXIT_VISUAL)
override fun executeForAllCarets( override fun executeForAllCarets(
editor: VimEditor, editor: VimEditor,
context: ExecutionContext, context: ExecutionContext,
@@ -39,7 +41,7 @@ public class DeleteJoinVisualLinesSpacesAction : VisualOperatorActionHandler.Sin
return true return true
} }
var res = true var res = true
editor.carets().sortedByDescending { it.offset }.forEach { caret -> editor.carets().sortedByDescending { it.offset.point }.forEach { caret ->
if (!caret.isValid) return@forEach if (!caret.isValid) return@forEach
val range = caretsAndSelections[caret] ?: return@forEach val range = caretsAndSelections[caret] ?: return@forEach
if (!injector.changeGroup.deleteJoinRange( if (!injector.changeGroup.deleteJoinRange(

View File

@@ -9,8 +9,7 @@
package com.maddyhome.idea.vim.action.editor package com.maddyhome.idea.vim.action.editor
import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.vim.annotations.CommandOrMotion import com.maddyhome.idea.vim.action.ComplicatedKeysAction
import com.intellij.vim.annotations.Mode
import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.ExecutionContext
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
@@ -20,37 +19,53 @@ import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.handler.IdeActionHandler import com.maddyhome.idea.vim.handler.IdeActionHandler
import com.maddyhome.idea.vim.handler.VimActionHandler import com.maddyhome.idea.vim.handler.VimActionHandler
import com.maddyhome.idea.vim.helper.enumSetOf import com.maddyhome.idea.vim.helper.enumSetOf
import java.awt.event.KeyEvent
import java.util.* import java.util.*
import javax.swing.KeyStroke
@CommandOrMotion(keys = ["<C-H>", "<BS>"], modes = [Mode.INSERT]) internal class VimEditorBackSpace : IdeActionHandler(IdeActions.ACTION_EDITOR_BACKSPACE), ComplicatedKeysAction {
internal class VimEditorBackSpace : IdeActionHandler(IdeActions.ACTION_EDITOR_BACKSPACE) { override val keyStrokesSet: Set<List<KeyStroke>> = setOf(
listOf(KeyStroke.getKeyStroke(KeyEvent.VK_H, KeyEvent.CTRL_DOWN_MASK)),
listOf(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0)),
)
override val type: Command.Type = Command.Type.DELETE override val type: Command.Type = Command.Type.DELETE
} }
@CommandOrMotion(keys = ["<Del>"], modes = [Mode.INSERT]) internal class VimEditorDelete : IdeActionHandler(IdeActions.ACTION_EDITOR_DELETE), ComplicatedKeysAction {
internal class VimEditorDelete : IdeActionHandler(IdeActions.ACTION_EDITOR_DELETE) { override val keyStrokesSet: Set<List<KeyStroke>> = setOf(
listOf(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0)),
)
override val type: Command.Type = Command.Type.DELETE override val type: Command.Type = Command.Type.DELETE
override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_SAVE_STROKE)
} }
@CommandOrMotion(keys = ["<Down>", "<kDown>"], modes = [Mode.INSERT]) internal class VimEditorDown : IdeActionHandler(IdeActions.ACTION_EDITOR_MOVE_CARET_DOWN), ComplicatedKeysAction {
internal class VimEditorDown : IdeActionHandler(IdeActions.ACTION_EDITOR_MOVE_CARET_DOWN) { override val keyStrokesSet: Set<List<KeyStroke>> = setOf(
listOf(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0)),
listOf(KeyStroke.getKeyStroke(KeyEvent.VK_KP_DOWN, 0)),
)
override val type: Command.Type = Command.Type.MOTION override val type: Command.Type = Command.Type.MOTION
override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_CLEAR_STROKES) override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_CLEAR_STROKES)
} }
@CommandOrMotion(keys = ["<Tab>", "<C-I>"], modes = [Mode.INSERT]) internal class VimEditorTab : IdeActionHandler(IdeActions.ACTION_EDITOR_TAB), ComplicatedKeysAction {
internal class VimEditorTab : IdeActionHandler(IdeActions.ACTION_EDITOR_TAB) { override val keyStrokesSet: Set<List<KeyStroke>> = setOf(
listOf(KeyStroke.getKeyStroke(KeyEvent.VK_I, KeyEvent.CTRL_DOWN_MASK)),
listOf(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0)),
)
override val type: Command.Type = Command.Type.INSERT override val type: Command.Type = Command.Type.INSERT
override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_SAVE_STROKE) override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_SAVE_STROKE)
} }
@CommandOrMotion(keys = ["<Up>", "<kUp>"], modes = [Mode.INSERT]) internal class VimEditorUp : IdeActionHandler(IdeActions.ACTION_EDITOR_MOVE_CARET_UP), ComplicatedKeysAction {
internal class VimEditorUp : IdeActionHandler(IdeActions.ACTION_EDITOR_MOVE_CARET_UP) { override val keyStrokesSet: Set<List<KeyStroke>> = setOf(
listOf(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0)),
listOf(KeyStroke.getKeyStroke(KeyEvent.VK_KP_UP, 0)),
)
override val type: Command.Type = Command.Type.MOTION override val type: Command.Type = Command.Type.MOTION
override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_CLEAR_STROKES) override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_CLEAR_STROKES)
} }
@CommandOrMotion(keys = ["K"], modes = [Mode.NORMAL])
internal class VimQuickJavaDoc : VimActionHandler.SingleExecution() { internal class VimQuickJavaDoc : VimActionHandler.SingleExecution() {
override val type: Command.Type = Command.Type.OTHER_READONLY override val type: Command.Type = Command.Type.OTHER_READONLY

View File

@@ -7,9 +7,8 @@
*/ */
package com.maddyhome.idea.vim.action.ex package com.maddyhome.idea.vim.action.ex
import com.intellij.vim.annotations.CommandOrMotion
import com.intellij.vim.annotations.Mode
import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.action.ComplicatedKeysAction
import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.command.Command import com.maddyhome.idea.vim.command.Command
@@ -17,14 +16,17 @@ import com.maddyhome.idea.vim.command.CommandFlags
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
import java.util.* import java.util.*
import javax.swing.KeyStroke
/** /**
* Called by KeyHandler to process the contents of the ex entry panel * Called by KeyHandler to process the contents of the ex entry panel
* *
* The mapping for this action means that the ex command is executed as a write action * The mapping for this action means that the ex command is executed as a write action
*/ */
@CommandOrMotion(keys = ["<CR>", "<C-M>", "<C-J>"], modes = [Mode.CMD_LINE]) public class ProcessExEntryAction : VimActionHandler.SingleExecution(), ComplicatedKeysAction {
public class ProcessExEntryAction : VimActionHandler.SingleExecution() { override val keyStrokesSet: Set<List<KeyStroke>> =
parseKeysSet("<CR>", "<C-M>", 0x0a.toChar().toString(), 0x0d.toChar().toString())
override val type: Command.Type = Command.Type.OTHER_SELF_SYNCHRONIZED override val type: Command.Type = Command.Type.OTHER_SELF_SYNCHRONIZED
override val flags: EnumSet<CommandFlags> = EnumSet.of(CommandFlags.FLAG_COMPLETE_EX) override val flags: EnumSet<CommandFlags> = EnumSet.of(CommandFlags.FLAG_COMPLETE_EX)

View File

@@ -21,19 +21,19 @@ import com.maddyhome.idea.vim.state.mode.SelectionType
public class CommandState(private val machine: VimStateMachine) { public class CommandState(private val machine: VimStateMachine) {
public val isOperatorPending: Boolean public val isOperatorPending: Boolean
get() = machine.isOperatorPending(machine.mode) get() = machine.isOperatorPending
public val mode: Mode public val mode: CommandState.Mode
get() { get() {
val myMode = machine.mode val myMode = machine.mode
return when (myMode) { return when (myMode) {
is com.maddyhome.idea.vim.state.mode.Mode.CMD_LINE -> Mode.CMD_LINE com.maddyhome.idea.vim.state.mode.Mode.CMD_LINE -> CommandState.Mode.CMD_LINE
com.maddyhome.idea.vim.state.mode.Mode.INSERT -> Mode.INSERT com.maddyhome.idea.vim.state.mode.Mode.INSERT -> CommandState.Mode.INSERT
is com.maddyhome.idea.vim.state.mode.Mode.NORMAL -> Mode.COMMAND is com.maddyhome.idea.vim.state.mode.Mode.NORMAL -> CommandState.Mode.COMMAND
is com.maddyhome.idea.vim.state.mode.Mode.OP_PENDING -> Mode.OP_PENDING is com.maddyhome.idea.vim.state.mode.Mode.OP_PENDING -> CommandState.Mode.OP_PENDING
com.maddyhome.idea.vim.state.mode.Mode.REPLACE -> Mode.REPLACE com.maddyhome.idea.vim.state.mode.Mode.REPLACE -> CommandState.Mode.REPLACE
is com.maddyhome.idea.vim.state.mode.Mode.SELECT -> Mode.SELECT is com.maddyhome.idea.vim.state.mode.Mode.SELECT -> CommandState.Mode.SELECT
is com.maddyhome.idea.vim.state.mode.Mode.VISUAL -> Mode.VISUAL is com.maddyhome.idea.vim.state.mode.Mode.VISUAL -> CommandState.Mode.VISUAL
} }
} }

View File

@@ -9,6 +9,8 @@
package com.maddyhome.idea.vim.common package com.maddyhome.idea.vim.common
import com.intellij.application.options.CodeStyle import com.intellij.application.options.CodeStyle
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project import com.intellij.openapi.project.Project
import com.intellij.psi.codeStyle.CommonCodeStyleSettings.IndentOptions import com.intellij.psi.codeStyle.CommonCodeStyleSettings.IndentOptions
@@ -37,12 +39,13 @@ internal class IndentConfig private constructor(indentOptions: IndentOptions) {
companion object { companion object {
@JvmStatic @JvmStatic
fun create(editor: Editor): IndentConfig { fun create(editor: Editor, context: DataContext): IndentConfig {
return create(editor, editor.project) return create(editor, PlatformDataKeys.PROJECT.getData(context))
} }
@JvmStatic @JvmStatic
fun create(editor: Editor, project: Project?): IndentConfig { @JvmOverloads
fun create(editor: Editor, project: Project? = editor.project): IndentConfig {
val indentOptions = if (project != null) { val indentOptions = if (project != null) {
CodeStyle.getIndentOptions(project, editor.document) CodeStyle.getIndentOptions(project, editor.document)
} else { } else {

View File

@@ -7,42 +7,27 @@
*/ */
package com.maddyhome.idea.vim.extension package com.maddyhome.idea.vim.extension
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import com.maddyhome.idea.vim.KeyHandler import com.maddyhome.idea.vim.KeyHandler
import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.action.change.Extension import com.maddyhome.idea.vim.action.change.Extension
import com.maddyhome.idea.vim.api.ExecutionContext
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.injector import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.MappingMode import com.maddyhome.idea.vim.command.MappingMode
import com.maddyhome.idea.vim.state.mode.SelectionType
import com.maddyhome.idea.vim.common.CommandAlias import com.maddyhome.idea.vim.common.CommandAlias
import com.maddyhome.idea.vim.common.CommandAliasHandler import com.maddyhome.idea.vim.common.CommandAliasHandler
import com.maddyhome.idea.vim.common.TextRange
import com.maddyhome.idea.vim.helper.CommandLineHelper import com.maddyhome.idea.vim.helper.CommandLineHelper
import com.maddyhome.idea.vim.helper.TestInputModel import com.maddyhome.idea.vim.helper.TestInputModel
import com.maddyhome.idea.vim.helper.noneOfEnum
import com.maddyhome.idea.vim.helper.vimStateMachine import com.maddyhome.idea.vim.helper.vimStateMachine
import com.maddyhome.idea.vim.key.MappingOwner import com.maddyhome.idea.vim.key.MappingOwner
import com.maddyhome.idea.vim.key.OperatorFunction import com.maddyhome.idea.vim.key.OperatorFunction
import com.maddyhome.idea.vim.newapi.vim import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.state.mode.SelectionType
import com.maddyhome.idea.vim.ui.ModalEntry import com.maddyhome.idea.vim.ui.ModalEntry
import com.maddyhome.idea.vim.vimscript.model.Executable
import com.maddyhome.idea.vim.vimscript.model.ExecutionResult
import com.maddyhome.idea.vim.vimscript.model.VimLContext
import com.maddyhome.idea.vim.vimscript.model.datatypes.VimDataType
import com.maddyhome.idea.vim.vimscript.model.expressions.Expression
import com.maddyhome.idea.vim.vimscript.model.expressions.Scope
import com.maddyhome.idea.vim.vimscript.model.statements.FunctionDeclaration
import com.maddyhome.idea.vim.vimscript.model.statements.FunctionFlag
import java.awt.event.KeyEvent import java.awt.event.KeyEvent
import java.util.*
import javax.swing.KeyStroke import javax.swing.KeyStroke
/** /**
@@ -53,9 +38,6 @@ import javax.swing.KeyStroke
* @author vlan * @author vlan
*/ */
public object VimExtensionFacade { public object VimExtensionFacade {
private val LOG = logger<VimExtensionFacade>()
/** The 'map' command for mapping keys to handlers defined in extensions. */ /** The 'map' command for mapping keys to handlers defined in extensions. */
@JvmStatic @JvmStatic
public fun putExtensionHandlerMapping( public fun putExtensionHandlerMapping(
@@ -134,6 +116,12 @@ public object VimExtensionFacade {
.setAlias(name, CommandAlias.Call(minimumNumberOfArguments, maximumNumberOfArguments, name, handler)) .setAlias(name, CommandAlias.Call(minimumNumberOfArguments, maximumNumberOfArguments, name, handler))
} }
/** Sets the value of 'operatorfunc' to be used as the operator function in 'g@'. */
@JvmStatic
public fun setOperatorFunction(function: OperatorFunction) {
VimPlugin.getKey().operatorFunction = function
}
/** /**
* Runs normal mode commands similar to ':normal! {commands}'. * Runs normal mode commands similar to ':normal! {commands}'.
* Mappings doesn't work with this function * Mappings doesn't work with this function
@@ -143,9 +131,8 @@ public object VimExtensionFacade {
*/ */
@JvmStatic @JvmStatic
public fun executeNormalWithoutMapping(keys: List<KeyStroke>, editor: Editor) { public fun executeNormalWithoutMapping(keys: List<KeyStroke>, editor: Editor) {
val context = injector.executionContextManager.getEditorExecutionContext(editor.vim) val context = injector.executionContextManager.onEditor(editor.vim)
val keyHandler = KeyHandler.getInstance() keys.forEach { KeyHandler.getInstance().handleKey(editor.vim, it, context, false, false) }
keys.forEach { keyHandler.handleKey(editor.vim, it, context, false, false, keyHandler.keyHandlerState) }
} }
/** Returns a single key stroke from the user input similar to 'getchar()'. */ /** Returns a single key stroke from the user input similar to 'getchar()'. */
@@ -153,26 +140,22 @@ public object VimExtensionFacade {
public fun inputKeyStroke(editor: Editor): KeyStroke { public fun inputKeyStroke(editor: Editor): KeyStroke {
if (editor.vim.vimStateMachine.isDotRepeatInProgress) { if (editor.vim.vimStateMachine.isDotRepeatInProgress) {
val input = Extension.consumeKeystroke() val input = Extension.consumeKeystroke()
LOG.trace("inputKeyStroke: dot repeat in progress. Input: $input")
return input ?: error("Not enough keystrokes saved: ${Extension.lastExtensionHandler}") return input ?: error("Not enough keystrokes saved: ${Extension.lastExtensionHandler}")
} }
val key: KeyStroke? = if (ApplicationManager.getApplication().isUnitTestMode) { val key: KeyStroke? = if (ApplicationManager.getApplication().isUnitTestMode) {
LOG.trace("Unit test mode is active")
val mappingStack = KeyHandler.getInstance().keyStack val mappingStack = KeyHandler.getInstance().keyStack
mappingStack.feedSomeStroke() ?: TestInputModel.getInstance(editor).nextKeyStroke()?.also { mappingStack.feedSomeStroke() ?: TestInputModel.getInstance(editor).nextKeyStroke()?.also {
if (injector.registerGroup.isRecording) { if (editor.vim.vimStateMachine.isRecording) {
KeyHandler.getInstance().modalEntryKeys += it KeyHandler.getInstance().modalEntryKeys += it
} }
} }
} else { } else {
LOG.trace("Getting char from the modal entry...")
var ref: KeyStroke? = null var ref: KeyStroke? = null
ModalEntry.activate(editor.vim) { stroke: KeyStroke? -> ModalEntry.activate(editor.vim) { stroke: KeyStroke? ->
ref = stroke ref = stroke
false false
} }
LOG.trace("Got char $ref")
ref ref
} }
val result = key ?: KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE.toChar()) val result = key ?: KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE.toChar())
@@ -182,8 +165,8 @@ public object VimExtensionFacade {
/** Returns a string typed in the input box similar to 'input()'. */ /** Returns a string typed in the input box similar to 'input()'. */
@JvmStatic @JvmStatic
public fun inputString(editor: Editor, context: DataContext, prompt: String, finishOn: Char?): String { public fun inputString(editor: Editor, prompt: String, finishOn: Char?): String {
return service<CommandLineHelper>().inputString(editor.vim, context.vim, prompt, finishOn) ?: "" return service<CommandLineHelper>().inputString(editor.vim, prompt, finishOn) ?: ""
} }
/** Get the current contents of the given register similar to 'getreg()'. */ /** Get the current contents of the given register similar to 'getreg()'. */
@@ -216,65 +199,4 @@ public object VimExtensionFacade {
public fun setRegister(register: Char, keys: List<KeyStroke?>?, type: SelectionType) { public fun setRegister(register: Char, keys: List<KeyStroke?>?, type: SelectionType) {
VimPlugin.getRegister().setKeys(register, keys?.filterNotNull() ?: emptyList(), type) VimPlugin.getRegister().setKeys(register, keys?.filterNotNull() ?: emptyList(), type)
} }
@JvmStatic
public fun exportScriptFunction(
scope: Scope?,
name: String,
args: List<String>,
defaultArgs: List<Pair<String, Expression>>,
hasOptionalArguments: Boolean,
flags: EnumSet<FunctionFlag>,
function: ScriptFunction
) {
var functionDeclaration: FunctionDeclaration? = null
val body = listOf(object : Executable {
// This context is set to the function declaration during initialisation and then set to the function execution
// context during execution
override lateinit var vimContext: VimLContext
override var rangeInScript: TextRange = TextRange(0, 0)
override fun execute(editor: VimEditor, context: ExecutionContext): ExecutionResult {
return function.execute(editor, context, functionDeclaration!!.functionVariables)
}
})
functionDeclaration = FunctionDeclaration(
scope,
name,
args,
defaultArgs,
body,
replaceExisting = true,
flags,
hasOptionalArguments
)
functionDeclaration.rangeInScript = TextRange(0, 0)
body.forEach { it.vimContext = functionDeclaration }
injector.functionService.storeFunction(functionDeclaration)
}
}
public fun VimExtensionFacade.exportOperatorFunction(name: String, function: OperatorFunction) {
exportScriptFunction(null, name, listOf("type"), emptyList(), false, noneOfEnum()) {
editor, context, args ->
val type = args["type"]?.asString()
val selectionType = when (type) {
"line" -> SelectionType.LINE_WISE
"block" -> SelectionType.BLOCK_WISE
"char" -> SelectionType.CHARACTER_WISE
else -> return@exportScriptFunction ExecutionResult.Error
}
if (function.apply(editor, context, selectionType)) {
ExecutionResult.Success
}
else {
ExecutionResult.Error
}
}
}
public fun interface ScriptFunction {
public fun execute(editor: VimEditor, context: ExecutionContext, args: Map<String, VimDataType>): ExecutionResult
} }

View File

@@ -53,11 +53,6 @@ internal object VimExtensionRegistrar : VimExtensionRegistrator {
@Synchronized @Synchronized
private fun registerExtension(extensionBean: ExtensionBeanClass) { private fun registerExtension(extensionBean: ExtensionBeanClass) {
val name = extensionBean.name ?: extensionBean.instance.name val name = extensionBean.name ?: extensionBean.instance.name
if (name == "sneak" && extensionBean.name == null) {
// Filter out the old ideavim-sneak extension that used to be a separate plugin
// https://github.com/Mishkun/ideavim-sneak
return
}
if (name in registeredExtensions) return if (name in registeredExtensions) return
registeredExtensions.add(name) registeredExtensions.add(name)
@@ -67,7 +62,7 @@ internal object VimExtensionRegistrar : VimExtensionRegistrator {
VimPlugin.getOptionGroup().addGlobalOptionChangeListener(option) { VimPlugin.getOptionGroup().addGlobalOptionChangeListener(option) {
if (injector.optionGroup.getOptionValue(option, OptionAccessScope.GLOBAL(null)).asBoolean()) { if (injector.optionGroup.getOptionValue(option, OptionAccessScope.GLOBAL(null)).asBoolean()) {
initExtension(extensionBean, name) initExtension(extensionBean, name)
PluginState.Util.enabledExtensions.add(name) PluginState.enabledExtensions.add(name)
} else { } else {
extensionBean.instance.dispose() extensionBean.instance.dispose()
} }
@@ -87,31 +82,6 @@ internal object VimExtensionRegistrar : VimExtensionRegistrator {
} }
} }
/**
* During vim initialization process, it firstly loads the .vimrc file, then executes scripts from the plugins folder.
* This practically means that the .vimrc file is initialized first, then the plugins are loaded.
* See `:h initialization`
*
* In IdeaVim we don't have a separate plugins folder to load it after .ideavimrc load. However, we can collect
* the list of plugins mentioned in the .ideavimrc and load them after .ideavimrc execution is finished.
*
* Why this matters? Because this affects the order of commands are executed. For example:
* ```
* plug 'tommcdo/vim-exchange'
* let g:exchange_no_mappings=1
* ```
* Here the user will expect that the exchange plugin won't have default mappings. However, if we load vim-exchange
* immediately, this variable won't be initialized at the moment of plugin initialization.
*
* There is also a tricky case for mappings override:
* ```
* plug 'tommcdo/vim-exchange'
* map X <Plug>(ExchangeLine)
* ```
* For this case, a plugin with a good implementation detects that there is already a defined mapping for
* `<Plug>(ExchangeLine)` and doesn't register the default cxx mapping. However, such detection requires the mapping
* to be defined before the plugin initialization.
*/
@JvmStatic @JvmStatic
fun enableDelayedExtensions() { fun enableDelayedExtensions() {
delayedExtensionEnabling.forEach { delayedExtensionEnabling.forEach {

View File

@@ -251,7 +251,7 @@ public class VimArgTextObjExtension implements VimExtension {
final ArgumentTextObjectHandler textObjectHandler = new ArgumentTextObjectHandler(isInner); final ArgumentTextObjectHandler textObjectHandler = new ArgumentTextObjectHandler(isInner);
//noinspection DuplicatedCode //noinspection DuplicatedCode
if (!vimStateMachine.isOperatorPending(editor.getMode())) { if (!vimStateMachine.isOperatorPending()) {
editor.nativeCarets().forEach((VimCaret caret) -> { editor.nativeCarets().forEach((VimCaret caret) -> {
final TextRange range = textObjectHandler.getRange(editor, caret, context, count, 0); final TextRange range = textObjectHandler.getRange(editor, caret, context, count, 0);
if (range != null) { if (range != null) {

View File

@@ -11,7 +11,6 @@ import com.intellij.codeInsight.actions.AsyncActionExecutionService
import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiComment import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement import com.intellij.psi.PsiElement
@@ -22,26 +21,26 @@ import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.ImmutableVimCaret 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.getLineEndOffset import com.maddyhome.idea.vim.api.getLineEndOffset
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.command.Argument import com.maddyhome.idea.vim.command.Argument
import com.maddyhome.idea.vim.command.Command import com.maddyhome.idea.vim.command.Command
import com.maddyhome.idea.vim.command.CommandFlags import com.maddyhome.idea.vim.command.CommandFlags
import com.maddyhome.idea.vim.command.MappingMode import com.maddyhome.idea.vim.command.MappingMode
import com.maddyhome.idea.vim.state.mode.Mode
import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.state.mode.SelectionType
import com.maddyhome.idea.vim.command.TextObjectVisualType import com.maddyhome.idea.vim.command.TextObjectVisualType
import com.maddyhome.idea.vim.common.CommandAliasHandler import com.maddyhome.idea.vim.common.CommandAliasHandler
import com.maddyhome.idea.vim.common.TextRange import com.maddyhome.idea.vim.common.TextRange
import com.maddyhome.idea.vim.ex.ranges.Ranges import com.maddyhome.idea.vim.ex.ranges.Ranges
import com.maddyhome.idea.vim.extension.ExtensionHandler import com.maddyhome.idea.vim.extension.ExtensionHandler
import com.maddyhome.idea.vim.extension.VimExtension import com.maddyhome.idea.vim.extension.VimExtension
import com.maddyhome.idea.vim.extension.VimExtensionFacade
import com.maddyhome.idea.vim.extension.VimExtensionFacade.addCommand import com.maddyhome.idea.vim.extension.VimExtensionFacade.addCommand
import com.maddyhome.idea.vim.extension.VimExtensionFacade.executeNormalWithoutMapping import com.maddyhome.idea.vim.extension.VimExtensionFacade.executeNormalWithoutMapping
import com.maddyhome.idea.vim.extension.VimExtensionFacade.putExtensionHandlerMapping import com.maddyhome.idea.vim.extension.VimExtensionFacade.putExtensionHandlerMapping
import com.maddyhome.idea.vim.extension.VimExtensionFacade.putKeyMapping import com.maddyhome.idea.vim.extension.VimExtensionFacade.putKeyMapping
import com.maddyhome.idea.vim.extension.VimExtensionFacade.putKeyMappingIfMissing import com.maddyhome.idea.vim.extension.VimExtensionFacade.putKeyMappingIfMissing
import com.maddyhome.idea.vim.extension.exportOperatorFunction import com.maddyhome.idea.vim.extension.VimExtensionFacade.setOperatorFunction
import com.maddyhome.idea.vim.handler.TextObjectActionHandler import com.maddyhome.idea.vim.handler.TextObjectActionHandler
import com.maddyhome.idea.vim.helper.PsiHelper import com.maddyhome.idea.vim.helper.PsiHelper
import com.maddyhome.idea.vim.helper.vimStateMachine import com.maddyhome.idea.vim.helper.vimStateMachine
@@ -49,19 +48,17 @@ import com.maddyhome.idea.vim.key.OperatorFunction
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
import com.maddyhome.idea.vim.state.mode.Mode
import com.maddyhome.idea.vim.state.mode.SelectionType
import java.util.* import java.util.*
internal class CommentaryExtension : VimExtension { internal class CommentaryExtension : VimExtension {
object Util { companion object {
fun doCommentary( fun doCommentary(
editor: VimEditor, editor: VimEditor,
context: ExecutionContext, context: ExecutionContext,
range: TextRange, range: TextRange,
selectionType: SelectionType, selectionType: SelectionType,
resetCaret: Boolean = true, resetCaret: Boolean,
): Boolean { ): Boolean {
val mode = editor.vimStateMachine.mode val mode = editor.vimStateMachine.mode
if (mode !is Mode.VISUAL) { if (mode !is Mode.VISUAL) {
@@ -69,33 +66,27 @@ internal class CommentaryExtension : VimExtension {
} }
return runWriteAction { return runWriteAction {
// Treat block- and character-wise selections as block comments. Fall back if the first action isn't available // Treat block- and character-wise selections as block comments. Be ready to fall back to if the first action
// isn't available
val actions = if (selectionType === SelectionType.LINE_WISE) { val actions = if (selectionType === SelectionType.LINE_WISE) {
listOf(IdeActions.ACTION_COMMENT_LINE, IdeActions.ACTION_COMMENT_BLOCK) listOf(IdeActions.ACTION_COMMENT_LINE, IdeActions.ACTION_COMMENT_BLOCK)
} else { } else {
listOf(IdeActions.ACTION_COMMENT_BLOCK, IdeActions.ACTION_COMMENT_LINE) listOf(IdeActions.ACTION_COMMENT_BLOCK, IdeActions.ACTION_COMMENT_LINE)
} }
val project = editor.ij.project!! val res = Ref.create<Boolean>(true)
val callback = { afterCommenting(mode, editor, resetCaret, range) } AsyncActionExecutionService.getInstance(editor.ij.project!!).withExecutionAfterAction(actions[0], {
actions.any { executeActionWithCallbackOnSuccess(it, project, context, callback) } res.set(injector.actionExecutor.executeAction(actions[0], context))
}, { afterCommenting(mode, editor, resetCaret, range) })
if (!res.get()) {
AsyncActionExecutionService.getInstance(editor.ij.project!!).withExecutionAfterAction(actions[1], {
res.set(injector.actionExecutor.executeAction(actions[1], context))
}, { afterCommenting(mode, editor, resetCaret, range) })
}
res.get()
} }
} }
private fun executeActionWithCallbackOnSuccess(
action: String,
project: Project,
context: ExecutionContext,
callback: () -> Unit,
): Boolean {
val res = Ref.create<Boolean>(false)
AsyncActionExecutionService.getInstance(project).withExecutionAfterAction(
action,
{ res.set(injector.actionExecutor.executeAction(action, context)) },
{ if (res.get()) callback() })
return res.get()
}
private fun afterCommenting( private fun afterCommenting(
mode: Mode, mode: Mode,
editor: VimEditor, editor: VimEditor,
@@ -114,17 +105,12 @@ internal class CommentaryExtension : VimExtension {
// first non-whitespace character, then the caret is in the right place. If it's inserted at the first column, // first non-whitespace character, then the caret is in the right place. If it's inserted at the first column,
// then the caret is now in a bit of a weird place. We can't detect this scenario, so we just have to accept // then the caret is now in a bit of a weird place. We can't detect this scenario, so we just have to accept
// the difference // the difference
// TODO: If we don't move the caret to the start offset, we should maintain the current logical position
if (resetCaret) { if (resetCaret) {
editor.primaryCaret().moveToOffset(range.startOffset) editor.primaryCaret().moveToOffset(range.startOffset)
} }
} }
} }
companion object {
private const val OPERATOR_FUNC = "CommentaryOperatorFunc"
}
override fun getName() = "commentary" override fun getName() = "commentary"
override fun init() { override fun init() {
@@ -151,16 +137,6 @@ internal class CommentaryExtension : VimExtension {
putKeyMapping(MappingMode.N, injector.parser.parseKeys("<Plug>(CommentLine)"), owner, plugCommentaryLineKeys, true) putKeyMapping(MappingMode.N, injector.parser.parseKeys("<Plug>(CommentLine)"), owner, plugCommentaryLineKeys, true)
addCommand("Commentary", CommentaryCommandAliasHandler()) addCommand("Commentary", CommentaryCommandAliasHandler())
VimExtensionFacade.exportOperatorFunction(OPERATOR_FUNC, CommentaryOperatorFunction())
}
private class CommentaryOperatorFunction : OperatorFunction {
// todo make it multicaret
override fun apply(editor: VimEditor, context: ExecutionContext, selectionType: SelectionType?): Boolean {
val range = injector.markService.getChangeMarks(editor.primaryCaret()) ?: return false
return Util.doCommentary(editor, context, range, selectionType ?: SelectionType.CHARACTER_WISE, true)
}
} }
/** /**
@@ -169,13 +145,24 @@ internal class CommentaryExtension : VimExtension {
* E.g. handles the `gc` in `gc_`, by setting the operator function, then invoking `g@` to receive the `_` motion to * E.g. handles the `gc` in `gc_`, by setting the operator function, then invoking `g@` to receive the `_` motion to
* invoke the operator. This object is both the mapping handler and the operator function. * invoke the operator. This object is both the mapping handler and the operator function.
*/ */
private class CommentaryOperatorHandler : ExtensionHandler { private class CommentaryOperatorHandler : OperatorFunction, ExtensionHandler {
override val isRepeatable = true override val isRepeatable = true
// In this operator we process selection by ourselves. This is necessary for rider, VIM-1758
override fun postProcessSelection(): Boolean {
return false
}
override fun execute(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments) { override fun execute(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments) {
injector.globalOptions().operatorfunc = OPERATOR_FUNC setOperatorFunction(this)
executeNormalWithoutMapping(injector.parser.parseKeys("g@"), editor.ij) executeNormalWithoutMapping(injector.parser.parseKeys("g@"), editor.ij)
} }
// todo make it multicaret
override fun apply(editor: VimEditor, context: ExecutionContext, selectionType: SelectionType?): Boolean {
val range = injector.markService.getChangeMarks(editor.primaryCaret()) ?: return false
return doCommentary(editor, context, range, selectionType ?: SelectionType.CHARACTER_WISE, true)
}
} }
private class CommentaryMappingHandler : ExtensionHandler { private class CommentaryMappingHandler : ExtensionHandler {
@@ -249,7 +236,7 @@ internal class CommentaryExtension : VimExtension {
*/ */
private class CommentaryCommandAliasHandler : CommandAliasHandler { private class CommentaryCommandAliasHandler : CommandAliasHandler {
override fun execute(command: String, ranges: Ranges, editor: VimEditor, context: ExecutionContext) { override fun execute(command: String, ranges: Ranges, editor: VimEditor, context: ExecutionContext) {
Util.doCommentary(editor, context, ranges.getTextRange(editor, -1), SelectionType.LINE_WISE, false) doCommentary(editor, context, ranges.getTextRange(editor, -1), SelectionType.LINE_WISE, false)
} }
} }
} }

View File

@@ -19,22 +19,24 @@ import com.intellij.openapi.util.Key
import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.getOffset import com.maddyhome.idea.vim.api.getOffset
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.api.setChangeMarks import com.maddyhome.idea.vim.api.setChangeMarks
import com.maddyhome.idea.vim.command.MappingMode import com.maddyhome.idea.vim.command.MappingMode
import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.state.mode.SelectionType
import com.maddyhome.idea.vim.state.mode.SelectionType.CHARACTER_WISE
import com.maddyhome.idea.vim.state.mode.selectionType
import com.maddyhome.idea.vim.common.TextRange import com.maddyhome.idea.vim.common.TextRange
import com.maddyhome.idea.vim.extension.ExtensionHandler import com.maddyhome.idea.vim.extension.ExtensionHandler
import com.maddyhome.idea.vim.extension.VimExtension import com.maddyhome.idea.vim.extension.VimExtension
import com.maddyhome.idea.vim.extension.VimExtensionFacade
import com.maddyhome.idea.vim.extension.VimExtensionFacade.executeNormalWithoutMapping import com.maddyhome.idea.vim.extension.VimExtensionFacade.executeNormalWithoutMapping
import com.maddyhome.idea.vim.extension.VimExtensionFacade.getRegister import com.maddyhome.idea.vim.extension.VimExtensionFacade.getRegister
import com.maddyhome.idea.vim.extension.VimExtensionFacade.putExtensionHandlerMapping import com.maddyhome.idea.vim.extension.VimExtensionFacade.putExtensionHandlerMapping
import com.maddyhome.idea.vim.extension.VimExtensionFacade.putKeyMappingIfMissing import com.maddyhome.idea.vim.extension.VimExtensionFacade.putKeyMappingIfMissing
import com.maddyhome.idea.vim.extension.VimExtensionFacade.setOperatorFunction
import com.maddyhome.idea.vim.extension.VimExtensionFacade.setRegister import com.maddyhome.idea.vim.extension.VimExtensionFacade.setRegister
import com.maddyhome.idea.vim.extension.exportOperatorFunction
import com.maddyhome.idea.vim.helper.fileSize import com.maddyhome.idea.vim.helper.fileSize
import com.maddyhome.idea.vim.state.mode.mode
import com.maddyhome.idea.vim.helper.moveToInlayAwareLogicalPosition import com.maddyhome.idea.vim.helper.moveToInlayAwareLogicalPosition
import com.maddyhome.idea.vim.helper.moveToInlayAwareOffset import com.maddyhome.idea.vim.helper.moveToInlayAwareOffset
import com.maddyhome.idea.vim.key.OperatorFunction import com.maddyhome.idea.vim.key.OperatorFunction
@@ -43,8 +45,6 @@ import com.maddyhome.idea.vim.mark.VimMarkConstants
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
import com.maddyhome.idea.vim.state.mode.SelectionType
import com.maddyhome.idea.vim.state.mode.selectionType
import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.NonNls
/** /**
@@ -72,13 +72,30 @@ internal class VimExchangeExtension : VimExtension {
putKeyMappingIfMissing(MappingMode.X, injector.parser.parseKeys("X"), owner, injector.parser.parseKeys(EXCHANGE_CMD), true) putKeyMappingIfMissing(MappingMode.X, injector.parser.parseKeys("X"), owner, injector.parser.parseKeys(EXCHANGE_CMD), true)
putKeyMappingIfMissing(MappingMode.N, injector.parser.parseKeys("cxc"), owner, injector.parser.parseKeys(EXCHANGE_CLEAR_CMD), true) putKeyMappingIfMissing(MappingMode.N, injector.parser.parseKeys("cxc"), owner, injector.parser.parseKeys(EXCHANGE_CLEAR_CMD), true)
putKeyMappingIfMissing(MappingMode.N, injector.parser.parseKeys("cxx"), owner, injector.parser.parseKeys(EXCHANGE_LINE_CMD), true) putKeyMappingIfMissing(MappingMode.N, injector.parser.parseKeys("cxx"), owner, injector.parser.parseKeys(EXCHANGE_LINE_CMD), true)
VimExtensionFacade.exportOperatorFunction(OPERATOR_FUNC, Operator())
} }
object Util { companion object {
@NonNls
const val EXCHANGE_CMD = "<Plug>(Exchange)"
@NonNls
const val EXCHANGE_CLEAR_CMD = "<Plug>(ExchangeClear)"
@NonNls
const val EXCHANGE_LINE_CMD = "<Plug>(ExchangeLine)"
val EXCHANGE_KEY = Key<Exchange>("exchange") val EXCHANGE_KEY = Key<Exchange>("exchange")
// End mark has always greater of eq offset than start mark
class Exchange(val type: SelectionType, val start: Mark, val end: Mark, val text: String) {
private var myHighlighter: RangeHighlighter? = null
fun setHighlighter(highlighter: RangeHighlighter) {
myHighlighter = highlighter
}
fun getHighlighter(): RangeHighlighter? = myHighlighter
}
fun clearExchange(editor: Editor) { fun clearExchange(editor: Editor) {
editor.getUserData(EXCHANGE_KEY)?.getHighlighter()?.let { editor.getUserData(EXCHANGE_KEY)?.getHighlighter()?.let {
editor.markupModel.removeHighlighter(it) editor.markupModel.removeHighlighter(it)
@@ -87,25 +104,18 @@ internal class VimExchangeExtension : VimExtension {
} }
} }
companion object {
@NonNls private const val EXCHANGE_CMD = "<Plug>(Exchange)"
@NonNls private const val EXCHANGE_CLEAR_CMD = "<Plug>(ExchangeClear)"
@NonNls private const val EXCHANGE_LINE_CMD = "<Plug>(ExchangeLine)"
@NonNls private const val OPERATOR_FUNC = "ExchangeOperatorFunc"
}
private class ExchangeHandler(private val isLine: Boolean) : ExtensionHandler { private class ExchangeHandler(private val isLine: Boolean) : ExtensionHandler {
override val isRepeatable = true override val isRepeatable = true
override fun execute(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments) { override fun execute(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments) {
injector.globalOptions().operatorfunc = OPERATOR_FUNC setOperatorFunction(Operator(false))
executeNormalWithoutMapping(injector.parser.parseKeys(if (isLine) "g@_" else "g@"), editor.ij) executeNormalWithoutMapping(injector.parser.parseKeys(if (isLine) "g@_" else "g@"), editor.ij)
} }
} }
private class ExchangeClearHandler : ExtensionHandler { private class ExchangeClearHandler : ExtensionHandler {
override fun execute(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments) { override fun execute(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments) {
Util.clearExchange(editor.ij) clearExchange(editor.ij)
} }
} }
@@ -115,12 +125,12 @@ internal class VimExchangeExtension : VimExtension {
val mode = editor.mode val mode = editor.mode
// Leave visual mode to create selection marks // Leave visual mode to create selection marks
executeNormalWithoutMapping(injector.parser.parseKeys("<Esc>"), editor.ij) executeNormalWithoutMapping(injector.parser.parseKeys("<Esc>"), editor.ij)
Operator(true).apply(editor, context, mode.selectionType ?: SelectionType.CHARACTER_WISE) Operator(true).apply(editor, context, mode.selectionType ?: CHARACTER_WISE)
} }
} }
} }
private class Operator(private val isVisual: Boolean = false) : OperatorFunction { private class Operator(private val isVisual: Boolean) : OperatorFunction {
fun Editor.getMarkOffset(mark: Mark) = IjVimEditor(this).getOffset(mark.line, mark.col) fun Editor.getMarkOffset(mark: Mark) = IjVimEditor(this).getOffset(mark.line, mark.col)
fun SelectionType.getString() = when (this) { fun SelectionType.getString() = when (this) {
SelectionType.CHARACTER_WISE -> "v" SelectionType.CHARACTER_WISE -> "v"
@@ -138,7 +148,7 @@ internal class VimExchangeExtension : VimExtension {
else -> HighlighterTargetArea.EXACT_RANGE else -> HighlighterTargetArea.EXACT_RANGE
} }
val isVisualLine = ex.type == SelectionType.LINE_WISE val isVisualLine = ex.type == SelectionType.LINE_WISE
val endAdj = if (!(isVisualLine) && (hlArea == HighlighterTargetArea.EXACT_RANGE || isVisual)) 1 else 0 val endAdj = if (!(isVisualLine) && (hlArea == HighlighterTargetArea.EXACT_RANGE || (isVisual))) 1 else 0
return ijEditor.markupModel.addRangeHighlighter( return ijEditor.markupModel.addRangeHighlighter(
ijEditor.getMarkOffset(ex.start), ijEditor.getMarkOffset(ex.start),
(ijEditor.getMarkOffset(ex.end) + endAdj).coerceAtMost(ijEditor.fileSize), (ijEditor.getMarkOffset(ex.end) + endAdj).coerceAtMost(ijEditor.fileSize),
@@ -148,12 +158,12 @@ internal class VimExchangeExtension : VimExtension {
) )
} }
val currentExchange = getExchange(ijEditor, isVisual, selectionType ?: SelectionType.CHARACTER_WISE) val currentExchange = getExchange(ijEditor, isVisual, selectionType ?: CHARACTER_WISE)
val exchange1 = ijEditor.getUserData(Util.EXCHANGE_KEY) val exchange1 = ijEditor.getUserData(EXCHANGE_KEY)
if (exchange1 == null) { if (exchange1 == null) {
val highlighter = highlightExchange(currentExchange) val highlighter = highlightExchange(currentExchange)
currentExchange.setHighlighter(highlighter) currentExchange.setHighlighter(highlighter)
ijEditor.putUserData(Util.EXCHANGE_KEY, currentExchange) ijEditor.putUserData(EXCHANGE_KEY, currentExchange)
return true return true
} else { } else {
val cmp = compareExchanges(exchange1, currentExchange) val cmp = compareExchanges(exchange1, currentExchange)
@@ -179,7 +189,7 @@ internal class VimExchangeExtension : VimExtension {
} }
} }
exchange(ijEditor, ex1, ex2, reverse, expand) exchange(ijEditor, ex1, ex2, reverse, expand)
Util.clearExchange(ijEditor) clearExchange(ijEditor)
return true return true
} }
} }
@@ -344,14 +354,4 @@ internal class VimExchangeExtension : VimExtension {
} }
} }
} }
// End mark has always greater of eq offset than start mark
class Exchange(val type: SelectionType, val start: Mark, val end: Mark, val text: String) {
private var myHighlighter: RangeHighlighter? = null
fun setHighlighter(highlighter: RangeHighlighter) {
myHighlighter = highlighter
}
fun getHighlighter(): RangeHighlighter? = myHighlighter
}
} }

View File

@@ -99,7 +99,7 @@ internal class Matchit : VimExtension {
// Normally we want to jump to the start of the matching pair. But when moving forward in operator // Normally we want to jump to the start of the matching pair. But when moving forward in operator
// pending mode, we want to include the entire match. isInOpPending makes that distinction. // pending mode, we want to include the entire match. isInOpPending makes that distinction.
val isInOpPending = commandState.isOperatorPending(editor.mode) val isInOpPending = commandState.isOperatorPending
if (isInOpPending) { if (isInOpPending) {
val matchitAction = MatchitAction() val matchitAction = MatchitAction()
@@ -217,8 +217,6 @@ private object FileTypePatterns {
return if (fileTypeName in htmlLikeFileTypes) { return if (fileTypeName in htmlLikeFileTypes) {
this.htmlPatterns this.htmlPatterns
} else if (fileTypeName == "JAVA" || fileExtension == "java") {
this.javaPatterns
} else if (fileTypeName == "Ruby" || fileExtension == "rb") { } else if (fileTypeName == "Ruby" || fileExtension == "rb") {
this.rubyPatterns this.rubyPatterns
} else if (fileTypeName == "RHTML" || fileExtension == "erb") { } else if (fileTypeName == "RHTML" || fileExtension == "erb") {
@@ -244,7 +242,6 @@ private object FileTypePatterns {
) )
private val htmlPatterns = createHtmlPatterns() private val htmlPatterns = createHtmlPatterns()
private val javaPatterns = createJavaPatterns()
private val rubyPatterns = createRubyPatterns() private val rubyPatterns = createRubyPatterns()
private val rubyAndHtmlPatterns = rubyPatterns + htmlPatterns private val rubyAndHtmlPatterns = rubyPatterns + htmlPatterns
private val phpPatterns = createPhpPatterns() private val phpPatterns = createPhpPatterns()
@@ -274,14 +271,6 @@ private object FileTypePatterns {
) )
} }
private fun createJavaPatterns(): LanguagePatterns {
return (
LanguagePatterns("\\b(?<!else\\s+)if\\b", "\\belse\\s+if\\b", "\\belse(?!\\s+if)\\b") +
LanguagePatterns("\\bdo\\b", "\\bwhile\\b") +
LanguagePatterns("\\btry\\b", "\\bcatch\\b", "\\bfinally\\b")
)
}
private fun createRubyPatterns(): LanguagePatterns { private fun createRubyPatterns(): LanguagePatterns {
// Original patterns: https://github.com/vim/vim/blob/master/runtime/ftplugin/ruby.vim // Original patterns: https://github.com/vim/vim/blob/master/runtime/ftplugin/ruby.vim
// We use non-capturing groups (?:) since we don't need any back refs. The \\b marker takes care of word boundaries. // We use non-capturing groups (?:) since we don't need any back refs. The \\b marker takes care of word boundaries.

View File

@@ -246,7 +246,7 @@ internal class VimMultipleCursorsExtension : VimExtension {
// Note that ignoreCase is not overridden by the `\C` in the pattern // Note that ignoreCase is not overridden by the `\C` in the pattern
val pattern = makePattern(text, whole) val pattern = makePattern(text, whole)
val matches = injector.searchHelper.findAll(IjVimEditor(editor), pattern, 0, -1, false) val matches = SearchHelper.findAll(editor, pattern, 0, -1, false)
for (match in matches) { for (match in matches) {
if (match.contains(primaryCaret.offset)) { if (match.contains(primaryCaret.offset)) {
primaryCaret.vim.moveToOffset(match.startOffset) primaryCaret.vim.moveToOffset(match.startOffset)
@@ -322,7 +322,7 @@ internal class VimMultipleCursorsExtension : VimExtension {
searchOptions.add(SearchOptions.WRAP) searchOptions.add(SearchOptions.WRAP)
} }
return injector.searchHelper.findPattern(IjVimEditor(editor), makePattern(text, whole), startOffset, 1, searchOptions)?.startOffset ?: -1 return SearchHelper.findPattern(editor, makePattern(text, whole), startOffset, 1, searchOptions)?.startOffset ?: -1
} }
private fun makePattern(text: String, whole: Boolean): String { private fun makePattern(text: String, whole: Boolean): String {

View File

@@ -8,21 +8,25 @@
package com.maddyhome.idea.vim.extension.nerdtree package com.maddyhome.idea.vim.extension.nerdtree
import com.intellij.ide.projectView.ProjectView
import com.intellij.ide.projectView.impl.AbstractProjectViewPane
import com.intellij.ide.projectView.impl.ProjectViewImpl
import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys
import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.getUserData import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.putUserData import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.util.Key import com.intellij.openapi.startup.ProjectActivity
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowId import com.intellij.openapi.wm.ToolWindowId
import com.intellij.openapi.wm.ex.ToolWindowManagerEx import com.intellij.openapi.wm.ex.ToolWindowManagerEx
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.ui.KeyStrokeAdapter import com.intellij.ui.KeyStrokeAdapter
import com.intellij.ui.TreeExpandCollapse import com.intellij.ui.TreeExpandCollapse
import com.intellij.ui.speedSearch.SpeedSearchSupply import com.intellij.ui.speedSearch.SpeedSearchSupply
@@ -49,8 +53,6 @@ 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.vimscript.model.datatypes.VimString import com.maddyhome.idea.vim.vimscript.model.datatypes.VimString
import java.awt.event.KeyEvent import java.awt.event.KeyEvent
import javax.swing.JComponent
import javax.swing.JTree
import javax.swing.KeyStroke import javax.swing.KeyStroke
import javax.swing.SwingConstants import javax.swing.SwingConstants
@@ -128,14 +130,15 @@ internal class NerdTree : VimExtension {
addCommand("NERDTreeFind", IjCommandHandler("SelectInProjectView")) addCommand("NERDTreeFind", IjCommandHandler("SelectInProjectView"))
addCommand("NERDTreeRefreshRoot", IjCommandHandler("Synchronize")) addCommand("NERDTreeRefreshRoot", IjCommandHandler("Synchronize"))
synchronized(Util.monitor) { synchronized(monitor) {
Util.commandsRegistered = true commandsRegistered = true
ProjectManager.getInstance().openProjects.forEach { project -> installDispatcher(project) }
} }
} }
class IjCommandHandler(private val actionId: String) : CommandAliasHandler { class IjCommandHandler(private val actionId: String) : CommandAliasHandler {
override fun execute(command: String, ranges: Ranges, editor: VimEditor, context: ExecutionContext) { override fun execute(command: String, ranges: Ranges, editor: VimEditor, context: ExecutionContext) {
Util.callAction(editor, actionId, context) callAction(editor, actionId, context)
} }
} }
@@ -146,7 +149,7 @@ internal class NerdTree : VimExtension {
if (toolWindow.isVisible) { if (toolWindow.isVisible) {
toolWindow.hide() toolWindow.hide()
} else { } else {
Util.callAction(editor, "ActivateProjectToolWindow", context) callAction(editor, "ActivateProjectToolWindow", context)
} }
} }
} }
@@ -161,8 +164,39 @@ internal class NerdTree : VimExtension {
} }
} }
class ProjectViewListener(private val project: Project) : ToolWindowManagerListener {
override fun toolWindowShown(toolWindow: ToolWindow) {
if (ToolWindowId.PROJECT_VIEW != toolWindow.id) return
val dispatcher = NerdDispatcher.getInstance(project)
if (dispatcher.speedSearchListenerInstalled) return
// I specify nullability explicitly as we've got a lot of exceptions saying this property is null
val currentProjectViewPane: AbstractProjectViewPane? = ProjectView.getInstance(project).currentProjectViewPane
val tree = currentProjectViewPane?.tree ?: return
val supply = SpeedSearchSupply.getSupply(tree, true) ?: return
// NB: Here might be some issues with concurrency, but it's not really bad, I think
dispatcher.speedSearchListenerInstalled = true
supply.addChangeListener {
dispatcher.waitForSearch = false
}
}
}
// TODO I'm not sure is this activity runs at all? Should we use [RunOnceUtil] instead?
class NerdStartupActivity : ProjectActivity {
override suspend fun execute(project: Project) {
synchronized(monitor) {
if (!commandsRegistered) return
installDispatcher(project)
}
}
}
class NerdDispatcher : DumbAwareAction() { class NerdDispatcher : DumbAwareAction() {
internal var waitForSearch = false internal var waitForSearch = false
internal var speedSearchListenerInstalled = false
override fun actionPerformed(e: AnActionEvent) { override fun actionPerformed(e: AnActionEvent) {
var keyStroke = getKeyStroke(e) ?: return var keyStroke = getKeyStroke(e) ?: return
@@ -180,7 +214,7 @@ internal class NerdTree : VimExtension {
val action = nextNode.actionHolder val action = nextNode.actionHolder
when (action) { when (action) {
is NerdAction.ToIj -> Util.callAction(null, action.name, e.dataContext.vim) is NerdAction.ToIj -> callAction(null, action.name, e.dataContext.vim)
is NerdAction.Code -> e.project?.let { action.action(it, e.dataContext, e) } is NerdAction.Code -> e.project?.let { action.action(it, e.dataContext, e) }
} }
} }
@@ -210,6 +244,10 @@ internal class NerdTree : VimExtension {
} }
companion object { companion object {
fun getInstance(project: Project): NerdDispatcher {
return project.getService(NerdDispatcher::class.java)
}
private const val ESCAPE_KEY_CODE = 27 private const val ESCAPE_KEY_CODE = 27
} }
@@ -245,14 +283,19 @@ internal class NerdTree : VimExtension {
registerCommand( registerCommand(
"NERDTreeMapActivateNode", "NERDTreeMapActivateNode",
"o", "o",
NerdAction.Code { _, dataContext, e -> NerdAction.Code { project, dataContext, _ ->
val tree = getTree(e) ?: return@Code val tree = ProjectView.getInstance(project).currentProjectViewPane.tree
val row = tree.selectionRows?.getOrNull(0) ?: return@Code val array = CommonDataKeys.NAVIGATABLE_ARRAY.getData(dataContext)?.filter { it.canNavigateToSource() }
if (tree.isExpanded(row)) { if (array.isNullOrEmpty()) {
tree.collapseRow(row) val row = tree.selectionRows?.getOrNull(0) ?: return@Code
if (tree.isExpanded(row)) {
tree.collapseRow(row)
} else {
tree.expandRow(row)
}
} else { } else {
tree.expandRow(row) array.forEach { it.navigate(true) }
} }
}, },
) )
@@ -313,7 +356,7 @@ internal class NerdTree : VimExtension {
currentWindow?.split(SwingConstants.VERTICAL, true, file, true) currentWindow?.split(SwingConstants.VERTICAL, true, file, true)
// FIXME: 22.01.2021 This solution bouncing a bit // FIXME: 22.01.2021 This solution bouncing a bit
Util.callAction(null, "ActivateProjectToolWindow", context.vim) callAction(null, "ActivateProjectToolWindow", context.vim)
}, },
) )
registerCommand( registerCommand(
@@ -325,14 +368,14 @@ internal class NerdTree : VimExtension {
val currentWindow = splitters.currentWindow val currentWindow = splitters.currentWindow
currentWindow?.split(SwingConstants.HORIZONTAL, true, file, true) currentWindow?.split(SwingConstants.HORIZONTAL, true, file, true)
Util.callAction(null, "ActivateProjectToolWindow", context.vim) callAction(null, "ActivateProjectToolWindow", context.vim)
}, },
) )
registerCommand( registerCommand(
"NERDTreeMapOpenRecursively", "NERDTreeMapOpenRecursively",
"O", "O",
NerdAction.Code { _, _, e -> NerdAction.Code { project, _, _ ->
val tree = getTree(e) ?: return@Code val tree = ProjectView.getInstance(project).currentProjectViewPane.tree
TreeExpandCollapse.expandAll(tree) TreeExpandCollapse.expandAll(tree)
tree.selectionPath?.let { tree.selectionPath?.let {
TreeUtil.scrollToVisible(tree, it, false) TreeUtil.scrollToVisible(tree, it, false)
@@ -342,8 +385,8 @@ internal class NerdTree : VimExtension {
registerCommand( registerCommand(
"NERDTreeMapCloseChildren", "NERDTreeMapCloseChildren",
"X", "X",
NerdAction.Code { _, _, e -> NerdAction.Code { project, _, _ ->
val tree = getTree(e) ?: return@Code val tree = ProjectView.getInstance(project).currentProjectViewPane.tree
TreeExpandCollapse.collapse(tree) TreeExpandCollapse.collapse(tree)
tree.selectionPath?.let { tree.selectionPath?.let {
TreeUtil.scrollToVisible(tree, it, false) TreeUtil.scrollToVisible(tree, it, false)
@@ -353,8 +396,8 @@ internal class NerdTree : VimExtension {
registerCommand( registerCommand(
"NERDTreeMapCloseDir", "NERDTreeMapCloseDir",
"x", "x",
NerdAction.Code { _, _, e -> NerdAction.Code { project, _, _ ->
val tree = getTree(e) ?: return@Code val tree = ProjectView.getInstance(project).currentProjectViewPane.tree
val currentPath = tree.selectionPath ?: return@Code val currentPath = tree.selectionPath ?: return@Code
if (tree.isExpanded(currentPath)) { if (tree.isExpanded(currentPath)) {
tree.collapsePath(currentPath) tree.collapsePath(currentPath)
@@ -372,8 +415,8 @@ internal class NerdTree : VimExtension {
registerCommand( registerCommand(
"NERDTreeMapJumpParent", "NERDTreeMapJumpParent",
"p", "p",
NerdAction.Code { _, _, e -> NerdAction.Code { project, _, _ ->
val tree = getTree(e) ?: return@Code val tree = ProjectView.getInstance(project).currentProjectViewPane.tree
val currentPath = tree.selectionPath ?: return@Code val currentPath = tree.selectionPath ?: return@Code
val parentPath = currentPath.parentPath ?: return@Code val parentPath = currentPath.parentPath ?: return@Code
if (parentPath.parentPath != null) { if (parentPath.parentPath != null) {
@@ -386,8 +429,8 @@ internal class NerdTree : VimExtension {
registerCommand( registerCommand(
"NERDTreeMapJumpFirstChild", "NERDTreeMapJumpFirstChild",
"K", "K",
NerdAction.Code { _, _, e -> NerdAction.Code { project, _, _ ->
val tree = getTree(e) ?: return@Code val tree = ProjectView.getInstance(project).currentProjectViewPane.tree
val currentPath = tree.selectionPath ?: return@Code val currentPath = tree.selectionPath ?: return@Code
val parent = currentPath.parentPath ?: return@Code val parent = currentPath.parentPath ?: return@Code
val row = tree.getRowForPath(parent) val row = tree.getRowForPath(parent)
@@ -399,8 +442,8 @@ internal class NerdTree : VimExtension {
registerCommand( registerCommand(
"NERDTreeMapJumpLastChild", "NERDTreeMapJumpLastChild",
"J", "J",
NerdAction.Code { _, _, e -> NerdAction.Code { project, _, _ ->
val tree = getTree(e) ?: return@Code val tree = ProjectView.getInstance(project).currentProjectViewPane.tree
val currentPath = tree.selectionPath ?: return@Code val currentPath = tree.selectionPath ?: return@Code
val currentPathCount = currentPath.pathCount val currentPathCount = currentPath.pathCount
@@ -421,12 +464,12 @@ internal class NerdTree : VimExtension {
) )
registerCommand( registerCommand(
"NERDTreeMapJumpNextSibling", "NERDTreeMapJumpNextSibling",
"<A-J>", "<C-J>",
NerdAction.ToIj("Tree-selectNextSibling"), NerdAction.ToIj("Tree-selectNextSibling"),
) )
registerCommand( registerCommand(
"NERDTreeMapJumpPrevSibling", "NERDTreeMapJumpPrevSibling",
"<A-K>", "<C-K>",
NerdAction.ToIj("Tree-selectPreviousSibling"), NerdAction.ToIj("Tree-selectPreviousSibling"),
) )
registerCommand( registerCommand(
@@ -445,31 +488,30 @@ internal class NerdTree : VimExtension {
registerCommand( registerCommand(
"/", "/",
NerdAction.Code { _, _, e -> NerdAction.Code { project, _, _ ->
val tree = getTree(e) ?: return@Code NerdDispatcher.getInstance(project).waitForSearch = true
tree.getUserData(KEY)?.waitForSearch = true
}, },
) )
registerCommand( registerCommand(
"<ESC>", "<ESC>",
NerdAction.Code { _, _, e -> NerdAction.Code { project, _, _ ->
val tree = getTree(e) ?: return@Code val instance = NerdDispatcher.getInstance(project)
tree.getUserData(KEY)?.waitForSearch = false if (instance.waitForSearch) {
instance.waitForSearch = false
}
}, },
) )
for (c in ('a'..'z') + ('A'..'Z')) {
val ks = KeyStroke.getKeyStroke(c)
if (ks !in actionsRoot) {
registerCommand(c.toString(), NerdAction.Code { _, _, _ -> })
}
}
} }
object Util { companion object {
const val pluginName = "NERDTree"
internal val monitor = Any() internal val monitor = Any()
internal var commandsRegistered = false internal var commandsRegistered = false
private val LOG = logger<NerdTree>()
fun callAction(editor: VimEditor?, name: String, context: ExecutionContext) { fun callAction(editor: VimEditor?, name: String, context: ExecutionContext) {
val action = ActionManager.getInstance().getAction(name) ?: run { val action = ActionManager.getInstance().getAction(name) ?: run {
VimPlugin.showMessage(MessageHelper.message("action.not.found.0", name)) VimPlugin.showMessage(MessageHelper.message("action.not.found.0", name))
@@ -484,60 +526,45 @@ internal class NerdTree : VimExtension {
} }
} }
} }
}
companion object { private fun addCommand(alias: String, handler: CommandAliasHandler) {
const val pluginName = "NERDTree" VimPlugin.getCommand().setAlias(alias, CommandAlias.Call(0, -1, alias, handler))
private val LOG = logger<NerdTree>() }
private val KEY = Key.create<NerdDispatcher>("IdeaVim-NerdTree-Dispatcher")
fun installDispatcher(component: JComponent) { private fun registerCommand(variable: String, default: String, action: NerdAction) {
if (component.getUserData(KEY) != null) return val variableValue = VimPlugin.getVariableService().getGlobalVariableValue(variable)
val mappings = if (variableValue is VimString) {
val dispatcher = NerdDispatcher() variableValue.value
component.putUserData(KEY, dispatcher) } else {
default
val shortcuts = collectShortcuts(actionsRoot).map { RequiredShortcut(it, MappingOwner.Plugin.get(pluginName)) }
dispatcher.registerCustomShortcutSet(KeyGroup.toShortcutSet(shortcuts), component)
SpeedSearchSupply.getSupply(component, true)?.addChangeListener {
dispatcher.waitForSearch = false
} }
actionsRoot.addLeafs(mappings, action)
}
private fun registerCommand(default: String, action: NerdAction) {
actionsRoot.addLeafs(default, action)
}
private val actionsRoot: RootNode<NerdAction> = RootNode()
private var currentNode: CommandPartNode<NerdAction> = actionsRoot
private fun collectShortcuts(node: Node<NerdAction>): Set<KeyStroke> {
return if (node is CommandPartNode<NerdAction>) {
val res = node.keys.toMutableSet()
res += node.values.map { collectShortcuts(it) }.flatten()
res
} else {
emptySet()
}
}
private fun installDispatcher(project: Project) {
val dispatcher = NerdDispatcher.getInstance(project)
val shortcuts = collectShortcuts(actionsRoot).map { RequiredShortcut(it, MappingOwner.Plugin.get(pluginName)) }
dispatcher.registerCustomShortcutSet(
KeyGroup.toShortcutSet(shortcuts),
(ProjectView.getInstance(project) as ProjectViewImpl).component,
)
} }
} }
} }
private fun addCommand(alias: String, handler: CommandAliasHandler) {
VimPlugin.getCommand().setAlias(alias, CommandAlias.Call(0, -1, alias, handler))
}
private fun registerCommand(variable: String, default: String, action: NerdAction) {
val variableValue = VimPlugin.getVariableService().getGlobalVariableValue(variable)
val mappings = if (variableValue is VimString) {
variableValue.value
} else {
default
}
actionsRoot.addLeafs(mappings, action)
}
private fun registerCommand(default: String, action: NerdAction) {
actionsRoot.addLeafs(default, action)
}
private val actionsRoot: RootNode<NerdAction> = RootNode()
private var currentNode: CommandPartNode<NerdAction> = actionsRoot
private fun collectShortcuts(node: Node<NerdAction>): Set<KeyStroke> {
return if (node is CommandPartNode<NerdAction>) {
val res = node.keys.toMutableSet()
res += node.values.map { collectShortcuts(it) }.flatten()
res
} else {
emptySet()
}
}
private fun getTree(e: AnActionEvent): JTree? {
return e.dataContext.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT) as? JTree
}

View File

@@ -1,25 +0,0 @@
package com.maddyhome.idea.vim.extension.nerdtree
import com.intellij.ide.ApplicationInitializedListener
import com.intellij.openapi.application.ApplicationManager
import com.intellij.util.ui.StartupUiUtil
import kotlinx.coroutines.CoroutineScope
import java.awt.AWTEvent
import java.awt.event.FocusEvent
import javax.swing.JTree
@Suppress("UnstableApiUsage")
internal class NerdTreeApplicationListener : ApplicationInitializedListener {
override suspend fun execute(asyncScope: CoroutineScope) {
StartupUiUtil.addAwtListener(::handleEvent, AWTEvent.FOCUS_EVENT_MASK, ApplicationManager.getApplication().getService(NerdTreeDisposableService::class.java))
}
private fun handleEvent(event: AWTEvent) {
if (event is FocusEvent && event.id == FocusEvent.FOCUS_GAINED) {
val source = event.source
if (source is JTree) {
NerdTree.installDispatcher(source)
}
}
}
}

View File

@@ -1,9 +0,0 @@
package com.maddyhome.idea.vim.extension.nerdtree
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.Service
@Service
internal class NerdTreeDisposableService : Disposable {
override fun dispose() {}
}

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