local EnvTr = reaper.GetSelectedTrackEnvelope(0);
if EnvTr then;
reaper.PreventUIRefresh(1);
reaper.Undo_BeginBlock();
local startLoop,endLoop = reaper.GetSet_LoopTimeRange(0,0,0,0,0);
local Cur = reaper.GetCursorPosition();
reaper.GetSet_LoopTimeRange(1,0,9^9,(9^9)+1,0);
reaper.Main_OnCommand(42082,0)--Insert automation item
reaper.Main_OnCommand(42086,0)--Delete automation items
reaper.GetSet_LoopTimeRange(1,0,startLoop,endLoop,0);
reaper.SetEditCurPos(Cur,false,false);
reaper.Main_OnCommand(42093,0)--load
if startLoop ~= endLoop then;
local CountAutoItem = reaper.CountAutomationItems(EnvTr);
for i = 1,CountAutoItem do;
local Sel = reaper.GetSetAutomationItemInfo(EnvTr,i-1,"D_UISEL",0,0);
if Sel == 1 then;
reaper.GetSetAutomationItemInfo(EnvTr,i-1,"D_POSITION",startLoop,1);
local leng = reaper.GetSetAutomationItemInfo(EnvTr,i-1,"D_LENGTH",0,0);
local rate = reaper.GetSetAutomationItemInfo(EnvTr,i-1,"D_PLAYRATE",0,0);
local timSel = endLoop - startLoop;
local NewRate = (leng * rate) / timSel;
reaper.GetSetAutomationItemInfo(EnvTr,i-1,"D_PLAYRATE",NewRate,1);
reaper.GetSetAutomationItemInfo(EnvTr,i-1,"D_LENGTH",timSel,1);
end;
end;
end;
reaper.Undo_EndBlock("Insert and stretch automation item by time selection",-1);
reaper.PreventUIRefresh(-1);
end;