1local function get_insert_index()
2 local selected = reaper.GetSelectedTrack(0, 0)
3 if not selected then
4 return reaper.CountTracks(0)
5 end
6
7 local track_number = reaper.GetMediaTrackInfo_Value(selected, "IP_TRACKNUMBER")
8 return math.floor(track_number)
9end
10
11local function focus_new_track(track)
12 reaper.SetOnlyTrackSelected(track)
13 reaper.SetMixerScroll(track)
14 reaper.Main_OnCommand(40913, 0) -- Vertical scroll selected tracks into view.
15end
16
17local function set_track_name(track, name)
18 reaper.GetSetMediaTrackInfo_String(track, "P_NAME", name, true)
19end
20
21local function get_action_name(options)
22 if options.action_name and options.action_name ~= "" then
23 return options.action_name
24 end
25
26 if options.track_name and options.track_name ~= "" then
27 return "Add " .. options.track_name
28 end
29
30 return "Add track"
31end
32
33local function insert_track(options)
34 local action_name = get_action_name(options)
35 local fx_name = options.fx_name
36 local needs_midi_input = options.needs_midi_input
37
38 if needs_midi_input == nil then
39 needs_midi_input = fx_name ~= nil and fx_name ~= ""
40 end
41
42 reaper.Undo_BeginBlock()
43 reaper.PreventUIRefresh(1)
44
45 local insert_index = get_insert_index()
46 reaper.InsertTrackAtIndex(insert_index, true)
47
48 local track = reaper.GetTrack(0, insert_index)
49 local fx_index = -1
50 local requested_fx = fx_name ~= nil and fx_name ~= ""
51
52 if track then
53 reaper.SetMediaTrackInfo_Value(track, "I_RECMON", 1)
54
55 if needs_midi_input then
56 reaper.SetMediaTrackInfo_Value(track, "I_RECINPUT", 4096 + 63)
57 end
58
59 if options.track_name and options.track_name ~= "" then
60 set_track_name(track, options.track_name)
61 end
62
63 if requested_fx then
64 fx_index = reaper.TrackFX_AddByName(track, fx_name, false, -1000)
65 if fx_index >= 0 then
66 reaper.TrackFX_Show(track, fx_index, 1)
67 end
68 end
69
70 focus_new_track(track)
71 reaper.TrackList_AdjustWindows(false)
72 reaper.UpdateArrange()
73 end
74
75 reaper.PreventUIRefresh(-1)
76
77 if requested_fx and fx_index < 0 then
78 reaper.Undo_EndBlock(action_name .. " (FX not found)", -1)
79 reaper.ShowMessageBox(
80 'Could not find FX named "' .. fx_name .. '". The track was still created.',
81 action_name,
82 0
83 )
84 return
85 end
86
87 reaper.Undo_EndBlock(action_name, -1)
88end
89
90return insert_track