Skip to content

Improved Carapace PowerShell completer code #1263

Description

@tahir-hassan

Carapace PowerShell Completer code

I have re-written the Carapace PowerShell completer code:

using namespace System.Management.Automation
using namespace System.Management.Automation.Language
using namespace System.Collections.Generic
using namespace System.Diagnostics.CodeAnalysis

$_carapace_completer = {
	[SuppressMessageAttribute("PSAvoidUsingInvokeExpression", "", Scope = "Function", Target = "*")]
	param([string]$wordToComplete, [CommandAst]$commandAst, [int]$cursorPosition)

	$elems = [List[string]]::new();

	foreach ($commandElem in $commandAst.CommandElements) {
		if ($cursorPosition -lt $commandElem.Extent.StartOffset) {
			break;
		} else {
			$text = if ($commandElem.StaticType -eq [string]) {
				$commandElem.Value
			} else {
				$commandElem.Extent.Text
			}
			$elems.Add($text);
		}
	}

	$elems[0] = $elems[0] -replace '\.exe$', '';
	if (-not $wordToComplete) {
		$elems.Add("");
	}

	[CompletionResult[]]$completions =
		carapace $elems[0] powershell $elems |
		ConvertFrom-Json |
		ForEach-Object { [CompletionResult]::new($_.CompletionText, $_.ListItemText.replace('`e[', "`e["), [CompletionResultType]::ParameterValue, $_.ToolTip.replace('`e[', "`e[")) };

	if ($completions) {
		$completions
	} else {
		$lastElem = $elems[-1];
        # either 1. no word to complete, 2. contains an asterisk, 3. starts with either ./ .\ which means file path 4. all lowercase
		if ($lastElem -eq '' -or $lastElem.Contains("*") -or $lastElem -match "^\.[/\\]" -or $lastElem -cnotmatch "[A-Z]") {
			return; # trigger default powershell completion
		} else {
			"" # prevent default file completion - user intended to have command arg completion
		}
	}
}

Improvements

  • It is greatly simplified
  • Allows powershell default completion in certain cases, for example lowercase file completion.

Questions

  • Is there any way I can integrate my code into Carapace?
  • Are there any test cases?

Thank you for your time.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions