Code: Select all
-- CSV rainbow, v0.7, 2024-01-11.
-- See https://forum.farmanager.com/viewtopic.php?p=161836#p161836
-- Based on https://forum.farmanager.com/viewtopic.php?p=151601#p151601
import S,C,Ct,match from lpeg
F=far.Flags
{Flags:flags,BackgroundColor:bgc}=far.AdvControl F.ACTL_GETCOLOR,far.Colors.COL_EDITORTEXT
flags=bit64.band flags,bit64.bor F.FCF_FG_4BIT,F.FCF_BG_4BIT
bgc=bit64.band bgc,0x00FFFFFF --make transparent (e.g. for Colorer's cross)
colors={ --TODO substitute another color if same as background
{Flags:flags,ForegroundColor:0xFF00000F,BackgroundColor:bgc},{Flags:flags,ForegroundColor:0xFF000005,BackgroundColor:bgc}
{Flags:flags,ForegroundColor:0xFF00000E,BackgroundColor:bgc},{Flags:flags,ForegroundColor:0xFF000007,BackgroundColor:bgc}
{Flags:flags,ForegroundColor:0xFF00000D,BackgroundColor:bgc},{Flags:flags,ForegroundColor:0xFF000006,BackgroundColor:bgc}
{Flags:flags,ForegroundColor:0xFF00000C,BackgroundColor:bgc},{Flags:flags,ForegroundColor:0xFF000008,BackgroundColor:bgc}
{Flags:flags,ForegroundColor:0xFF00000B,BackgroundColor:bgc},{Flags:flags,ForegroundColor:0xFF000004,BackgroundColor:bgc}
{Flags:flags,ForegroundColor:0xFF00000A,BackgroundColor:bgc},{Flags:flags,ForegroundColor:0xFF000003,BackgroundColor:bgc}
{Flags:flags,ForegroundColor:0xFF000009,BackgroundColor:bgc},{Flags:flags,ForegroundColor:0xFF000002,BackgroundColor:bgc}
}
editors={}
colorguid=win.Uuid'D63B25A7-982F-4C17-B6B0-FAC1CC0F9FE7'
visLineFirstLast=(eid)->
ei=editor.GetInfo eid
ei.TopScreenLine,math.min ei.TopScreenLine+ei.WindowSizeY,ei.TotalLines
addLine=(eid,aggrF)->(acc,i)->acc+aggrF (editor.GetString eid,i,0).StringText
accumOverRange=(first,last,accOp,init)->
res=init or 0
for i=first,last do res=accOp res,i
res
maxKeyVal=(a,f)->
if #a>0
k,m=1,f a[1]
for i=2,#a
n=f a[i]
if n>m then k,m=i,n
k,m
csv=(c)->
field=C '"'*(1-S'"'+'""')^0*'"'+(1-S(c..'"')+'""')^0
(s)->match Ct(field*(c*field)^0),s
redraw=0
Event
group:'EditorEvent'
action:(id,Event)->
if Event==F.EE_CLOSE then editors[id]=nil
if Event==F.EE_REDRAW and redraw==0
first,last=visLineFirstLast id
if not editors[id]
fn=editor.GetFileName id
if far.ProcessName F.PN_CMPNAMELIST,'*.csv',fn,F.PN_SKIPPATH
s={',',';','\t',':','|'}
i=maxKeyVal s,(c)->accumOverRange first,last,addLine id,(l)->#(csv(c)l) --max sum num fields
editors[id]=s[i]
if editors[id]
redraw+=1
sv=csv editors[id]
for i=first,last
r=sv (editor.GetString id,i,0).StringText
pos=1
for j=1,#r
editor.AddColor id,i,pos,pos+r[j]\len!-1,F.ECF_AUTODELETE,colors[(j-1)%#colors+1],0,colorguid
pos+=r[j]\len!+1
redraw-=1