26. března 2013

PowerShell ISE: Tab Indentation

Using PowerShell daily and writing PowerShell scripts (roughly estimated) weekly I suffer from ISE not being able to indent my code by tabs. Let's see what can be done to fix this bad behaviour.

First of all, why not just leave the code indented with spaces?

The answer is quite complex but imagine you share your script with another developer who is accustomed to another indentation style (I prefer 4-chars tabs, he 3-chars tabs for example). If I insert 4 spaces into my code, he will have unnecessary difficulties reading my code or replacing the spaces. If character is used (and colleague's favourite editor supports customization of width), my code will be displayed according to his preferences without any interference from my colleague's side. Automagically.
(ISE doesn't support customizable indentation at all, unfortunatelly. But hopefully your colleague is smart enough to not use this editor. ;-))

So... Let's move on to modification of PowerShell ISE.

Insert the following code into the PowerShell ISE profile which is usually found in something like:
%USERPROFILE%\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1
(just type $Profile in ISE console)

Function Replace-SpacesWithTabs()
{
    Param(
        [int]$NumberOfSpaces = 4
    )

    $Pattern = "[ ]{$($NumberOfSpaces)}"

    $Editor = $psISE.CurrentFile.Editor
    $CaretColumn = $Editor.CaretColumn
    $CaretLine = $Editor.CaretLine
    foreach ($ln in 1..$Editor.LineCount) {
        $Editor.SetCaretPosition($ln, 1)

        if ($Editor.CaretLineText -match "\S") {
            $MatchPosition = $Editor.CaretLineText.IndexOf($Matches[0])
            $WhiteStr = $Editor.CaretLineText.SubString(0, $MatchPosition)
            $Line = $Editor.CaretLineText.SubString($MatchPosition)

            $txt = $WhiteStr -replace $Pattern, "`t"
            $Editor.SelectCaretLine()
            $Editor.InsertText($txt + $Line)
        }
    }

    $Editor.SetCaretPosition($CaretLine, $CaretColumn)
}

$psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add(
    "Replace space indentation", {
        Replace-SpacesWithTabs  
    },
    "Control+Alt+I"
)


Replace-SpacesWithTabs() function replaces every group of specified number of space characters (at the beginning of a line only) with a character. The rest of the code inserts an item into the Add-ons menu.

Usage is quite simple. Open, copy or create a file. Edit is as usually. When you need to replace indentation spaces with tabs, press the specified keyboard shortcut. Of course, you are encouraged to check that the indentation has been modified. Changes to the code can be undone by the usual Ctrl + Z keystroke.

PS: If you know how to replace (only) the leading spaces with tabs in a more efficient way, you're welcome to share the knowledge in the comments bellow.

Žádné komentáře: