1
0
mirror of https://github.com/chylex/IntelliJ-AceJump.git synced 2025-09-15 22:32:11 +02:00

50 Commits

Author SHA1 Message Date
568128f474 Set version to chylex-26 2024-10-31 03:57:33 +01:00
018d29007c Add option to invert behavior of holding Shift when searching, and toggle with Enter 2024-10-31 03:57:33 +01:00
cb814e0999 Set version to chylex-25 2024-09-05 09:11:05 +02:00
1fc06e8120 Update for latest IdeaVim 2024-09-05 09:10:21 +02:00
841f2fd125 Set version to chylex-24 2024-09-05 06:44:02 +02:00
6c8f19e311 Fix edge case where generated tags may have a double character tag that is the only tag starting with its first character 2024-09-05 06:43:41 +02:00
ce4f3b5f03 Fix IntelliJ SDK warning about services in class initializer 2024-09-05 02:44:39 +02:00
46f42c88eb Optimize screen visibility checks during search
Search results are tested for visibility on the screen. There is already an optimization that only checks results on visible lines, but the number of offset-to-XY conversions still scales linearly with the number of results, which can be very large in files with long lines.

A simple observation is that every line has a first and last offset that is visible on the screen (which may be different for each line due to proportional fonts).

This commit caches the visible offset range for every line involved in one search query, so testing visibility of a search result becomes a check if its offset is inside its line's visible offset range. Finding the visible offset range requires two XY-to-offset conversions per line, so the total number of conversions is bounded by the number of lines that can fit on the screen.

The worst case for this optimization is when every line has exactly one search result; before, this would lead to one offset-to-XY conversion per line, whereas now it leads to two XY-to-offset conversions per line. However, the maximum number of conversions is twice the number of visible lines, which will generally be very small.
2024-09-05 02:12:48 +02:00
43dfec940e Set version to chylex-23 2024-09-04 11:40:16 +02:00
abe06ec7be Increase width of editor fade opacity slider 2024-09-04 11:39:59 +02:00
3fc3cbc7f8 Optimize tagging 2024-09-04 11:33:26 +02:00
5979579042 Set version to chylex-22 2024-09-04 08:50:33 +02:00
ea61d49aa6 Refactor TagMarker to reduce allocations during rendering 2024-09-04 08:50:13 +02:00
dbc6db108d Redo tag generation (eliminate explicit prefix chars) 2024-09-04 08:44:52 +02:00
01c38df82a Search in the middle of words again unless pressing an uppercase letter, and rebind Space to cycling search boundaries 2024-09-03 21:50:03 +02:00
a3a86cf447 Update for IDEA 2024.2 2024-09-03 20:58:08 +02:00
59fbd4e19c Set version to chylex-21 2024-07-15 13:46:02 +02:00
6e08d56cdf Update for IDEA 2024.1 & latest IdeaVim 2024-07-15 13:45:39 +02:00
9a14fb87e3 Set version to chylex-20 2024-03-27 13:53:41 +01:00
d22bcc220e Update IdeaVim integration 2024-03-27 13:53:25 +01:00
1f76a8bd25 Set version to chylex-19 2023-12-29 21:45:12 +01:00
2e31ddd504 Use top row remapping only for tags 2023-12-29 21:45:12 +01:00
47a34f6f14 Disable searching in the middle of a word unless Space is pressed when typing tag 2023-12-29 21:45:12 +01:00
575283b2be Set version to chylex-18 2023-12-18 05:25:09 +01:00
8bb34d7f75 Make editor fade opacity configurable 2023-12-18 05:24:57 +01:00
8d1ef031d2 Set version to chylex-17 2023-12-18 03:44:20 +01:00
a9375ec414 Remove unused code 2023-12-18 03:44:01 +01:00
b42112cc9e Do not try to tag folded regions 2023-12-18 02:36:41 +01:00
8e42c82821 Use distance from current caret for tag order 2023-12-18 02:32:54 +01:00
48bcf9f284 Add QWERTZ (CZ) layout that remaps top row to digits 2023-12-18 00:58:37 +01:00
2681d9901f Change priority order of two-character tags 2023-12-18 00:45:28 +01:00
b13d629046 Add option to set different colors for two-character tags 2023-12-17 22:41:36 +01:00
92dcd033fb Make priority of unknown characters lower than known characters 2023-12-17 21:49:24 +01:00
fa3505b850 Set version to chylex-16 2023-12-14 00:09:49 +01:00
dacac684f0 Make two-character tag prefixes customizable 2023-12-14 00:09:27 +01:00
e627db3a24 Fix Shift mode not working when accepting a tag 2023-12-13 22:52:18 +01:00
084d729baa Set version to chylex-15 2023-12-13 20:16:51 +01:00
e01edccb5b Redesign tags to look like easymotion vim plugin 2023-12-13 20:16:13 +01:00
655ccde60e Work around IntelliJ terminal plugin stealing Enter keys 2023-12-13 17:48:23 +01:00
eb2ea55fb8 Rework tagging to match easymotion (no search query refinement, no double letter tags) 2023-12-13 15:19:57 +01:00
a6381a2a34 Update Gradle to 8.5 and IntelliJ to 2023.3 2023-12-12 23:19:03 +01:00
e005983d4c Set version to chylex-14 2023-11-17 08:56:13 +01:00
8f4d9748ad Scroll after jumping in vim mode 2023-11-17 08:55:49 +01:00
76c6458ef4 Re-add action to go to declaration after jump 2023-11-17 08:52:46 +01:00
2f53e9da6d Update for IdeaVIM chylex-20 2023-11-17 08:52:23 +01:00
100001ffca Set version to chylex-13 2023-10-04 02:41:33 +02:00
184896a6cb Update for IdeaVIM chylex-16 2023-10-04 02:41:05 +02:00
8563400946 Set plugin version to chylex-12 2023-10-04 02:40:51 +02:00
a07c61a384 Fully depend on IdeaVIM and remake actions 2023-07-28 07:50:39 +02:00
e072003c5c Update dependency versions and gitignore 2023-07-27 22:07:17 +02:00
45 changed files with 1090 additions and 1606 deletions

23
.gitignore vendored
View File

@@ -1,20 +1,5 @@
### JetBrains template /.idea/*
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio !/.idea/runConfigurations
## Directory-based project format: /.gradle/
.idea /build/
*.iml
## Plugin-specific files:
# IntelliJ
/out/
### Gradle template
.gradle
build/
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
# Mac OS
.DS_Store

View File

@@ -1,26 +1,54 @@
@file:Suppress("ConvertLambdaToReference")
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins { plugins {
idea kotlin("jvm") version "1.9.10"
kotlin("jvm") version "1.5.10" id("org.jetbrains.intellij") version "1.17.3"
id("org.jetbrains.intellij") version "1.11.0"
} }
group = "org.acejump"
version = "chylex-26"
repositories { repositories {
mavenCentral() mavenCentral()
} }
intellij { intellij {
version.set("2022.3.1") version.set("2024.2")
updateSinceUntilBuild.set(false) updateSinceUntilBuild.set(false)
pluginsRepositories.custom("https://intellij.chylex.com")
plugins.add("IdeaVIM:chylex-15") plugins.add("IdeaVIM:chylex-41")
plugins.add("com.intellij.classic.ui:242.20224.159")
pluginsRepositories {
custom("https://intellij.chylex.com")
marketplace()
}
}
kotlin {
jvmToolchain(17)
}
dependencies {
testImplementation("org.junit.jupiter:junit-jupiter:5.9.2")
}
tasks.patchPluginXml {
sinceBuild.set("242")
}
tasks.buildSearchableOptions {
enabled = false
}
tasks.test {
useJUnitPlatform()
} }
tasks.withType<KotlinCompile> { tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "11" kotlinOptions.freeCompilerArgs = listOf(
kotlinOptions.freeCompilerArgs = listOf("-Xjvm-default=all") "-Xjvm-default=all"
)
} }
group = "org.acejump"
version = "chylex-11"

Binary file not shown.

View File

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

294
gradlew vendored
View File

@@ -1,7 +1,7 @@
#!/usr/bin/env sh #!/bin/sh
# #
# Copyright 2015 the original author or authors. # Copyright © 2015-2021 the original authors.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -17,67 +17,99 @@
# #
############################################################################## ##############################################################################
## #
## Gradle start up script for UN*X # Gradle start up script for POSIX generated by Gradle.
## #
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
############################################################################## ##############################################################################
# Attempt to set APP_HOME # Attempt to set APP_HOME
# Resolve links: $0 may be a link # Resolve links: $0 may be a link
PRG="$0" app_path=$0
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do # Need this for daisy-chained symlinks.
ls=`ls -ld "$PRG"` while
link=`expr "$ls" : '.*-> \(.*\)$'` APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
if expr "$link" : '/.*' > /dev/null; then [ -h "$app_path" ]
PRG="$link" do
else ls=$( ls -ld "$app_path" )
PRG=`dirname "$PRG"`"/$link" link=${ls#*' -> '}
fi case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle" # This is normally unused
APP_BASE_NAME=`basename "$0"` # shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum" MAX_FD=maximum
warn () { warn () {
echo "$*" echo "$*"
} } >&2
die () { die () {
echo echo
echo "$*" echo "$*"
echo echo
exit 1 exit 1
} } >&2
# OS specific support (must be 'true' or 'false'). # OS specific support (must be 'true' or 'false').
cygwin=false cygwin=false
msys=false msys=false
darwin=false darwin=false
nonstop=false nonstop=false
case "`uname`" in case "$( uname )" in #(
CYGWIN* ) CYGWIN* ) cygwin=true ;; #(
cygwin=true Darwin* ) darwin=true ;; #(
;; MSYS* | MINGW* ) msys=true ;; #(
Darwin* ) NONSTOP* ) nonstop=true ;;
darwin=true
;;
MSYS* | MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
@@ -87,9 +119,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
if [ -n "$JAVA_HOME" ] ; then if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables # IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java" JAVACMD=$JAVA_HOME/jre/sh/java
else else
JAVACMD="$JAVA_HOME/bin/java" JAVACMD=$JAVA_HOME/bin/java
fi fi
if [ ! -x "$JAVACMD" ] ; then if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@@ -98,88 +130,120 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi fi
else else
JAVACMD="java" JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. if ! command -v java >/dev/null 2>&1
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.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
MAX_FD_LIMIT=`ulimit -H -n` case $MAX_FD in #(
if [ $? -eq 0 ] ; then max*)
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
MAX_FD="$MAX_FD_LIMIT" # shellcheck disable=SC2039,SC3045
fi MAX_FD=$( ulimit -H -n ) ||
ulimit -n $MAX_FD warn "Could not query maximum file descriptor limit"
if [ $? -ne 0 ] ; then esac
warn "Could not set maximum file descriptor limit: $MAX_FD" case $MAX_FD in #(
fi '' | soft) :;; #(
else *)
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
fi # shellcheck disable=SC2039,SC3045
fi ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac esac
fi fi
# Escape application args # Collect all arguments for the java command, stacking in reverse order:
save () { # * args from the command line
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done # * the main class name
echo " " # * -classpath
} # * -D...appname settings
APP_ARGS=`save "$@"` # * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# Collect all arguments for the java command, following the shell quoting and substitution rules # For Cygwin or MSYS, switch paths to Windows format before running java
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@" exec "$JAVACMD" "$@"

11
gradlew.bat vendored
View File

@@ -26,6 +26,7 @@ if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0 set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=. if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0 set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME% set APP_HOME=%DIRNAME%
@@ -40,7 +41,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1 %JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute if %ERRORLEVEL% equ 0 goto execute
echo. echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
@@ -75,13 +76,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
:end :end
@rem End local scope for the variables with windows NT shell @rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd if %ERRORLEVEL% equ 0 goto mainEnd
:fail :fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code! rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 set EXIT_CODE=%ERRORLEVEL%
exit /b 1 if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd :mainEnd
if "%OS%"=="Windows_NT" endlocal if "%OS%"=="Windows_NT" endlocal

View File

@@ -0,0 +1,13 @@
package org.acejump.action;
import com.maddyhome.idea.vim.VimPlugin;
import com.maddyhome.idea.vim.api.VimEditor;
import com.maddyhome.idea.vim.state.mode.SelectionType;
final class AceVimUtil {
private AceVimUtil() {}
public static void enterVisualMode(final VimEditor vim, final SelectionType mode) {
VimPlugin.getVisualMotion().enterVisualMode(vim, mode);
}
}

View File

@@ -7,8 +7,6 @@ import com.intellij.openapi.project.Project
import com.intellij.util.IncorrectOperationException import com.intellij.util.IncorrectOperationException
import it.unimi.dsi.fastutil.ints.IntArrayList import it.unimi.dsi.fastutil.ints.IntArrayList
annotation class ExternalUsage
/** /**
* Returns an immutable version of the currently edited document. * Returns an immutable version of the currently edited document.
*/ */
@@ -23,7 +21,7 @@ val Project.openEditors: List<Editor>
return try { return try {
FileEditorManagerEx.getInstanceEx(this) FileEditorManagerEx.getInstanceEx(this)
.splitters .splitters
.selectedEditors .getSelectedEditors()
.mapNotNull { (it as? TextEditor)?.editor } .mapNotNull { (it as? TextEditor)?.editor }
} catch (e: IncorrectOperationException) { } catch (e: IncorrectOperationException) {
emptyList() emptyList()
@@ -52,57 +50,6 @@ fun CharSequence.countMatchingCharacters(selfOffset: Int, otherText: String): In
return i return i
} }
/**
* Determines which characters form a "word" for the purposes of functions below.
*/
val Char.isWordPart
get() = this in 'a'..'z' || this.isJavaIdentifierPart()
/**
* Finds index of the first character in a word.
*/
inline fun CharSequence.wordStart(pos: Int, isPartOfWord: (Char) -> Boolean = Char::isWordPart): Int {
var start = pos
while (start > 0 && isPartOfWord(this[start - 1])) {
--start
}
return start
}
/**
* Finds index of the last character in a word.
*/
inline fun CharSequence.wordEnd(pos: Int, isPartOfWord: (Char) -> Boolean = Char::isWordPart): Int {
var end = pos
val limit = length - 1
while (end < limit && isPartOfWord(this[end + 1])) {
++end
}
return end
}
/**
* Finds index of the first word character following a sequence of non-word characters following the end of a word.
*/
inline fun CharSequence.wordEndPlus(pos: Int, isPartOfWord: (Char) -> Boolean = Char::isWordPart): Int {
var end = this.wordEnd(pos, isPartOfWord)
val limit = length - 1
while (end < limit && !isPartOfWord(this[end + 1])) {
++end
}
if (end < limit && isPartOfWord(this[end + 1])) {
++end
}
return end
}
fun MutableMap<Editor, IntArrayList>.clone(): MutableMap<Editor, IntArrayList> { fun MutableMap<Editor, IntArrayList>.clone(): MutableMap<Editor, IntArrayList> {
val clone = HashMap<Editor, IntArrayList>(size) val clone = HashMap<Editor, IntArrayList>(size)

View File

@@ -1,52 +0,0 @@
package org.acejump.action
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys.EDITOR
import com.intellij.openapi.project.DumbAwareAction
import org.acejump.boundaries.Boundaries
import org.acejump.openEditors
import org.acejump.search.Pattern
import org.acejump.session.Session
import org.acejump.session.SessionManager
/**
* Base class for keyboard-activated actions that create or update an AceJump [Session].
*/
abstract class AceKeyboardAction : DumbAwareAction() {
final override fun update(action: AnActionEvent) {
action.presentation.isEnabled = action.getData(EDITOR) != null
}
final override fun actionPerformed(e: AnActionEvent) {
val editor = e.getData(EDITOR) ?: return
val project = e.project
if (project != null) {
val jumpEditors = project.openEditors
.sortedBy { if (it === editor) 0 else 1 }
.ifEmpty { listOf(editor) }
invoke(SessionManager.start(editor, jumpEditors))
}
else {
invoke(SessionManager.start(editor))
}
}
abstract operator fun invoke(session: Session)
/**
* Generic action type that starts a regex search.
*/
abstract class BaseRegexSearchAction(private val pattern: Pattern, private val boundaries: Boundaries) : AceKeyboardAction() {
override fun invoke(session: Session) {
session.defaultBoundary = boundaries
session.startRegexSearch(pattern)
}
}
/**
* Starts or ends an AceJump session in quick jump mode.
*/
object ActivateAceJump : AceKeyboardAction() {
override fun invoke(session: Session) = session.startJumpMode()
}
}

View File

@@ -1,6 +1,5 @@
package org.acejump.action package org.acejump.action
import com.intellij.find.actions.ShowUsagesAction
import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationManager
@@ -14,60 +13,35 @@ import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory
import com.intellij.openapi.project.Project import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.playback.commands.ActionCommand import com.intellij.openapi.ui.playback.commands.ActionCommand
import org.acejump.countMatchingCharacters import org.acejump.search.Tag
import org.acejump.immutableText
import org.acejump.isWordPart
import org.acejump.search.SearchProcessor
import org.acejump.wordStart
/** /**
* Base class for actions available after typing a tag. * Base class for actions available after typing a tag.
*/ */
sealed class AceTagAction { sealed class AceTagAction {
abstract operator fun invoke(editor: Editor, searchProcessor: SearchProcessor, offset: Int, shiftMode: Boolean, isFinal: Boolean) abstract operator fun invoke(tag: Tag, shiftMode: Boolean, isFinal: Boolean)
abstract class BaseJumpAction : AceTagAction() { abstract class BaseJumpAction : AceTagAction() {
override fun invoke(editor: Editor, searchProcessor: SearchProcessor, offset: Int, shiftMode: Boolean, isFinal: Boolean) { override fun invoke(tag: Tag, shiftMode: Boolean, isFinal: Boolean) {
val editor = tag.editor
val caretModel = editor.caretModel val caretModel = editor.caretModel
val oldCarets = if (shiftMode) caretModel.caretsAndSelections else emptyList() val oldCarets = if (shiftMode) caretModel.caretsAndSelections else emptyList()
recordCaretPosition(editor) editor.project?.let { addCurrentPositionToHistory(it, editor.document) }
if (isFinal) { if (isFinal) {
ensureEditorFocused(editor) ensureEditorFocused(editor)
} }
moveCaretTo(editor, getCaretOffset(editor, searchProcessor, offset)) moveCaretTo(editor, tag.offset)
if (shiftMode) { if (shiftMode) {
caretModel.caretsAndSelections = oldCarets + caretModel.caretsAndSelections caretModel.caretsAndSelections = oldCarets + caretModel.caretsAndSelections
} }
} }
abstract fun getCaretOffset(editor: Editor, searchProcessor: SearchProcessor, offset: Int): Int
}
abstract class BaseWordAction : BaseJumpAction() {
final override fun getCaretOffset(editor: Editor, searchProcessor: SearchProcessor, offset: Int): Int {
val matchingChars = countMatchingCharacters(editor, searchProcessor, offset)
val targetOffset = offset + matchingChars
val isInsideWord = matchingChars > 0 && editor.immutableText.let { it[targetOffset - 1].isWordPart && it[targetOffset].isWordPart }
return getCaretOffset(editor, offset, targetOffset, isInsideWord)
}
abstract fun getCaretOffset(editor: Editor, queryStartOffset: Int, queryEndOffset: Int, isInsideWord: Boolean): Int
} }
private companion object { private companion object {
fun countMatchingCharacters(editor: Editor, searchProcessor: SearchProcessor, offset: Int): Int {
return editor.immutableText.countMatchingCharacters(offset, searchProcessor.query.rawText)
}
fun recordCaretPosition(editor: Editor) = with(editor) {
project?.let { addCurrentPositionToHistory(it, document) }
}
fun moveCaretTo(editor: Editor, offset: Int) = with(editor) { fun moveCaretTo(editor: Editor, offset: Int) = with(editor) {
selectionModel.removeSelection(true) selectionModel.removeSelection(true)
caretModel.removeSecondaryCarets() caretModel.removeSecondaryCarets()
@@ -86,7 +60,7 @@ sealed class AceTagAction {
val project = editor.project ?: return val project = editor.project ?: return
val fem = FileEditorManagerEx.getInstanceEx(project) val fem = FileEditorManagerEx.getInstanceEx(project)
val window = fem.windows.firstOrNull { (it.selectedEditor?.selectedWithProvider?.fileEditor as? TextEditor)?.editor === editor } val window = fem.windows.firstOrNull { (it.selectedComposite?.selectedWithProvider?.fileEditor as? TextEditor)?.editor === editor }
if (window != null && window !== fem.currentWindow) { if (window != null && window !== fem.currentWindow) {
fem.currentWindow = window fem.currentWindow = window
} }
@@ -109,27 +83,7 @@ sealed class AceTagAction {
* On default action, places the caret at the first character of the search query. * On default action, places the caret at the first character of the search query.
* On shift action, adds the new caret to existing carets. * On shift action, adds the new caret to existing carets.
*/ */
object JumpToSearchStart : BaseJumpAction() { object JumpToSearchStart : BaseJumpAction()
override fun getCaretOffset(editor: Editor, searchProcessor: SearchProcessor, offset: Int): Int {
return offset
}
}
/**
* On default action, places the caret at the start of a word. Word detection uses [Character.isJavaIdentifierPart] to count some special
* characters, such as underscores, as part of a word. If there is no word at the last character of the search query, then the caret is
* placed at the first character of the search query.
*
* On shift action, adds the new caret to existing carets.
*/
object JumpToWordStart : BaseWordAction() {
override fun getCaretOffset(editor: Editor, queryStartOffset: Int, queryEndOffset: Int, isInsideWord: Boolean): Int {
return if (isInsideWord)
editor.immutableText.wordStart(queryEndOffset)
else
queryStartOffset
}
}
/** /**
* On default action, performs the Go To Declaration action, available via `Navigate | Declaration or Usages`. * On default action, performs the Go To Declaration action, available via `Navigate | Declaration or Usages`.
@@ -137,44 +91,9 @@ sealed class AceTagAction {
* Always places the caret at the start of the word. * Always places the caret at the start of the word.
*/ */
object GoToDeclaration : AceTagAction() { object GoToDeclaration : AceTagAction() {
override fun invoke(editor: Editor, searchProcessor: SearchProcessor, offset: Int, shiftMode: Boolean, isFinal: Boolean) { override fun invoke(tag: Tag, shiftMode: Boolean, isFinal: Boolean) {
JumpToWordStart(editor, searchProcessor, offset, shiftMode = false, isFinal = isFinal) JumpToSearchStart.invoke(tag, shiftMode = false, isFinal = isFinal)
ApplicationManager.getApplication().invokeLater { performAction(if (shiftMode) IdeActions.ACTION_GOTO_TYPE_DECLARATION else IdeActions.ACTION_GOTO_DECLARATION) } ApplicationManager.getApplication().invokeLater { performAction(if (shiftMode) IdeActions.ACTION_GOTO_TYPE_DECLARATION else IdeActions.ACTION_GOTO_DECLARATION) }
} }
} }
/**
* On default action, performs the Show Usages action, available via the context menu.
* On shift action, performs the Find Usages action, available via the context menu.
* Always places the caret at the start of the word.
*/
object ShowUsages : AceTagAction() {
override fun invoke(editor: Editor, searchProcessor: SearchProcessor, offset: Int, shiftMode: Boolean, isFinal: Boolean) {
JumpToWordStart(editor, searchProcessor, offset, shiftMode = false, isFinal = isFinal)
ApplicationManager.getApplication().invokeLater { performAction(if (shiftMode) IdeActions.ACTION_FIND_USAGES else ShowUsagesAction.ID) }
}
}
/**
* Performs the Show Context Actions action, available via the context menu or Alt+Enter.
* Always places the caret at the start of the word.
*/
object ShowIntentions : AceTagAction() {
override fun invoke(editor: Editor, searchProcessor: SearchProcessor, offset: Int, shiftMode: Boolean, isFinal: Boolean) {
JumpToWordStart(editor, searchProcessor, offset, shiftMode = false, isFinal = isFinal)
ApplicationManager.getApplication().invokeLater { performAction(IdeActions.ACTION_SHOW_INTENTION_ACTIONS) }
}
}
/**
* On default action, performs the Refactor This action, available via the main menu.
* On shift action, performs the Rename... refactoring, available via the main menu.
* Always places the caret at the start of the word.
*/
object Refactor : AceTagAction() {
override fun invoke(editor: Editor, searchProcessor: SearchProcessor, offset: Int, shiftMode: Boolean, isFinal: Boolean) {
JumpToWordStart(editor, searchProcessor, offset, shiftMode = false, isFinal = isFinal)
ApplicationManager.getApplication().invokeLater { performAction(if (shiftMode) IdeActions.ACTION_RENAME else "Refactorings.QuickListPopupAction") }
}
}
} }

View File

@@ -1,66 +1,189 @@
package org.acejump.action package org.acejump.action
import org.acejump.boundaries.Boundaries import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.project.DumbAwareAction
import com.maddyhome.idea.vim.KeyHandler
import com.maddyhome.idea.vim.action.change.change.ChangeVisualAction
import com.maddyhome.idea.vim.action.change.delete.DeleteVisualAction
import com.maddyhome.idea.vim.action.copy.YankVisualAction
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.group.visual.vimSetSelection
import com.maddyhome.idea.vim.helper.inVisualMode
import com.maddyhome.idea.vim.helper.vimSelectionStart
import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.state.mode.Mode.OP_PENDING
import com.maddyhome.idea.vim.state.mode.SelectionType
import org.acejump.boundaries.StandardBoundaries.AFTER_CARET
import org.acejump.boundaries.StandardBoundaries.BEFORE_CARET
import org.acejump.boundaries.StandardBoundaries.CARET_LINE
import org.acejump.boundaries.StandardBoundaries.VISIBLE_ON_SCREEN import org.acejump.boundaries.StandardBoundaries.VISIBLE_ON_SCREEN
import org.acejump.modes.ActionMode import org.acejump.modes.JumpMode
import org.acejump.session.Session import org.acejump.search.Pattern
import org.acejump.search.Tag
import org.acejump.session.SessionManager
import org.acejump.session.SessionState
sealed class AceVimAction : AceKeyboardAction() { sealed class AceVimAction : DumbAwareAction() {
protected abstract val boundary: Boundaries protected abstract val mode: AceVimMode
final override fun invoke(session: Session) { final override fun actionPerformed(e: AnActionEvent) {
session.defaultBoundary = boundary val editor = e.getData(CommonDataKeys.EDITOR) ?: return
start(session) val context = e.dataContext.vim
val caret = editor.caretModel.currentCaret
val initialOffset = caret.offset
val selectionStart = if (editor.inVisualMode) caret.vimSelectionStart else null
val session = SessionManager.start(editor, mode.getJumpEditors(editor))
session.defaultBoundary = mode.boundaries
session.startJumpMode {
object : JumpMode() {
override fun accept(state: SessionState, acceptedTag: Tag) {
AceTagAction.JumpToSearchStart.invoke(acceptedTag, shiftMode = wasUpperCase, isFinal = true)
if (selectionStart != null) {
caret.vim.vimSetSelection(selectionStart, caret.offset, moveCaretToSelectionEnd = true)
}
else {
val vim = editor.vim
if (vim.mode is OP_PENDING) {
val keyHandler = KeyHandler.getInstance()
val key = keyHandler.keyHandlerState.commandBuilder.keys.singleOrNull()?.keyChar
keyHandler.fullReset(vim)
AceVimUtil.enterVisualMode(vim, SelectionType.CHARACTER_WISE)
caret.vim.vimSetSelection(caret.offset, initialOffset, moveCaretToSelectionEnd = true)
val action = when (key) {
'd' -> DeleteVisualAction()
'c' -> ChangeVisualAction()
'y' -> YankVisualAction()
else -> null
} }
protected abstract fun start(session: Session) if (action != null) {
ApplicationManager.getApplication().invokeLater {
WriteAction.run<Nothing> {
keyHandler.keyHandlerState.commandBuilder.addAction(action)
class GoToDeclaration : AceVimAction() { val cmd = keyHandler.keyHandlerState.commandBuilder.buildCommand()
override val boundary = VISIBLE_ON_SCREEN val operatorArguments = OperatorArguments(vim.mode is OP_PENDING, cmd.rawCount, injector.vimState.mode)
override fun start(session: Session) {
session.startJumpMode { ActionMode(AceTagAction.GoToDeclaration, shiftMode = false) } injector.vimState.executingCommand = cmd
injector.actionExecutor.executeVimAction(vim, action, context, operatorArguments)
}
keyHandler.reset(vim)
}
}
} }
} }
class GoToTypeDeclaration : AceVimAction() { injector.scroll.scrollCaretIntoView(editor.vim)
override val boundary = VISIBLE_ON_SCREEN mode.finishSession(editor, session)
override fun start(session: Session) { }
session.startJumpMode { ActionMode(AceTagAction.GoToDeclaration, shiftMode = true) }
} }
} }
class ShowIntentions : AceVimAction() { mode.setupSession(editor, session)
override val boundary = VISIBLE_ON_SCREEN
override fun start(session: Session) {
session.startJumpMode { ActionMode(AceTagAction.ShowIntentions, shiftMode = false) }
}
} }
class ShowUsages : AceVimAction() { class JumpAllEditors : AceVimAction() {
override val boundary = VISIBLE_ON_SCREEN override val mode = AceVimMode.JumpAllEditors
override fun start(session: Session) {
session.startJumpMode { ActionMode(AceTagAction.ShowUsages, shiftMode = false) }
}
} }
class FindUsages : AceVimAction() { class JumpForward : AceVimAction() {
override val boundary = VISIBLE_ON_SCREEN override val mode = AceVimMode.Jump(AFTER_CARET.intersection(VISIBLE_ON_SCREEN))
override fun start(session: Session) {
session.startJumpMode { ActionMode(AceTagAction.ShowUsages, shiftMode = true) }
}
} }
class Refactor : AceVimAction() { class JumpBackward : AceVimAction() {
override val boundary = VISIBLE_ON_SCREEN override val mode = AceVimMode.Jump(BEFORE_CARET.intersection(VISIBLE_ON_SCREEN))
override fun start(session: Session) {
session.startJumpMode { ActionMode(AceTagAction.Refactor, shiftMode = false) }
}
} }
class Rename : AceVimAction() { class JumpTillForward : AceVimAction() {
override val boundary = VISIBLE_ON_SCREEN override val mode = AceVimMode.JumpTillForward(AFTER_CARET.intersection(VISIBLE_ON_SCREEN))
override fun start(session: Session) { }
session.startJumpMode { ActionMode(AceTagAction.Refactor, shiftMode = true) }
class JumpTillBackward : AceVimAction() {
override val mode = AceVimMode.JumpTillBackward(BEFORE_CARET.intersection(VISIBLE_ON_SCREEN))
}
class JumpOnLineForward : AceVimAction() {
override val mode = AceVimMode.Jump(AFTER_CARET.intersection(CARET_LINE))
}
class JumpOnLineBackward : AceVimAction() {
override val mode = AceVimMode.Jump(BEFORE_CARET.intersection(CARET_LINE))
}
class JumpLineIndentsForward : AceVimAction() {
override val mode = AceVimMode.JumpToPattern(Pattern.LINE_INDENTS, AFTER_CARET.intersection(VISIBLE_ON_SCREEN))
}
class JumpLineIndentsBackward : AceVimAction() {
override val mode = AceVimMode.JumpToPattern(Pattern.LINE_INDENTS, BEFORE_CARET.intersection(VISIBLE_ON_SCREEN))
}
class JumpLWordForward : AceVimAction() {
override val mode = AceVimMode.JumpToPattern(Pattern.VIM_LWORD, AFTER_CARET.intersection(VISIBLE_ON_SCREEN))
}
class JumpUWordForward : AceVimAction() {
override val mode = AceVimMode.JumpToPattern(Pattern.VIM_UWORD, AFTER_CARET.intersection(VISIBLE_ON_SCREEN))
}
class JumpLWordBackward : AceVimAction() {
override val mode = AceVimMode.JumpToPattern(Pattern.VIM_LWORD, BEFORE_CARET.intersection(VISIBLE_ON_SCREEN))
}
class JumpUWordBackward : AceVimAction() {
override val mode = AceVimMode.JumpToPattern(Pattern.VIM_UWORD, BEFORE_CARET.intersection(VISIBLE_ON_SCREEN))
}
class JumpLWordEndForward : AceVimAction() {
override val mode = AceVimMode.JumpToPattern(Pattern.VIM_LWORD_END, AFTER_CARET.intersection(VISIBLE_ON_SCREEN))
}
class JumpUWordEndForward : AceVimAction() {
override val mode = AceVimMode.JumpToPattern(Pattern.VIM_UWORD_END, AFTER_CARET.intersection(VISIBLE_ON_SCREEN))
}
class JumpLWordEndBackward : AceVimAction() {
override val mode = AceVimMode.JumpToPattern(Pattern.VIM_LWORD_END, BEFORE_CARET.intersection(VISIBLE_ON_SCREEN))
}
class JumpUWordEndBackward : AceVimAction() {
override val mode = AceVimMode.JumpToPattern(Pattern.VIM_UWORD_END, BEFORE_CARET.intersection(VISIBLE_ON_SCREEN))
}
class JumpAllEditorsGoToDeclaration : DumbAwareAction() {
override fun update(action: AnActionEvent) {
action.presentation.isEnabled = action.getData(CommonDataKeys.EDITOR) != null
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
override fun actionPerformed(e: AnActionEvent) {
val editor = e.getData(CommonDataKeys.EDITOR) ?: return
val session = SessionManager.start(editor, AceVimMode.JumpAllEditors.getJumpEditors(editor))
session.defaultBoundary = VISIBLE_ON_SCREEN
session.startJumpMode {
object : JumpMode() {
override fun accept(state: SessionState, acceptedTag: Tag) {
AceTagAction.GoToDeclaration.invoke(acceptedTag, shiftMode = wasUpperCase, isFinal = true)
}
}
}
} }
} }
} }

View File

@@ -1,4 +1,4 @@
package org.acejump.vim package org.acejump.action
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import org.acejump.boundaries.Boundaries import org.acejump.boundaries.Boundaries
@@ -8,8 +8,7 @@ import org.acejump.search.Pattern
import org.acejump.session.Session import org.acejump.session.Session
sealed class AceVimMode { sealed class AceVimMode {
open val boundaries: Boundaries abstract val boundaries: Boundaries
get() = StandardBoundaries.VISIBLE_ON_SCREEN
open fun getJumpEditors(mainEditor: Editor): List<Editor> { open fun getJumpEditors(mainEditor: Editor): List<Editor> {
return listOf(mainEditor) return listOf(mainEditor)
@@ -21,6 +20,7 @@ sealed class AceVimMode {
class Jump(override val boundaries: Boundaries) : AceVimMode() class Jump(override val boundaries: Boundaries) : AceVimMode()
object JumpAllEditors : AceVimMode() { object JumpAllEditors : AceVimMode() {
override val boundaries = StandardBoundaries.VISIBLE_ON_SCREEN
override fun getJumpEditors(mainEditor: Editor): List<Editor> { override fun getJumpEditors(mainEditor: Editor): List<Editor> {
val project = mainEditor.project ?: return super.getJumpEditors(mainEditor) val project = mainEditor.project ?: return super.getJumpEditors(mainEditor)

View File

@@ -18,6 +18,11 @@ sealed class EditorOffsetCache {
*/ */
abstract fun visibleArea(editor: Editor): Pair<Point, Point> abstract fun visibleArea(editor: Editor): Pair<Point, Point>
/**
* Returns whether the offset is in the visible area rectangle.
*/
abstract fun isVisible(editor: Editor, offset: Int): Boolean
/** /**
* Returns the editor offset at the provided pixel coordinate. * Returns the editor offset at the provided pixel coordinate.
*/ */
@@ -36,6 +41,7 @@ sealed class EditorOffsetCache {
private class Cache : EditorOffsetCache() { private class Cache : EditorOffsetCache() {
private var visibleArea: Pair<Point, Point>? = null private var visibleArea: Pair<Point, Point>? = null
private val lineToVisibleOffsetRange = Int2ObjectOpenHashMap<IntRange>()
private val pointToOffset = Object2IntOpenHashMap<Point>().apply { defaultReturnValue(-1) } private val pointToOffset = Object2IntOpenHashMap<Point>().apply { defaultReturnValue(-1) }
private val offsetToPoint = Int2ObjectOpenHashMap<Point>() private val offsetToPoint = Int2ObjectOpenHashMap<Point>()
@@ -43,6 +49,24 @@ sealed class EditorOffsetCache {
return visibleArea ?: Uncached.visibleArea(editor).also { visibleArea = it } return visibleArea ?: Uncached.visibleArea(editor).also { visibleArea = it }
} }
override fun isVisible(editor: Editor, offset: Int): Boolean {
val visualLine = editor.offsetToVisualLine(offset, false)
var visibleRange = lineToVisibleOffsetRange.get(visualLine)
if (visibleRange == null) {
val (topLeft, bottomRight) = visibleArea(editor)
val lineY = editor.visualLineToY(visualLine)
val firstVisibleOffset = xyToOffset(editor, Point(topLeft.x, lineY))
val lastVisibleOffset = xyToOffset(editor, Point(bottomRight.x, lineY))
visibleRange = firstVisibleOffset..lastVisibleOffset
lineToVisibleOffsetRange.put(visualLine, visibleRange)
}
return offset in visibleRange
}
override fun xyToOffset(editor: Editor, pos: Point): Int { override fun xyToOffset(editor: Editor, pos: Point): Int {
val offset = pointToOffset.getInt(pos) val offset = pointToOffset.getInt(pos)
@@ -51,7 +75,6 @@ sealed class EditorOffsetCache {
} }
return Uncached.xyToOffset(editor, pos).also { return Uncached.xyToOffset(editor, pos).also {
@Suppress("ReplacePutWithAssignment")
pointToOffset.put(pos, it) pointToOffset.put(pos, it)
} }
} }
@@ -64,7 +87,6 @@ sealed class EditorOffsetCache {
} }
return Uncached.offsetToXY(editor, offset).also { return Uncached.offsetToXY(editor, offset).also {
@Suppress("ReplacePutWithAssignment")
offsetToPoint.put(offset, it) offsetToPoint.put(offset, it)
} }
} }
@@ -80,6 +102,15 @@ sealed class EditorOffsetCache {
) )
} }
override fun isVisible(editor: Editor, offset: Int): Boolean {
val (topLeft, bottomRight) = visibleArea(editor)
val pos = offsetToXY(editor, offset)
val x = pos.x
val y = pos.y
return x >= topLeft.x && y >= topLeft.y && x <= bottomRight.x && y <= bottomRight.y
}
override fun xyToOffset(editor: Editor, pos: Point): Int { override fun xyToOffset(editor: Editor, pos: Point): Int {
return editor.logicalPositionToOffset(editor.xyToLogicalPosition(pos)) return editor.logicalPositionToOffset(editor.xyToLogicalPosition(pos))
} }

View File

@@ -13,23 +13,7 @@ enum class StandardBoundaries : Boundaries {
} }
override fun isOffsetInside(editor: Editor, offset: Int, cache: EditorOffsetCache): Boolean { override fun isOffsetInside(editor: Editor, offset: Int, cache: EditorOffsetCache): Boolean {
return cache.isVisible(editor, offset)
// If we are not using a cache, calling getOffsetRange will cause additional 1-2 pixel coordinate -> offset lookups, which is a lot
// more expensive than one lookup compared against the visible area.
// However, if we are using a cache, it's likely that the topmost and bottommost positions are already cached whereas the provided
// offset isn't, so we save a lookup for every offset outside the range.
if (cache !== EditorOffsetCache.Uncached && offset !in getOffsetRange(editor, cache)) {
return false
}
val (topLeft, bottomRight) = cache.visibleArea(editor)
val pos = cache.offsetToXY(editor, offset)
val x = pos.x
val y = pos.y
return x >= topLeft.x && y >= topLeft.y && x <= bottomRight.x && y <= bottomRight.y
} }
}, },

View File

@@ -20,11 +20,12 @@ class AceConfig : PersistentStateComponent<AceSettings> {
val layout get() = settings.layout val layout get() = settings.layout
val minQueryLength get() = settings.minQueryLength val minQueryLength get() = settings.minQueryLength
val invertUppercaseMode get() = settings.invertUppercaseMode
val editorFadeOpacity get() = settings.editorFadeOpacity
val jumpModeColor get() = settings.jumpModeColor val jumpModeColor get() = settings.jumpModeColor
val textHighlightColor get() = settings.textHighlightColor val tagForegroundColor1 get() = settings.tagForegroundColor1
val tagForegroundColor get() = settings.tagForegroundColor val tagForegroundColor2 get() = settings.tagForegroundColor2
val tagBackgroundColor get() = settings.tagBackgroundColor val searchHighlightColor get() = settings.searchHighlightColor
val acceptedTagColor get() = settings.acceptedTagColor
} }
override fun getState(): AceSettings { override fun getState(): AceSettings {

View File

@@ -15,21 +15,23 @@ class AceConfigurable : Configurable {
panel.allowedChars != settings.allowedChars || panel.allowedChars != settings.allowedChars ||
panel.keyboardLayout != settings.layout || panel.keyboardLayout != settings.layout ||
panel.minQueryLengthInt != settings.minQueryLength || panel.minQueryLengthInt != settings.minQueryLength ||
panel.invertUppercaseMode != settings.invertUppercaseMode ||
panel.editorFadeOpacityPercent != settings.editorFadeOpacity ||
panel.jumpModeColor != settings.jumpModeColor || panel.jumpModeColor != settings.jumpModeColor ||
panel.textHighlightColor != settings.textHighlightColor || panel.tagForegroundColor1 != settings.tagForegroundColor1 ||
panel.tagForegroundColor != settings.tagForegroundColor || panel.tagForegroundColor2 != settings.tagForegroundColor2 ||
panel.tagBackgroundColor != settings.tagBackgroundColor || panel.searchHighlightColor != settings.searchHighlightColor
panel.acceptedTagColor != settings.acceptedTagColor
override fun apply() { override fun apply() {
settings.allowedChars = panel.allowedChars settings.allowedChars = panel.allowedChars
settings.layout = panel.keyboardLayout settings.layout = panel.keyboardLayout
settings.minQueryLength = panel.minQueryLengthInt ?: settings.minQueryLength settings.minQueryLength = panel.minQueryLengthInt ?: settings.minQueryLength
settings.invertUppercaseMode = panel.invertUppercaseMode
settings.editorFadeOpacity = panel.editorFadeOpacityPercent
panel.jumpModeColor?.let { settings.jumpModeColor = it } panel.jumpModeColor?.let { settings.jumpModeColor = it }
panel.textHighlightColor?.let { settings.textHighlightColor = it } panel.tagForegroundColor1?.let { settings.tagForegroundColor1 = it }
panel.tagForegroundColor?.let { settings.tagForegroundColor = it } panel.tagForegroundColor2?.let { settings.tagForegroundColor2 = it }
panel.tagBackgroundColor?.let { settings.tagBackgroundColor = it } panel.searchHighlightColor?.let { settings.searchHighlightColor = it }
panel.acceptedTagColor?.let { settings.acceptedTagColor = it }
KeyLayoutCache.reset(settings) KeyLayoutCache.reset(settings)
} }

View File

@@ -8,20 +8,19 @@ import java.awt.Color
data class AceSettings( data class AceSettings(
var layout: KeyLayout = QWERTY, var layout: KeyLayout = QWERTY,
var allowedChars: String = layout.allChars, var allowedChars: String = layout.allChars,
var invertUppercaseMode: Boolean = false,
var minQueryLength: Int = 1, var minQueryLength: Int = 1,
var editorFadeOpacity: Int = 70,
@OptionTag("jumpModeRGB", converter = ColorConverter::class) @OptionTag("jumpModeRGB", converter = ColorConverter::class)
var jumpModeColor: Color = Color(0xFFFFFF), var jumpModeColor: Color = Color(0xFFFFFF),
@OptionTag("textHighlightRGB", converter = ColorConverter::class)
var textHighlightColor: Color = Color(0x394B58),
@OptionTag("tagForegroundRGB", converter = ColorConverter::class) @OptionTag("tagForegroundRGB", converter = ColorConverter::class)
var tagForegroundColor: Color = Color(0xFFFFFF), var tagForegroundColor1: Color = Color(0xFFFFFF),
@OptionTag("tagBackgroundRGB", converter = ColorConverter::class) @OptionTag("tagForeground2RGB", converter = ColorConverter::class)
var tagBackgroundColor: Color = Color(0x008299), var tagForegroundColor2: Color = Color(0xFFFFFF),
@OptionTag("acceptedTagRGB", converter = ColorConverter::class) @OptionTag("searchHighlightRGB", converter = ColorConverter::class)
var acceptedTagColor: Color = Color(0x394B58) var searchHighlightColor: Color = Color(0x008299),
) )

View File

@@ -2,18 +2,23 @@ package org.acejump.config
import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.ComboBox
import com.intellij.ui.ColorPanel import com.intellij.ui.ColorPanel
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBSlider
import com.intellij.ui.components.JBTextArea import com.intellij.ui.components.JBTextArea
import com.intellij.ui.components.JBTextField import com.intellij.ui.components.JBTextField
import com.intellij.ui.layout.Cell import com.intellij.ui.dsl.builder.COLUMNS_LARGE
import com.intellij.ui.layout.GrowPolicy.MEDIUM_TEXT import com.intellij.ui.dsl.builder.COLUMNS_SHORT
import com.intellij.ui.layout.GrowPolicy.SHORT_TEXT import com.intellij.ui.dsl.builder.columns
import com.intellij.ui.layout.panel import com.intellij.ui.dsl.builder.panel
import org.acejump.input.KeyLayout import org.acejump.input.KeyLayout
import java.awt.Color import java.awt.Color
import java.awt.Dimension
import java.awt.Font import java.awt.Font
import java.util.Hashtable
import javax.swing.JCheckBox import javax.swing.JCheckBox
import javax.swing.JComponent import javax.swing.JLabel
import javax.swing.JPanel import javax.swing.JPanel
import javax.swing.JSlider
import javax.swing.text.JTextComponent import javax.swing.text.JTextComponent
import kotlin.reflect.KProperty import kotlin.reflect.KProperty
@@ -22,74 +27,95 @@ import kotlin.reflect.KProperty
*/ */
@Suppress("UsePropertyAccessSyntax") @Suppress("UsePropertyAccessSyntax")
internal class AceSettingsPanel { internal class AceSettingsPanel {
private val tagCharsField = JBTextField() private val tagAllowedCharsField = JBTextField()
private val keyboardLayoutCombo = ComboBox<KeyLayout>() private val keyboardLayoutCombo = ComboBox<KeyLayout>()
private val keyboardLayoutArea = JBTextArea().apply { isEditable = false } private val keyboardLayoutArea = JBTextArea().apply { isEditable = false }
private val minQueryLengthField = JBTextField() private val minQueryLengthField = JBTextField()
private val invertUppercaseModeCheckBox = JBCheckBox("Invert uppercase mode")
private val editorFadeOpacitySlider = JBSlider(0, 10).apply {
labelTable = Hashtable((0..10).associateWith { JLabel("${it * 10}") })
paintTrack = true
paintLabels = true
paintTicks = true
minorTickSpacing = 1
majorTickSpacing = 1
minimumSize = Dimension(275, minimumSize.height)
}
private val jumpModeColorWheel = ColorPanel() private val jumpModeColorWheel = ColorPanel()
private val textHighlightColorWheel = ColorPanel() private val tagForeground1ColorWheel = ColorPanel()
private val tagForegroundColorWheel = ColorPanel() private val tagForeground2ColorWheel = ColorPanel()
private val tagBackgroundColorWheel = ColorPanel() private val searchHighlightColorWheel = ColorPanel()
private val acceptedTagColorWheel = ColorPanel()
init { init {
tagCharsField.apply { font = Font("monospaced", font.style, font.size) } tagAllowedCharsField.apply { font = Font("monospaced", font.style, font.size) }
keyboardLayoutArea.apply { font = Font("monospaced", font.style, font.size) } keyboardLayoutArea.apply { font = Font("monospaced", font.style, font.size) }
keyboardLayoutCombo.setupEnumItems { keyChars = it.rows.joinToString("\n") } keyboardLayoutCombo.setupEnumItems { keyChars = it.rows.joinToString("\n") }
} }
internal val rootPanel: JPanel = panel { internal val rootPanel: JPanel = panel {
fun Cell.short(component: JComponent) = component(growPolicy = SHORT_TEXT) group("Characters and Layout") {
fun Cell.medium(component: JComponent) = component(growPolicy = MEDIUM_TEXT) row("Allowed characters in tags:") { cell(tagAllowedCharsField).columns(COLUMNS_LARGE) }
row("Keyboard layout:") { cell(keyboardLayoutCombo).columns(COLUMNS_SHORT) }
titledRow("Characters and Layout") { row("Keyboard design:") { cell(keyboardLayoutArea).columns(COLUMNS_SHORT) }
row("Allowed characters in tags:") { medium(tagCharsField) }
row("Keyboard layout:") { short(keyboardLayoutCombo) }
row("Keyboard design:") { short(keyboardLayoutArea) }
} }
titledRow("Behavior") { group("Behavior") {
row("Minimum typed characters (1-10):") { short(minQueryLengthField) } row("Minimum typed characters (1-10):") { cell(minQueryLengthField).columns(COLUMNS_SHORT) }
row { cell(invertUppercaseModeCheckBox) }
} }
titledRow("Colors") { group("Colors") {
row("Caret background:") { short(jumpModeColorWheel) } row("Caret background:") {
row("Searched text background:") { short(textHighlightColorWheel) } cell(jumpModeColorWheel)
row("Tag foreground:") { short(tagForegroundColorWheel) } }
row("Tag background:") { short(tagBackgroundColorWheel) } row("Tag foreground:") {
row("Accepted tag position background:") { short(acceptedTagColorWheel) } cell(tagForeground1ColorWheel)
cell(tagForeground2ColorWheel)
}
row("Search highlight:") {
cell(searchHighlightColorWheel)
}
row("Editor fade opacity (%):") {
cell(editorFadeOpacitySlider)
}
} }
} }
// Property-to-property delegation: https://stackoverflow.com/q/45074596/1772342 // Property-to-property delegation: https://stackoverflow.com/q/45074596/1772342
internal var allowedChars by tagCharsField internal var allowedChars by tagAllowedCharsField
internal var keyboardLayout by keyboardLayoutCombo internal var keyboardLayout by keyboardLayoutCombo
internal var keyChars by keyboardLayoutArea internal var keyChars by keyboardLayoutArea
internal var minQueryLength by minQueryLengthField internal var minQueryLength by minQueryLengthField
internal var invertUppercaseMode by invertUppercaseModeCheckBox
internal var editorFadeOpacity by editorFadeOpacitySlider
internal var jumpModeColor by jumpModeColorWheel internal var jumpModeColor by jumpModeColorWheel
internal var textHighlightColor by textHighlightColorWheel internal var tagForegroundColor1 by tagForeground1ColorWheel
internal var tagForegroundColor by tagForegroundColorWheel internal var tagForegroundColor2 by tagForeground2ColorWheel
internal var tagBackgroundColor by tagBackgroundColorWheel internal var searchHighlightColor by searchHighlightColorWheel
internal var acceptedTagColor by acceptedTagColorWheel
internal var minQueryLengthInt internal var minQueryLengthInt
get() = minQueryLength.toIntOrNull()?.coerceIn(1, 10) get() = minQueryLength.toIntOrNull()?.coerceIn(1, 10)
set(value) { minQueryLength = value.toString() } set(value) { minQueryLength = value.toString() }
internal var editorFadeOpacityPercent
get() = editorFadeOpacity * 10
set(value) { editorFadeOpacity = value / 10 }
fun reset(settings: AceSettings) { fun reset(settings: AceSettings) {
allowedChars = settings.allowedChars allowedChars = settings.allowedChars
keyboardLayout = settings.layout keyboardLayout = settings.layout
minQueryLength = settings.minQueryLength.toString() minQueryLength = settings.minQueryLength.toString()
invertUppercaseMode = settings.invertUppercaseMode
editorFadeOpacityPercent = settings.editorFadeOpacity
jumpModeColor = settings.jumpModeColor jumpModeColor = settings.jumpModeColor
textHighlightColor = settings.textHighlightColor tagForegroundColor1 = settings.tagForegroundColor1
tagForegroundColor = settings.tagForegroundColor tagForegroundColor2 = settings.tagForegroundColor2
tagBackgroundColor = settings.tagBackgroundColor searchHighlightColor = settings.searchHighlightColor
acceptedTagColor = settings.acceptedTagColor
} }
// Removal pending support for https://youtrack.jetbrains.com/issue/KT-8575 // Removal pending support for https://youtrack.jetbrains.com/issue/KT-8575
private operator fun JTextComponent.getValue(a: AceSettingsPanel, p: KProperty<*>) = text.toLowerCase() private operator fun JTextComponent.getValue(a: AceSettingsPanel, p: KProperty<*>) = text.lowercase()
private operator fun JTextComponent.setValue(a: AceSettingsPanel, p: KProperty<*>, s: String) = setText(s) private operator fun JTextComponent.setValue(a: AceSettingsPanel, p: KProperty<*>, s: String) = setText(s)
private operator fun ColorPanel.getValue(a: AceSettingsPanel, p: KProperty<*>) = selectedColor private operator fun ColorPanel.getValue(a: AceSettingsPanel, p: KProperty<*>) = selectedColor
@@ -98,6 +124,9 @@ internal class AceSettingsPanel {
private operator fun JCheckBox.getValue(a: AceSettingsPanel, p: KProperty<*>) = isSelected private operator fun JCheckBox.getValue(a: AceSettingsPanel, p: KProperty<*>) = isSelected
private operator fun JCheckBox.setValue(a: AceSettingsPanel, p: KProperty<*>, selected: Boolean) = setSelected(selected) private operator fun JCheckBox.setValue(a: AceSettingsPanel, p: KProperty<*>, selected: Boolean) = setSelected(selected)
private operator fun JSlider.getValue(a: AceSettingsPanel, p: KProperty<*>) = value
private operator fun JSlider.setValue(a: AceSettingsPanel, p: KProperty<*>, value: Int) = setValue(value)
private operator fun <T> ComboBox<T>.getValue(a: AceSettingsPanel, p: KProperty<*>) = selectedItem as T private operator fun <T> ComboBox<T>.getValue(a: AceSettingsPanel, p: KProperty<*>) = selectedItem as T
private operator fun <T> ComboBox<T>.setValue(a: AceSettingsPanel, p: KProperty<*>, item: T) = setSelectedItem(item) private operator fun <T> ComboBox<T>.setValue(a: AceSettingsPanel, p: KProperty<*>, item: T) = setSelectedItem(item)

View File

@@ -10,7 +10,6 @@ import com.intellij.openapi.editor.actionSystem.TypedActionHandler
* sessions' own handlers. * sessions' own handlers.
*/ */
internal object EditorKeyListener : TypedActionHandler { internal object EditorKeyListener : TypedActionHandler {
private val action = TypedAction.getInstance()
private val attached = mutableMapOf<Editor, TypedActionHandler>() private val attached = mutableMapOf<Editor, TypedActionHandler>()
private var originalHandler: TypedActionHandler? = null private var originalHandler: TypedActionHandler? = null
@@ -20,8 +19,9 @@ internal object EditorKeyListener : TypedActionHandler {
fun attach(editor: Editor, callback: TypedActionHandler) { fun attach(editor: Editor, callback: TypedActionHandler) {
if (attached.isEmpty()) { if (attached.isEmpty()) {
originalHandler = action.rawHandler val typedAction = TypedAction.getInstance()
action.setupRawHandler(this) originalHandler = typedAction.rawHandler
typedAction.setupRawHandler(this)
} }
attached[editor] = callback attached[editor] = callback
@@ -31,7 +31,7 @@ internal object EditorKeyListener : TypedActionHandler {
attached.remove(editor) attached.remove(editor)
if (attached.isEmpty()) { if (attached.isEmpty()) {
originalHandler?.let(action::setupRawHandler) originalHandler?.let(TypedAction.getInstance()::setupRawHandler)
originalHandler = null originalHandler = null
} }
} }

View File

@@ -1,60 +1,52 @@
package org.acejump.input package org.acejump.input
import it.unimi.dsi.fastutil.objects.Object2IntMap
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap
import java.awt.geom.Point2D
import kotlin.math.floor
/** /**
* Defines common keyboard layouts. Each layout has a key priority order, based on each key's distance from the home row and how * Defines common keyboard layouts. Each layout has a key priority order, based on each key's distance from the home row and how
* ergonomically difficult they are to press. * ergonomically difficult they are to press.
*/ */
@Suppress("unused") @Suppress("unused", "SpellCheckingInspection")
enum class KeyLayout(internal val rows: Array<String>, priority: String) { enum class KeyLayout(
internal val rows: Array<String>,
priority: String,
private val characterSides: Pair<Set<Char>, Set<Char>> = Pair(emptySet(), emptySet()),
internal val characterRemapping: Map<Char, Char> = emptyMap(),
) {
COLEMK(arrayOf("1234567890", "qwfpgjluy", "arstdhneio", "zxcvbkm"), priority = "tndhseriaovkcmbxzgjplfuwyq5849673210"), COLEMK(arrayOf("1234567890", "qwfpgjluy", "arstdhneio", "zxcvbkm"), priority = "tndhseriaovkcmbxzgjplfuwyq5849673210"),
WORKMN(arrayOf("1234567890", "qdrwbjfup", "ashtgyneoi", "zxmcvkl"), priority = "tnhegysoaiclvkmxzwfrubjdpq5849673210"), WORKMN(arrayOf("1234567890", "qdrwbjfup", "ashtgyneoi", "zxmcvkl"), priority = "tnhegysoaiclvkmxzwfrubjdpq5849673210"),
DVORAK(arrayOf("1234567890", "pyfgcrl", "aoeuidhtns", "qjkxbmwvz"), priority = "uhetidonasxkbjmqwvzgfycprl5849673210"), DVORAK(arrayOf("1234567890", "pyfgcrl", "aoeuidhtns", "qjkxbmwvz"), priority = "uhetidonasxkbjmqwvzgfycprl5849673210"),
QWERTY(arrayOf("1234567890", "qwertyuiop", "asdfghjkl", "zxcvbnm"), priority = "fjghdkslavncmbxzrutyeiwoqp5849673210"), QWERTY(arrayOf("1234567890", "qwertyuiop", "asdfghjkl", "zxcvbnm"), priority = "fjghdkslavncmbxzrutyeiwoqp5849673210", characterSides = sides(listOf("123456", "qwert", "asdfg", "zxcvb"), listOf("7890", "yuiop", "hjkl", "nm"))),
QWERTZ(arrayOf("1234567890", "qwertzuiop", "asdfghjkl", "yxcvbnm"), priority = "fjghdkslavncmbxyrutzeiwoqp5849673210"), QWERTZ(arrayOf("1234567890", "qwertzuiop", "asdfghjkl", "yxcvbnm"), priority = "fjghdkslavncmbxyrutzeiwoqp5849673210", characterSides = sides(listOf("123456", "qwert", "asdfg", "yxcvb"), listOf("7890", "zuiop", "hjkl", "nm"))),
QWERTZ_CZ(arrayOf("1234567890", "qwertzuiop", "asdfghjkl", "yxcvbnm"), priority = "fjghdkslavncmbxyrutzeiwoqp5849673210", characterSides = sides(listOf("123456", "qwert", "asdfg", "yxcvb"), listOf("7890", "zuiop", "hjkl", "nm")), characterRemapping = mapOf(
'+' to '1',
'ě' to '2',
'š' to '3',
'č' to '4',
'ř' to '5',
'ž' to '6',
'ý' to '7',
'á' to '8',
'í' to '9',
'é' to '0'
)),
QGMLWY(arrayOf("1234567890", "qgmlwyfub", "dstnriaeoh", "zxcvjkp"), priority = "naterisodhvkcpjxzlfmuwygbq5849673210"), QGMLWY(arrayOf("1234567890", "qgmlwyfub", "dstnriaeoh", "zxcvjkp"), priority = "naterisodhvkcpjxzlfmuwygbq5849673210"),
QGMLWB(arrayOf("1234567890", "qgmlwbyuv", "dstnriaeoh", "zxcfjkp"), priority = "naterisodhfkcpjxzlymuwbgvq5849673210"), QGMLWB(arrayOf("1234567890", "qgmlwbyuv", "dstnriaeoh", "zxcfjkp"), priority = "naterisodhfkcpjxzlymuwbgvq5849673210"),
NORMAN(arrayOf("1234567890", "qwdfkjurl", "asetgynioh", "zxcvbpm"), priority = "tneigysoahbvpcmxzjkufrdlwq5849673210"); NORMAN(arrayOf("1234567890", "qwdfkjurl", "asetgynioh", "zxcvbpm"), priority = "tneigysoahbvpcmxzjkufrdlwq5849673210");
internal val allChars = rows.joinToString("").toCharArray().apply(CharArray::sort).joinToString("") internal val allChars = rows.joinToString("").toCharArray().apply(CharArray::sort).joinToString("")
internal val allPriorities = priority.mapIndexed { index, char -> char to index }.toMap() private val allPriorities = priority.mapIndexed { index, char -> char to index }.toMap()
private val keyDistances: Map<Char, Object2IntMap<Char>> by lazy { fun priority(char: Char): Int {
val keyDistanceMap = mutableMapOf<Char, Object2IntMap<Char>>() return allPriorities[char] ?: allChars.length
val keyLocations = mutableMapOf<Char, Point2D>() }
for ((rowIndex, rowChars) in rows.withIndex()) { fun areOnSameSide(c1: Char, c2: Char): Boolean {
val keyY = rowIndex * 1.2F // Slightly increase cost of traveling between rows. return (c1 in characterSides.first && c2 in characterSides.first) || (c1 in characterSides.second && c2 in characterSides.second)
for ((columnIndex, char) in rowChars.withIndex()) {
val keyX = columnIndex + (0.25F * rowIndex) // Assume a 1/4-key uniform stagger.
keyLocations[char] = Point2D.Float(keyX, keyY)
} }
} }
for (fromChar in allChars) { private fun sides(left: List<String>, right: List<String>): Pair<Set<Char>, Set<Char>> {
val distances = Object2IntOpenHashMap<Char>() return Pair(
val fromLocation = keyLocations.getValue(fromChar) left.flatMapTo(mutableSetOf()) { it.toCharArray().toSet() },
right.flatMapTo(mutableSetOf()) { it.toCharArray().toSet() }
for (toChar in allChars) { )
distances[toChar] = floor(2F * fromLocation.distanceSq(keyLocations.getValue(toChar))).toInt()
}
keyDistanceMap[fromChar] = distances
}
keyDistanceMap
}
internal inline fun priority(crossinline tagToChar: (String) -> Char): (String) -> Int? {
return { allPriorities[tagToChar(it)] }
}
internal fun distanceBetweenKeys(char1: Char, char2: Char): Int {
return keyDistances.getValue(char1).getValue(char2)
}
} }

View File

@@ -1,30 +1,22 @@
package org.acejump.input package org.acejump.input
import org.acejump.config.AceSettings import org.acejump.config.AceSettings
import kotlin.math.pow
import kotlin.math.roundToInt
/** /**
* Stores data specific to the selected keyboard layout. We want to assign tags with easily reachable keys first, and ideally have tags * Stores data specific to the selected keyboard layout. We want to assign tags with easily reachable keys first, and ideally have tags
* with repeated keys (ex. FF, JJ) or adjacent keys (ex. GH, UJ). * with repeated keys (ex. FF, JJ) or adjacent keys (ex. GH, UJ).
*/ */
internal object KeyLayoutCache { internal object KeyLayoutCache {
/** lateinit var allowedTagsSorted: List<String>
* Sorts tags according to current keyboard layout settings, and some predefined rules that force tags with digits, and tags with two
* keys far apart, to be sorted after other (easier to type) tags.
*/
lateinit var tagOrder: Comparator<String>
private set
/**
* Returns all possible two key tags, pre-sorted according to [tagOrder].
*/
lateinit var allPossibleTags: List<String>
private set private set
/** /**
* Called before any lazily initialized properties are used, to ensure that they are initialized even if the settings are missing. * Called before any lazily initialized properties are used, to ensure that they are initialized even if the settings are missing.
*/ */
fun ensureInitialized(settings: AceSettings) { fun ensureInitialized(settings: AceSettings) {
if (!::tagOrder.isInitialized) { if (!::allowedTagsSorted.isInitialized) {
reset(settings) reset(settings)
} }
} }
@@ -33,19 +25,38 @@ internal object KeyLayoutCache {
* Re-initializes cached data according to updated settings. * Re-initializes cached data according to updated settings.
*/ */
fun reset(settings: AceSettings) { fun reset(settings: AceSettings) {
tagOrder = compareBy( val allowedChars = processCharList(settings.allowedChars).ifEmpty { processCharList(settings.layout.allChars) }
{ it[0].isDigit() || it[1].isDigit() }, val allowedTags = mutableSetOf<String>()
{ settings.layout.distanceBetweenKeys(it[0], it[1]) },
settings.layout.priority { it[0] }
)
val allPossibleChars = settings.allowedChars for (c1 in allowedChars) {
.toCharArray() allowedTags.add("$c1")
.filter(Char::isLetterOrDigit)
.distinct()
.joinToString("")
.ifEmpty(settings.layout::allChars)
allPossibleTags = allPossibleChars.flatMap { a -> allPossibleChars.map { b -> "$a$b".intern() } }.sortedWith(tagOrder) for (c2 in allowedChars) {
if (c1 != c2) {
allowedTags.add("$c1$c2")
}
}
}
allowedTagsSorted = allowedTags.sortedBy { rankPriority(settings.layout, it) }
}
private fun processCharList(charList: String): List<Char> {
return charList.toCharArray().map(Char::lowercaseChar).distinct()
}
private fun rankPriority(layout: KeyLayout, tag: String): Int {
val c1 = tag.first()
val p1 = (1.0 + layout.priority(c1)).pow(3)
if (tag.length == 1) {
return p1.roundToInt()
}
val c2 = tag.last()
val p2 = (1.0 + layout.priority(c2)).pow(3)
val multiplier = if (layout.areOnSameSide(c1, c2)) 2 else 1
return (((p1 * 50) + p2 + 1000) * multiplier).roundToInt()
} }
} }

View File

@@ -1,12 +0,0 @@
package org.acejump.modes
import org.acejump.action.AceTagAction
import org.acejump.search.Tag
import org.acejump.session.SessionState
class ActionMode(private val action: AceTagAction, private val shiftMode: Boolean) : JumpMode() {
override fun accept(state: SessionState, acceptedTag: Tag): Boolean {
state.act(action, acceptedTag, shiftMode, isFinal = true)
return true
}
}

View File

@@ -18,8 +18,7 @@ open class JumpMode : SessionMode {
return state.type(charTyped) return state.type(charTyped)
} }
override fun accept(state: SessionState, acceptedTag: Tag): Boolean { override fun accept(state: SessionState, acceptedTag: Tag) {
state.act(AceTagAction.JumpToSearchStart, acceptedTag, wasUpperCase, isFinal = true) AceTagAction.JumpToSearchStart.invoke(acceptedTag, shiftMode = wasUpperCase, isFinal = true)
return true
} }
} }

View File

@@ -9,5 +9,5 @@ interface SessionMode {
val caretColor: Color val caretColor: Color
fun type(state: SessionState, charTyped: Char, acceptedTag: Tag?): TypeResult fun type(state: SessionState, charTyped: Char, acceptedTag: Tag?): TypeResult
fun accept(state: SessionState, acceptedTag: Tag): Boolean fun accept(state: SessionState, acceptedTag: Tag)
} }

View File

@@ -3,32 +3,25 @@ package org.acejump.search
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import it.unimi.dsi.fastutil.ints.IntArrayList import it.unimi.dsi.fastutil.ints.IntArrayList
import org.acejump.boundaries.Boundaries import org.acejump.boundaries.Boundaries
import org.acejump.boundaries.EditorOffsetCache
import org.acejump.clone
import org.acejump.config.AceConfig
import org.acejump.immutableText import org.acejump.immutableText
import org.acejump.isWordPart
import org.acejump.matchesAt import org.acejump.matchesAt
/** /**
* Searches editor text for matches of a [SearchQuery], and updates previous results when the user [type]s a character. * Searches editor text for matches of a [SearchQuery], and updates previous results when the user [refineQuery]s a character.
*/ */
class SearchProcessor private constructor(query: SearchQuery, results: MutableMap<Editor, IntArrayList>) { class SearchProcessor private constructor(query: SearchQuery, val boundaries: Boundaries, val invertUppercaseMode: Boolean, private val results: MutableMap<Editor, IntArrayList>) {
companion object { internal constructor(editors: List<Editor>, query: SearchQuery, boundaries: Boundaries, invertUppercaseMode: Boolean) : this(query, boundaries, invertUppercaseMode, mutableMapOf()) {
fun fromChar(editors: List<Editor>, char: Char, boundaries: Boundaries): SearchProcessor { val regex = query.toRegex(invertUppercaseMode)
return SearchProcessor(editors, SearchQuery.Literal(char.toString()), boundaries)
}
fun fromRegex(editors: List<Editor>, pattern: String, boundaries: Boundaries): SearchProcessor {
return SearchProcessor(editors, SearchQuery.RegularExpression(pattern), boundaries)
}
}
private constructor(editors: List<Editor>, query: SearchQuery, boundaries: Boundaries) : this(query, mutableMapOf()) {
val regex = query.toRegex()
if (regex != null) { if (regex != null) {
for (editor in editors) { for (editor in editors) {
val cache = EditorOffsetCache.new()
val offsets = IntArrayList() val offsets = IntArrayList()
val offsetRange = boundaries.getOffsetRange(editor) val offsetRange = boundaries.getOffsetRange(editor, cache)
var result = regex.find(editor.immutableText, offsetRange.first) var result = regex.find(editor.immutableText, offsetRange.first)
while (result != null) { while (result != null) {
@@ -38,7 +31,7 @@ class SearchProcessor private constructor(query: SearchQuery, results: MutableMa
if (highlightEnd > offsetRange.last) { if (highlightEnd > offsetRange.last) {
break break
} }
else if (boundaries.isOffsetInside(editor, index)) { else if (boundaries.isOffsetInside(editor, index, cache) && !editor.foldingModel.isOffsetCollapsed(index)) {
offsets.add(index) offsets.add(index)
} }
@@ -53,97 +46,40 @@ class SearchProcessor private constructor(query: SearchQuery, results: MutableMa
internal var query = query internal var query = query
private set private set
internal var results = results val resultsCopy
private set get() = results.clone()
/** val isQueryFinished
* Appends a character to the search query and removes all search results that no longer match the query. If the last typed character get() = query.rawText.length >= AceConfig.minQueryLength
* transitioned the search query from a non-word to a word, it notifies the [Tagger] to reassign all tags. If the new query does not
* make sense because it would remove every result, the change is reverted and this function returns false.
*/
fun type(char: Char, tagger: Tagger): Boolean {
val newQuery = query.rawText + char
val canMatchTag = tagger.canQueryMatchAnyTag(newQuery)
// If the typed character is not compatible with any existing tag or as a continuation of any previous occurrence, reject the query
// change and return false to indicate that nothing else should happen.
if (newQuery.length > 1 && !canMatchTag && !isContinuation(newQuery)) {
return false
}
// If the typed character transitioned the search query from a non-word to a word, and the typed character does not belong to an
// existing tag, we basically restart the search at the beginning of every new word, and unmark existing results so that all tags get
// regenerated immediately afterwards. Although this causes tags to change, it is one solution for conflicts between tag characters and
// search query characters, and moving searches across word boundaries during search should be fairly uncommon.
if (!canMatchTag && newQuery.length >= 2 && !newQuery[newQuery.length - 2].isWordPart && char.isWordPart) {
query = SearchQuery.Literal(char.toString())
tagger.unmark()
for ((editor, offsets) in results) {
val chars = editor.immutableText
val iter = offsets.iterator()
while (iter.hasNext()) {
val movedOffset = iter.nextInt() + newQuery.length - 1
if (movedOffset < chars.length && chars[movedOffset].equals(char, ignoreCase = true)) {
iter.set(movedOffset)
}
else {
iter.remove()
}
}
}
}
else {
removeObsoleteResults(newQuery, tagger)
query = SearchQuery.Literal(newQuery)
}
fun refineQuery(char: Char): Boolean {
if (char == '\n') {
return true return true
} }
else {
/** query = query.refine(char)
* Returns true if the new query is a continuation of any remaining search query. removeObsoleteResults()
*/ return isQueryFinished
private fun isContinuation(newQuery: String): Boolean {
for ((editor, offsets) in results) {
val chars = editor.immutableText
if (offsets.any { chars.matchesAt(it, newQuery, ignoreCase = true) }) {
return true
} }
} }
return false
}
/** /**
* After updating the query, removes all results that no longer match the search query. * After updating the query, removes all results that no longer match the search query.
*/ */
private fun removeObsoleteResults(newQuery: String, tagger: Tagger) { private fun removeObsoleteResults() {
val lastCharOffset = newQuery.lastIndex val query = query.rawText
val lastChar = newQuery[lastCharOffset]
val ignoreCase = newQuery[0].isLowerCase()
for ((editor, offsets) in results.entries.toList()) { for (entry in results) {
val chars = editor.immutableText val editor = entry.key
val offsetIter = entry.value.iterator()
val remaining = IntArrayList() while (offsetIter.hasNext()) {
val iter = offsets.iterator() val offset = offsetIter.nextInt()
while (iter.hasNext()) { if (!editor.immutableText.matchesAt(offset, query, ignoreCase = true)) {
val offset = iter.nextInt() offsetIter.remove()
val endOffset = offset + lastCharOffset }
val lastTypedCharMatches = endOffset < chars.length && chars[endOffset].equals(lastChar, ignoreCase) }
if (lastTypedCharMatches || tagger.isQueryCompatibleWithTagAt(newQuery, Tag(editor, offset))) {
remaining.add(offset)
}
}
results[editor] = remaining
} }
} }
} }

View File

@@ -8,6 +8,11 @@ import org.acejump.countMatchingCharacters
internal sealed class SearchQuery { internal sealed class SearchQuery {
abstract val rawText: String abstract val rawText: String
/**
* Returns a new query with the given character appended.
*/
abstract fun refine(char: Char): SearchQuery
/** /**
* Returns how many characters the search occurrence highlight should cover. * Returns how many characters the search occurrence highlight should cover.
*/ */
@@ -16,32 +21,40 @@ internal sealed class SearchQuery {
/** /**
* Converts the query into a regular expression to find the initial matches. * Converts the query into a regular expression to find the initial matches.
*/ */
abstract fun toRegex(): Regex? abstract fun toRegex(invertUppercaseMode: Boolean): Regex?
/** /**
* Searches for all occurrences of a literal text query. If the first character of the query is lowercase, then the entire query will be * Searches for all occurrences of a literal text query.
* case-insensitive. * If the first character of the query is lowercase, then the entire query will be case-insensitive,
* * and only beginnings of words and camel humps will be matched.
* Each occurrence must either match the entire query, or match the query up to a point so that the rest of the query matches the
* beginning of a tag at the location of the occurrence.
*/ */
class Literal(override val rawText: String) : SearchQuery() { class Literal(override val rawText: String) : SearchQuery() {
init { init {
require(rawText.isNotEmpty()) require(rawText.isNotEmpty())
} }
override fun refine(char: Char): SearchQuery {
return Literal(rawText + char)
}
override fun getHighlightLength(text: CharSequence, offset: Int): Int { override fun getHighlightLength(text: CharSequence, offset: Int): Int {
return text.countMatchingCharacters(offset, rawText) return text.countMatchingCharacters(offset, rawText)
} }
override fun toRegex(): Regex { override fun toRegex(invertUppercaseMode: Boolean): Regex {
val options = mutableSetOf(RegexOption.MULTILINE) val firstChar = rawText.first()
val pattern = if (firstChar.isLowerCase() xor invertUppercaseMode) {
if (rawText.first().isLowerCase()) { val fullPattern = Regex.escape(rawText)
options.add(RegexOption.IGNORE_CASE) "(?i)$fullPattern"
}
else {
val firstCharUppercasePattern = Regex.escape(firstChar.uppercase())
val firstCharLowercasePattern = Regex.escape(firstChar.lowercase())
val remainingPattern = if (rawText.length > 1) Regex.escape(rawText.drop(1)) else ""
"(?:$firstCharUppercasePattern|(?<![a-zA-Z])$firstCharLowercasePattern)$remainingPattern"
} }
return Regex(Regex.escape(rawText), options) return Regex(pattern, setOf(RegexOption.MULTILINE))
} }
} }
@@ -51,11 +64,15 @@ internal sealed class SearchQuery {
class RegularExpression(private val pattern: String) : SearchQuery() { class RegularExpression(private val pattern: String) : SearchQuery() {
override val rawText = "" override val rawText = ""
override fun refine(char: Char): SearchQuery {
return Literal(char.toString())
}
override fun getHighlightLength(text: CharSequence, offset: Int): Int { override fun getHighlightLength(text: CharSequence, offset: Int): Int {
return 1 return 1
} }
override fun toRegex(): Regex { override fun toRegex(invertUppercaseMode: Boolean): Regex {
return Regex(pattern, setOf(RegexOption.MULTILINE, RegexOption.IGNORE_CASE)) return Regex(pattern, setOf(RegexOption.MULTILINE, RegexOption.IGNORE_CASE))
} }
} }

View File

@@ -1,231 +0,0 @@
package org.acejump.search
import com.intellij.openapi.editor.Editor
import it.unimi.dsi.fastutil.ints.IntList
import it.unimi.dsi.fastutil.ints.IntOpenHashSet
import org.acejump.boundaries.EditorOffsetCache
import org.acejump.boundaries.StandardBoundaries
import org.acejump.config.AceConfig
import org.acejump.immutableText
import org.acejump.input.KeyLayoutCache
import org.acejump.isWordPart
import org.acejump.wordEndPlus
import java.util.IdentityHashMap
import kotlin.math.max
/*
* Solves the Tag Assignment Problem. The tag assignment problem can be stated
* thusly: Given a set of indices I in document d, and a set of tags T, find a
* bijection f: T*⊂T → I*⊂I s.t. d[i..k] + t ∉ d[i'..(k + |t|)], ∀ i' ∈ I\{i},
* ∀ k ∈ (i, |d|-|t|], where t ∈ T, i ∈ I. Maximize |I*|. This can be relaxed
* to t=t[0] and ∀ k ∈ (i, i+K] for some fixed K, in most natural documents.
*
* More concretely, tags are typically two-character strings containing alpha-
* numeric symbols. Documents are plaintext files. Indices are produced by a
* search query of length N, i.e. the preceding N characters of every index i in
* document d are identical. For characters proceeding d[i], all bets are off.
* We can assume that P(d[i]|d[i-1]) has some structure for d~D. Ultimately, we
* want a fast algorithm which maximizes the number of tagged document indices.
*
* Tags are used by the typist to select indices within a document. To select an
* index, the typist starts by activating AceJump and searching for a character.
* As soon as the first character is received, we begin to scan the document for
* matching locations and assign as many valid tags as possible. When subsequent
* characters are received, we refine the search results to match either:
*
* 1.) The plaintext query alone, or
* 2.) The concatenation of plaintext query and partial tag
*
* The constraint in paragraph no. 1 tries to impose the following criteria:
*
* 1.) All valid key sequences will lead to a unique location in the document
* 2.) All indices in the document will be reachable by a short key sequence
*
* If there is an insufficient number of two-character tags to cover every index
* (which typically occurs when the user searches for a common character within
* a long document), then we attempt to maximize the number of tags assigned to
* document indices. The key is, all tags must be assigned as soon as possible,
* i.e. as soon as the first character is received or whenever the user ceases
* typing (at the very latest). Once assigned, a visible tag must never change
* at any time during the selection process, so as not to confuse the user.
*/
internal class Solver private constructor(
private val editorPriority: List<Editor>,
private val queryLength: Int,
private val newResults: Map<Editor, IntList>,
private val allResults: Map<Editor, IntList>,
) {
companion object {
fun solve(
editorPriority: List<Editor>,
query: SearchQuery,
newResults: Map<Editor, IntList>,
allResults: Map<Editor, IntList>,
tags: List<String>,
caches: Map<Editor, EditorOffsetCache>,
): Map<String, Tag> {
return Solver(editorPriority, max(1, query.rawText.length), newResults, allResults).map(tags, caches)
}
}
private var newTags = HashMap<String, Tag>(KeyLayoutCache.allPossibleTags.size)
private val newTagIndices = newResults.keys.associateWith { IntOpenHashSet() }
private var allWordFragments = HashSet<String>(allResults.values.sumBy(IntList::size)).apply {
for ((editor, offsets) in allResults) {
val chars = editor.immutableText
val iter = offsets.iterator()
while (iter.hasNext()) {
forEachWordFragment(chars, iter.nextInt(), this::add)
}
}
}
private fun generateEligibleSites(availableTags: List<String>): Map<String, MutableList<Tag>> {
val eligibleSitesByTag = HashMap<String, MutableList<Tag>>(100)
val tagsByFirstLetter = availableTags.groupBy { it[0] }
for ((editor, offsets) in newResults) {
val chars = editor.immutableText
val iter = offsets.iterator()
while (iter.hasNext()) {
val site = iter.nextInt()
for ((firstLetter, tags) in tagsByFirstLetter.entries) {
if (canTagBeginWithChar(chars, site, firstLetter)) {
for (tag in tags) {
eligibleSitesByTag.getOrPut(tag, ::mutableListOf).add(Tag(editor, site))
}
}
}
}
}
return eligibleSitesByTag
}
private fun generateMatchingSites(
eligibleSites: Map<String, MutableList<Tag>>,
caches: Map<Editor, EditorOffsetCache>,
): Map<String, Iterator<Tag>> {
val matchingSites = HashMap<MutableList<Tag>, Iterator<Tag>>()
val matchingSitesSorted = IdentityHashMap<String, Iterator<Tag>>() // Keys are guaranteed to be from a single collection.
val siteOrder = siteOrder(caches)
for ((mark, tags) in eligibleSites.entries) {
matchingSitesSorted[mark] = matchingSites.getOrPut(tags) {
@Suppress("ConvertLambdaToReference")
tags.toMutableList().apply { sortWith(siteOrder) }.iterator()
}
}
return matchingSitesSorted
}
fun map(availableTags: List<String>, caches: Map<Editor, EditorOffsetCache>): Map<String, Tag> {
val eligibleSitesByTag = generateEligibleSites(availableTags)
val matchingSitesSorted = generateMatchingSites(eligibleSitesByTag, caches)
val tagOrder = KeyLayoutCache.tagOrder
.thenComparingInt { eligibleSitesByTag.getValue(it).size }
.thenBy(AceConfig.layout.priority(String::last))
val sortedTags = eligibleSitesByTag.keys.toMutableList().apply {
sortWith(tagOrder)
}
var totalAssigned = 0
val totalResults = newResults.values.sumBy(IntList::size)
for (tag in sortedTags) {
if (totalAssigned == totalResults) {
break
}
if (tryToAssignTag(tag, matchingSitesSorted.getValue(tag))) {
totalAssigned++
}
}
return newTags
}
private fun tryToAssignTag(mark: String, tags: Iterator<Tag>): Boolean {
if (newTags.containsKey(mark)) {
return false
}
while (tags.hasNext()) {
val tag = tags.next()
val assigned = newTagIndices.getValue(tag.editor)
if (tag.offset !in assigned) {
newTags[mark] = tag
assigned.add(tag.offset)
return true
}
}
return false
}
private fun siteOrder(caches: Map<Editor, EditorOffsetCache>) = Comparator<Tag> { a, b ->
val aEditor = a.editor
val bEditor = b.editor
if (aEditor !== bEditor) {
val aEditorIndex = editorPriority.indexOf(aEditor)
val bEditorIndex = editorPriority.indexOf(bEditor)
// For multiple editors, prioritize them based on the provided order.
return@Comparator if (aEditorIndex < bEditorIndex) -1 else 1
}
val aIsVisible = StandardBoundaries.VISIBLE_ON_SCREEN.isOffsetInside(aEditor, a.offset, caches.getValue(aEditor))
val bIsVisible = StandardBoundaries.VISIBLE_ON_SCREEN.isOffsetInside(bEditor, b.offset, caches.getValue(bEditor))
if (aIsVisible != bIsVisible) {
// Sites in immediate view should come first.
return@Comparator if (aIsVisible) -1 else 1
}
val aIsNotWordStart = aEditor.immutableText[max(0, a.offset - 1)].isWordPart
val bIsNotWordStart = bEditor.immutableText[max(0, b.offset - 1)].isWordPart
if (aIsNotWordStart != bIsNotWordStart) {
// Ensure that the first letter of a word is prioritized for tagging.
return@Comparator if (bIsNotWordStart) -1 else 1
}
when {
a.offset < b.offset -> -1
a.offset > b.offset -> 1
else -> 0
}
}
private fun canTagBeginWithChar(chars: CharSequence, site: Int, char: Char): Boolean {
if (char.toString() in allWordFragments) {
return false
}
forEachWordFragment(chars, site) {
if (it + char in allWordFragments) {
return false
}
}
return true
}
private inline fun forEachWordFragment(chars: CharSequence, site: Int, callback: (String) -> Unit) {
val left = max(0, site + queryLength - 1)
val right = chars.wordEndPlus(site)
val builder = StringBuilder(1 + right - left)
for (i in left..right) {
builder.append(chars[i].toLowerCase())
callback(builder.toString())
}
}
}

View File

@@ -1,93 +1,136 @@
package org.acejump.search package org.acejump.search
import com.google.common.collect.ArrayListMultimap import com.google.common.collect.ArrayListMultimap
import com.google.common.collect.HashBiMap
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import it.unimi.dsi.fastutil.ints.IntArrayList
import it.unimi.dsi.fastutil.ints.IntList import it.unimi.dsi.fastutil.ints.IntList
import org.acejump.ExternalUsage import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap
import org.acejump.boundaries.EditorOffsetCache import org.acejump.boundaries.EditorOffsetCache
import org.acejump.boundaries.StandardBoundaries import org.acejump.boundaries.StandardBoundaries.VISIBLE_ON_SCREEN
import org.acejump.immutableText import org.acejump.input.KeyLayoutCache
import org.acejump.input.KeyLayoutCache.allPossibleTags
import org.acejump.isWordPart
import org.acejump.matchesAt
import org.acejump.view.TagMarker import org.acejump.view.TagMarker
import java.util.AbstractMap.SimpleImmutableEntry
import kotlin.collections.component1 import kotlin.collections.component1
import kotlin.collections.component2 import kotlin.collections.component2
import kotlin.math.min import kotlin.math.min
/** /**
* Assigns tags to search occurrences, updates them when the search query changes, and requests a jump if the search query matches a tag. * Assigns tags to search occurrences.
* The ordering of [editors] may be used to prioritize tagging editors earlier in the list in case of conflicts. * The ordering of [editors] may be used to prioritize tagging editors earlier in the list in case of conflicts.
*/ */
class Tagger(private val editors: List<Editor>) { class Tagger(private val editors: List<Editor>, results: Map<Editor, IntList>) {
private var tagMap = HashBiMap.create<String, Tag>() private var tagMap: Map<String, Tag>
private var typedTag = ""
val hasTags internal val markers: Map<Editor, Collection<TagMarker>>
get() = tagMap.isNotEmpty() get() {
val markers = ArrayListMultimap.create<Editor, TagMarker>(editors.size, min(tagMap.values.size, 40))
@ExternalUsage for ((mark, tag) in tagMap) {
internal val tags val marker = TagMarker.create(mark, tag.offset, typedTag)
get() = tagMap.map { SimpleImmutableEntry(it.key, it.value) }.sortedBy { it.value.offset } markers.put(tag.editor, marker)
/**
* Removes all markers, allowing them to be regenerated from scratch.
*/
internal fun unmark() {
tagMap = HashBiMap.create()
} }
/** return markers.asMap()
* Assigns tags to as many results as possible, keeping previously assigned tags. Returns a [TaggingResult.Accept] if the current search
* query matches any existing tag and we should jump to it and end the session, or [TaggingResult.Mark] to continue the session with
* updated tag markers.
*
* Note that the [results] collection will be mutated.
*/
internal fun update(query: SearchQuery, results: Map<Editor, IntList>): TaggingResult {
val isRegex = query is SearchQuery.RegularExpression
val queryText = if (isRegex) " ${query.rawText}" else query.rawText[0] + query.rawText.drop(1).toLowerCase()
val availableTags = allPossibleTags.filter { !queryText.endsWith(it[0]) && it !in tagMap }
if (!isRegex) {
for (entry in tagMap.entries) {
if (entry solves queryText) {
return TaggingResult.Accept(entry.value)
}
} }
if (queryText.length == 1) { init {
for ((editor, offsets) in results) {
removeResultsWithOverlappingTags(editor, offsets)
}
}
}
if (!isRegex || tagMap.isEmpty()) {
tagMap = assignTagsAndMerge(results, availableTags, query, queryText)
}
val resultTags = results.flatMap { (editor, offsets) -> offsets.map { Tag(editor, it) } }
return TaggingResult.Mark(createTagMarkers(resultTags, query.rawText.ifEmpty { null }))
}
/**
* Assigns as many unassigned tags as possible, and merges them with the existing compatible tags.
*/
private fun assignTagsAndMerge(
results: Map<Editor, IntList>, availableTags: List<String>, query: SearchQuery, queryText: String,
): HashBiMap<String, Tag> {
val caches = results.keys.associateWith { EditorOffsetCache.new() } val caches = results.keys.associateWith { EditorOffsetCache.new() }
sortResults(results, caches)
val tagSites = results
.flatMap { (editor, sites) -> sites.map { site -> Tag(editor, site) } }
.sortedWith(siteOrder(editors, caches))
tagMap = generateTags(tagSites.size).zip(tagSites).toMap()
}
internal fun type(char: Char): TaggingResult {
val newTypedTag = typedTag + char.lowercaseChar()
val matchingTag = tagMap[newTypedTag]
if (matchingTag != null) {
return TaggingResult.Accept(matchingTag)
}
val newTagMap = tagMap.filter { it.key.startsWith(newTypedTag) }
if (newTagMap.isEmpty()) {
return TaggingResult.Nothing
}
typedTag = newTypedTag
tagMap = newTagMap
return TaggingResult.Mark(markers)
}
private companion object {
private fun generateTags(tagCount: Int): List<String> {
val allowedTagsSorted = KeyLayoutCache.allowedTagsSorted
val tags = mutableListOf<String>()
val containedSingleCharTags = mutableSetOf<Char>()
val blockedSingleCharTags = mutableSetOf<Char>()
val doubleCharTagCountsByFirstChar = Object2IntOpenHashMap<Char>()
for (tag in allowedTagsSorted) {
val firstChar = tag.first()
if (tag.length == 1) {
if (firstChar in blockedSingleCharTags) {
continue
}
containedSingleCharTags.add(firstChar)
}
else {
if (containedSingleCharTags.remove(firstChar)) {
tags.remove(firstChar.toString())
}
blockedSingleCharTags.add(firstChar)
doubleCharTagCountsByFirstChar.addTo(firstChar, 1)
}
tags.add(tag)
if (tags.size >= tagCount) {
break
}
}
// In rare cases, the final tag list may contain a double character tag that is the only tag starting with its first character,
// so we replace it with the single character tag.
for (entry in doubleCharTagCountsByFirstChar.object2IntEntrySet()) {
if (entry.intValue != 1) {
continue
}
tags.removeAt(tags.indexOfFirst { it.first() == entry.key })
val tag = entry.key.toString()
var previousTagIndex = -1
// The implementation of searching where to place the single character tag is theoretically slow,
// but getting here is so rare it doesn't matter.
for (i in allowedTagsSorted.indexOf(tag) - 1 downTo 0) {
previousTagIndex = tags.indexOf(allowedTagsSorted[i])
if (previousTagIndex != -1) {
break
}
}
tags.add(previousTagIndex + 1, tag)
}
return tags
}
private fun sortResults(results: Map<Editor, IntList>, caches: Map<Editor, EditorOffsetCache>) {
for ((editor, offsets) in results) { for ((editor, offsets) in results) {
val cache = caches.getValue(editor) val cache = caches.getValue(editor)
offsets.sort { a, b -> offsets.sort { a, b ->
val aIsVisible = StandardBoundaries.VISIBLE_ON_SCREEN.isOffsetInside(editor, a, cache) val aIsVisible = VISIBLE_ON_SCREEN.isOffsetInside(editor, a, cache)
val bIsVisible = StandardBoundaries.VISIBLE_ON_SCREEN.isOffsetInside(editor, b, cache) val bIsVisible = VISIBLE_ON_SCREEN.isOffsetInside(editor, b, cache)
when { when {
aIsVisible && !bIsVisible -> -1 aIsVisible && !bIsVisible -> -1
@@ -96,134 +139,36 @@ class Tagger(private val editors: List<Editor>) {
} }
} }
} }
val allAssignedTags = mutableMapOf<String, Tag>()
val oldCompatibleTags = tagMap.filter { (mark, tag) ->
isTagCompatibleWithQuery(mark, tag, queryText) || results[tag.editor]?.contains(tag.offset) == true
} }
val vacantResults: Map<Editor, IntList> private fun siteOrder(editorPriority: List<Editor>, caches: Map<Editor, EditorOffsetCache>) = Comparator<Tag> { a, b ->
val aEditor = a.editor
val bEditor = b.editor
if (oldCompatibleTags.isEmpty()) { if (aEditor !== bEditor) {
vacantResults = results val aEditorIndex = editorPriority.indexOf(aEditor)
} val bEditorIndex = editorPriority.indexOf(bEditor)
else { // For multiple editors, prioritize them based on the provided order.
val vacant = mutableMapOf<Editor, IntList>() return@Comparator if (aEditorIndex < bEditorIndex) -1 else 1
for ((editor, offsets) in results) {
val list = IntArrayList()
val iter = offsets.iterator()
while (iter.hasNext()) {
val tag = Tag(editor, iter.nextInt())
if (tag !in oldCompatibleTags.values) {
list.add(tag.offset)
}
} }
vacant[editor] = list val aCaches = caches.getValue(aEditor)
val bCaches = caches.getValue(bEditor)
val aIsVisible = VISIBLE_ON_SCREEN.isOffsetInside(aEditor, a.offset, aCaches)
val bIsVisible = VISIBLE_ON_SCREEN.isOffsetInside(bEditor, b.offset, bCaches)
if (aIsVisible != bIsVisible) {
// Sites in immediate view should come first.
return@Comparator if (aIsVisible) -1 else 1
} }
vacantResults = vacant val firstEditor = editorPriority[0]
} val caretPosition = caches.getValue(firstEditor).offsetToXY(firstEditor, firstEditor.caretModel.offset)
allAssignedTags.putAll(oldCompatibleTags) val aDistance = aCaches.offsetToXY(aEditor, a.offset).distanceSq(caretPosition)
allAssignedTags.putAll(Solver.solve(editors, query, vacantResults, results, availableTags, caches)) val bDistance = bCaches.offsetToXY(bEditor, b.offset).distanceSq(caretPosition)
val assignedMarkers = allAssignedTags.keys.groupBy { it[0] } return@Comparator aDistance.compareTo(bDistance)
return allAssignedTags.mapKeysTo(HashBiMap.create(allAssignedTags.size)) { (tag, _) ->
if (canShortenTag(tag, assignedMarkers, queryText))
tag[0].toString()
else
tag
}
}
private infix fun Map.Entry<String, Tag>.solves(query: String): Boolean {
return query.endsWith(key, true) && isTagCompatibleWithQuery(key, value, query)
}
private fun isTagCompatibleWithQuery(marker: String, tag: Tag, query: String): Boolean {
return tag.editor.immutableText.matchesAt(tag.offset, getPlaintextPortion(query, marker), ignoreCase = true)
}
fun isQueryCompatibleWithTagAt(query: String, tag: Tag): Boolean {
return tagMap.inverse()[tag].let { it != null && isTagCompatibleWithQuery(it, tag, query) }
}
fun canQueryMatchAnyTag(query: String): Boolean {
return tagMap.any { (tag, offset) ->
val tagPortion = getTagPortion(query, tag)
tagPortion.isNotEmpty() && tag.startsWith(tagPortion, ignoreCase = true) && isTagCompatibleWithQuery(tag, offset, query)
}
}
private fun removeResultsWithOverlappingTags(editor: Editor, offsets: IntList) {
val iter = offsets.iterator()
val chars = editor.immutableText
while (iter.hasNext()) {
if (!chars.canTagWithoutOverlap(iter.nextInt())) {
iter.remove() // Very uncommon, so slow removal is fine.
}
}
}
private fun createTagMarkers(tags: Collection<Tag>, literalQueryText: String?): MutableMap<Editor, Collection<TagMarker>> {
val tagMapInv = tagMap.inverse()
val markers = ArrayListMultimap.create<Editor, TagMarker>(editors.size, min(tags.size, 50))
for (tag in tags) {
val mark = tagMapInv[tag] ?: continue
val editor = tag.editor
val marker = TagMarker.create(editor, mark, tag.offset, literalQueryText)
markers.put(editor, marker)
}
return markers.asMap()
}
private companion object {
private fun CharSequence.canTagWithoutOverlap(loc: Int) = when {
loc - 1 < 0 -> true
loc + 1 >= length -> true
this[loc] isUnlike this[loc - 1] -> true
this[loc] isUnlike this[loc + 1] -> true
this[loc] != this[loc - 1] -> true
this[loc] != this[loc + 1] -> true
this[loc + 1] == '\r' || this[loc + 1] == '\n' -> true
this[loc - 1] == this[loc] && this[loc] == this[loc + 1] -> false
this[loc + 1].isWhitespace() && this[(loc + 2).coerceAtMost(length - 1)].isWhitespace() -> true
else -> false
}
private infix fun Char.isUnlike(other: Char): Boolean {
return this.isWordPart xor other.isWordPart || this.isWhitespace() xor other.isWhitespace()
}
private fun getPlaintextPortion(query: String, marker: String) = when {
query.endsWith(marker, true) -> query.dropLast(marker.length)
query.endsWith(marker.first(), true) -> query.dropLast(1)
else -> query
}
private fun getTagPortion(query: String, marker: String) = when {
query.endsWith(marker, true) -> query.takeLast(marker.length)
query.endsWith(marker.first(), true) -> query.takeLast(1)
else -> ""
}
private fun canShortenTag(marker: String, markers: Map<Char, List<String>>, queryText: String): Boolean {
// Avoid matching query - will trigger a jump.
// TODO: lift this constraint.
val queryEndsWith = queryText.endsWith(marker[0]) || queryText.endsWith(marker)
if (queryEndsWith) {
return false
}
val startingWithSameLetter = markers[marker[0]]
return startingWithSameLetter == null || startingWithSameLetter.singleOrNull() == marker
} }
} }
} }

View File

@@ -4,6 +4,7 @@ import com.intellij.openapi.editor.Editor
import org.acejump.view.TagMarker import org.acejump.view.TagMarker
internal sealed class TaggingResult { internal sealed class TaggingResult {
object Nothing : TaggingResult()
class Accept(val tag: Tag) : TaggingResult() class Accept(val tag: Tag) : TaggingResult()
class Mark(val markers: MutableMap<Editor, Collection<TagMarker>>) : TaggingResult() class Mark(val markers: Map<Editor, Collection<TagMarker>>) : TaggingResult()
} }

View File

@@ -1,23 +1,29 @@
package org.acejump.session package org.acejump.session
import com.intellij.codeInsight.hint.HintManagerImpl import com.intellij.codeInsight.hint.HintManagerImpl
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ScrollType import com.intellij.openapi.editor.ScrollType
import com.intellij.openapi.editor.actionSystem.TypedActionHandler
import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.editor.colors.impl.AbstractColorsScheme import com.intellij.openapi.editor.colors.impl.AbstractColorsScheme
import org.acejump.ExternalUsage import it.unimi.dsi.fastutil.ints.IntList
import org.acejump.boundaries.Boundaries import org.acejump.boundaries.Boundaries
import org.acejump.boundaries.StandardBoundaries import org.acejump.boundaries.StandardBoundaries
import org.acejump.clone
import org.acejump.config.AceConfig import org.acejump.config.AceConfig
import org.acejump.input.EditorKeyListener import org.acejump.input.EditorKeyListener
import org.acejump.input.KeyLayoutCache import org.acejump.input.KeyLayoutCache
import org.acejump.modes.JumpMode import org.acejump.modes.JumpMode
import org.acejump.modes.SessionMode import org.acejump.modes.SessionMode
import org.acejump.search.* import org.acejump.search.Pattern
import org.acejump.search.SearchProcessor
import org.acejump.search.SearchQuery
import org.acejump.search.Tag
import org.acejump.session.TypeResult.AcceptTag
import org.acejump.session.TypeResult.ChangeMode
import org.acejump.session.TypeResult.ChangeState
import org.acejump.session.TypeResult.EndSession
import org.acejump.session.TypeResult.Nothing
import org.acejump.view.TagCanvas import org.acejump.view.TagCanvas
import org.acejump.view.TagMarker
import org.acejump.view.TextHighlighter import org.acejump.view.TextHighlighter
/** /**
@@ -27,8 +33,7 @@ class Session(private val mainEditor: Editor, private val jumpEditors: List<Edit
private val editorSettings = EditorSettings.setup(mainEditor) private val editorSettings = EditorSettings.setup(mainEditor)
private lateinit var mode: SessionMode private lateinit var mode: SessionMode
private var state: SessionStateImpl? = null private var state: SessionState? = null
private var tagger = Tagger(jumpEditors)
private var acceptedTag: Tag? = null private var acceptedTag: Tag? = null
set(value) { set(value) {
@@ -43,69 +48,48 @@ class Session(private val mainEditor: Editor, private val jumpEditors: List<Edit
private val textHighlighter = TextHighlighter() private val textHighlighter = TextHighlighter()
private val tagCanvases = jumpEditors.associateWith(::TagCanvas) private val tagCanvases = jumpEditors.associateWith(::TagCanvas)
@ExternalUsage
val tags
get() = tagger.tags
var defaultBoundary: Boundaries = StandardBoundaries.VISIBLE_ON_SCREEN var defaultBoundary: Boundaries = StandardBoundaries.VISIBLE_ON_SCREEN
private val actions = object : SessionActions {
override fun showHighlights(results: Map<Editor, IntList>, query: SearchQuery) {
textHighlighter.renderOccurrences(results, query)
}
override fun hideHighlights() {
textHighlighter.reset()
}
override fun setTagMarkers(markers: Map<Editor, Collection<TagMarker>>) {
for ((editor, canvas) in tagCanvases) {
canvas.setMarkers(markers[editor].orEmpty())
}
}
}
init { init {
KeyLayoutCache.ensureInitialized(AceConfig.settings) KeyLayoutCache.ensureInitialized(AceConfig.settings)
EditorKeyListener.attach(mainEditor) { editor, charTyped, _ -> typeCharacter(editor, charTyped) }
}
EditorKeyListener.attach(mainEditor, object : TypedActionHandler { private fun typeCharacter(editor: Editor, charTyped: Char) {
override fun execute(editor: Editor, charTyped: Char, context: DataContext) {
val state = state ?: return val state = state ?: return
val hadTags = tagger.hasTags
editorSettings.startEditing(editor) editorSettings.startEditing(editor)
val result = mode.type(state, charTyped, acceptedTag) val result = mode.type(state, charTyped, acceptedTag)
editorSettings.stopEditing(editor) editorSettings.stopEditing(editor)
when (result) { when (result) {
TypeResult.Nothing -> return; Nothing -> return
is TypeResult.UpdateResults -> updateSearch(result.processor, markImmediately = hadTags) is ChangeState -> this.state = result.state
is TypeResult.ChangeMode -> setMode(result.mode) is ChangeMode -> setMode(result.mode)
TypeResult.RestartSearch -> restart().also { is AcceptTag -> {
this@Session.state = SessionStateImpl(jumpEditors, tagger, defaultBoundary)
}
TypeResult.EndSession -> end()
}
}
})
}
/**
* Updates text highlights and tag markers according to the current search state. Dispatches jumps if the search query matches a tag.
*/
private fun updateSearch(processor: SearchProcessor, markImmediately: Boolean) {
val query = processor.query
val results = processor.results
if (!markImmediately && query.rawText.let { it.length < AceConfig.minQueryLength && it.all(Char::isLetterOrDigit) }) {
textHighlighter.renderOccurrences(results, query)
return
}
when (val result = tagger.update(query, results.clone())) {
is TaggingResult.Accept -> {
acceptedTag = result.tag acceptedTag = result.tag
textHighlighter.renderFinal(result.tag, processor.query) mode.accept(state, result.tag)
if (state?.let { mode.accept(it, result.tag) } == true) {
end() end()
return
}
} }
is TaggingResult.Mark -> { EndSession -> end()
for ((editor, canvas) in tagCanvases) {
canvas.setMarkers(result.markers[editor].orEmpty())
}
textHighlighter.renderOccurrences(results, query)
}
} }
} }
@@ -129,7 +113,7 @@ class Session(private val mainEditor: Editor, private val jumpEditors: List<Edit
} }
setMode(mode()) setMode(mode())
state = SessionStateImpl(jumpEditors, tagger, defaultBoundary) state = SessionState.WaitForKey(actions, jumpEditors, defaultBoundary, AceConfig.invertUppercaseMode)
} }
/** /**
@@ -140,22 +124,18 @@ class Session(private val mainEditor: Editor, private val jumpEditors: List<Edit
setMode(JumpMode()) setMode(JumpMode())
} }
tagger = Tagger(jumpEditors) for (canvas in tagCanvases.values) {
tagCanvases.values.forEach { it.setMarkers(emptyList()) } canvas.setMarkers(emptyList())
}
val processor = SearchProcessor.fromRegex(jumpEditors, pattern.regex, defaultBoundary) val processor = SearchProcessor(jumpEditors, SearchQuery.RegularExpression(pattern.regex), defaultBoundary, AceConfig.invertUppercaseMode)
state = SessionStateImpl(jumpEditors, tagger, defaultBoundary, processor) textHighlighter.renderOccurrences(processor.resultsCopy, processor.query)
updateSearch(processor, markImmediately = true) state = SessionState.SelectTag(actions, jumpEditors, processor)
} }
fun tagImmediately() { fun tagImmediately() {
val state = state ?: return typeCharacter(mainEditor, '\n')
val processor = state.currentProcessor
if (processor != null) {
updateSearch(processor, markImmediately = true)
}
} }
/** /**
@@ -170,7 +150,6 @@ class Session(private val mainEditor: Editor, private val jumpEditors: List<Edit
*/ */
fun restart() { fun restart() {
state = null state = null
tagger = Tagger(jumpEditors)
acceptedTag = null acceptedTag = null
tagCanvases.values.forEach(TagCanvas::removeMarkers) tagCanvases.values.forEach(TagCanvas::removeMarkers)
textHighlighter.reset() textHighlighter.reset()
@@ -185,7 +164,6 @@ class Session(private val mainEditor: Editor, private val jumpEditors: List<Edit
* Should only be used from [SessionManager] to dispose a successfully ended session. * Should only be used from [SessionManager] to dispose a successfully ended session.
*/ */
internal fun dispose() { internal fun dispose() {
tagger = Tagger(jumpEditors)
tagCanvases.values.forEach(TagCanvas::unbind) tagCanvases.values.forEach(TagCanvas::unbind)
textHighlighter.reset() textHighlighter.reset()
EditorKeyListener.detach(mainEditor) EditorKeyListener.detach(mainEditor)

View File

@@ -0,0 +1,13 @@
package org.acejump.session
import com.intellij.openapi.editor.Editor
import it.unimi.dsi.fastutil.ints.IntList
import org.acejump.search.SearchQuery
import org.acejump.view.TagMarker
internal interface SessionActions {
fun showHighlights(results: Map<Editor, IntList>, query: SearchQuery)
fun hideHighlights()
fun setTagMarkers(markers: Map<Editor, Collection<TagMarker>>)
}

View File

@@ -1,9 +1,95 @@
package org.acejump.session package org.acejump.session
import org.acejump.action.AceTagAction import com.intellij.openapi.editor.Editor
import org.acejump.search.Tag import org.acejump.boundaries.Boundaries
import org.acejump.boundaries.StandardBoundaries
import org.acejump.config.AceConfig
import org.acejump.search.SearchProcessor
import org.acejump.search.SearchQuery
import org.acejump.search.Tagger
import org.acejump.search.TaggingResult
interface SessionState { sealed interface SessionState {
fun type(char: Char): TypeResult fun type(char: Char): TypeResult
fun act(action: AceTagAction, tag: Tag, shiftMode: Boolean, isFinal: Boolean)
class WaitForKey internal constructor(
private val actions: SessionActions,
private val jumpEditors: List<Editor>,
private val defaultBoundary: Boundaries,
private val invertUppercaseMode: Boolean,
) : SessionState {
override fun type(char: Char): TypeResult {
val searchProcessor = SearchProcessor(jumpEditors, SearchQuery.Literal(char.toString()), defaultBoundary, invertUppercaseMode)
return if (searchProcessor.isQueryFinished) {
TypeResult.ChangeState(SelectTag(actions, jumpEditors, searchProcessor))
}
else {
TypeResult.ChangeState(RefineSearchQuery(actions, jumpEditors, searchProcessor))
}
}
}
class RefineSearchQuery internal constructor(
private val actions: SessionActions,
private val jumpEditors: List<Editor>,
private val searchProcessor: SearchProcessor,
) : SessionState {
init {
actions.showHighlights(searchProcessor.resultsCopy, searchProcessor.query)
}
override fun type(char: Char): TypeResult {
return if (searchProcessor.refineQuery(char)) {
actions.hideHighlights()
TypeResult.ChangeState(SelectTag(actions, jumpEditors, searchProcessor))
}
else {
actions.showHighlights(searchProcessor.resultsCopy, searchProcessor.query)
TypeResult.Nothing
}
}
}
class SelectTag internal constructor(
private val actions: SessionActions,
private val jumpEditors: List<Editor>,
private val searchProcessor: SearchProcessor,
) : SessionState {
private val tagger = Tagger(jumpEditors, searchProcessor.resultsCopy)
init {
actions.setTagMarkers(tagger.markers)
}
override fun type(char: Char): TypeResult {
if (char == ' ') {
val query = searchProcessor.query
if (query is SearchQuery.Literal) {
val newBoundaries = when (searchProcessor.boundaries) {
StandardBoundaries.VISIBLE_ON_SCREEN -> StandardBoundaries.AFTER_CARET
StandardBoundaries.AFTER_CARET -> StandardBoundaries.BEFORE_CARET
StandardBoundaries.BEFORE_CARET -> StandardBoundaries.VISIBLE_ON_SCREEN
else -> searchProcessor.boundaries
}
val newSearchProcessor = SearchProcessor(jumpEditors, query, newBoundaries, searchProcessor.invertUppercaseMode)
return TypeResult.ChangeState(SelectTag(actions, jumpEditors, newSearchProcessor))
}
}
else if (char == '\n') {
val newSearchProcessor = SearchProcessor(jumpEditors, searchProcessor.query, searchProcessor.boundaries, !searchProcessor.invertUppercaseMode)
return TypeResult.ChangeState(SelectTag(actions, jumpEditors, newSearchProcessor))
}
return when (val result = tagger.type(AceConfig.layout.characterRemapping.getOrDefault(char, char))) {
is TaggingResult.Nothing -> TypeResult.Nothing
is TaggingResult.Accept -> TypeResult.AcceptTag(result.tag)
is TaggingResult.Mark -> {
actions.setTagMarkers(result.markers)
TypeResult.Nothing
}
}
}
}
} }

View File

@@ -1,36 +0,0 @@
package org.acejump.session
import com.intellij.openapi.editor.Editor
import org.acejump.action.AceTagAction
import org.acejump.boundaries.Boundaries
import org.acejump.search.SearchProcessor
import org.acejump.search.Tag
import org.acejump.search.Tagger
internal class SessionStateImpl(
private val jumpEditors: List<Editor>,
private val tagger: Tagger,
private val defaultBoundary: Boundaries,
processor: SearchProcessor? = null
) : SessionState {
internal var currentProcessor: SearchProcessor? = processor
override fun type(char: Char): TypeResult {
val processor = currentProcessor
if (processor == null) {
val newProcessor = SearchProcessor.fromChar(jumpEditors, char, defaultBoundary)
return TypeResult.UpdateResults(newProcessor.also { currentProcessor = it })
}
if (processor.type(char, tagger)) {
return TypeResult.UpdateResults(processor)
}
return TypeResult.Nothing
}
override fun act(action: AceTagAction, tag: Tag, shiftMode: Boolean, isFinal: Boolean) {
currentProcessor?.let { action(tag.editor, it, tag.offset, shiftMode, isFinal) }
}
}

View File

@@ -1,12 +1,12 @@
package org.acejump.session package org.acejump.session
import org.acejump.modes.SessionMode import org.acejump.modes.SessionMode
import org.acejump.search.SearchProcessor import org.acejump.search.Tag
sealed class TypeResult { sealed class TypeResult {
object Nothing : TypeResult() object Nothing : TypeResult()
class UpdateResults(val processor: SearchProcessor) : TypeResult() class ChangeState(val state: SessionState) : TypeResult()
class ChangeMode(val mode: SessionMode) : TypeResult() class ChangeMode(val mode: SessionMode) : TypeResult()
object RestartSearch : TypeResult() class AcceptTag(val tag: Tag) : TypeResult()
object EndSession : TypeResult() object EndSession : TypeResult()
} }

View File

@@ -2,10 +2,10 @@ package org.acejump.view
import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.event.CaretEvent import com.intellij.ui.ColorUtil
import com.intellij.openapi.editor.event.CaretListener
import org.acejump.boundaries.EditorOffsetCache import org.acejump.boundaries.EditorOffsetCache
import org.acejump.boundaries.StandardBoundaries import org.acejump.boundaries.StandardBoundaries
import org.acejump.config.AceConfig
import java.awt.Graphics import java.awt.Graphics
import java.awt.Graphics2D import java.awt.Graphics2D
import java.awt.Rectangle import java.awt.Rectangle
@@ -16,8 +16,9 @@ import javax.swing.SwingUtilities
/** /**
* Holds all active tag markers and renders them on top of the editor. * Holds all active tag markers and renders them on top of the editor.
*/ */
internal class TagCanvas(private val editor: Editor) : JComponent(), CaretListener { internal class TagCanvas(private val editor: Editor) : JComponent() {
private var markers: Collection<TagMarker>? = null private var markers: Collection<TagMarker> = emptyList()
private var visible = false
init { init {
val contentComponent = editor.contentComponent val contentComponent = editor.contentComponent
@@ -27,43 +28,38 @@ internal class TagCanvas(private val editor: Editor) : JComponent(), CaretListen
if (ApplicationInfo.getInstance().build.components.first() < 173) { if (ApplicationInfo.getInstance().build.components.first() < 173) {
SwingUtilities.convertPoint(this, location, editor.component.rootPane).let { setLocation(-it.x, -it.y) } SwingUtilities.convertPoint(this, location, editor.component.rootPane).let { setLocation(-it.x, -it.y) }
} }
editor.caretModel.addCaretListener(this)
} }
fun unbind() { fun unbind() {
markers = null
editor.contentComponent.remove(this) editor.contentComponent.remove(this)
editor.caretModel.removeCaretListener(this) editor.contentComponent.repaint()
}
/**
* Ensures that all tags and the outline around the selected tag are repainted. It should not be necessary to repaint the entire tag
* canvas, but the cost of repainting visible tags is negligible.
*/
override fun caretPositionChanged(event: CaretEvent) {
repaint()
} }
fun setMarkers(markers: Collection<TagMarker>) { fun setMarkers(markers: Collection<TagMarker>) {
this.markers = markers this.markers = markers
this.visible = true
repaint() repaint()
} }
fun removeMarkers() { fun removeMarkers() {
this.markers = emptyList() this.markers = emptyList()
} this.visible = false
repaint()
override fun paint(g: Graphics) {
if (!markers.isNullOrEmpty()) {
super.paint(g)
}
} }
override fun paintChildren(g: Graphics) { override fun paintChildren(g: Graphics) {
super.paintChildren(g) super.paintChildren(g)
val markers = markers ?: return if (!visible) {
return
}
g.color = ColorUtil.withAlpha(editor.colorsScheme.defaultBackground, (AceConfig.editorFadeOpacity * 0.01).coerceIn(0.0, 1.0))
g.fillRect(0, 0, width - 1, height - 1)
if (markers.isEmpty()) {
return
}
(g as Graphics2D).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) (g as Graphics2D).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
@@ -73,18 +69,8 @@ internal class TagCanvas(private val editor: Editor) : JComponent(), CaretListen
val viewRange = StandardBoundaries.VISIBLE_ON_SCREEN.getOffsetRange(editor, cache) val viewRange = StandardBoundaries.VISIBLE_ON_SCREEN.getOffsetRange(editor, cache)
val occupied = mutableListOf<Rectangle>() val occupied = mutableListOf<Rectangle>()
// If there is a tag at the caret location, prioritize its rendering over all other tags. This is helpful for seeing which tag is
// currently selected while navigating highly clustered tags, although it does end up rearranging nearby tags which can be confusing.
// TODO instead of immediately painting, we could calculate the layout of everything first, and then remove tags that interfere with
// the caret tag to avoid changing the alignment of the caret tag
val caretOffset = editor.caretModel.offset
val caretMarker = markers.find { it.offsetL == caretOffset || it.offsetR == caretOffset }
caretMarker?.paint(g, editor, cache, font, occupied)
for (marker in markers) { for (marker in markers) {
if (marker.isOffsetInRange(viewRange) && marker !== caretMarker) { if (marker.offset in viewRange) {
marker.paint(g, editor, cache, font, occupied) marker.paint(g, editor, cache, font, occupied)
} }
} }

View File

@@ -2,23 +2,19 @@ package org.acejump.view
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.colors.EditorFontType import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.ui.ColorUtil
import org.acejump.config.AceConfig import org.acejump.config.AceConfig
import java.awt.Font import java.awt.Font
import java.awt.FontMetrics
/** /**
* Stores font metrics for aligning and rendering [TagMarker]s. * Stores font metrics for aligning and rendering [TagMarker]s.
*/ */
internal class TagFont(editor: Editor) { internal class TagFont(editor: Editor) {
val tagFont: Font = editor.colorsScheme.getFont(EditorFontType.BOLD) val tagFont: Font = editor.colorsScheme.getFont(EditorFontType.PLAIN)
val tagCharWidth = editor.component.getFontMetrics(tagFont).charWidth('W') val tagCharWidth = editor.component.getFontMetrics(tagFont).charWidth('W')
val foregroundColor = AceConfig.tagForegroundColor val foregroundColor1 = AceConfig.tagForegroundColor1
var backgroundColor = AceConfig.tagBackgroundColor val foregroundColor2 = AceConfig.tagForegroundColor2
val isForegroundDark = ColorUtil.isDark(foregroundColor)
val editorFontMetrics: FontMetrics = editor.component.getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN))
val lineHeight = editor.lineHeight val lineHeight = editor.lineHeight
val baselineDistance = editor.ascent val baselineDistance = editor.ascent
} }

View File

@@ -2,91 +2,37 @@ package org.acejump.view
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.scale.JBUIScale
import org.acejump.boundaries.EditorOffsetCache import org.acejump.boundaries.EditorOffsetCache
import org.acejump.boundaries.StandardBoundaries
import org.acejump.countMatchingCharacters
import org.acejump.immutableText
import java.awt.Color import java.awt.Color
import java.awt.Graphics2D import java.awt.Graphics2D
import java.awt.Point import java.awt.Point
import java.awt.Rectangle import java.awt.Rectangle
import kotlin.math.max
/** /**
* Describes a 1 or 2 character shortcut that points to a specific character in the editor. * Describes a 1 or 2 character shortcut that points to a specific character in the editor.
*/ */
internal class TagMarker( internal class TagMarker(
private val tag: String, private val firstChar: String,
val offsetL: Int, private val secondChar: String,
val offsetR: Int, val offset: Int
private val shiftR: Int,
private val hasSpaceRight: Boolean
) { ) {
private val length = tag.length private constructor(tag: String, offset: Int) : this(tag.first().toString(), tag.drop(1), offset)
private val length = firstChar.length + secondChar.length
companion object { companion object {
private const val ARC = 1
/** /**
* TODO This might be due to DPI settings. * TODO This might be due to DPI settings.
*/ */
private val HIGHLIGHT_OFFSET = if (SystemInfo.isMac) -0.5 else 0.0 private val HIGHLIGHT_OFFSET = if (SystemInfo.isMac) -0.5 else 0.0
private val SHADOW_COLOR = Color(0F, 0F, 0F, 0.35F)
/** /**
* Creates a new tag, precomputing some information about the nearby characters to reduce rendering overhead. If the last typed * Creates a new tag, precomputing some information about the nearby characters to reduce rendering overhead. If the last typed
* character ([literalQueryText]) matches the first [tag] character, only the second [tag] character is displayed. * character ([typedTag]) matches the first [tag] character, only the second [tag] character is displayed.
*/ */
fun create(editor: Editor, tag: String, offset: Int, literalQueryText: String?): TagMarker { fun create(tag: String, offset: Int, typedTag: String): TagMarker {
val chars = editor.immutableText return TagMarker(tag.drop(typedTag.length), offset)
val matching = literalQueryText?.let { chars.countMatchingCharacters(offset, it) } ?: 0
val hasSpaceRight = offset + 1 >= chars.length || chars[offset + 1].isWhitespace()
val displayedTag = if (literalQueryText != null && literalQueryText.last().equals(tag.first(), ignoreCase = true))
tag.drop(1).toUpperCase()
else
tag.toUpperCase()
return TagMarker(displayedTag, offset, offset + max(0, matching - 1), tag.length - displayedTag.length, hasSpaceRight)
} }
/**
* Renders the tag background.
*/
private fun drawHighlight(g: Graphics2D, rect: Rectangle, color: Color) {
g.color = color
g.translate(0.0, HIGHLIGHT_OFFSET)
g.fillRoundRect(rect.x, rect.y, rect.width, rect.height + 1, ARC, ARC)
g.translate(0.0, -HIGHLIGHT_OFFSET)
}
/**
* Renders the tag text.
*/
private fun drawForeground(g: Graphics2D, font: TagFont, point: Point, text: String) {
val x = point.x + 2
val y = point.y + font.baselineDistance
g.font = font.tagFont
if (!font.isForegroundDark) {
g.color = SHADOW_COLOR
g.drawString(text, x + 1, y + 1)
}
g.color = font.foregroundColor
g.drawString(text, x, y)
}
}
/**
* Returns true if the left-aligned offset is in the range. Use to cull tags outside visible range.
* Only the left offset is checked, because if the tag was right-aligned on the last index of the range, it would not be visible anyway.
*/
fun isOffsetInRange(range: IntRange): Boolean {
return offsetL in range
} }
/** /**
@@ -96,43 +42,43 @@ internal class TagMarker(
fun paint(g: Graphics2D, editor: Editor, cache: EditorOffsetCache, font: TagFont, occupied: MutableList<Rectangle>): Rectangle? { fun paint(g: Graphics2D, editor: Editor, cache: EditorOffsetCache, font: TagFont, occupied: MutableList<Rectangle>): Rectangle? {
val rect = alignTag(editor, cache, font, occupied) ?: return null val rect = alignTag(editor, cache, font, occupied) ?: return null
drawHighlight(g, rect, font.backgroundColor) drawHighlight(g, rect, editor.colorsScheme.defaultBackground)
drawForeground(g, font, rect.location, tag) drawForeground(g, font, rect.location)
occupied.add(JBUIScale.scale(2).let { Rectangle(rect.x - it, rect.y, rect.width + (2 * it), rect.height) }) occupied.add(rect)
return rect return rect
} }
/**
* Renders the tag background.
*/
private fun drawHighlight(g: Graphics2D, rect: Rectangle, color: Color) {
g.color = color
g.translate(0.0, HIGHLIGHT_OFFSET)
g.fillRect(rect.x, rect.y, rect.width, rect.height + 1)
g.translate(0.0, -HIGHLIGHT_OFFSET)
}
/**
* Renders the tag text.
*/
private fun drawForeground(g: Graphics2D, font: TagFont, point: Point) {
val x = point.x
val y = point.y + font.baselineDistance
g.font = font.tagFont
g.color = font.foregroundColor1
g.drawString(firstChar, x, y)
if (secondChar.isNotEmpty()) {
g.color = font.foregroundColor2
g.drawString(secondChar, x + font.tagCharWidth, y)
}
}
private fun alignTag(editor: Editor, cache: EditorOffsetCache, font: TagFont, occupied: List<Rectangle>): Rectangle? { private fun alignTag(editor: Editor, cache: EditorOffsetCache, font: TagFont, occupied: List<Rectangle>): Rectangle? {
val boundaries = StandardBoundaries.VISIBLE_ON_SCREEN val pos = cache.offsetToXY(editor, offset)
val rect = Rectangle(pos.x, pos.y, font.tagCharWidth * length, font.lineHeight)
if (hasSpaceRight || offsetL == 0 || editor.immutableText[offsetL - 1].let { it == '\n' || it == '\r' }) { return rect.takeIf { occupied.none(it::intersects) }
val rectR = createRightAlignedTagRect(editor, cache, font)
return rectR.takeIf { boundaries.isOffsetInside(editor, offsetR, cache) && occupied.none(rectR::intersects) }
}
val rectL = createLeftAlignedTagRect(editor, cache, font)
if (occupied.none(rectL::intersects)) {
return rectL.takeIf { boundaries.isOffsetInside(editor, offsetL, cache) }
}
val rectR = createRightAlignedTagRect(editor, cache, font)
if (occupied.none(rectR::intersects)) {
return rectR.takeIf { boundaries.isOffsetInside(editor, offsetR, cache) }
}
return null
}
private fun createRightAlignedTagRect(editor: Editor, cache: EditorOffsetCache, font: TagFont): Rectangle {
val pos = cache.offsetToXY(editor, offsetR)
val shift = font.editorFontMetrics.charWidth(editor.immutableText[offsetR]) + (font.tagCharWidth * shiftR)
return Rectangle(pos.x + shift, pos.y, (font.tagCharWidth * length) + 4, font.lineHeight)
}
private fun createLeftAlignedTagRect(editor: Editor, cache: EditorOffsetCache, font: TagFont): Rectangle {
val pos = cache.offsetToXY(editor, offsetL)
val shift = -(font.tagCharWidth * length)
return Rectangle(pos.x + shift - 4, pos.y, (font.tagCharWidth * length) + 4, font.lineHeight)
} }
} }

View File

@@ -6,13 +6,12 @@ import com.intellij.openapi.editor.markup.CustomHighlighterRenderer
import com.intellij.openapi.editor.markup.HighlighterLayer import com.intellij.openapi.editor.markup.HighlighterLayer
import com.intellij.openapi.editor.markup.HighlighterTargetArea import com.intellij.openapi.editor.markup.HighlighterTargetArea
import com.intellij.openapi.editor.markup.RangeHighlighter import com.intellij.openapi.editor.markup.RangeHighlighter
import it.unimi.dsi.fastutil.ints.IntArrayList import com.intellij.ui.ColorUtil
import it.unimi.dsi.fastutil.ints.IntList import it.unimi.dsi.fastutil.ints.IntList
import org.acejump.boundaries.EditorOffsetCache import org.acejump.boundaries.EditorOffsetCache
import org.acejump.config.AceConfig import org.acejump.config.AceConfig
import org.acejump.immutableText import org.acejump.immutableText
import org.acejump.search.SearchQuery import org.acejump.search.SearchQuery
import org.acejump.search.Tag
import java.awt.Color import java.awt.Color
import java.awt.Graphics import java.awt.Graphics
@@ -32,13 +31,6 @@ internal class TextHighlighter {
}, query::getHighlightLength) }, query::getHighlightLength)
} }
/**
* Removes all current highlights and re-adds a single highlight at the position of the accepted tag with a different color.
*/
fun renderFinal(tag: Tag, query: SearchQuery) {
render(mutableMapOf(tag.editor to IntArrayList(intArrayOf(tag.offset))), AcceptedTagRenderer, query::getHighlightLength)
}
private inline fun render(results: Map<Editor, IntList>, renderer: CustomHighlighterRenderer, getHighlightLength: (CharSequence, Int) -> Int) { private inline fun render(results: Map<Editor, IntList>, renderer: CustomHighlighterRenderer, getHighlightLength: (CharSequence, Int) -> Int) {
for ((editor, offsets) in results) { for ((editor, offsets) in results) {
val highlights = previousHighlights[editor] val highlights = previousHighlights[editor]
@@ -88,7 +80,7 @@ internal class TextHighlighter {
*/ */
private object SearchedWordRenderer : CustomHighlighterRenderer { private object SearchedWordRenderer : CustomHighlighterRenderer {
override fun paint(editor: Editor, highlighter: RangeHighlighter, g: Graphics) { override fun paint(editor: Editor, highlighter: RangeHighlighter, g: Graphics) {
drawFilled(g, editor, highlighter.startOffset, highlighter.endOffset, AceConfig.textHighlightColor) drawFilled(g, editor, highlighter.startOffset, highlighter.endOffset, AceConfig.searchHighlightColor)
} }
} }
@@ -97,16 +89,7 @@ internal class TextHighlighter {
*/ */
private object RegexRenderer : CustomHighlighterRenderer { private object RegexRenderer : CustomHighlighterRenderer {
override fun paint(editor: Editor, highlighter: RangeHighlighter, g: Graphics) { override fun paint(editor: Editor, highlighter: RangeHighlighter, g: Graphics) {
drawSingle(g, editor, highlighter.startOffset, AceConfig.textHighlightColor) drawSingle(g, editor, highlighter.startOffset, AceConfig.searchHighlightColor)
}
}
/**
* Renders a filled highlight in the background of the accepted tag position and search query.
*/
private object AcceptedTagRenderer : CustomHighlighterRenderer {
override fun paint(editor: Editor, highlighter: RangeHighlighter, g: Graphics) {
drawFilled(g, editor, highlighter.startOffset, highlighter.endOffset, AceConfig.acceptedTagColor)
} }
} }
@@ -117,10 +100,10 @@ internal class TextHighlighter {
val start = EditorOffsetCache.Uncached.offsetToXY(editor, startOffset) val start = EditorOffsetCache.Uncached.offsetToXY(editor, startOffset)
val end = EditorOffsetCache.Uncached.offsetToXY(editor, endOffset) val end = EditorOffsetCache.Uncached.offsetToXY(editor, endOffset)
g.color = color g.color = ColorUtil.withAlpha(AceConfig.searchHighlightColor, 0.2)
g.fillRect(start.x, start.y + 1, end.x - start.x, editor.lineHeight - 1) g.fillRect(start.x, start.y + 1, end.x - start.x, editor.lineHeight - 1)
g.color = AceConfig.tagBackgroundColor g.color = color
g.drawRect(start.x, start.y, end.x - start.x, editor.lineHeight) g.drawRect(start.x, start.y, end.x - start.x, editor.lineHeight)
} }
@@ -130,10 +113,10 @@ internal class TextHighlighter {
val font = editor.colorsScheme.getFont(EditorFontType.PLAIN) val font = editor.colorsScheme.getFont(EditorFontType.PLAIN)
val lastCharWidth = editor.component.getFontMetrics(font).charWidth(char) val lastCharWidth = editor.component.getFontMetrics(font).charWidth(char)
g.color = color g.color = ColorUtil.withAlpha(AceConfig.searchHighlightColor, 0.2)
g.fillRect(pos.x, pos.y + 1, lastCharWidth, editor.lineHeight - 1) g.fillRect(pos.x, pos.y + 1, lastCharWidth, editor.lineHeight - 1)
g.color = AceConfig.tagBackgroundColor g.color = color
g.drawRect(pos.x, pos.y, lastCharWidth, editor.lineHeight) g.drawRect(pos.x, pos.y, lastCharWidth, editor.lineHeight)
} }
} }

View File

@@ -1,59 +0,0 @@
package org.acejump.vim
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.MappingMode
import com.maddyhome.idea.vim.extension.VimExtension
import com.maddyhome.idea.vim.extension.VimExtensionFacade
import com.maddyhome.idea.vim.key.MappingOwner
import org.acejump.boundaries.StandardBoundaries
import org.acejump.search.Pattern
class AceVimExtension : VimExtension {
private companion object {
const val NAME = "AceJump"
const val PLUG_PREFIX = "<Plug>(acejump)"
private val OWNER = MappingOwner.Plugin.get(NAME)
private fun register(keys: String, mode: AceVimMode) {
val keysPrefixed = injector.parser.parseKeys("${PLUG_PREFIX}$keys")
val keysCommand = injector.parser.parseKeys(command(keys))
VimExtensionFacade.putExtensionHandlerMapping(MappingMode.NVO, keysCommand, OWNER, AceVimHandler(mode), false)
VimExtensionFacade.putKeyMapping(MappingMode.NVO, keysPrefixed, OWNER, keysCommand, true)
}
private fun command(name: String): String {
return "<Plug>(acejump-$name)"
}
}
override fun getName(): String {
return NAME
}
override fun init() {
register("<Space>", AceVimMode.JumpAllEditors)
register("s", AceVimMode.JumpAllEditors)
register("f", AceVimMode.Jump(StandardBoundaries.AFTER_CARET))
register("F", AceVimMode.Jump(StandardBoundaries.BEFORE_CARET))
register("t", AceVimMode.JumpTillForward(StandardBoundaries.AFTER_CARET))
register("T", AceVimMode.JumpTillBackward(StandardBoundaries.BEFORE_CARET))
register("w", AceVimMode.JumpToPattern(Pattern.VIM_LWORD, StandardBoundaries.AFTER_CARET))
register("W", AceVimMode.JumpToPattern(Pattern.VIM_UWORD, StandardBoundaries.AFTER_CARET))
register("b", AceVimMode.JumpToPattern(Pattern.VIM_LWORD, StandardBoundaries.BEFORE_CARET))
register("B", AceVimMode.JumpToPattern(Pattern.VIM_UWORD, StandardBoundaries.BEFORE_CARET))
register("e", AceVimMode.JumpToPattern(Pattern.VIM_LWORD_END, StandardBoundaries.AFTER_CARET))
register("E", AceVimMode.JumpToPattern(Pattern.VIM_LWORD_END, StandardBoundaries.AFTER_CARET))
register("ge", AceVimMode.JumpToPattern(Pattern.VIM_UWORD_END, StandardBoundaries.BEFORE_CARET))
register("gE", AceVimMode.JumpToPattern(Pattern.VIM_UWORD_END, StandardBoundaries.BEFORE_CARET))
register("j", AceVimMode.JumpToPattern(Pattern.LINE_INDENTS, StandardBoundaries.AFTER_CARET))
register("k", AceVimMode.JumpToPattern(Pattern.LINE_INDENTS, StandardBoundaries.BEFORE_CARET))
register("l", AceVimMode.Jump(StandardBoundaries.AFTER_CARET.intersection(StandardBoundaries.CARET_LINE)))
register("h", AceVimMode.Jump(StandardBoundaries.BEFORE_CARET.intersection(StandardBoundaries.CARET_LINE)))
}
}

View File

@@ -1,92 +0,0 @@
package org.acejump.vim
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.WriteAction
import com.maddyhome.idea.vim.KeyHandler
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.action.change.change.ChangeVisualAction
import com.maddyhome.idea.vim.action.change.delete.DeleteVisualAction
import com.maddyhome.idea.vim.action.copy.YankVisualAction
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.MappingMode
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.command.VimStateMachine
import com.maddyhome.idea.vim.extension.ExtensionHandler
import com.maddyhome.idea.vim.group.visual.vimSetSelection
import com.maddyhome.idea.vim.helper.inVisualMode
import com.maddyhome.idea.vim.helper.vimSelectionStart
import com.maddyhome.idea.vim.helper.vimStateMachine
import com.maddyhome.idea.vim.newapi.ij
import org.acejump.action.AceTagAction
import org.acejump.modes.JumpMode
import org.acejump.search.Tag
import org.acejump.session.SessionManager
import org.acejump.session.SessionState
class AceVimHandler(private val mode: AceVimMode) : ExtensionHandler {
override fun execute(editor: VimEditor, context: ExecutionContext) {
val ij = editor.ij
val caret = ij.caretModel.currentCaret
val initialOffset = caret.offset
val selectionStart = if (ij.inVisualMode) caret.vimSelectionStart else null
val session = SessionManager.start(ij, mode.getJumpEditors(ij))
session.defaultBoundary = mode.boundaries
session.startJumpMode {
object : JumpMode() {
override fun accept(state: SessionState, acceptedTag: Tag): Boolean {
state.act(AceTagAction.JumpToSearchStart, acceptedTag, wasUpperCase, isFinal = true)
if (selectionStart != null) {
caret.vimSetSelection(selectionStart, caret.offset, moveCaretToSelectionEnd = true)
}
else {
val commandState = editor.vimStateMachine
if (commandState.isOperatorPending) {
val key = commandState.commandBuilder.keys.singleOrNull()?.keyChar
commandState.reset()
KeyHandler.getInstance().fullReset(editor)
VimPlugin.getVisualMotion().enterVisualMode(editor, VimStateMachine.SubMode.VISUAL_CHARACTER)
caret.vimSetSelection(caret.offset, initialOffset, moveCaretToSelectionEnd = true)
val action = when (key) {
'd' -> DeleteVisualAction()
'c' -> ChangeVisualAction()
'y' -> YankVisualAction()
else -> null
}
if (action != null) {
ApplicationManager.getApplication().invokeLater {
WriteAction.run<Nothing> {
commandState.commandBuilder.pushCommandPart(action)
val cmd = commandState.commandBuilder.buildCommand()
val operatorArguments = OperatorArguments(
commandState.mappingState.mappingMode == MappingMode.OP_PENDING,
cmd.rawCount, commandState.mode, commandState.subMode
)
commandState.setExecutingCommand(cmd)
injector.actionExecutor.executeVimAction(editor, action, context, operatorArguments)
// TODO does not update status
}
}
}
}
}
mode.finishSession(ij, session)
return true
}
}
}
mode.setupSession(ij, session)
}
}

View File

@@ -1,5 +0,0 @@
<idea-plugin>
<extensions defaultExtensionNs="IdeaVIM">
<vimExtension implementation="org.acejump.vim.AceVimExtension" name="acejump" />
</extensions>
</idea-plugin>

View File

@@ -9,12 +9,11 @@
</description> </description>
<depends>com.intellij.modules.platform</depends> <depends>com.intellij.modules.platform</depends>
<depends>IdeaVIM</depends>
<category>Navigation</category> <category>Navigation</category>
<vendor url="https://github.com/acejump/AceJump">AceJump</vendor> <vendor url="https://github.com/acejump/AceJump">AceJump</vendor>
<depends optional="true" config-file="acejump-ideavim.xml">IdeaVIM</depends>
<extensions defaultExtensionNs="com.intellij"> <extensions defaultExtensionNs="com.intellij">
<applicationService serviceImplementation="org.acejump.config.AceConfig"/> <applicationService serviceImplementation="org.acejump.config.AceConfig"/>
<applicationConfigurable groupId="tools" displayName="AceJump" <applicationConfigurable groupId="tools" displayName="AceJump"
@@ -25,38 +24,28 @@
implementationClass="org.acejump.action.AceEditorAction$Reset"/> implementationClass="org.acejump.action.AceEditorAction$Reset"/>
<editorActionHandler action="EditorBackSpace" order="first" <editorActionHandler action="EditorBackSpace" order="first"
implementationClass="org.acejump.action.AceEditorAction$ClearSearch"/> implementationClass="org.acejump.action.AceEditorAction$ClearSearch"/>
<editorActionHandler action="EditorEnter" order="first" <editorActionHandler action="EditorEnter" order="first, before terminalEnter"
implementationClass="org.acejump.action.AceEditorAction$TagImmediately"/> implementationClass="org.acejump.action.AceEditorAction$TagImmediately"/>
</extensions> </extensions>
<actions> <actions>
<action id="AceAction" <action id="AceVimAction_JumpAllEditors" class="org.acejump.action.AceVimAction$JumpAllEditors" text="AceJump Vim - Jump All Editors" />
class="org.acejump.action.AceKeyboardAction$ActivateAceJump" <action id="AceVimAction_JumpAllEditors_GoToDeclaration" class="org.acejump.action.AceVimAction$JumpAllEditorsGoToDeclaration" text="AceJump Vim - Jump All Editors - Go To Declaration" />
text="Activate AceJump"> <action id="AceVimAction_JumpForward" class="org.acejump.action.AceVimAction$JumpForward" text="AceJump Vim - Jump Forward" />
<keyboard-shortcut keymap="Mac OS X" first-keystroke="ctrl SEMICOLON"/> <action id="AceVimAction_JumpBackward" class="org.acejump.action.AceVimAction$JumpBackward" text="AceJump Vim - Jump Backward" />
<keyboard-shortcut keymap="Mac OS X 10.5+" first-keystroke="ctrl SEMICOLON"/> <action id="AceVimAction_JumpTillForward" class="org.acejump.action.AceVimAction$JumpTillForward" text="AceJump Vim - Jump Till Forward" />
<keyboard-shortcut keymap="$default" first-keystroke="ctrl SEMICOLON"/> <action id="AceVimAction_JumpTillBackward" class="org.acejump.action.AceVimAction$JumpTillBackward" text="AceJump Vim - Jump Till Backward" />
</action> <action id="AceVimAction_JumpOnLineForward" class="org.acejump.action.AceVimAction$JumpOnLineForward" text="AceJump Vim - Jump On Line Forward" />
<action id="AceVimAction_GoToDeclaration" <action id="AceVimAction_JumpOnLineBackward" class="org.acejump.action.AceVimAction$JumpOnLineBackward" text="AceJump Vim - Jump On Line Backward" />
class="org.acejump.action.AceVimAction$GoToDeclaration" <action id="AceVimAction_JumpLineIndentsForward" class="org.acejump.action.AceVimAction$JumpLineIndentsForward" text="AceJump Vim - Jump Line Indents Forward" />
text="AceJump Vim - GoToDeclaration"/> <action id="AceVimAction_JumpLineIndentsBackward" class="org.acejump.action.AceVimAction$JumpLineIndentsBackward" text="AceJump Vim - Jump Line Indents Backward" />
<action id="AceVimAction_GoToTypeDeclaration" <action id="AceVimAction_JumpLWordForward" class="org.acejump.action.AceVimAction$JumpLWordForward" text="AceJump Vim - Jump LWord Forward" />
class="org.acejump.action.AceVimAction$GoToTypeDeclaration" <action id="AceVimAction_JumpUWordForward" class="org.acejump.action.AceVimAction$JumpUWordForward" text="AceJump Vim - Jump UWord Forward" />
text="AceJump Vim - GoToTypeDeclaration"/> <action id="AceVimAction_JumpLWordBackward" class="org.acejump.action.AceVimAction$JumpLWordBackward" text="AceJump Vim - Jump LWord Backward" />
<action id="AceVimAction_ShowIntentions" <action id="AceVimAction_JumpUWordBackward" class="org.acejump.action.AceVimAction$JumpUWordBackward" text="AceJump Vim - Jump UWord Backward" />
class="org.acejump.action.AceVimAction$ShowIntentions" <action id="AceVimAction_JumpLWordEndForward" class="org.acejump.action.AceVimAction$JumpLWordEndForward" text="AceJump Vim - Jump LWord End Forward" />
text="AceJump Vim - ShowIntentions"/> <action id="AceVimAction_JumpUWordEndForward" class="org.acejump.action.AceVimAction$JumpUWordEndForward" text="AceJump Vim - Jump UWord End Forward" />
<action id="AceVimAction_ShowUsages" <action id="AceVimAction_JumpLWordEndBackward" class="org.acejump.action.AceVimAction$JumpLWordEndBackward" text="AceJump Vim - Jump LWord End Backward" />
class="org.acejump.action.AceVimAction$ShowUsages" <action id="AceVimAction_JumpUWordEndBackward" class="org.acejump.action.AceVimAction$JumpUWordEndBackward" text="AceJump Vim - Jump UWord End Backward" />
text="AceJump Vim - ShowUsages"/>
<action id="AceVimAction_FindUsages"
class="org.acejump.action.AceVimAction$FindUsages"
text="AceJump Vim - FindUsages"/>
<action id="AceVimAction_Refactor"
class="org.acejump.action.AceVimAction$Refactor"
text="AceJump Vim - Refactor"/>
<action id="AceVimAction_Rename"
class="org.acejump.action.AceVimAction$Rename"
text="AceJump Vim - Rename"/>
</actions> </actions>
</idea-plugin> </idea-plugin>

View File

@@ -1,36 +0,0 @@
import org.acejump.test.util.BaseTest
/**
* Functional test cases and end-to-end performance tests.
*
* TODO: Add more structure to test cases, use test resources to define files.
*/
class AceTest : BaseTest() {
fun `test that scanner finds all occurrences of single character`() =
assertEquals("test test test".search("t"), setOf(0, 3, 5, 8, 10, 13))
fun `test empty results for an absent query`() =
assertEmpty("test test test".search("best"))
fun `test sticky results on a query with extra characters`() =
assertEquals("test test test".search("testz"), setOf(0, 5, 10))
fun `test a query inside text with some variations`() =
assertEquals("abcd dabc cdab".search("cd"), setOf(2, 10))
fun `test a query containing a space character`() =
assertEquals("abcd dabc cdab".search("cd "), setOf(2))
fun `test a query containing a { character`() =
assertEquals("abcd{dabc cdab".search("cd{"), setOf(2))
fun `test tag selection`() {
"<caret>testing 1234".search("g")
typeAndWaitForResults(session.tags[0].key)
myFixture.checkResult("testin<caret>g 1234")
}
}

View File

@@ -1,11 +1,10 @@
import org.acejump.action.AceKeyboardAction
import org.acejump.action.AceVimAction
import org.acejump.test.util.BaseTest import org.acejump.test.util.BaseTest
import org.junit.Ignore
import java.io.File import java.io.File
import kotlin.random.Random import kotlin.random.Random
import kotlin.system.measureTimeMillis import kotlin.system.measureTimeMillis
@Ignore
class LatencyTest : BaseTest() { class LatencyTest : BaseTest() {
private fun `test tag latency`(editorText: String) { private fun `test tag latency`(editorText: String) {
@@ -15,7 +14,7 @@ class LatencyTest : BaseTest() {
for (query in chars) { for (query in chars) {
makeEditor(editorText) makeEditor(editorText)
myFixture.testAction(AceKeyboardAction.ActivateAceJump) myFixture.testAction(AceVimAction.JumpAllEditors())
time += measureTimeMillis { typeAndWaitForResults("$query") } time += measureTimeMillis { typeAndWaitForResults("$query") }
// TODO assert(Tagger.markers.isNotEmpty()) { "Should be tagged: $query" } // TODO assert(Tagger.markers.isNotEmpty()) { "Should be tagged: $query" }
resetEditor() resetEditor()

View File

@@ -7,7 +7,7 @@ import com.intellij.openapi.fileTypes.PlainTextFileType
import com.intellij.psi.PsiFile import com.intellij.psi.PsiFile
import com.intellij.testFramework.fixtures.BasePlatformTestCase import com.intellij.testFramework.fixtures.BasePlatformTestCase
import com.intellij.util.ui.UIUtil import com.intellij.util.ui.UIUtil
import org.acejump.action.AceKeyboardAction import org.acejump.action.AceVimAction
import org.acejump.session.SessionManager import org.acejump.session.SessionManager
abstract class BaseTest : BasePlatformTestCase() { abstract class BaseTest : BasePlatformTestCase() {
@@ -58,7 +58,7 @@ abstract class BaseTest : BasePlatformTestCase() {
private fun String.executeQuery(query: String) { private fun String.executeQuery(query: String) {
myFixture.run { myFixture.run {
makeEditor(this@executeQuery) makeEditor(this@executeQuery)
testAction(AceKeyboardAction.ActivateAceJump) testAction(AceVimAction.JumpAllEditors())
typeAndWaitForResults(query) typeAndWaitForResults(query)
} }
} }