local undo = "Insert new MIDI item"
local tr, retval, name, m_pos, qn_st, qn_end, ts_st, ts_end
function qntime(qn) local num = reaper.TimeMap2_QNToTime(0, qn) return num end
function timesel(bool)
local ts_st, ts_end = reaper.GetSet_LoopTimeRange(bool, false, 0, 0, false)
return ts_st, ts_end
end
function insert(st_p, end_p)
local item = reaper.CreateNewMIDIItemInProj(tr, st_p, end_p, false)
reaper.GetSetMediaItemTakeInfo_String(reaper.GetActiveTake(item), 'P_NAME', name, true)
reaper.SetMediaItemInfo_Value(item, 'B_LOOPSRC', 0)
reaper.SetMediaItemSelected(item, true)
end
reaper.BR_GetMouseCursorContext()
tr = reaper.BR_GetMouseCursorContext_Track()
if not tr then return end
reaper.Undo_BeginBlock()
reaper.PreventUIRefresh(-1)
retval, buf_name = reaper.GetTrackName( tr, 0)
if buf_name == "MASTER" then return end
retval, name = reaper.GetSetMediaTrackInfo_String(tr, 'P_NAME', '', false)
m_pos = reaper.BR_GetMouseCursorContext_Position()
retval, qn_st, qn_end = reaper.TimeMap_QNToMeasures(0, reaper.TimeMap_timeToQN(m_pos))
ts_st, ts_end = timesel(false)
if ts_st ~= ts_end then insert(ts_st, ts_end) timesel(true)
else local msr_st, msr_end = qntime(qn_st), qntime(qn_end) insert(msr_st, msr_end)
end
reaper.PreventUIRefresh(1)
reaper.Undo_EndBlock(undo, -1)