TabExpansion2.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
<#PSScriptInfo
.VERSION 1.0.5
.AUTHOR Roman Kuzmin
.COPYRIGHT (c) Roman Kuzmin
.GUID 550bc198-dd44-4bbc-8ad7-ccf4b8bd2aff
.TAGS TabExpansion2, Register-ArgumentCompleter
.LICENSEURI http://www.apache.org/licenses/LICENSE-2.0
.PROJECTURI https://github.com/nightroman/FarNet/blob/master/PowerShellFar/TabExpansion2.ps1
#>


<#
.Synopsis
    TabExpansion2 with completers added by profiles.
 
.Description
    The script replaces the built-in function TabExpansion2, creates the table
    TabExpansionOptions, and does nothing else. Initialization is performed on
    the first code completion via profiles *ArgumentCompleters.ps1.
 
    $TabExpansionOptions consists of empty entries:
 
        CustomArgumentCompleters = @{}
        NativeArgumentCompleters = @{}
        ResultProcessors = @()
        InputProcessors = @()
 
    Initialization via profiles. When TabExpansion2 is called the first time it
    invokes scripts like *ArgumentCompleters.ps1 found in the path. They add
    their completers to the options.
 
    TabExpansion2.ps1 (with extension if it is in the path) should be invoked
    in the beginning of an interactive session. Modules and other tools on
    loading may check for existence of the table and add their completers.
 
    Any found profile and completer issues are written as silent errors.
    Examine the variable $Error on troubleshooting.
 
    Extra table options:
 
        IgnoreHiddenShares
            $true tells to ignore hidden UNC shares.
 
        LiteralPaths
            $true tells to not escape special file characters.
 
        RelativePaths
            $true tells to replace paths with relative paths.
            $false tells to replace paths with absolute paths.
 
    Consider to use Register-ArgumentCompleter instead of adding completers to
    options directly. In this case *ArgumentCompleters.ps1 are compatible with
    v5 native and TabExpansionPlusPlus registrations.
 
    Consider to use Register-InputCompleter and Register-ResultCompleter
    instead of adding completers to options directly.
 
.Link
    wiki https://github.com/nightroman/FarNet/wiki/TabExpansion2
#>


# The global option table
New-Variable -Force -Name TabExpansionOptions -Scope Global -Description 'Custom completers and options.' -Value @{
    CustomArgumentCompleters = @{}
    NativeArgumentCompleters = @{}
    ResultProcessors = @()
    InputProcessors = @()
}

# Temporary initialization variable
$global:TabExpansionProfile = $true

<#
.Synopsis
    Registers argument completers.
.Description
    This command registers a script block as a completer for specified commands
    or parameter. It is compatible with v5 native and TabExpansionPlusPlus.
#>

function global:Register-ArgumentCompleter {
    [CmdletBinding(DefaultParameterSetName = 'PowerShellSet')]
    param(
        [Parameter(ParameterSetName = 'NativeSet', Mandatory = $true)]
        [Parameter(ParameterSetName = 'PowerShellSet')]
        [string[]]$CommandName = '',
        [Parameter(ParameterSetName = 'PowerShellSet', Mandatory = $true)]
        [string]$ParameterName = '',
        [Parameter(Mandatory = $true)]
        [scriptblock]$ScriptBlock,
        [Parameter(ParameterSetName = 'NativeSet')]
        [switch]$Native
    )

    $key = if ($Native) {'NativeArgumentCompleters'} else {'CustomArgumentCompleters'}
    foreach ($command in $CommandName) {
        if ($command -and $ParameterName) {
            $command += ":"
        }
        $TabExpansionOptions[$key]["${command}${ParameterName}"] = $ScriptBlock
    }
}

<#
.Synopsis
    Registers input completers.
.Description
    Input completers work before native. Each completer is invoked with the
    arguments $ast, $tokens, $positionOfCursor, $options. It returns either
    nothing in order to continue or a CommandCompletion instance which is
    used as the result.
 
    Register-InputCompleter is only used with this TabExpansion2.ps1,
    unlike Register-ArgumentCompleter which may be used in other cases.
.Outputs
    [System.Management.Automation.CommandCompletion]
#>

function global:Register-InputCompleter {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [scriptblock]$ScriptBlock
    )
    $TabExpansionOptions.InputProcessors += $ScriptBlock
}

<#
.Synopsis
    Registers result completers.
.Description
    Result completers work after native. They are invoked with the arguments
    $result $ast $tokens $positionOfCursor $options. They should not return
    anything, they should either do nothing or alter the $result.
 
    Register-InputCompleter is only used with this TabExpansion2.ps1,
    unlike Register-ArgumentCompleter which may be used in other cases.
#>

function global:Register-ResultCompleter {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [scriptblock]$ScriptBlock
    )
    $TabExpansionOptions.ResultProcessors += $ScriptBlock
}

function global:TabExpansion2 {
    [CmdletBinding(DefaultParameterSetName = 'ScriptInputSet')]
    param(
        [Parameter(ParameterSetName = 'ScriptInputSet', Mandatory= $true, Position = 0)]
        [string]$inputScript,
        [Parameter(ParameterSetName = 'ScriptInputSet', Mandatory = $true, Position = 1)]
        [int]$cursorColumn,
        [Parameter(ParameterSetName = 'AstInputSet', Mandatory = $true, Position = 0)]
        [System.Management.Automation.Language.Ast]$ast,
        [Parameter(ParameterSetName = 'AstInputSet', Mandatory = $true, Position = 1)]
        [System.Management.Automation.Language.Token[]]$tokens,
        [Parameter(ParameterSetName = 'AstInputSet', Mandatory = $true, Position = 2)]
        [System.Management.Automation.Language.IScriptPosition]$positionOfCursor,
        [Parameter(ParameterSetName = 'ScriptInputSet', Position = 2)]
        [Parameter(ParameterSetName = 'AstInputSet', Position = 3)]
        [Hashtable]$options
    )

    ${private:%} = $null

    ${private:*} = @{
        inputScript = $inputScript
        cursorColumn = $cursorColumn
        ast = $ast
        tokens = $tokens
        positionOfCursor = $positionOfCursor
        options = $options
    }
    Remove-Variable inputScript, cursorColumn, ast, tokens, positionOfCursor, options

    # take/init global options
    if (!${*}.options) {
        ${*}.options = $PSCmdlet.GetVariableValue('TabExpansionOptions')
        if ($PSCmdlet.GetVariableValue('TabExpansionProfile')) {
            Remove-Variable -Name TabExpansionProfile -Scope Global
            foreach(${%} in Get-Command -Name *ArgumentCompleters.ps1 -CommandType ExternalScript -All) {
                if (& ${%}.Definition) {
                    Write-Error -ErrorAction 0 "TabExpansion2: Unexpected output. Profile: $(${%}.Definition)"
                }
            }
        }
    }

    # parse input
    if ($PSCmdlet.ParameterSetName -eq 'ScriptInputSet') {
        ${%} = [System.Management.Automation.CommandCompletion]::MapStringInputToParsedInput(${*}.inputScript, ${*}.cursorColumn)
        ${*}.ast = ${%}.Item1
        ${*}.tokens = ${%}.Item2
        ${*}.positionOfCursor = ${%}.Item3
    }

    # input processors
    foreach(${%} in ${*}.options['InputProcessors']) {
        if (${*}.result = & ${%} ${*}.ast ${*}.tokens ${*}.positionOfCursor ${*}.options) {
            if (${*}.result -is [System.Management.Automation.CommandCompletion]) {
                return ${*}.result
            }
            Write-Error -ErrorAction 0 "TabExpansion2: Invalid result. Input processor: ${%}"
        }
    }

    # native
    ${*}.result = [System.Management.Automation.CommandCompletion]::CompleteInput(${*}.ast, ${*}.tokens, ${*}.positionOfCursor, ${*}.options)

    # result processors?
    if ((${*}.processors = ${*}.options['ResultProcessors'])) {
        # work around read only
        if (${*}.result.CompletionMatches.IsReadOnly) {
            if (${*}.result.CompletionMatches) {
                return ${*}.result
            }
            ${*}.result = &{
                param(${*})
                function TabExpansion {'*'}
                [System.Management.Automation.CommandCompletion]::CompleteInput("$(${*}.ast)", ${*}.positionOfCursor.Offset, $null)
            } ${*}
            ${*}.result.CompletionMatches.Clear()
        }

        # invoke processors
        foreach($_ in ${*}.processors) {
            if (& $_ ${*}.result ${*}.ast ${*}.tokens ${*}.positionOfCursor ${*}.options) {
                Write-Error -ErrorAction 0 "TabExpansion2: Unexpected output. Result processor: $_"
            }
        }
    }

    # nothing and cursor char is `\w`? try insert space
    if (!${*}.result.CompletionMatches -and ($_ = ${*}.inputScript) -and $_.Length -gt ${*}.cursorColumn -and $_[${*}.cursorColumn] -match '[\w$]') {
        return TabExpansion2 ($_.Insert(${*}.cursorColumn, ' ')) ${*}.cursorColumn
    }

    ${*}.result
}