Giter Site home page Giter Site logo

thqby / vscode-autohotkey2-lsp Goto Github PK

View Code? Open in Web Editor NEW
187.0 7.0 17.0 4.63 MB

Autohotkey v2 Language Support using vscode-lsp.

Home Page: https://marketplace.visualstudio.com/items?itemName=thqby.vscode-autohotkey2-lsp

License: GNU Lesser General Public License v3.0

TypeScript 35.89% AutoHotkey 61.46% JavaScript 2.65%
autohotkey v2 language-server vscode ahk lsp vscode-extension

vscode-autohotkey2-lsp's Introduction

English | 中文

AutoHotkey v2 Language Support

installs version

Repositories: Github | Gitee

AutoHotkey v2 Language support for VS Code, features realization based on v2 syntax analysis. Supports running on the Web, such as Chrome/Edge. https://vscode.dev or https://github.dev/github/dev

Language Features

Rename Symbol

Rename variables and function names in the scope in batches.

rename

Diagnostics

Simple syntax error diagnosis.

diagnostics

IntelliSense

Supports intelligent completion of variables, functions, parameters, class names, and method names within the scope (by simple type deduction), and supports the completion of include files and function libraries.

snippet1

snippet2

Signature

Support for intelligent prompts for function parameters.

signature

Document Symbol

  1. Displays class, method, function, variable, label, hotkey, hot string, block information in the left outline column.
  2. press Ctrl + P, Input @symbol_name to retrieve and jump
  3. You can comment a method with a semicolon or /* */ on the top line of a function, variable. Jsdoc-style annotations can mark variable types.
/**
 * @param {Array} a - a param
 * @return {Integer}
 */
fn(a*) {
  /** @type {Map} */
  d := Map()
  /**
   * @var {Map} e
   * @var {Object} f
   */
  e := Map(), f := {}
  /** @type {(a,b)=>Integer} */
  cb := (a, b) => a + b
  /** @type {ComObject<Excel.Sheet.12,Workbook>} */
  wb := ComObject('Excel.Sheet.12')
  return a[1] + a[2]
}
class abc {
  /** @type {Map} */
  p := dosomethingandreturnmap()
}

Semantic Highlight

Semantic highlighting is an addition to syntax highlighting, resolves symbols in the context of a project. The editor applies the highlighting from semantic tokens on top of the highlighting from grammars.

semanticTokens

Tags

usage: Add ;;(default) or ; TODO to the comment code Tags.

codeSymbole

Document Color

Compute and resolve colors inside a document to provide color picker in editor.

documentcolor

Hover

Supports hover prompts and comments for scoped variables, functions, global classes, and labels.
usage: Move the mouse over the symbol.

hover

Goto Definition

  1. Support for jumping to the declaration location of scoped variables, functions, global classes, and labels.
  2. usage: Press ctrl Then move the mouse over to the code and click.

gotoDefinition

Find All References

See all the source code locations where a certain variable/function is being used.

CodeFormat

usage:

  • Right-click the popup menu and click "Format document".
  • Press Shift+Alt+F.
  • Supports formatting code blocks when typing '}', formatting lines and indenting lines when typing '\n'. (editor.formatOnType needs to be enabled)
  • Supports the use of formatting instructions ;@format array_style: collapse, object_style: expand to change the object style of different blocks

codeFormat

Custom folding

Fold the part between ;@region tag and ;@endregion, ;{ and ;}

;#region tag
code
;#endregion

Context Menu

Quick Help

Open the help file and navigate to the keyword at the current cursor.

Run Script

Run the currently open script.

Run Selected Script

Run the code snippet at the cursor selection.

Compile Script

Compile the script to generate executable EXE files.

Debug Script

No additional configuration is required to start the installed Debug extensions, and support debugging with parameters.

Generate Comment

Generate JSDOC-style comments for a function or method.

Use in other editors

  1. Install Node.js.
  2. Download vscode-autohotkey2-lsp server using command line, or download and unpack through vscode marketplace.
mkdir vscode-autohotkey2-lsp
cd vscode-autohotkey2-lsp
curl -L -o install.js https://raw.githubusercontent.com/thqby/vscode-autohotkey2-lsp/main/tools/install.js
node install.js
  1. Set the LSP configuration of the editor that support LSP(Language Server Protocol), such as Sublime Text4, Vim, Neovim, Emacs, etc.

Sublime Text4

  • Package Control: Install Package, and install Sublime LSP plug-in.
  • Preferences: LSP Settings, add lsp configuration, language selector, and syntax highlighting. This is a simple example syntax highlighting, save the file in a similar path C:\Users\<USERNAME>\AppData\Roaming\Sublime Text\Packages\User\LSP-ahk2\AutoHotkey2.sublime-syntax.
{
  "clients": {
    "lsp-ahk2": {
      "enabled": true,
      "command": [
        "node",
        "<VSCODE-AUTOHOTKEY2-LSP>/server/dist/server.js",
        "--stdio"
      ], // Update the path of node.exe(maybe it's already in PATH, so you don't need to set it) and the folder of vscode-autohotkey2-lsp
      "selector": "source.ahk2", // Same as scope in AutoHotkey2.sublime-syntax
      "schemes": ["file", "buffer", "res"],
      "initializationOptions": {
        "locale": "en-us", // or "zh-cn"
        "AutoLibInclude": "Disabled", // or "Local" or "User and Standard" or "All"
        "CommentTags": "^;;\\s*(?<tag>.+)",
        "CompleteFunctionParens": false,
        "Diagnostics": {
          "ClassStaticMemberCheck": true,
          "ParamsCheck": true
        },
        "ActionWhenV1IsDetected": "Continue",
        "FormatOptions": {
          "array_style": "none",           // or "collapse" or "expand"
          "break_chained_methods": false,
          "ignore_comment": false,
          "indent_string": "\t",
          "max_preserve_newlines": 2,
          "brace_style": "One True Brace", // or "Allman" or "One True Brace Variant"
          "object_style": "none",          // or "collapse" or "expand"
          "preserve_newlines": true,
          "space_after_double_colon": true,
          "space_before_conditional": true,
          "space_in_empty_paren": false,
          "space_in_other": true,
          "space_in_paren": false,
          "wrap_line_length": 0
        },
        "InterpreterPath": "C:/Program Files/AutoHotkey/v2/AutoHotkey.exe",
        "WorkingDirs": [],
        "SymbolFoldingFromOpenBrace": false
      }
    }
  },
  "semantic_highlighting": true
}

Vim and Neovim

COC

cd $VIMRUNTIME\plugin
git clone --branch release https://github.com/neoclide/coc.nvim.git --depth=1
  • Open (n)vim and enter the command :CocConfig to enter the coc.nvim configuration file to add configuration information.
{
  "languageserver": {
    "lsp-ahk2": {
      "module": "<VSCODE-AUTOHOTKEY2-LSP>/server/dist/server.js",
      "filetypes": ["autohotkey"],
      "args": ["--node-ipc"],
      "initializationOptions": {
        // Same as initializationOptions for Sublime Text4
      }
    }
  }
}

nvim-lspconfig

  • Download nvim-lspconfig.
  • Add the following to your NVIM configuration (init.lua e.g.). Ensure that cmd points to the path of your vscode-autohotkey2-lsp installation and InterpreterPath points to your AHK exe.
local function custom_attach(client, bufnr)
  require("lsp_signature").on_attach({
    bind = true,
    use_lspsaga = false,
    floating_window = true,
    fix_pos = true,
    hint_enable = true,
    hi_parameter = "Search",
    handler_opts = { "double" },
  })
end

local ahk2_configs = {
  autostart = true,
  cmd = {
    "node",
    vim.fn.expand("$HOME/vscode-autohotkey2-lsp/server/dist/server.js"),
    "--stdio"
  },
  filetypes = { "ahk", "autohotkey", "ah2" },
  init_options = {
    locale = "en-us",
    InterpreterPath = "C:/Program Files/AutoHotkey/v2/AutoHotkey.exe",
    -- Same as initializationOptions for Sublime Text4, convert json literal to lua dictionary literal
  },
  single_file_support = true,
  flags = { debounce_text_changes = 500 },
  capabilities = capabilities,
  on_attach = custom_attach,
}
local configs = require "lspconfig.configs"
configs["ahk2"] = { default_config = ahk2_configs }
local nvim_lsp = require("lspconfig")
nvim_lsp.ahk2.setup({})

Use in Web Browser

visit https://github.dev or https://vscode.dev in Chrome/Edge, and install thqby.vscode-autohotkey2-lsp

vscode-autohotkey2-lsp's People

Contributors

axlefublr avatar banaanae avatar fupeijiang avatar lvalkov avatar mark-wiemer avatar nopdan avatar raptorx avatar reidprichard avatar thqby avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

vscode-autohotkey2-lsp's Issues

Wrong comment shown in hover prompt

The comment shown when hovering over a variable seems to be limited to one line, and not entirely predictable. With the following script, the extension (0.7.0) is showing me "It has two lines." for every variable: startup, var1, var2, var3 and var4.

somefunc startup ; This comment is irrelevant.

; This is a comment about the assignment below.
; It has two lines.
var1 := 1

; Another comment
; with two lines.
var2 := 1

somefunc(a) {
	
}

var3 := 2
var4 := 4

This was an attempt to demonstrate the issue, but in the original script, it was showing the equivalent of "with two lines." for var2, var3 and var4.

I found that without the top line, none of the variables showed any hover prompt. Going back a couple of steps and removing some irrelevant parts, the file was like this:

SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.

; This is a comment about the assignment below.
; It has two lines.
var1 := 1

In this case the hover prompt for Input and var1 was "Recommended for new scripts" (etc.). The top lines came from creating the example file from the v1 template, but both lines are valid syntax for v2.

Input is the first and only reference, but is not a definition; as of v2.0-a128, it can't possibly be an assignment (ByRef requires &).

Obviously, the comment at the top has no relevance to var1. If the SetWorkingDir line is removed or changed to use a naked variable, var1 shows "It has two lines" instead.

The most minor part of the issue is that the hover prompt only shows the last line of the comment. I would tend to write multi-line comments with semicolon, delimiting with an empty line. I use /* */ more rarely, such as to disable blocks of code that include multi-line semicolon comments.

Incorrect formatting on paste

When pasting into a quoted string, the pasted text is formatted as though it is an expression. For instance, pasting the regex pattern (?i:if) produces ( ? i : if ), which will obviously not work. This does not occur when pasting similar expressions (even valid ones like (a?b:c)) into a JavaScript string.

I was very surprised to find that the extension overrides the "global" editor.formatOnPaste setting, after wasting hours chasing VS Code bug reports trying to figure out why VS Code was messing with my pasted code. There seems to be no good reason for the extension to override editor.formatOnPaste, editor.detectIndentation or editor.autoIndent. It should respect the user's global preference.

IsSet 出了点毛病

非常感谢大佬的扩展

提个 IsSet 的小问题
首先是不自动补全了
然后是没有函数提示了(提示 保留字'IsSet'不得用作变量名)

然后某些语句中会提示出错了 (实际上正常运行)
比方说下面这样都会提示出错

i := IsSet(v)
i := IsSet(v) ? v : 0
Test()
{
    if A_Args.Length
        o := "test"
    return IsSet(o) ? o : ""
}

"Unknown operator use" for &

When following a question mark, & is incorrectly marked as an error.

a := b ? &c : &c := 0

The actual code was more like:

return (&v) => isSet(v) ? &v : &v := 0

Highlighting and diagnostics for illegal catch and catch-as clauses

The keyword as isn't being highlighted as such (instead, the variable.other scope has been applied to it).

According to the documentation, following catch may be a class name or comma-separated list of class names, therefore, anything following catch that is not the keyword as should be treated as an identifier and, if feasible, checked whether it corresponds to an actual class defined in the script. (If not, an Error diagnostic should be emitted.)

Lastly, following as must be a plain variable name (which need not be on the same line). Currently, no Error diagnostic is being emitted for that case (see last catch clause in the sample code).

try
	MsgBox('try')
catch as ErrorException
	MsgBox('catch as ErrorException')
catch MyCustomError as Exc
	MsgBox('catch MyCustomExceptionClass as Exc')
catch OSError as ; A plain variable name must follow.
	MsgBox('catch OSError as')

class MyCustomError extends Error
{
	
}

TryCatch

Tested with AutoHotkey_L v2.0-a137-f6f65742.

Detect misplaced or dangling control flow clauses

The following piece of code produces a compile time error, however, no diagnostic is provided.

if (true)
	foo := ''
	foo := '' ; An unintentional refactoring mistake.
else
	bar := ''

The emitted error is:

Error:  Unexpected "Else"

	Line#
	001: If (true)
	002: foo := ''
	003: foo := ''
--->	004: Else

The program will exit.

This is an easy error to commit by beginner and experienced (for instance, during refactoring) programmers alike or by those accustomed to indentation scope based languages such as Python. Therefore, I am of the opinion that it is worth having a diagnostic for.

else

Associates with the nearest applicable unclaimed single-line statement or block above it, belonging to an if, catch, for, any kind of loop or while.

until

After any kind of loop or for.

catch

After try or catch (provided it is associated with a try preceding it).

finally

After try, catch or else (provided it is associated with a try preceding it).

Tested with AutoHotkey_L v2.0-a137-f6f65742.

#Include <Name> incorrectly marked as invalid

#include <D> is incorrectly marked as an error ("Invalid file path") when Lib\D.ahk exists under the same directory as AutoHotkey.exe (i.e. D.ahk is in the "standard library"). The path to AutoHotkey.exe is set in the workspace launch.json (and is correctly used by the run/debug commands).

Highlighting of `this` in property getter

this is not highlighted on the second line:

class X {
    static Y[z] => this.A[1]
            || this.B[1] := C
}

but without [z], this is highlighted correctly:

class X {
    static Y => this.A[z]
            || this.B[z] := C
}

Detect duplicate function parameters

The following piece of code produces a compile time error, which the extension fails to detect and provide an appropriate diagnostic for.

somefunc(foo, foo) {

}

The emitted error is:

Error at line 1.

Line Text: foo)
Error: Duplicate parameter.

The program will exit.

Tested with AutoHotkey_L v2.0-a137-f6f65742.

Warning diagnostic for VarRef out parameters for built-in functions

The following list of built-in functions utilize VarRef out parameters to return multiple values back to the caller.
I think having a configurable (On/Off) Warning diagnostic to detect cases where an explicit VarRef hasn't been passed in would be beneficial as & could be accidentally omitted or the caller might not be aware it was required. While true that a VarRef could be supplied indirectly (as demonstrated in the example that follows), typically these functions won't be used that way. Nevertheless, in case they are, it would be necessary for the diagnostic to be configurable (via an extension setting or a linter-type comment, for instance).

x := 0
y := 0
VarRefOfX := &x
VarRefOfY := &y
CaretGetPos(VarRefOfX, VarRefOfY)
MsgBox('The caret is located at ' %VarRefOfX% ', ' %VarRefOfY% '.')
CaretGetPos(&OutputVarX, &OutputVarY)
ControlGetPos(&X, &Y, &Width, &Height, Control, WinTitle, WinText, ExcludeTitle, ExcludeText)
FileGetShortcut(LinkFile, &OutTarget, &OutDir, &OutArgs, &OutDescription, &OutIcon, &OutIconNum, &OutRunState)
ImageSearch(&OutputVarX, &OutputVarY, X1, Y1, X2, Y2, ImageFile)
LoadPicture(Filename, Options, &ImageType)
MonitorGet(N, &Left, &Top, &Right, &Bottom)
MonitorGetWorkArea(N, &Left, &Top, &Right, &Bottom)
MouseGetPos(&OutputVarX, &OutputVarY, &OutputVarWin, &OutputVarControl, Flag)
PixelSearch(&OutputVarX, &OutputVarY, X1, Y1, X2, Y2, ColorID, Variation)
RegExMatch(Haystack, NeedleRegEx, &OutputVar, StartingPos)
RegExReplace(Haystack, NeedleRegEx, Replacement, &OutputVarCount, Limit, StartingPos)
Run(Target, WorkingDir, Options, &OutputVarPID)
RunWait(Target, WorkingDir, Options, &OutputVarPID)
SplitPath(Path, &OutFileName, &OutDir, &OutExtension, &OutNameNoExt, &OutDrive)
StrReplace(Haystack, Needle, ReplaceText, CaseSense, &OutputVarCount, Limit)
VarSetStrCapacity(&TargetVar, RequestedCapacity)
WinGetClientPos(&X, &Y, &Width, &Height, WinTitle, WinText, ExcludeTitle, ExcludeText)
WinGetPos(&X, &Y, &Width, &Height, WinTitle, WinText, ExcludeTitle, ExcludeText)

Do note that this list intentionally does not include IsSetRef() since it is more commonly used to check a parameter containing a VarRef prior to dereferencing it.

Additionally, the following built-in methods also require VarRefs, however, I think the diagnostic for them should only be enabled if one can reliably assert the methods are being called on an Object of type Gui or Gui.Control. The reason for that is to prevent erroneous alert in case a user-defined Object's method name clashes with these built-in ones.

Gui.Prototype.GetPos(&X, &Y, &Width, &Height)
Gui.Prototype.GetClientPos(&X, &Y, &Width, &Height)
Gui.Control.Prototype.GetPos(&X, &Y, &Width, &Height)

Lastly, an Enumerator's Call method also requires VarRefs in case it is being invoked manually. That, however, is a rather rare case, which is further complicated by the fact that Enumerators are difficult to detect as they can also be functions and function objects of any kind. Reliably detecting those cases would essentially require being able to reliably detect ByRef usage in regular function calls.

Tested with AutoHotkey_L v2.0-a138-7538f26.

Disable insertion of () by auto-complete

The behaviour I am used to from multiple editors is that Tab or Enter inserts the suggestion as shown in the suggestion list. If I want parentheses, I type them. In SciTE, I don't have to press Tab or Enter; typing dl( will produce DllCall(. In Visual Studio, I type Fu{enter}( or Fu{tab}( to produce Function().

This extension automatically inserts () for functions and methods when I press Tab or Enter, and this is nearly never what I want. I end up with Function(("doesn't", "work")) or MsgBox( "I don't want parentheses at all.") or OnExit(CloseDoor()) instead of OnExit(CloseDoor).

My searches indicated that some LSPs already behave the way I want, or have individual settings to control it (unique to the LSP). I know almost nothing about the VSCode extension API, but it seems to me that insertion of () is hard-coded in completionProvider.ts:

				} else ci.insertText = ci.label + '($0)', ci.insertTextFormat = InsertTextFormat.Snippet;
			} else ci.insertText = ci.label + '()';

So please provide a setting to disable this.

My searches also indicated that some LSPs have a setting to control whether typing ( commits the current auto-complete suggestion, but I could take it either way.

Incorrect diagnostic for `ByRef` parameters in parametrized property definitions

It is permissible to declare ByRef parameters in static and instance dynamic properties alike. The following piece of code is valid, yet a diagnostic is being emitted.

class ClassName
{
	static Property[&Parameters]	; Use brackets only when parameters are present.
	{
		get {
			return 'value of property'
		}
		set {
			return 'Store or otherwise handle' value
		}
	}

	static ShortProperty[&Parameters]
	{
		get => 'Expression which calculates property value'
		set => 'Expression which stores or otherwise handles' value
	}

	static ShorterProperty[&Parameters] => 'Expression'
}

An Error diagnostic is being spuriously emitted by the LSP extension.

{
	"resource": "/c:/test.ahk",
	"owner": "_generated_diagnostic_collection_name_#0",
	"severity": 8,
	"message": "Invalid parameter definition",
	"startLineNumber": 3,
	"startColumn": 9,
	"endLineNumber": 13,
	"endColumn": 34
}

Tested with AutoHotkey_L v2.0-a138-7538f26.

crashed: ReferenceError: self is not defined

Version 1.1.0

OUTPUT tab:
image

c:\Users\User.vscode\extensions\thqby.vscode-autohotkey2-lsp-1.1.0\server\dist\server.js:1

ReferenceError: self is not defined
    at Object.4603 (c:\Users\User\.vscode\extensions\thqby.vscode-autohotkey2-lsp-1.1.0\server\dist\server.js:1:162374)
    at n (c:\Users\User\.vscode\extensions\thqby.vscode-autohotkey2-lsp-1.1.0\server\dist\server.js:1:319822)
    at c:\Users\User\.vscode\extensions\thqby.vscode-autohotkey2-lsp-1.1.0\server\dist\server.js:1:320189
    at Object.<anonymous> (c:\Users\User\.vscode\extensions\thqby.vscode-autohotkey2-lsp-1.1.0\server\dist\server.js:1:320216)
    at Module._compile (internal/modules/cjs/loader.js:1125:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1155:10)
    at Module.load (internal/modules/cjs/loader.js:982:32)
    at Module._load (internal/modules/cjs/loader.js:823:14)
    at Function.f._load (electron/js2c/asar_bundle.js:5:12913)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
[Error - 11:43:55 p.m.] Connection to server got closed. Server will not be restarted.

Syntax parse issue

Report errors: missing "]" and Unexpected "}"

x := [
{test:
100}
]

MsgBox(x[1].test)

多行注释的代码被破坏

格式化被多行注释包裹的代码,会在每行前追加"*"符,这使得难以还原被注释的代码。
或者有关闭它的选项吗?谢谢。

/*
 * t(){
 * 
 * }
 */

False error in object literal

This is a valid object literal:

x := {in: 1}

The extension indicates that it is not. I observed this in 0.6.8 and 0.6.9.

The left side of : in an object literal should permit any valid property name, and that includes in.

Names of properties, methods and window groups are permitted to be reserved words.

x.in already works correctly.

代码格式化 BUG

谢谢您提供的工具。

我发现了代码格式化的一个BUG,当else 后面是"()"时,它会把else当作函数。
比如

	if a=2
		b:=3
	else (b:=3,a:=2)

会处理为:

	if a = 2
		b := 3
	else(b := 3, a := 2)

顺便请问可以把ahk的格式化工具作为单独的命令行工具发布吗?
因为VSCODE不是我的主力编辑器,而我又十分依赖这个工具。谢谢。

Highlight quotes and escaped spaces inside string literals

"'foo'"		'"bar"'
"`'foo`'"	'`"bar`"'
'`'foo`''	"`"bar`""

'``'		"``"
'`n'		"`n"
'`r'		"`r"
'`b'		"`b"
'`t'		"`t"
'`s'		"`s"
'`v'		"`v"
'`a'		"`a"
'`f'		"`f"

image
The documentation states that in order "to include an actual quote mark inside a literal string, [...] enclose the string in the opposite type of quote mark." Currently, this rule isn't being taken into consideration (see first line in the screenshot).

Moreover, the escape sequence `s (space) appears to be flagged erroneously as invalid.illegal.unknown-escape (red).
EscapedSpace

语法高亮的颜色存在不一致性

在默认浅色的主题下,语法高亮的颜色逻辑是这样的:
紫色:#指令、关键字
红色:字符串常量中的转义字符
深红色:字符串常量、热字串的替换内容、#指令的字符串参数
绿色:数字常量、注释
青色:类名
黑色:运算符
黄色:函数、类方法
蓝色:内置变量、热键定义、热字串定义
黑蓝色:自定义变量、类属性

但是,目前存在以下例外:
=> 作为运算符,应为黑色,实为蓝色
static、global、in、and、or、not作为关键字,应为紫色,实为蓝色
在switch的case条件中,函数应为黄色,实为黑色
在定义热键时,PgUp应为蓝色,实为黄色(与PgDn形成反差)
在定义组合热键时, &应为蓝色,实为黑色

以上例外破坏了语法高亮的颜色的一致性,建议修复,非常感谢~

Highlighting and CodeIntel for instance and class value and dynamic properties

Code
class ClassName extends BaseClassName
{
	InstanceVar := 'Expression'

	static ClassVar := 'Expression'

	class NestedClass
	{
		; ...
	}

	Method()
	{
		; ...
	}

	static Method()
	{
		; ...
	}

	Property[Parameters]	; Use brackets only when parameters are present.
	{
		get {
			return 'value of property'
		}
		set {
			return 'Store or otherwise handle' value
		}
	}

	ShortProperty
	{
		get => 'Expression which calculates property value'
		set => 'Expression which stores or otherwise handles' value
	}

	ShorterProperty => 'Expression which calculates property value'
}

Instance and class (static) value (:=) and dynamic (=>, get, set, get/set) properties are currently not being highlighted. I suspect this is due to rather inconclusive scopes being assigned to them, namely variable.object, variable.other and (incorrectly) entity.name.function.
image

CodeIntel is being provided only in some cases.
image

Lastly, set has a second hidden parameter named value, therefore, I reckon applying a special highlight to it would be beneficial but only in that particular case.

Tested with AutoHotkey_L v2.0-a137-f6f65742.

格式化时多行注释的怪异行为

我注意到最新版本的格式化多行注释的行为已经改变,谢谢。

但出现了新的问题:

/*

a:=""

*/

会变成:

/*
/*

a:=""

*/
a:=""
/*

a:=""

*/
 */

Request textDocument/hover failed.

switches := []
switches := switches.Clone()
switches.push '/x'

When hovering over Clone or push, I get an error in the Output pane.

[Error - 6:51:03 pm] Request textDocument/hover failed.
Message: Request textDocument/hover failed with message: Maximum call stack size exceeded
Code: -32603

In the real script, switches is a function parameter, and its initial Array is provided by the caller.

Incorrect diagnostic for floating point and scientific notation optional parameters

The following floating point and scientific notation numbers are valid optional parameters.

somefunc_0(foo := .42) => foo
somefunc_1(foo := -.42) => foo
somefunc_2(foo := 1.0e4) => foo
somefunc_3(foo := -1.0e-4) => foo
somefunc_4(foo := 1.0E4) => foo
somefunc_5(foo := -1.0E-4) => foo
somefunc_6(foo := .5e4) => foo
somefunc_7(foo := -.5e-4) => foo
somefunc_8(foo := .5E4) => foo
somefunc_9(foo := -.5E-4) => foo

An Error diagnostic is being spuriously emitted by the LSP extension.

Invalid parameter definition

Tested with AutoHotkey_L v2.0-a137-f6f65742.

Improve class extends declaration diagnostics

The diagnostics for class declarations extending another class could be improved, which in turn could help to prevent triggering a potential extension error.

class Foo extends Exists
{
	Bar := ''
	static Baz := ''	
}

class Exists
{
	
}

ClassExtends

class <ClassName> extends without specifying the target class is an error:

Error at line 1.

Line Text: extends
Error: Syntax error in class definition.

The program will exit.

This is a candidate for a diagnostic.


Moreover, if one attempts to extends a class, which does not exist, and then the hover tooltip for a static class variable is the deriving class is triggered (as seen in the screencast above), VS Code reports an extension error:
image

[Error - hh:mm:ss a] Request textDocument/hover failed.
  Message: Request textDocument/hover failed with message: Cannot read property '__new' of undefined
  Code: -32603 

Edit 1: static methods are affected by this as well.

Tested with AutoHotkey_L v2.0-a137-f6f65742.

Auto-indent after if/else/loop/etc.

It would be helpful if the line after an if/else/loop/etc. (without braces) was auto-indented. The language configuration file has an indentation rule for this:

indentNextLinePattern - If a line matches this pattern, then only the next line after it should be indented once.

It seems to be ignored if the increaseIndentPattern and decreaseIndentPattern rules are not also defined.

I got a test pattern working by modifying ahk2.configuration.json, though in my case it stops working when I relaunch VS Code, until after I switch from an .ahk file to a non-.ahk file and back.

Highlighting of classes under `if a := b() {`

class SomeClass {
    ;...
}
if a := somemap.get(key, false) {
    return SomeClass(a, b)
}
; a := ...
return SomeClass(a, b)

The line under if a := somemap.get(key, false) { highlights SomeClass as a function.

If the optional parentheses are added around the if's condition, it correctly highlights as a class:

if (a := somemap.get(key, false)) {

Strange highlighting of hexadecimal prefixes, zero-padded integers and floats

        1111
   0.0001111

  0x00001111
   .00001111
   000001111

image
Is there a particular reason why hexadecimal numbers, zero-left-padded integers and floating point numbers without leading zeroes are being highlighted this way?
I expected them to be highlighted identically to the non-zero-padded integer and regular float (see first two lines in the screenshot).

Detect invalid fat arrow function declaration

The following piece of code produces a compile time error.

somefunc() =>

The emitted error is:

Error at line 1.

Line Text: somefunc() =>
Error: Invalid function declaration.

The program will exit.

According to the documentation, "a line that ends with an expression operator is automatically merged with the line below it." Since the fat arrow function operator => can be found in the Expression Operator Precedence Table in the documentation, we can safely conclude that it is, in fact, an expression operator. Furthermore, again based on the same table, we can see that the operator then expects an expression (expr). Therefore, a diagnostic should be emitted if the next below-line-to-merge is not an expression or in case there are no more lines remaining as seen in the example above (i.e. EoF).

Here are some more examples that produce similar errors.
A hotkey definition is merged to produce a malformed ternary expression.

somefunc() =>
Space::Enter
Error:  A ":" is missing its "?"

	Line#
	001: {
--->	001: Return Space::Enter
	001: }

The program will exit.

A class definition is merged in an attempt to produce a function, returning the string concatenation of the Class class Object, an uninitialized variable SomeClass and an empty Object {} (?).

somefunc() =>
class SomeClass {

}
Error:  Unexpected "{"

	Line#
	001: {
--->	001: Return class SomeClass { }
	001: }

The program will exit.

Tested with AutoHotkey_L v2.0-a137-f6f65742.

Highlighting of `this` and `super` inside class body

Code
class Foo extends Bar
{
	__New()
	{
		if (this.Method())
			this.Method()

		if (super.Method())
			super.Method()

		BooleanArray := [ this.Method(), super.Method() ]
		BooleanMap := Map( 'this', this.Method(), 'super', super.Method() )
		BooleanObject := { this: this.Method(), super: super.Method() }

		NestedFunction()
		{
			if (this.Method())
				this.Method()

			if (super.Method())
				super.Method()

			BooleanArray := [ this.Method(), super.Method() ]
			BooleanMap := Map( 'this', this.Method(), 'super', super.Method() )
			BooleanObject := { this: this.Method(), super: super.Method() }
		}

		NestedFunctionWithShadowedParameters(this, super)
		{
			if (this.Method())
				this.Method()

			if (super.Method())
				super.Method()

			BooleanArray := [ this.Method(), super.Method() ]
			BooleanMap := Map( 'this', this.Method(), 'super', super.Method() )
			BooleanObject := { this: this.Method(), super: super.Method() }
		}
	}

	Method() => true
}

class Bar
{
	Method() => true
}

Within class bodies, incorrect scopes (variable.other.*) are being applied to the hidden parameter this and the pseudo-keyword super whenever they are parenthesized and in a few other instances.

ThisSuper

The same issue can be observed in Array declarations. Map construction is also affected by virtue of being nothing more than a parenthesized function call. Suffice to say, any function calls, for that matter, suffer the same fate. Object declarations exhibit a different kind of issue. While the correct scopes are being applied to the object's property values, the same scopes are also incorrectly being applied to the object's property names.

Another issue I've come across concerns parametrized functions, which shadow this and super. Take the following nested function as an example:

image

In this case neither this nor super should be highlighted as referring to the deriving class itself or the base class (unless those exact references were passed in a call to the function, however, deducing that accurately might prove to be too challenging a task for static analysis), and yet they are.

Tested with AutoHotkey_L v2.0-a138-7538f26.

Typing a full stop triggers completion list unexpectedly

This happens in both single-line comments and block comments.

; End.   ←  triggers completion list with Add, AddActiveX, etc.

Maybe someone wants it this way, but I assume it's unintended since it's inconsistent with typing (, which triggers parameter info only outside of comments.

It's also triggered while typing . for concatenation, as in a . b. I think that's acceptable, since it's actually valid to write obj .property with space in between, but if possible I would set it to pop up only if there is a non-space character preceding ..

It's also triggered while typing . in a number such as 1.0. In this case it is at least limiting the list to members of Any (so maybe it is recognizing the type of value correctly?), but it seems unnecessarily distracting. The completion list seems unlikely to be useful in this context.

Highlighting and diagnostic issues in forced hook $ hotkeys

<#$a::MsgBox(A_ThisHotkey) ; Unknown token '#$a::MsgBox(A_ThisHotkey) [1, 2]'
#$a::MsgBox(A_ThisHotkey) ; Incorrect highlight scopes, not recognized as a hotkey.
+$a::MsgBox(A_ThisHotkey) ; Invalid symbol naming '$a' [3, 2]
^$a::MsgBox(A_ThisHotkey) ; Invalid symbol naming '$a' [4, 2]
!$a::MsgBox(A_ThisHotkey) ; Invalid symbol naming '$a' [5, 2]
~$a::MsgBox(A_ThisHotkey) ; Invalid symbol naming '$a' [6, 2]
*$a::MsgBox(A_ThisHotkey) ; Invalid symbol naming '$a' [7, 2]

All of the following are valid hotkey definitions. The issue seems to be triggered by placing the $ hook modifier symbol in a place other than at the very front of the hotkey definition.
image

Tested with AutoHotkey_L v2.0-a138-7538f26.

Highlighting of assigned-to parameters in function calls

foo(bar := '', baz := '', qux := '', quux := '')

In cases where parameters beyond the first one are being assigned-to in single line function calls, the assigned-to variable is incorrectly being scoped as a variable.other.property, while the colon : belonging to the assignment operator := - as punctuation.separator.key-value. The meta.objectliteral meta-scope is applied to both tokens. This seems to only affect the assignment operator (based on the few tests I have performed below).

ParameterProperty

Additional Tests
foo(bar := '', baz++)
foo(bar := '', baz--)
foo(bar := '', ++baz)
foo(bar := '', --baz)
foo(bar := '', baz ** 123)
foo(bar := '', -baz)
foo(bar := '', !baz)
foo(bar := '', ~baz)
foo(bar := '', &baz)
foo(bar := '', baz * 123)
foo(bar := '', baz / 123)
foo(bar := '', baz // 123)
foo(bar := '', baz + 123)
foo(bar := '', baz - 123)
foo(bar := '', baz << 123)
foo(bar := '', baz >> 123)
foo(bar := '', baz >>> 123)
foo(bar := '', baz & 123)
foo(bar := '', baz ^ 123)
foo(bar := '', baz | 123)
foo(bar := '', baz . '')
foo(bar := '', baz ~= '')
foo(bar := '', baz > 123)
foo(bar := '', baz < 123)
foo(bar := '', baz >= 123)
foo(bar := '', baz <= 123)
foo(bar := '', baz = 123)
foo(bar := '', baz == 123)
foo(bar := '', baz != 123)
foo(bar := '', baz !== 123)
foo(bar := '', baz IS 123)
foo(bar := '', baz IN 123)
foo(bar := '', baz CONTAINS 123)
foo(bar := '', NOT baz)
foo(bar := '', baz AND 123)
foo(bar := '', baz && 123)
foo(bar := '', baz OR 123)
foo(bar := '', baz || 123)
foo(bar := '', baz ? qux := 123 : quux := '')
foo(bar := '', baz := 123)
foo(bar := '', baz += 123)
foo(bar := '', baz -= 123)
foo(bar := '', baz *= 123)
foo(bar := '', baz /= 123)
foo(bar := '', baz //= 123)
foo(bar := '', baz .= '')
foo(bar := '', baz |= 123)
foo(bar := '', baz &= 123)
foo(bar := '', baz ^= 123)
foo(bar := '', baz >>= 123)
foo(bar := '', baz <<= 123)
foo(bar := '', baz >>>= 123)
foo(bar := '', baz() => baz)
foo(bar := '', (baz := '', 123))

Tested with AutoHotkey_L v2.0-a138-7538f26.

End of continuation section not recognized

a := '
	(
		...
	)x'
b := 1

When the ending quote mark is not immediately after the closing parentheses of the continuation section, it is not recognized. The remainder of the file (if it contains no )') is highlighted as a string. In my real script, I am using a continuation section to make a RegEx pattern more readable:

v2_qstr := '(?:
	(Join| `
		"(?:[^"`\r\n]|`.)*"
		'(?:[^'`\r\n]|`.)*'
	))'

The start (?: and end ) are purposely outside the continuation section, but still inside the string.

It is an error for a continuation section to lack a closing ), and an error for a quoted string to lack an ending quote, but in this case neither the continuation section nor the quote mark are flagged as errors.

Quoted strings cannot span multiple lines on their own. Even if the ending quote isn't recognized, the ) on the last line ends the continuation section, so the string cannot extend to subsequent lines (unless there are more continuation lines or sections).

Currently an unclosed " without a continuation section is correctly marked as an error, but the remainder of the file is also highlighted as a string (up to the next )", even though there is no continuation section).

Another highlighting issue with the code above, although a very minor one, is that `\ and `. are highlighted as invalid escape sequences. They aren't escape sequences: the continuation section's ` option marks all ` within the section as literal.

代码格式化导致热字串的X选项无法使用

举个例子:
:X:\a::MsgBox()的作用是,当用户输入\a后,弹出一个对话框。
但是,代码格式化器会给上述代码增加一个空格,变为:X:\a:: MsgBox(),此时程序不能编译通过,报错This line does not contain a recognized action.
这个空格不应该被插进去。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.