Skip to content

Commit 22ffb10

Browse files
committed
Update Edit-Code (the EditFunction submodule).
1 parent 786e47f commit 22ffb10

File tree

1 file changed

+60
-32
lines changed

1 file changed

+60
-32
lines changed

PotentialContribution/EditFunction.psm1

Lines changed: 60 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,33 @@
22

33
# The EditFunction is going into the ModuleBuilder module...
44
## Version History:
5+
# 4.0 - Added support for VS Code, fixed a bug in the internal SplitCommand
56
# 3.0 - made it work for file paths, and any script command. Added "edit" alias, and "NoWait" option.
67
# 2.1 - fixed the fix: always remove temp file, persist across-sessions in environment
78
# 2.0 - fixed persistence of editor options, made detection more clever
89
# 1.1 - refactored by June to (also) work on her machine (and have help)
910
# 1.0 - first draft, worked on my machine
1011

11-
function Split-Command {
12-
# The normal (unix) "Editor" environment variable can include parameters
13-
# so it can be executed from command by just appending the file name.
14-
# However, PowerShell can't deal with that, so:
12+
function SplitCommand {
13+
<#
14+
.SYNOPSIS
15+
SplitCommand divides the input command into the executable command and the parameters
16+
.DESCRIPTION
17+
Start-Process needs the command name separate from the parameters
18+
19+
The normal (unix) "Editor" environment variable (or the one in `git config core.editor`)
20+
can include parameters so it can be executed by just appending the file name.
21+
#>
1522
param(
23+
# The Editor command from the environment, like 'code -n -w'
1624
[Parameter(Mandatory=$true)]
1725
[string]$Command
1826
)
1927
$Parts = @($Command -Split " ")
2028

21-
for($count=$Parts.Length; $count -gt 1; $count--) {
29+
for ($count=0; $count -lt $Parts.Length; $count++) {
2230
$Editor = ($Parts[0..$count] -join " ").Trim("'",'"')
23-
if((Test-Path $Editor) -and (Get-Command $Editor -ErrorAction Ignore)) {
31+
if (Get-Command $Editor -ErrorAction Ignore) {
2432
$Editor
2533
$Parts[$($Count+1)..$($Parts.Length)] -join " "
2634
break
@@ -32,9 +40,11 @@ function Find-Editor {
3240
#.Synopsis
3341
# Find a simple code editor
3442
#.Description
35-
# Tries to find a text editor based on the PSEditor preference variable, the EDITOR environment variable, or your configuration for git. As a fallback it searches for Sublime, Notepad++, or Atom, and finally falls back to Notepad.
43+
# Tries to find a text editor based on the PSEditor preference variable, the EDITOR environment variable, or your configuration for git.
44+
# As a fallback it searches for Sublime, VSCode, Atom, or Notepad++, and finally falls back to Notepad.
3645
#
37-
# I have deliberately excluded PowerShell_ISE because it is a single-instance app which doesn't support "wait" if it's already running. That is, if PowerShell_ISE is already running, issuing a command like this will return immediately:
46+
# I have deliberately excluded PowerShell_ISE because it is a single-instance app which doesn't support "wait" if it's already running.
47+
# That is, if PowerShell_ISE is already running, issuing a command like this will return immediately:
3848
#
3949
# Start-Process PowerShell_ISE $Profile -Wait
4050
[CmdletBinding()]
@@ -44,32 +54,38 @@ function Find-Editor {
4454
# Defaults to the value of $PSEditor.Command or $PSEditor or Env:Editor if any of them are set.
4555
[Parameter(Position=1)]
4656
[System.String]
47-
$Editor = $(if($global:PSEditor.Command){ $global:PSEditor.Command } else { $global:PSEditor } ),
57+
$Editor = $(
58+
if($global:PSEditor.Command){
59+
$global:PSEditor.Command
60+
} else {
61+
$global:PSEditor
62+
}
63+
),
4864

4965
# Specifies commandline parameters for the editor.
50-
# Edit-Function.ps1 passes these editor-specific parameters to the editor you select.
66+
# Edit-Code.ps1 passes these editor-specific parameters to the editor you select.
5167
# For example, sublime uses -n -w to trigger a mode where closing the *tab* will return
5268
[Parameter(Position=2)]
5369
[System.String]
5470
$Parameters = $global:PSEditor.Parameters
5571
)
5672

5773
end {
58-
do { # This is the GOTO hack: use break to skip to the end once we find it:
74+
do {# This is the GOTO hack: use break to skip to the end once we find it:
5975
# In this test, we let the Get-Command error leak out on purpose
6076
if($Editor -and (Get-Command $Editor)) { break }
6177

6278
if ($Editor -and !(Get-Command $Editor -ErrorAction Ignore))
6379
{
6480
Write-Verbose "Editor is not a valid command, split it:"
65-
$Editor, $Parameters = Split-Command $Editor
81+
$Editor, $Parameters = SplitCommand $Editor
6682
if($Editor) { break }
6783
}
6884

6985
if (Test-Path Env:Editor)
7086
{
7187
Write-Verbose "Editor was not passed in, trying Env:Editor"
72-
$Editor, $Parameters = Split-Command $Env:Editor
88+
$Editor, $Parameters = SplitCommand $Env:Editor
7389
if($Editor) { break }
7490
}
7591

@@ -78,7 +94,7 @@ function Find-Editor {
7894
{
7995
Write-Verbose "PSEditor and Env:Editor not found, searching git config"
8096
if($CoreEditor = git config core.editor) {
81-
$Editor, $Parameters = Split-Command $CoreEditor
97+
$Editor, $Parameters = SplitCommand $CoreEditor
8298
if($Editor) { break }
8399
}
84100
}
@@ -92,10 +108,12 @@ function Find-Editor {
92108
}
93109
if($Editor = Get-Command "code.cmd", "code-insiders" -ErrorAction Ignore | Select-Object -Expand Path -first 1)
94110
{
111+
$Parameters = "-n -w"
95112
break
96113
}
97114
if($Editor = Get-Command "atom.exe" -ErrorAction Ignore | Select-Object -Expand Path -first 1)
98115
{
116+
$Parameters = "-n -w"
99117
break
100118
}
101119
if($Editor = Get-Command "notepad++.exe" -ErrorAction Ignore | Select-Object -Expand Path -first 1)
@@ -105,7 +123,7 @@ function Find-Editor {
105123
}
106124
# Search the slow way for sublime
107125
Write-Verbose "Editor still not found, getting desperate:"
108-
if(($Editor = Get-Item "C:\Program Files\DevTools\Sublime Text ?\sublime_text.exe" -ErrorAction Ignore | Sort {$_.VersionInfo.FileVersion} -Descending | Select-Object -First 1) -or
126+
if(($Editor = Get-Item "C:\Program Files\Sublime Text ?\sublime_text.exe" -ErrorAction Ignore | Sort {$_.VersionInfo.FileVersion} -Descending | Select-Object -First 1) -or
109127
($Editor = Get-ChildItem C:\Program*\* -recurse -filter "sublime_text.exe" -ErrorAction Ignore | Select-Object -First 1))
110128
{
111129
$Parameters = "-n -w"
@@ -159,32 +177,31 @@ function Find-Editor {
159177
function Edit-Code {
160178
<#
161179
.SYNOPSIS
162-
Creates and edits functions (or scripts) in the session in a script editor.
163-
180+
Opens folders, files, or functions in your favorite code editor (configurable)
164181
165182
.DESCRIPTION
166-
The Edit-Function command lets you create or edit functions in your session in your favorite text editor.
183+
The Edit-Code command lets you open a folder, a file, or even a script function from your session in your favorite text editor.
167184
168185
It opens the specified function in the editor that you specify, and when you finish editing the function and close the editor, the script updates the function in your session with the new function code.
169186
170-
Functions are tricky to edit, because most code editors require a file, and determine syntax highlighting based on the extension of that file. Edit-Function creates a temporary file with the function code.
187+
Functions are tricky to edit, because most code editors require a file, and determine syntax highlighting based on the extension of that file. Edit-Code creates a temporary file with the function code.
171188
172189
If you have a favorite editor, you can use the Editor parameter to specify it once, and the script will save it as your preference. If you don't specify an editor, it tries to determine an editor using the PSEditor preference variable, the EDITOR environment variable, or your configuration for git. As a fallback it searches for Sublime, and finally falls back to Notepad.
173190
174191
REMEMBER: Because functions are specific to a session, your function edits are lost when you close the session unless you save them in a permanent file, such as your Windows PowerShell profile.
175192
176193
.EXAMPLE
177-
Edit-Function Prompt
194+
Edit-Code Prompt
178195
179196
Opens the prompt function in a default editor (gitpad, Sublime, Notepad, whatever)
180197
181198
.EXAMPLE
182-
dir Function:\cd* | Edit-Function -Editor "C:\Program Files\Sublime Text 3\subl.exe" -Param "-n -w"
199+
dir Function:\cd* | Edit-Code -Editor "C:\Program Files\Sublime Text 3\subl.exe" -Param "-n -w"
183200
184-
Pipes all functions starting with cd to Edit-Function, which opens them one at a time in a new sublime window (opens each one after the other closes).
201+
Pipes all functions starting with cd to Edit-Code, which opens them one at a time in a new sublime window (opens each one after the other closes).
185202
186203
.EXAMPLE
187-
Get-Command TabExpan* | Edit-Function -Editor 'C:\Program Files\SAPIEN Technologies, Inc\PowerShell Studio 2014\PowerShell Studio.exe
204+
Get-Command TabExpan* | Edit-Code -Editor 'C:\Program Files\SAPIEN Technologies, Inc\PowerShell Studio 2014\PowerShell Studio.exe
188205
189206
Edits the TabExpansion and/or TabExpansion2 (whichever exists) in PowerShell Studio 2014 using the full path to the .exe file.
190207
Note that this also sets PowerShell Studio as your default editor for future calls.
@@ -197,29 +214,41 @@ function Edit-Code {
197214
- Think I should detect notepad2 or notepad++ or something?
198215
199216
About ISE: it doesn't support waiting for the editor to close, sorry.
217+
If you're sure you don't care about that, and want to use PowerShell ISE, you can set it in $PSEditor or pass it as a parameter.
200218
#>
201219
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSShouldProcess","")]
220+
[Alias("edit")]
202221
[CmdletBinding(DefaultParameterSetName="Command")]
203222
param (
204-
# Specifies the name of a function or script to create or edit. Enter a function name or pipe a function to Edit-Function.ps1. This parameter is required. If the function doesn't exist in the session, Edit-Function creates it.
223+
# Specifies the name of a function or script to create or edit. Enter a function name or pipe a function to Edit-Code.
224+
# This parameter is required. If the function doesn't exist in the session, Edit-Code creates it.
205225
[Parameter(Position=0, Mandatory = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName="Command")]
206226
[Alias("PSPath")]
207227
[String]
208228
$Command,
209229

210-
# Specifies the name of a function or script to create or edit. Enter a function name or pipe a function to Edit-Function.ps1. This parameter is required. If the function doesn't exist in the session, Edit-Function creates it.
230+
# Specifies the name of a function or script to create or edit. Enter a function name or pipe a function to Edit-Code.ps1.
231+
# This parameter is required. If the function doesn't exist in the session, Edit-Code creates it.
211232
[Parameter(Mandatory = $true, ParameterSetName="File", ValueFromPipelineByPropertyName = $true)]
212233
[String[]]
213234
$Path,
214235

215-
# Specifies a code editor. If the editor is in the Path environment variable (Get-Command <editor>), you can enter just the editor name. Otherwise, enter the path to the executable file for the editor.
236+
# Specifies a code editor.
237+
# If the editor is in the Path environment variable (Get-Command <editor>), you can enter just the editor name.
238+
# Otherwise, enter the path to the executable file for the editor.
216239
# Defaults to the value of $PSEditor.Command or $PSEditor or Env:Editor if any of them are set.
217240
[Parameter(Position=1)]
218241
[String]
219-
$Editor = $(if($global:PSEditor.Command){ $global:PSEditor.Command } else { $global:PSEditor } ),
242+
$Editor = $(
243+
if ($global:PSEditor.Command) {
244+
$global:PSEditor.Command
245+
} else {
246+
$global:PSEditor
247+
}
248+
),
220249

221250
# Specifies commandline parameters for the editor.
222-
# Edit-Function.ps1 passes these editor-specific parameters to the editor you select.
251+
# Edit-Code.ps1 passes these editor-specific parameters to the editor you select.
223252
# For example, sublime uses -n -w to trigger a mode where closing the *tab* will return
224253
[Parameter(Position=2)]
225254
[String]
@@ -235,7 +264,7 @@ function Edit-Code {
235264
[Switch]$Force
236265
)
237266
begin {
238-
# This is a terrible idea ...
267+
# This is probably a terrible idea ...
239268
$TextApplications = ".cmd",".bat",".vbs",".pl",".rb",".py",".wsf",".js",".ps1"
240269
$NonFileCharacters = "[$(([IO.Path]::GetInvalidFileNameChars() | %{ [regex]::escape($_) }) -join '|')]"
241270

@@ -336,11 +365,11 @@ function Edit-Code {
336365
Write-Verbose "$PSEditor '$File'"
337366
if ($PSEditor.Parameters)
338367
{
339-
Start-Process -FilePath $PSEditor.Command -ArgumentList $PSEditor.Parameters, """$file""" -Wait:($Wait)
368+
Start-Process -FilePath $PSEditor.Command -ArgumentList $PSEditor.Parameters, """$file""" -Wait:($Wait) -NoNewWindow
340369
}
341370
else
342371
{
343-
Start-Process -FilePath $PSEditor.Command -ArgumentList """$file""" -Wait:($Wait)
372+
Start-Process -FilePath $PSEditor.Command -ArgumentList """$file""" -Wait:($Wait) -NoNewWindow
344373
}
345374

346375
# Remove it if we created it
@@ -362,5 +391,4 @@ function Edit-Code {
362391
}
363392
}
364393

365-
Set-Alias edit Edit-Code
366394
Export-ModuleMember -Function Edit-Code, Find-Editor -Alias edit

0 commit comments

Comments
 (0)