Experimental function: SwapLines
This function will allow you to swap lines in a variable or text file, valid options:
1,5 -> Swap lines 1 and 5
1-5,13-27 -> swap lines 1 to 5 with lines 13-27
To test this function you do need TF.ahk, see first post, as it depends on some helper functions.
Not sure if it should be added to TF, so give it a spin and let me know if you have any suggestions or find errors
Code:
;#include tf.ahk ; remove comment if you don't include TF in your library
test=
(
1-this is line 1
2-this is line 2
3-this is line 3
4-this is line 4
5-this is line 5
6-this is line 6
7-this is line 7
8-this is line 8
9-this is line 9
10-this is line 10
)
MsgBox % TF_SwapLines(test, "2,4")
;MsgBox % TF_SwapLines(test, "1-5,6-12") ; Note 12 > end of file, should work correctly
;MsgBox % TF_SwapLines(test, "2-4,8-10")
;MsgBox % TF_SwapLines(test, "1-2,5-10")
;MsgBox % TF_SwapLines(test, "1,5-10")
;MsgBox % TF_SwapLines(test, "2-4,8")
;MsgBox % TF_SwapLines(test, "1,10")
; swap 2 lines or two sections of lines in a text file, HugoV
TF_SwapLines(Text, SwapLines)
{
IfInString, SwapLines, + ; check if "incremental" values where used if so Return
Return
StringReplace, SwapLines, SwapLines, `,,`,, UseErrorLevel
If (ErrorLevel > 1) ; too many parameters
Return
TF_GetData(OW, Text, FileName)
StringSplit, Line, Text, `n, `r
Text=
Loop % Line0
Order .= A_Index ","
Order:= "," . Order
IfInString, SwapLines, - ; check if it is a section of lines if so make use of MakeMatchList
{
StringSplit, Swap, SwapLines, `,
Loop % Swap0
If (InStr(Swap%A_Index%,"-") > 0)
{
StringSplit, SectionsCheck, Swap%A_Index%, - ; built in check to see if last line of swap section isn't beyond end of file to prevent inserting empty lines
If (SectionsCheck2 > Line0)
Swap%A_Index% := SectionsCheck1 "-" Line0
Swap%A_Index% := _MakeMatchList(TextFile, Swap%A_Index%)
}
}
Else ; just swap two lines
{
StringSplit, Swap, SwapLines, `,
}
StringReplace, Order, Order, `,%Swap2%`,, `,%Swap1%`,
StringReplace, Order, Order, `,%Swap1%`,, `,%Swap2%`,
StringTrimRight, Order, Order, 1 ; remove trailing ,
StringTrimLeft, Order, Order, 1 ; remove leading ,
Loop, Parse, Order, `, ; create output with lines in the new order (the swapped lines)
; Text .= Line%A_Index% "|" Line%A_LoopField% "`n" ; test line remove comment and comment line below to show test results side by side
Text .= Line%A_LoopField% "`n"
Return TF_ReturnOutPut(OW, Text, FileName, 0)
}