IDE script to Sort Selection

I don’t know if this has been covered, but I needed it today, so here is an IDE script to property sort the selected code lines and optionally remove duplicates. Enjoy.

//
// Find the EOL
//
dim eol as string
if Text.InStr( &uD + &uA ) <> 0 then
  eol = &uD + &uA
elseif Text.InStr( &uD ) <> 0 then
  eol = &uD
elseif Text.InStr( &uA ) <> 0 then
  eol = &uA
else
  //
  // There are no lines, so nothing to do
  //
  beep
  return
end if

//
// Make sure we select from the beginning of a line to the end
//
dim bestSelStart as integer = SelStart
while bestSelStart > 0 and Text.Mid( bestSelStart + 1 - eol.Len, eol.Len ) <> eol
  bestSelStart = bestSelStart - 1
wend

dim bestSelEnd as integer = SelStart + SelLength - 1
while bestSelEnd < Text.Len and Text.Mid( bestSelEnd + 1, eol.Len ) <> eol
  bestSelEnd = bestSelEnd + 1
wend

SelStart = bestSelStart
SelLength = bestSelEnd - bestSelStart

dim origText as string
origText = SelText

dim s as string
s = origText.Trim

dim lines() as string 
lines = split( s.Trim, eol )
if lines.Ubound < 1 then
  beep
  return
end if

lines.Sort

//
// See if there are dupes
//
dim removeDupes as boolean
for index as integer = 1 to lines.Ubound
  if lines( index ).Trim = lines( index - 1 ).Trim then
    dim button as string = ShowDialog( "Text contains duplicates. Remove them?", "Such as: " + lines( index ), "Yes", "Abort", "No" )
    if button = "Abort" then
      return
    elseif button = "Yes" then
      removeDupes = true
    end if
    exit for index 
  end if
next

if removeDupes then
  for index as integer = lines.Ubound downto 1
    if lines( index ).Trim = lines( index - 1 ).Trim then
      lines.Remove index
    end if
  next
end if

dim newText as string
newText = join( lines, eol )

if newText <> SelText then
  SelText = newText
end if

Thanks. But I am unclear in what context you want to sort alphabetically lines of code. Just curious.

Code like this:

Register ObjectG
Register ObjectH
Register ObjectB
Register ObjectZ
<20 lines later>
Register ObjectG