Skip to content

Instantly share code, notes, and snippets.

@viktorsml
Last active September 2, 2023 09:57
Show Gist options
  • Select an option

  • Save viktorsml/fa9d021a887f008de409a64f8d268ee8 to your computer and use it in GitHub Desktop.

Select an option

Save viktorsml/fa9d021a887f008de409a64f8d268ee8 to your computer and use it in GitHub Desktop.
Custom PowerShell Profile
{
"$schema": "https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/schema.json",
"final_space": false,
"console_title": true,
"console_title_style": "template",
"console_title_template": "Terminal: {{.User}}@{{.Host}} in {{.Path}}",
"blocks": [
{
"type": "prompt",
"alignment": "left",
"vertical_offset": 1,
"horizontal_offset": 0,
"segments": [
{
"type": "session",
"style": "diamond",
"foreground": "#fafafa",
"properties": {
"user_info_separator": "<#7a7a7a>\uf1fa</>",
"display_default": false,
"display_host": false,
"user_color": "#76D4FF",
"host_color": "#76D4FF",
"postfix": "<#7a7a7a> \ue0b1</>"
}
},
{
"type": "root",
"style": "diamond",
"foreground": "#ffff66",
"properties": {
"root_icon": "\uF0E7",
"postfix": "<#7a7a7a> \ue0b1</>"
}
},
{
"type": "path",
"style": "diamond",
"foreground": "#fafafa",
"properties": {
"prefix": "<#f2f200> \ue5ff </>",
"style": "full",
"enable_hyperlink": false,
"folder_icon": "<#B5B2C2>\ue5fe </>"
}
},
{
"type": "text",
"style": "diamond",
"trailing_diamond": "\ue0b0",
"foreground": "#fafafa",
"properties": {
"text": "",
"postfix": "",
"prefix": ""
}
}
]
},
{
"type": "prompt",
"alignment": "right",
"segments": [
{
"type": "text",
"style": "diamond",
"foreground": "#fafafa",
"leading_diamond": "\ue0b2",
"properties": {
"text": "",
"prefix": "",
"postfix": ""
}
},
{
"type": "git",
"style": "diamond",
"foreground": "#FFC251",
"foreground_templates": [
"{{ if or (.Working.Changed) (.Staging.Changed) }}#FFC251{{ end }}",
"{{ if gt .Ahead 0 }}#2EC4B6{{ end }}",
"{{ if gt .Behind 0 }}#BA76E7{{ end }}"
],
"properties": {
"fetch_stash_count": true,
"fetch_status": true,
"fetch_upstream_icon": true,
"template": "{{ .UpstreamIcon }}{{ .HEAD }}{{ .BranchStatus }}{{ if .Working.Changed }}<#E84855> \uF044 {{ .Working.String }}</>{{ end }}{{ if and (.Working.Changed) (.Staging.Changed) }} |{{ end }}{{ if .Staging.Changed }}<#2ec4b6> \uF046 {{ .Staging.String }}</>{{ end }}{{ if gt .StashCount 0 }} \uF692 {{ .StashCount }}{{ end }}"
}
}
]
},
{
"type": "prompt",
"alignment": "left",
"newline": true,
"segments": [
{
"type": "text",
"style": "plain",
"foreground": "#7a7a7a",
"properties": {
"text": "$"
}
}
]
},
{
"type": "rprompt",
"alignment": "right",
"segments": [
{
"type": "executiontime",
"style": "plain",
"foreground": "#FFCE5C",
"properties": {
"threshold": 500,
"style": "roundrock",
"postfix": "<#fafafa> \uf252 </>"
}
},
{
"type": "exit",
"style": "plain",
"foreground": "#9FD356",
"properties": {
"display_exit_code": true,
"always_numeric": true,
"always_enabled": false,
"error_color": "#E84855",
"color_background": false,
"prefix": " \uf705 "
}
}
]
}
]
}
# Prompt Theme
Set-PoshPrompt -Theme R:\personal-environment\scripts\powershell\custom-theme.json
Remove-Alias cd
# Modules
Import-Module npm-completion
Import-Module Terminal-Icons
Import-Module PSReadline -RequiredVersion 2.2.0
# Aliases
# New-Alias <alias> <aliased-command>
New-Alias o ii
New-Alias cl clear
New-Alias nano C:\Progra~1\Git\usr\bin\nano.exe
New-Alias oneinc "C:/Code/oneinc-cli/oneinc.ps1"
# Autocomplete
Set-PSReadlineKeyHandler -Key Tab -Function MenuComplete
Set-PSReadlineKeyHandler -Key UpArrow -Function HistorySearchBackward
Set-PSReadlineKeyHandler -Key DownArrow -Function HistorySearchForward
# PSReadLine settings
# Set-PSReadLineOption -PredictionViewStyle ListView
# Set-PSReadLineOption -EditMode Windows
if ($host.Version.Major -eq 7){
# Only PowerShell 7 supports HistoryAndPlugin
Set-PSReadLineOption -PredictionSource HistoryAndPlugin
} else{
# Use history as the prediction source on 5.1
Set-PSReadLineOption -PredictionSource History
}
# Custom functions
function cdh { Set-Location (git rev-parse --show-toplevel) }
function cdh.. { cdh; cd .. }
function bro-speedup-git { $GitPromptSettings.EnableFileStatus = $false }
function touch { New-Item -ItemType file $args }
function winrar { & 'C:\Program Files\WinRAR\WinRAR.exe' x $args }
function edge { start microsoft-edge:$args }
function inspect { cat $args | peco }
function public-ip { (Invoke-WebRequest -uri "http://ifconfig.me/ip").Content }
function fork ($pathToOpenInFork = 'repo') {
if ('repo' -eq $pathToOpenInFork) {
$pathToOpenInFork = (git rev-parse --show-toplevel)
} else {
$fullPathToOpenInFork = (Get-Item $pathToOpenInFork).FullName
}
Invoke-Expression "$env:LOCALAPPDATA\Fork\fork.exe $fullPathToOpenInFork"
}
function search {
param(
[parameter(Mandatory=$true)] [String] $fileToSearch,
[parameter(Mandatory=$false)] [String] $searchLocationPath = "$(Get-Location)",
[parameter(Mandatory=$false)] [String] $filesToExclude,
[parameter(Mandatory=$false)] [switch] $local
)
if ('repo' -eq $searchLocationPath) { $searchLocationPath = (git rev-parse --show-toplevel) }
$searchMessage = "`nSearching for `"$fileToSearch`" inside `"$searchLocationPath`""
$searchCommandToRun = "Get-ChildItem -Path $searchLocationPath -Filter $fileToSearch -ErrorAction SilentlyContinue -Force"
if ('' -ne $filesToExclude) {
$searchMessage = "$searchMessage excluding `"$filesToExclude`""
$searchCommandToRun = "$searchCommandToRun -Exclude $filesToExclude"
}
if ($false -eq $local) { $searchCommandToRun = "$searchCommandToRun -Recurse" }
Write-Color -Text "$searchMessage ...`n" -Color Cyan
Invoke-Expression $searchCommandToRun | % { Write-Host $_.FullName }
}
function look {
param(
[parameter(Mandatory=$true)] [String] $textToSearch,
[parameter(Mandatory=$false)] [String] $searchLocationPath = "$(Get-Location)",
[parameter(Mandatory=$false)] [switch] $fileOnly
)
$searchQuery = "Get-ChildItem -Recurse -Path $searchLocationPath | Select-String $textToSearch -List"
if ($fileOnly) {
$searchQuery = "$searchQuery | Select Path"
}
Invoke-Expression $searchQuery
}
# Chocolatey profile
$ChocolateyProfile = "$env:ChocolateyInstall\helpers\chocolateyProfile.psm1"
if (Test-Path($ChocolateyProfile)) {
Import-Module "$ChocolateyProfile"
}
# Zoxide
Invoke-Expression (& {
$hook = if ($PSVersionTable.PSVersion.Major -lt 6) { 'prompt' } else { 'pwd' }
(zoxide init --hook $hook --cmd cd powershell) -join "`n"
})
# Autocomplete for winget
Register-ArgumentCompleter -Native -CommandName winget -ScriptBlock {
param($wordToComplete, $commandAst, $cursorPosition)
[Console]::InputEncoding = [Console]::OutputEncoding = $OutputEncoding = [System.Text.Utf8Encoding]::new()
$Local:word = $wordToComplete.Replace('"', '""')
$Local:ast = $commandAst.ToString().Replace('"', '""')
winget complete --word="$Local:word" --commandline "$Local:ast" --position $cursorPosition | ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
}
}
# This key handler shows the entire or filtered history using Out-GridView. The
# typed text is used as the substring pattern for filtering. A selected command
# is inserted to the command line without invoking. Multiple command selection
# is supported, e.g. selected by Ctrl + Click.
Set-PSReadLineKeyHandler -Key F7 `
-BriefDescription History `
-LongDescription 'Show command history' `
-ScriptBlock {
$pattern = $null
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$pattern, [ref]$null)
if ($pattern)
{
$pattern = [regex]::Escape($pattern)
}
$history = [System.Collections.ArrayList]@(
$last = ''
$lines = ''
foreach ($line in [System.IO.File]::ReadLines((Get-PSReadLineOption).HistorySavePath)) {
if ($line.EndsWith('`')) {
$line = $line.Substring(0, $line.Length - 1)
$lines = if ($lines) {
"$lines`n$line"
} else {
$line
}
continue
}
if ($lines) {
$line = "$lines`n$line"
$lines = ''
}
if (($line -cne $last) -and (!$pattern -or ($line -match $pattern))) {
$last = $line
$line
}
}
)
$history.Reverse()
$command = $history | Out-GridView -Title History -PassThru
if ($command)
{
[Microsoft.PowerShell.PSConsoleReadLine]::RevertLine()
[Microsoft.PowerShell.PSConsoleReadLine]::Insert(($command -join "`n"))
}
}
#region Smart Insert/Delete
Set-PSReadLineKeyHandler -Key '(','{','[' `
-BriefDescription InsertPairedBraces `
-LongDescription "Insert matching braces" `
-ScriptBlock {
param($key, $arg)
$closeChar = switch ($key.KeyChar)
{
<#case#> '(' { [char]')'; break }
<#case#> '{' { [char]'}'; break }
<#case#> '[' { [char]']'; break }
}
$selectionStart = $null
$selectionLength = $null
[Microsoft.PowerShell.PSConsoleReadLine]::GetSelectionState([ref]$selectionStart, [ref]$selectionLength)
$line = $null
$cursor = $null
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor)
if ($selectionStart -ne -1)
{
# Text is selected, wrap it in brackets
[Microsoft.PowerShell.PSConsoleReadLine]::Replace($selectionStart, $selectionLength, $key.KeyChar + $line.SubString($selectionStart, $selectionLength) + $closeChar)
[Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($selectionStart + $selectionLength + 2)
} else {
# No text is selected, insert a pair
[Microsoft.PowerShell.PSConsoleReadLine]::Insert("$($key.KeyChar)$closeChar")
[Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($cursor + 1)
}
}
Set-PSReadLineKeyHandler -Key ')',']','}' `
-BriefDescription SmartCloseBraces `
-LongDescription "Insert closing brace or skip" `
-ScriptBlock {
param($key, $arg)
$line = $null
$cursor = $null
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor)
if ($line[$cursor] -eq $key.KeyChar)
{
[Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($cursor + 1)
}
else
{
[Microsoft.PowerShell.PSConsoleReadLine]::Insert("$($key.KeyChar)")
}
}
Set-PSReadLineKeyHandler -Key Backspace `
-BriefDescription SmartBackspace `
-LongDescription "Delete previous character or matching quotes/parens/braces" `
-ScriptBlock {
param($key, $arg)
$line = $null
$cursor = $null
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor)
if ($cursor -gt 0)
{
$toMatch = $null
if ($cursor -lt $line.Length)
{
switch ($line[$cursor])
{
<#case#> '"' { $toMatch = '"'; break }
<#case#> "'" { $toMatch = "'"; break }
<#case#> ')' { $toMatch = '('; break }
<#case#> ']' { $toMatch = '['; break }
<#case#> '}' { $toMatch = '{'; break }
}
}
if ($toMatch -ne $null -and $line[$cursor-1] -eq $toMatch)
{
[Microsoft.PowerShell.PSConsoleReadLine]::Delete($cursor - 1, 2)
}
else
{
[Microsoft.PowerShell.PSConsoleReadLine]::BackwardDeleteChar($key, $arg)
}
}
}
#endregion Smart Insert/Delete
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment