lua: Fix formatting with lua-format

This commit is contained in:
Marty Oehme 2020-11-06 15:03:33 +01:00
parent b57db544b7
commit 0e34af1992
Signed by: Marty
GPG key ID: B7538B8F50A1C800
13 changed files with 3867 additions and 3385 deletions

View file

@ -1,7 +1,9 @@
local accounts = {} local accounts = {}
local status, gmailuser = pipe_from('gpg2 --decrypt --no-tty --quiet --no-verbose --for-your-eyes-only --pinentry-mode ask ~/.local/share/pass/misc/aerc-gmail-app-password.gpg | grep username | cut -d: -f2') local status, gmailuser = pipe_from(
local status, gmailpass = pipe_from('gpg2 --decrypt --no-tty --quiet --no-verbose --for-your-eyes-only --pinentry-mode ask ~/.local/share/pass/misc/aerc-gmail-app-password.gpg | head -n1') 'gpg2 --decrypt --no-tty --quiet --no-verbose --for-your-eyes-only --pinentry-mode ask ~/.local/share/pass/misc/aerc-gmail-app-password.gpg | grep username | cut -d: -f2')
local status, gmailpass = pipe_from(
'gpg2 --decrypt --no-tty --quiet --no-verbose --for-your-eyes-only --pinentry-mode ask ~/.local/share/pass/misc/aerc-gmail-app-password.gpg | head -n1')
-- Setup an imap account called gmail -- Setup an imap account called gmail
accounts.gmail = IMAP { accounts.gmail = IMAP {
server = "imap.gmail.com", server = "imap.gmail.com",

View file

@ -20,9 +20,7 @@ CONTINUOUS=false
UPDATE_TIME = 120 UPDATE_TIME = 120
-- implement simple wait function in case server does not support IDLE mode -- implement simple wait function in case server does not support IDLE mode
function sleep(n) function sleep(n) os.execute("sleep " .. tonumber(n)) end
os.execute("sleep " .. tonumber(n))
end
-- will set filters to be grabbed from XDG-compliant filter directory -- will set filters to be grabbed from XDG-compliant filter directory
-- can be overridden with env var IMAPFILTER_FILTERDIR -- can be overridden with env var IMAPFILTER_FILTERDIR
@ -62,11 +60,14 @@ end
-- create global variable containing the configuration files -- create global variable containing the configuration files
configDir = getConfigDir() configDir = getConfigDir()
assert(configDir, "No configuration directory found. Ensure " .. os.getenv("HOME") .. "/.config/imapfilter exists.") assert(configDir,
"No configuration directory found. Ensure " .. os.getenv("HOME") ..
"/.config/imapfilter exists.")
-- create global variable containing account access -- create global variable containing account access
accounts = loadfile(configDir .. "/accounts.lua")() accounts = loadfile(configDir .. "/accounts.lua")()
assert(accounts, "No accounts configured. Ensure accounts.lua exists and returns a table of accounts.") assert(accounts,
"No accounts configured. Ensure accounts.lua exists and returns a table of accounts.")
-- immediately act on the filters once -- immediately act on the filters once
applyFilters(getFilterDir()) applyFilters(getFilterDir())
@ -77,7 +78,9 @@ while CONTINUOUS==true do
applyFilters(getFilterDir()) applyFilters(getFilterDir())
if has_idle == false then if has_idle == false then
print("Server does not support idle, application will be polling again in " .. UPDATE_TIME .. "minutes.") print(
"Server does not support idle, application will be polling again in " ..
UPDATE_TIME .. "minutes.")
sleep(UPDATE_TIME) sleep(UPDATE_TIME)
end end
end end

View file

@ -27,17 +27,14 @@ function getSenderList(rollupfile)
local file = io.open(rollupfile) local file = io.open(rollupfile)
if file then if file then
for line in file:lines() do for line in file:lines() do table.insert(rollupSenders, line) end
table.insert(rollupSenders, line)
end
else else
print("ERROR: rollup did not find rollup.txt file containing mail addresses at " .. rollupfile or "" ) print(
"ERROR: rollup did not find rollup.txt file containing mail addresses at " ..
rollupfile or "")
end end
return rollupSenders return rollupSenders
end end
sendToFolder ( sendToFolder(accounts.gmail["Inbox"], accounts.gmail["Dump"],
accounts.gmail["Inbox"], getSenderList(getRollupFile()))
accounts.gmail["Dump"],
getSenderList(getRollupFile())
)

View file

@ -5,9 +5,7 @@ local hqprofile = "highquality"
local function powerstate() local function powerstate()
local f = io.open("/sys/class/power_supply/AC/online") local f = io.open("/sys/class/power_supply/AC/online")
if f == nil then if f == nil then return end
return
end
local t = f:read("*n") local t = f:read("*n")
f:close() f:close()
return t return t

View file

@ -78,7 +78,6 @@ local settings = {
-- Use ~ for home directory. Leave as empty to use mpv/playlists -- Use ~ for home directory. Leave as empty to use mpv/playlists
playlist_savepath = "", playlist_savepath = "",
-- show playlist or filename every time a new file is loaded -- show playlist or filename every time a new file is loaded
-- 2 shows playlist, 1 shows current file(filename strip applied) as osd text, 0 shows nothing -- 2 shows playlist, 1 shows current file(filename strip applied) as osd text, 0 shows nothing
-- instead of using this you can also call script-message playlistmanager show playlist/filename -- instead of using this you can also call script-message playlistmanager show playlist/filename
@ -96,7 +95,6 @@ local settings = {
-- allow the playlist cursor to loop from end to start and vice versa -- allow the playlist cursor to loop from end to start and vice versa
loop_cursor = true, loop_cursor = true,
-- #### VISUAL SETTINGS -- #### VISUAL SETTINGS
-- prefer to display titles for following files: "all", "url", "none". Sorting still uses filename. -- prefer to display titles for following files: "all", "url", "none". Sorting still uses filename.
@ -154,20 +152,19 @@ local settings = {
playing_hovered_file = "▶ %name", playing_hovered_file = "▶ %name",
playing_selected_file = "➤ %name", playing_selected_file = "➤ %name",
-- what to show when playlist is truncated -- what to show when playlist is truncated
playlist_sliced_prefix = "...", playlist_sliced_prefix = "...",
playlist_sliced_suffix = "..." playlist_sliced_suffix = "..."
} }
local opts = require("mp.options") local opts = require("mp.options")
opts.read_options(settings, "playlistmanager", function(list) update_opts(list) end) opts.read_options(settings, "playlistmanager",
function(list) update_opts(list) end)
local utils = require("mp.utils") local utils = require("mp.utils")
local msg = require("mp.msg") local msg = require("mp.msg")
local assdraw = require("mp.assdraw") local assdraw = require("mp.assdraw")
-- check os -- check os
if settings.system == "auto" then if settings.system == "auto" then
local o = {} local o = {}
@ -202,7 +199,8 @@ function update_opts(changelog)
-- parse filename json -- parse filename json
if changelog.filename_replace then if changelog.filename_replace then
if (settings.filename_replace ~= "") then if (settings.filename_replace ~= "") then
settings.filename_replace = utils.parse_json(settings.filename_replace) settings.filename_replace = utils.parse_json(
settings.filename_replace)
else else
settings.filename_replace = false settings.filename_replace = false
end end
@ -210,7 +208,8 @@ function update_opts(changelog)
-- parse loadfiles json -- parse loadfiles json
if changelog.loadfiles_filetypes then if changelog.loadfiles_filetypes then
settings.loadfiles_filetypes = utils.parse_json(settings.loadfiles_filetypes) settings.loadfiles_filetypes = utils.parse_json(
settings.loadfiles_filetypes)
filetype_lookup = {} filetype_lookup = {}
-- create loadfiles set -- create loadfiles set
@ -219,12 +218,11 @@ function update_opts(changelog)
end end
end end
if changelog.resolve_titles then if changelog.resolve_titles then resolve_titles() end
resolve_titles()
end
if changelog.playlist_display_timeout then if changelog.playlist_display_timeout then
keybindstimer = mp.add_periodic_timer(settings.playlist_display_timeout, remove_keybinds) keybindstimer = mp.add_periodic_timer(settings.playlist_display_timeout,
remove_keybinds)
keybindstimer:kill() keybindstimer:kill()
end end
@ -263,7 +261,8 @@ function on_loaded()
mp.commandv('show-text', strippedname) mp.commandv('show-text', strippedname)
end end
if settings.set_title_stripped then if settings.set_title_stripped then
mp.set_property("title", settings.title_prefix..strippedname..settings.title_suffix) mp.set_property("title", settings.title_prefix .. strippedname ..
settings.title_suffix)
end end
local didload = false local didload = false
@ -277,7 +276,11 @@ function on_loaded()
if promised_sort then if promised_sort then
promised_sort = false promised_sort = false
msg.info("Your playlist is sorted before starting playback") msg.info("Your playlist is sorted before starting playback")
if didload then sortplaylist() else sortplaylist(true) end if didload then
sortplaylist()
else
sortplaylist(true)
end
end end
-- if we promised to listen and sort on playlist size increase do it -- if we promised to listen and sort on playlist size increase do it
@ -315,8 +318,11 @@ function stripfilename(pathfile, media_title)
local tmp = pathfile local tmp = pathfile
if settings.filename_replace and not media_title then if settings.filename_replace and not media_title then
for k, v in ipairs(settings.filename_replace) do for k, v in ipairs(settings.filename_replace) do
if ( v['ext'] and (v['ext'][ext] or (ext and not protocol and v['ext']['all'])) ) if (v['ext'] and
or ( v['protocol'] and (v['protocol'][protocol] or (protocol and not ext and v['protocol']['all'])) ) then (v['ext'][ext] or (ext and not protocol and v['ext']['all']))) or
(v['protocol'] and
(v['protocol'][protocol] or
(protocol and not ext and v['protocol']['all']))) then
for ruleindex, indexrules in ipairs(v['rules']) do for ruleindex, indexrules in ipairs(v['rules']) do
for rule, override in pairs(indexrules) do for rule, override in pairs(indexrules) do
tmp = tmp:gsub(rule, override) tmp = tmp:gsub(rule, override)
@ -325,7 +331,8 @@ function stripfilename(pathfile, media_title)
end end
end end
end end
if settings.slice_longfilenames and tmp:len()>settings.slice_longfilenames_amount+5 then if settings.slice_longfilenames and tmp:len() >
settings.slice_longfilenames_amount + 5 then
tmp = tmp:sub(1, settings.slice_longfilenames_amount) .. " ..." tmp = tmp:sub(1, settings.slice_longfilenames_amount) .. " ..."
end end
return tmp return tmp
@ -334,19 +341,22 @@ end
-- gets a nicename of playlist entry at 0-based position i -- gets a nicename of playlist entry at 0-based position i
function get_name_from_index(i, notitle) function get_name_from_index(i, notitle)
refresh_globals() refresh_globals()
if plen <= i then msg.error("no index in playlist", i, "length", plen); return nil end if plen <= i then
msg.error("no index in playlist", i, "length", plen);
return nil
end
local _, name = nil local _, name = nil
local title = mp.get_property('playlist/' .. i .. '/title') local title = mp.get_property('playlist/' .. i .. '/title')
local name = mp.get_property('playlist/' .. i .. '/filename') local name = mp.get_property('playlist/' .. i .. '/filename')
local should_use_title = settings.prefer_titles == 'all' or name:match('^https?://') and settings.prefer_titles == 'url' local should_use_title = settings.prefer_titles == 'all' or
name:match('^https?://') and
settings.prefer_titles == 'url'
-- check if file has a media title stored or as property -- check if file has a media title stored or as property
if not title and should_use_title then if not title and should_use_title then
local mtitle = mp.get_property('media-title') local mtitle = mp.get_property('media-title')
if i == pos and mp.get_property('filename') ~= mtitle then if i == pos and mp.get_property('filename') ~= mtitle then
if not url_table[name] then if not url_table[name] then url_table[name] = mtitle end
url_table[name] = mtitle
end
title = mtitle title = mtitle
elseif url_table[name] then elseif url_table[name] then
title = url_table[name] title = url_table[name]
@ -354,7 +364,9 @@ function get_name_from_index(i, notitle)
end end
-- if we have media title use a more conservative strip -- if we have media title use a more conservative strip
if title and not notitle and should_use_title then return stripfilename(title, true) end if title and not notitle and should_use_title then
return stripfilename(title, true)
end
-- remove paths if they exist, keeping protocols for stripping -- remove paths if they exist, keeping protocols for stripping
if string.sub(name, 1, 1) == '/' or name:match("^%a:[/\\]") then if string.sub(name, 1, 1) == '/' or name:match("^%a:[/\\]") then
@ -364,25 +376,24 @@ function get_name_from_index(i, notitle)
end end
function parse_header(string) function parse_header(string)
local esc_title = stripfilename(mp.get_property("media-title"), true):gsub("%%", "%%%%") local esc_title = stripfilename(mp.get_property("media-title"), true):gsub(
local esc_file = stripfilename(mp.get_property("filename")):gsub("%%", "%%%%") "%%", "%%%%")
return string:gsub("%%N", "\\N") local esc_file = stripfilename(mp.get_property("filename")):gsub("%%",
:gsub("%%pos", mp.get_property_number("playlist-pos",0)+1) "%%%%")
:gsub("%%plen", mp.get_property("playlist-count")) return string:gsub("%%N", "\\N"):gsub("%%pos", mp.get_property_number(
:gsub("%%cursor", cursor+1) "playlist-pos", 0) + 1):gsub(
:gsub("%%mediatitle", esc_title) "%%plen", mp.get_property("playlist-count")):gsub("%%cursor",
:gsub("%%filename", esc_file) cursor + 1)
-- undo name escape :gsub("%%mediatitle", esc_title):gsub("%%filename", esc_file) -- undo name escape
:gsub("%%%%", "%%") :gsub("%%%%", "%%")
end end
function parse_filename(string, name, index) function parse_filename(string, name, index)
local base = tostring(plen):len() local base = tostring(plen):len()
local esc_name = stripfilename(name):gsub("%%", "%%%%") local esc_name = stripfilename(name):gsub("%%", "%%%%")
return string:gsub("%%N", "\\N") return string:gsub("%%N", "\\N"):gsub("%%pos", string.format(
:gsub("%%pos", string.format("%0"..base.."d", index+1)) "%0" .. base .. "d", index + 1))
:gsub("%%name", esc_name) :gsub("%%name", esc_name) -- undo name escape
-- undo name escape
:gsub("%%%%", "%%") :gsub("%%%%", "%%")
end end
@ -413,7 +424,6 @@ function parse_filename_by_index(index)
return parse_filename(template, get_name_from_index(index), index) return parse_filename(template, get_name_from_index(index), index)
end end
function draw_playlist() function draw_playlist()
refresh_globals() refresh_globals()
local ass = assdraw.ass_new() local ass = assdraw.ass_new()
@ -436,14 +446,15 @@ function draw_playlist()
start = plen - settings.showamount start = plen - settings.showamount
showrest = true showrest = true
end end
if start > 0 and not showall then ass:append(settings.playlist_sliced_prefix.."\\N") end if start > 0 and not showall then
ass:append(settings.playlist_sliced_prefix .. "\\N")
end
for index = start, start + settings.showamount - 1, 1 do for index = start, start + settings.showamount - 1, 1 do
if index == plen then break end if index == plen then break end
ass:append(parse_filename_by_index(index) .. "\\N") ass:append(parse_filename_by_index(index) .. "\\N")
if index == start+settings.showamount-1 and not showall and not showrest then if index == start + settings.showamount - 1 and not showall and
ass:append(settings.playlist_sliced_suffix) not showrest then ass:append(settings.playlist_sliced_suffix) end
end
end end
local w, h = mp.get_osd_size() local w, h = mp.get_osd_size()
if settings.scale_playlist_by_window then w, h = 0, 0 end if settings.scale_playlist_by_window then w, h = 0, 0 end
@ -496,7 +507,10 @@ function removefile()
refresh_globals() refresh_globals()
if plen == 0 then return end if plen == 0 then return end
selection = nil selection = nil
if cursor==pos then mp.command("script-message unseenplaylist mark true \"playlistmanager avoid conflict when removing file\"") end if cursor == pos then
mp.command(
"script-message unseenplaylist mark true \"playlistmanager avoid conflict when removing file\"")
end
mp.commandv("playlist-remove", cursor) mp.commandv("playlist-remove", cursor)
if cursor == plen - 1 then cursor = cursor - 1 end if cursor == plen - 1 then cursor = cursor - 1 end
showplaylist() showplaylist()
@ -506,7 +520,9 @@ function moveup()
refresh_globals() refresh_globals()
if plen == 0 then return end if plen == 0 then return end
if cursor ~= 0 then if cursor ~= 0 then
if selection then mp.commandv("playlist-move", cursor,cursor-1) end if selection then
mp.commandv("playlist-move", cursor, cursor - 1)
end
cursor = cursor - 1 cursor = cursor - 1
elseif settings.loop_cursor then elseif settings.loop_cursor then
if selection then mp.commandv("playlist-move", cursor, plen) end if selection then mp.commandv("playlist-move", cursor, plen) end
@ -519,7 +535,9 @@ function movedown()
refresh_globals() refresh_globals()
if plen == 0 then return end if plen == 0 then return end
if cursor ~= plen - 1 then if cursor ~= plen - 1 then
if selection then mp.commandv("playlist-move", cursor,cursor+2) end if selection then
mp.commandv("playlist-move", cursor, cursor + 2)
end
cursor = cursor + 1 cursor = cursor + 1
elseif settings.loop_cursor then elseif settings.loop_cursor then
if selection then mp.commandv("playlist-move", cursor, 0) end if selection then mp.commandv("playlist-move", cursor, 0) end
@ -542,15 +560,11 @@ function playfile()
if cursor ~= pos or is_idle then if cursor ~= pos or is_idle then
mp.set_property("playlist-pos", cursor) mp.set_property("playlist-pos", cursor)
else else
if cursor~=plen-1 then if cursor ~= plen - 1 then cursor = cursor + 1 end
cursor = cursor + 1
end
Watch_later() Watch_later()
mp.commandv("playlist-next", "weak") mp.commandv("playlist-next", "weak")
end end
if settings.show_playlist_on_fileload ~= 2 then if settings.show_playlist_on_fileload ~= 2 then remove_keybinds() end
remove_keybinds()
end
end end
function get_files_windows(dir) function get_files_windows(dir)
@ -634,7 +648,8 @@ function playlist(force_dir)
elseif file ~= filename then elseif file ~= filename then
mp.commandv("loadfile", utils.join_path(dir, file), appendstr) mp.commandv("loadfile", utils.join_path(dir, file), appendstr)
msg.info("Prepended to playlist: " .. file) msg.info("Prepended to playlist: " .. file)
mp.commandv("playlist-move", mp.get_property_number("playlist-count", 1)-1, c) mp.commandv("playlist-move",
mp.get_property_number("playlist-count", 1) - 1, c)
c = c + 1 c = c + 1
else else
cur = true cur = true
@ -659,9 +674,7 @@ function playlist(force_dir)
end end
function parse_home(path) function parse_home(path)
if not path:find("^~") then if not path:find("^~") then return path end
return path
end
local home_dir = os.getenv("HOME") or os.getenv("USERPROFILE") local home_dir = os.getenv("HOME") or os.getenv("USERPROFILE")
if not home_dir then if not home_dir then
local drive = os.getenv("HOMEDRIVE") local drive = os.getenv("HOMEDRIVE")
@ -693,23 +706,35 @@ function save_playlist()
-- create savepath if it doesn't exist -- create savepath if it doesn't exist
if utils.readdir(savepath) == nil then if utils.readdir(savepath) == nil then
local windows_args = {'powershell', '-NoProfile', '-Command', 'mkdir', savepath} local windows_args = {
'powershell', '-NoProfile', '-Command', 'mkdir', savepath
}
local unix_args = {'mkdir', savepath} local unix_args = {'mkdir', savepath}
local args = settings.system == 'windows' and windows_args or unix_args local args = settings.system == 'windows' and windows_args or unix_args
local res = utils.subprocess({args = args, cancellable = false}) local res = utils.subprocess({args = args, cancellable = false})
if res.status ~= 0 then if res.status ~= 0 then
msg.error("Failed to create playlist save directory "..savepath..". Error: "..(res.error or "unknown")) msg.error("Failed to create playlist save directory " .. savepath ..
". Error: " .. (res.error or "unknown"))
return return
end end
end end
local date = os.date("*t") local date = os.date("*t")
local datestring = ("%02d-%02d-%02d_%02d-%02d-%02d"):format(date.year, date.month, date.day, date.hour, date.min, date.sec) local datestring = ("%02d-%02d-%02d_%02d-%02d-%02d"):format(date.year,
date.month,
date.day,
date.hour,
date.min,
date.sec)
local savepath = utils.join_path(savepath, datestring.."_playlist-size_"..length..".m3u") local savepath = utils.join_path(savepath,
datestring .. "_playlist-size_" .. length ..
".m3u")
local file, err = io.open(savepath, "w") local file, err = io.open(savepath, "w")
if not file then if not file then
msg.error("Error in creating playlist file, check permissions. Error: "..(err or "unknown")) msg.error(
"Error in creating playlist file, check permissions. Error: " ..
(err or "unknown"))
else else
local i = 0 local i = 0
while i < length do while i < length do
@ -732,10 +757,11 @@ end
function alphanumsort(a, b) function alphanumsort(a, b)
local function padnum(d) local function padnum(d)
local dec, n = string.match(d, "(%.?)0*(.+)") local dec, n = string.match(d, "(%.?)0*(.+)")
return #dec > 0 and ("%.12f"):format(d) or ("%s%03d%s"):format(dec, #n, n) return #dec > 0 and ("%.12f"):format(d) or
("%s%03d%s"):format(dec, #n, n)
end end
return tostring(a):lower():gsub("%.?%d+",padnum)..("%3d"):format(#b) return tostring(a):lower():gsub("%.?%d+", padnum) .. ("%3d"):format(#b) <
< tostring(b):lower():gsub("%.?%d+",padnum)..("%3d"):format(#a) tostring(b):lower():gsub("%.?%d+", padnum) .. ("%3d"):format(#a)
end end
function dosort(a, b) function dosort(a, b)
@ -757,14 +783,10 @@ function sortplaylist(startover)
inner = inner - 1 inner = inner - 1
end end
inner = inner + 1 inner = inner + 1
if outer ~= inner then if outer ~= inner then mp.commandv('playlist-move', outer, inner) end
mp.commandv('playlist-move', outer, inner)
end
end end
cursor = mp.get_property_number('playlist-pos', 0) cursor = mp.get_property_number('playlist-pos', 0)
if startover then if startover then mp.set_property('playlist-pos', 0) end
mp.set_property('playlist-pos', 0)
end
if playlist_visible then showplaylist() end if playlist_visible then showplaylist() end
end end
@ -780,9 +802,7 @@ end
function reverseplaylist() function reverseplaylist()
local length = mp.get_property_number('playlist-count', 0) local length = mp.get_property_number('playlist-count', 0)
if length < 2 then return end if length < 2 then return end
for outer=1, length-1, 1 do for outer = 1, length - 1, 1 do mp.commandv('playlist-move', outer, 0) end
mp.commandv('playlist-move', outer, 0)
end
if playlist_visible then showplaylist() end if playlist_visible then showplaylist() end
end end
@ -835,7 +855,8 @@ end
function remove_keybinds() function remove_keybinds()
keybindstimer:kill() keybindstimer:kill()
keybindstimer = mp.add_periodic_timer(settings.playlist_display_timeout, remove_keybinds) keybindstimer = mp.add_periodic_timer(settings.playlist_display_timeout,
remove_keybinds)
keybindstimer:kill() keybindstimer:kill()
mp.set_osd_ass(0, 0, "") mp.set_osd_ass(0, 0, "")
playlist_visible = false playlist_visible = false
@ -850,26 +871,20 @@ function remove_keybinds()
end end
end end
keybindstimer = mp.add_periodic_timer(settings.playlist_display_timeout, remove_keybinds) keybindstimer = mp.add_periodic_timer(settings.playlist_display_timeout,
remove_keybinds)
keybindstimer:kill() keybindstimer:kill()
if not settings.dynamic_binds then if not settings.dynamic_binds then add_keybinds() end
add_keybinds()
end
if settings.loadfiles_on_start and mp.get_property_number('playlist-count', 0) == 0 then if settings.loadfiles_on_start and mp.get_property_number('playlist-count', 0) ==
playlist() 0 then playlist() end
end
promised_sort_watch = false promised_sort_watch = false
if settings.sortplaylist_on_file_add then if settings.sortplaylist_on_file_add then promised_sort_watch = true end
promised_sort_watch = true
end
promised_sort = false promised_sort = false
if settings.sortplaylist_on_start then if settings.sortplaylist_on_start then promised_sort = true end
promised_sort = true
end
mp.observe_property('playlist-count', "number", function() mp.observe_property('playlist-count', "number", function()
if playlist_visible then showplaylist() end if playlist_visible then showplaylist() end
@ -888,16 +903,14 @@ function resolve_titles()
while i < length do while i < length do
local filename = mp.get_property('playlist/' .. i .. '/filename') local filename = mp.get_property('playlist/' .. i .. '/filename')
local title = mp.get_property('playlist/' .. i .. '/title') local title = mp.get_property('playlist/' .. i .. '/title')
if i ~= pos if i ~= pos and filename and filename:match('^https?://') and not title and
and filename not url_table[filename] and not requested_urls[filename] then
and filename:match('^https?://')
and not title
and not url_table[filename]
and not requested_urls[filename]
then
requested_urls[filename] = true requested_urls[filename] = true
local args = { 'youtube-dl', '--no-playlist', '--flat-playlist', '-sJ', filename } local args = {
'youtube-dl', '--no-playlist', '--flat-playlist', '-sJ',
filename
}
local req = mp.command_native_async( local req = mp.command_native_async(
{ {
name = "subprocess", name = "subprocess",
@ -906,30 +919,38 @@ function resolve_titles()
capture_stdout = true capture_stdout = true
}, function(success, res) }, function(success, res)
if res.killed_by_us then if res.killed_by_us then
msg.verbose('Request to resolve url title ' .. filename .. ' timed out') msg.verbose(
'Request to resolve url title ' .. filename ..
' timed out')
return return
end end
if res.status == 0 then if res.status == 0 then
local json, err = utils.parse_json(res.stdout) local json, err = utils.parse_json(res.stdout)
if not err then if not err then
local is_playlist = json['_type'] and json['_type'] == 'playlist' local is_playlist =
local title = (is_playlist and '[playlist]: ' or '') .. json['title'] json['_type'] and json['_type'] == 'playlist'
msg.verbose(filename .. " resolved to '" .. title .. "'") local title =
(is_playlist and '[playlist]: ' or '') ..
json['title']
msg.verbose(filename .. " resolved to '" .. title ..
"'")
url_table[filename] = title url_table[filename] = title
refresh_globals() refresh_globals()
if playlist_visible then showplaylist() end if playlist_visible then
showplaylist()
end
return return
else else
msg.error("Failed parsing json, reason: "..(err or "unknown")) msg.error("Failed parsing json, reason: " ..
(err or "unknown"))
end end
else else
msg.error("Failed to resolve url title "..filename.." Error: "..(res.error or "unknown")) msg.error("Failed to resolve url title " .. filename ..
" Error: " .. (res.error or "unknown"))
end end
end) end)
mp.add_timeout(5, function() mp.add_timeout(5, function() mp.abort_async_command(req) end)
mp.abort_async_command(req)
end)
end end
i = i + 1 i = i + 1
@ -948,16 +969,33 @@ function handlemessage(msg, value, value2)
end end
end end
if msg == "show" and value == "filename" and strippedname and value2 then if msg == "show" and value == "filename" and strippedname and value2 then
mp.commandv('show-text', strippedname, tonumber(value2)*1000 ) ; return mp.commandv('show-text', strippedname, tonumber(value2) * 1000);
return
end end
if msg == "show" and value == "filename" and strippedname then if msg == "show" and value == "filename" and strippedname then
mp.commandv('show-text', strippedname ) ; return mp.commandv('show-text', strippedname);
return
end
if msg == "sort" then
sortplaylist(value);
return
end
if msg == "shuffle" then
shuffleplaylist();
return
end
if msg == "reverse" then
reverseplaylist();
return
end
if msg == "loadfiles" then
playlist(value);
return
end
if msg == "save" then
save_playlist();
return
end end
if msg == "sort" then sortplaylist(value) ; return end
if msg == "shuffle" then shuffleplaylist() ; return end
if msg == "reverse" then reverseplaylist() ; return end
if msg == "loadfiles" then playlist(value) ; return end
if msg == "save" then save_playlist() ; return end
end end
mp.register_script_message("playlistmanager", handlemessage) mp.register_script_message("playlistmanager", handlemessage)

View file

@ -2,7 +2,6 @@
-- --
-- This script skips sponsored segments of YouTube videos -- This script skips sponsored segments of YouTube videos
-- using data from https://github.com/ajayyy/SponsorBlock -- using data from https://github.com/ajayyy/SponsorBlock
local ON_WINDOWS = package.config:sub(1, 1) ~= '/' local ON_WINDOWS = package.config:sub(1, 1) ~= '/'
local options = { local options = {
@ -71,9 +70,7 @@ mp.options = require "mp.options"
mp.options.read_options(options, "sponsorblock") mp.options.read_options(options, "sponsorblock")
local legacy = mp.command_native_async == nil local legacy = mp.command_native_async == nil
if legacy then if legacy then options.local_database = false end
options.local_database = false
end
local utils = require "mp.utils" local utils = require "mp.utils"
if mp.get_script_directory == nil then if mp.get_script_directory == nil then
@ -83,7 +80,9 @@ else
end end
local sponsorblock = utils.join_path(scripts_dir, "shared/sponsorblock.py") local sponsorblock = utils.join_path(scripts_dir, "shared/sponsorblock.py")
local uid_path = utils.join_path(scripts_dir, "shared/sponsorblock.txt") local uid_path = utils.join_path(scripts_dir, "shared/sponsorblock.txt")
local database_file = options.local_database and utils.join_path(scripts_dir, "shared/sponsorblock.db") or "" local database_file = options.local_database and
utils.join_path(scripts_dir, "shared/sponsorblock.db") or
""
local youtube_id = nil local youtube_id = nil
local ranges = {} local ranges = {}
local init = false local init = false
@ -97,7 +96,12 @@ local volume_before = mp.get_property_number("volume")
function file_exists(name) function file_exists(name)
local f = io.open(name, "r") local f = io.open(name, "r")
if f ~= nil then io.close(f) return true else return false end if f ~= nil then
io.close(f)
return true
else
return false
end
end end
function t_count(t) function t_count(t)
@ -106,15 +110,14 @@ function t_count(t)
return count return count
end end
function time_sort(a, b) function time_sort(a, b) return a.time < b.time end
return a.time < b.time
end
function clean_chapters() function clean_chapters()
local chapters = mp.get_property_native("chapter-list") local chapters = mp.get_property_native("chapter-list")
local new_chapters = {} local new_chapters = {}
for _, chapter in pairs(chapters) do for _, chapter in pairs(chapters) do
if chapter.title ~= "Preview segment start" and chapter.title ~= "Preview segment end" then if chapter.title ~= "Preview segment start" and chapter.title ~=
"Preview segment end" then
table.insert(new_chapters, chapter) table.insert(new_chapters, chapter)
end end
end end
@ -124,7 +127,11 @@ end
function create_chapter(chapter_title, chapter_time) function create_chapter(chapter_title, chapter_time)
local chapters = mp.get_property_native("chapter-list") local chapters = mp.get_property_native("chapter-list")
local duration = mp.get_property_native("duration") local duration = mp.get_property_native("duration")
table.insert(chapters, {title=chapter_title, time=(duration == nil or duration > chapter_time) and chapter_time or duration - .001}) table.insert(chapters, {
title = chapter_title,
time = (duration == nil or duration > chapter_time) and chapter_time or
duration - .001
})
table.sort(chapters, time_sort) table.sort(chapters, time_sort)
mp.set_property_native("chapter-list", chapters) mp.set_property_native("chapter-list", chapters)
end end
@ -134,7 +141,8 @@ function getranges(_, exists, db, more)
if options.server_fallback then if options.server_fallback then
mp.add_timeout(0, function() getranges(true, true, "") end) mp.add_timeout(0, function() getranges(true, true, "") end)
else else
return mp.osd_message("[sponsorblock] database update failed, gave up") return mp.osd_message(
"[sponsorblock] database update failed, gave up")
end end
end end
if db ~= "" and db ~= database_file then db = database_file end if db ~= "" and db ~= database_file then db = database_file end
@ -151,20 +159,23 @@ function getranges(_, exists, db, more)
end end
local sponsors local sponsors
local args = { local args = {
options.python_path, options.python_path, sponsorblock, "ranges", db, options.server_address,
sponsorblock,
"ranges",
db,
options.server_address,
youtube_id youtube_id
} }
if not legacy then if not legacy then
sponsors = mp.command_native({name = "subprocess", capture_stdout = true, playback_only = false, args = args}) sponsors = mp.command_native({
name = "subprocess",
capture_stdout = true,
playback_only = false,
args = args
})
else else
sponsors = utils.subprocess({args = args}) sponsors = utils.subprocess({args = args})
end end
if not string.match(sponsors.stdout, "^%s*(.*%S)") then return end if not string.match(sponsors.stdout, "^%s*(.*%S)") then return end
if string.match(sponsors.stdout, "error") then return getranges(true, true) end if string.match(sponsors.stdout, "error") then
return getranges(true, true)
end
local new_ranges = {} local new_ranges = {}
local r_count = 0 local r_count = 0
if more then r_count = -1 end if more then r_count = -1 end
@ -176,7 +187,8 @@ function getranges(_, exists, db, more)
start_time = tonumber(string.match(t, '[^,]+')) start_time = tonumber(string.match(t, '[^,]+'))
end_time = tonumber(string.sub(string.match(t, ',[^,]+'), 2)) end_time = tonumber(string.sub(string.match(t, ',[^,]+'), 2))
for o_uuid, o_t in pairs(ranges) do for o_uuid, o_t in pairs(ranges) do
if (start_time >= o_t.start_time and start_time <= o_t.end_time) or (o_t.start_time >= start_time and o_t.start_time <= end_time) then if (start_time >= o_t.start_time and start_time <= o_t.end_time) or
(o_t.start_time >= start_time and o_t.start_time <= end_time) then
new_ranges[o_uuid] = o_t new_ranges[o_uuid] = o_t
goto continue goto continue
end end
@ -189,29 +201,31 @@ function getranges(_, exists, db, more)
} }
end end
if options.make_chapters then if options.make_chapters then
create_chapter("Sponsor start (" .. string.sub(uuid, 1, 6) .. ")", start_time) create_chapter("Sponsor start (" .. string.sub(uuid, 1, 6) ..
create_chapter("Sponsor end (" .. string.sub(uuid, 1, 6) .. ")", end_time) ")", start_time)
create_chapter("Sponsor end (" .. string.sub(uuid, 1, 6) .. ")",
end_time)
end end
end end
::continue:: ::continue::
r_count = r_count + 1 r_count = r_count + 1
end end
local c_count = t_count(ranges) local c_count = t_count(ranges)
if c_count == 0 or r_count >= c_count then if c_count == 0 or r_count >= c_count then ranges = new_ranges end
ranges = new_ranges
end
end end
function fast_forward() function fast_forward()
local last_speed = mp.get_property_number("speed") local last_speed = mp.get_property_number("speed")
local new_speed = math.min(last_speed + options.fast_forward_increase, options.fast_forward_cap) local new_speed = math.min(last_speed + options.fast_forward_increase,
options.fast_forward_cap)
if new_speed <= last_speed then return end if new_speed <= last_speed then return end
mp.set_property("speed", new_speed) mp.set_property("speed", new_speed)
end end
function fade_audio(step) function fade_audio(step)
local last_volume = mp.get_property_number("volume") local last_volume = mp.get_property_number("volume")
local new_volume = math.max(options.audio_fade_cap, math.min(last_volume + step, volume_before)) local new_volume = math.max(options.audio_fade_cap,
math.min(last_volume + step, volume_before))
if new_volume == last_volume then if new_volume == last_volume then
if step >= 0 then fade_dir = nil end if step >= 0 then fade_dir = nil end
if fade_timer ~= nil then fade_timer:kill() end if fade_timer ~= nil then fade_timer:kill() end
@ -225,7 +239,8 @@ function skip_ads(name, pos)
if pos == nil then return end if pos == nil then return end
local sponsor_ahead = false local sponsor_ahead = false
for uuid, t in pairs(ranges) do for uuid, t in pairs(ranges) do
if (options.fast_forward == uuid or not options.skip_once or not t.skipped) and t.start_time <= pos and t.end_time > pos then if (options.fast_forward == uuid or not options.skip_once or
not t.skipped) and t.start_time <= pos and t.end_time > pos then
if options.fast_forward == uuid then return end if options.fast_forward == uuid then return end
if options.fast_forward == false then if options.fast_forward == false then
mp.osd_message("[sponsorblock] sponsor skipped") mp.osd_message("[sponsorblock] sponsor skipped")
@ -237,20 +252,18 @@ function skip_ads(name, pos)
last_skip = {uuid = uuid, dir = nil} last_skip = {uuid = uuid, dir = nil}
if options.report_views or options.auto_upvote then if options.report_views or options.auto_upvote then
local args = { local args = {
options.python_path, options.python_path, sponsorblock, "stats", database_file,
sponsorblock, options.server_address, youtube_id, uuid,
"stats", options.report_views and "1" or "", uid_path,
database_file, options.user_id, options.auto_upvote and "1" or ""
options.server_address,
youtube_id,
uuid,
options.report_views and "1" or "",
uid_path,
options.user_id,
options.auto_upvote and "1" or ""
} }
if not legacy then if not legacy then
mp.command_native_async({name = "subprocess", playback_only = false, args = args}, function () end) mp.command_native_async(
{
name = "subprocess",
playback_only = false,
args = args
}, function() end)
else else
utils.subprocess_detached({args = args}) utils.subprocess_detached({args = args})
end end
@ -260,22 +273,29 @@ function skip_ads(name, pos)
speed_timer = mp.add_periodic_timer(1, fast_forward) speed_timer = mp.add_periodic_timer(1, fast_forward)
end end
return return
elseif (not options.skip_once or not t.skipped) and t.start_time <= pos + 1 and t.end_time > pos + 1 then elseif (not options.skip_once or not t.skipped) and t.start_time <= pos +
1 and t.end_time > pos + 1 then
sponsor_ahead = true sponsor_ahead = true
end end
end end
if options.audio_fade then if options.audio_fade then
if sponsor_ahead then if sponsor_ahead then
if fade_dir ~= false then if fade_dir ~= false then
if fade_dir == nil then volume_before = mp.get_property_number("volume") end if fade_dir == nil then
volume_before = mp.get_property_number("volume")
end
if fade_timer ~= nil then fade_timer:kill() end if fade_timer ~= nil then fade_timer:kill() end
fade_dir = false fade_dir = false
fade_timer = mp.add_periodic_timer(.1, function() fade_audio(-options.audio_fade_step) end) fade_timer = mp.add_periodic_timer(.1, function()
fade_audio(-options.audio_fade_step)
end)
end end
elseif fade_dir == false then elseif fade_dir == false then
fade_dir = true fade_dir = true
if fade_timer ~= nil then fade_timer:kill() end if fade_timer ~= nil then fade_timer:kill() end
fade_timer = mp.add_periodic_timer(.1, function() fade_audio(options.audio_fade_step) end) fade_timer = mp.add_periodic_timer(.1, function()
fade_audio(options.audio_fade_step)
end)
end end
end end
if options.fast_forward and options.fast_forward ~= true then if options.fast_forward and options.fast_forward ~= true then
@ -286,25 +306,27 @@ function skip_ads(name, pos)
end end
function vote(dir) function vote(dir)
if last_skip.uuid == "" then return mp.osd_message("[sponsorblock] no sponsors skipped, can't submit vote") end if last_skip.uuid == "" then
return mp.osd_message(
"[sponsorblock] no sponsors skipped, can't submit vote")
end
local updown = dir == "1" and "up" or "down" local updown = dir == "1" and "up" or "down"
if last_skip.dir == dir then return mp.osd_message("[sponsorblock] " .. updown .. "vote already submitted") end if last_skip.dir == dir then
return mp.osd_message("[sponsorblock] " .. updown ..
"vote already submitted")
end
last_skip.dir = dir last_skip.dir = dir
local args = { local args = {
options.python_path, options.python_path, sponsorblock, "stats", database_file,
sponsorblock, options.server_address, youtube_id, last_skip.uuid, "", uid_path,
"stats", options.user_id, dir
database_file,
options.server_address,
youtube_id,
last_skip.uuid,
"",
uid_path,
options.user_id,
dir
} }
if not legacy then if not legacy then
mp.command_native_async({name = "subprocess", playback_only = false, args = args}, function () end) mp.command_native_async({
name = "subprocess",
playback_only = false,
args = args
}, function() end)
else else
utils.subprocess({args = args}) utils.subprocess({args = args})
end end
@ -312,13 +334,14 @@ function vote(dir)
end end
function update() function update()
mp.command_native_async({name = "subprocess", playback_only = false, args = { mp.command_native_async({
options.python_path, name = "subprocess",
sponsorblock, playback_only = false,
"update", args = {
database_file, options.python_path, sponsorblock, "update", database_file,
options.server_address options.server_address
}}, getranges) }
}, getranges)
end end
function file_loaded() function file_loaded()
@ -327,15 +350,18 @@ function file_loaded()
segment = {a = 0, b = 0, progress = 0, first = true} segment = {a = 0, b = 0, progress = 0, first = true}
last_skip = {uuid = "", dir = nil} last_skip = {uuid = "", dir = nil}
local video_path = mp.get_property("path") local video_path = mp.get_property("path")
local youtube_id1 = string.match(video_path, "https?://youtu%.be/([%a%d%-_]+).*") local youtube_id1 = string.match(video_path,
local youtube_id2 = string.match(video_path, "https?://w?w?w?%.?youtube%.com/v/([%a%d%-_]+).*") "https?://youtu%.be/([%a%d%-_]+).*")
local youtube_id2 = string.match(video_path,
"https?://w?w?w?%.?youtube%.com/v/([%a%d%-_]+).*")
local youtube_id3 = string.match(video_path, "/watch%?v=([%a%d%-_]+).*") local youtube_id3 = string.match(video_path, "/watch%?v=([%a%d%-_]+).*")
local youtube_id4 = string.match(video_path, "/embed/([%a%d%-_]+).*") local youtube_id4 = string.match(video_path, "/embed/([%a%d%-_]+).*")
local local_pattern = nil local local_pattern = nil
if options.local_pattern ~= "" then if options.local_pattern ~= "" then
local_pattern = string.match(video_path, options.local_pattern) local_pattern = string.match(video_path, options.local_pattern)
end end
youtube_id = youtube_id1 or youtube_id2 or youtube_id3 or youtube_id4 or local_pattern youtube_id = youtube_id1 or youtube_id2 or youtube_id3 or youtube_id4 or
local_pattern
if not youtube_id then return end if not youtube_id then return end
init = true init = true
if not options.local_database then if not options.local_database then
@ -344,7 +370,9 @@ function file_loaded()
local exists = file_exists(database_file) local exists = file_exists(database_file)
if exists and options.server_fallback then if exists and options.server_fallback then
getranges(true, true) getranges(true, true)
mp.add_timeout(0, function() getranges(true, true, "", true) end) mp.add_timeout(0, function()
getranges(true, true, "", true)
end)
elseif exists then elseif exists then
getranges(true, true) getranges(true, true)
elseif options.server_fallback then elseif options.server_fallback then
@ -352,30 +380,25 @@ function file_loaded()
end end
end end
if initialized then return end if initialized then return end
if options.skip then if options.skip then mp.observe_property("time-pos", "native", skip_ads) end
mp.observe_property("time-pos", "native", skip_ads)
end
if options.display_name ~= "" then if options.display_name ~= "" then
local args = { local args = {
options.python_path, options.python_path, sponsorblock, "username", database_file,
sponsorblock, options.server_address, youtube_id, "", "", uid_path,
"username", options.user_id, options.display_name
database_file,
options.server_address,
youtube_id,
"",
"",
uid_path,
options.user_id,
options.display_name
} }
if not legacy then if not legacy then
mp.command_native_async({name = "subprocess", playback_only = false, args = args}, function () end) mp.command_native_async({
name = "subprocess",
playback_only = false,
args = args
}, function() end)
else else
utils.subprocess_detached({args = args}) utils.subprocess_detached({args = args})
end end
end end
if not options.local_database or (not options.auto_update and file_exists(database_file)) then return end if not options.local_database or
(not options.auto_update and file_exists(database_file)) then return end
update() update()
end end
@ -383,17 +406,19 @@ function set_segment()
if not youtube_id then return end if not youtube_id then return end
local pos = mp.get_property_number("time-pos") local pos = mp.get_property_number("time-pos")
if pos == nil then return end if pos == nil then return end
if segment.progress > 1 then if segment.progress > 1 then segment.progress = segment.progress - 2 end
segment.progress = segment.progress - 2
end
if segment.progress == 1 then if segment.progress == 1 then
segment.progress = 0 segment.progress = 0
segment.b = pos segment.b = pos
mp.osd_message("[sponsorblock] segment boundary B set, press again for boundary A", 3) mp.osd_message(
"[sponsorblock] segment boundary B set, press again for boundary A",
3)
else else
segment.progress = 1 segment.progress = 1
segment.a = pos segment.a = pos
mp.osd_message("[sponsorblock] segment boundary A set, press again for boundary B", 3) mp.osd_message(
"[sponsorblock] segment boundary A set, press again for boundary B",
3)
end end
if options.make_chapters and not segment.first then if options.make_chapters and not segment.first then
local start_time = math.min(segment.a, segment.b) local start_time = math.min(segment.a, segment.b)
@ -414,25 +439,30 @@ function submit_segment()
if end_time - start_time == 0 or end_time == 0 then if end_time - start_time == 0 or end_time == 0 then
mp.osd_message("[sponsorblock] empty segment, not submitting") mp.osd_message("[sponsorblock] empty segment, not submitting")
elseif segment.progress <= 1 then elseif segment.progress <= 1 then
mp.osd_message(string.format("[sponsorblock] press Shift+G again to confirm: %.2d:%.2d:%.2d to %.2d:%.2d:%.2d", math.floor(start_time/(60*60)), math.floor(start_time/60%60), math.floor(start_time%60), math.floor(end_time/(60*60)), math.floor(end_time/60%60), math.floor(end_time%60)), 5) mp.osd_message(string.format(
"[sponsorblock] press Shift+G again to confirm: %.2d:%.2d:%.2d to %.2d:%.2d:%.2d",
math.floor(start_time / (60 * 60)),
math.floor(start_time / 60 % 60),
math.floor(start_time % 60),
math.floor(end_time / (60 * 60)),
math.floor(end_time / 60 % 60),
math.floor(end_time % 60)), 5)
segment.progress = segment.progress + 2 segment.progress = segment.progress + 2
else else
mp.osd_message("[sponsorblock] submitting segment...", 30) mp.osd_message("[sponsorblock] submitting segment...", 30)
local submit local submit
local args = { local args = {
options.python_path, options.python_path, sponsorblock, "submit", database_file,
sponsorblock, options.server_address, youtube_id, tostring(start_time),
"submit", tostring(end_time), uid_path, options.user_id
database_file,
options.server_address,
youtube_id,
tostring(start_time),
tostring(end_time),
uid_path,
options.user_id
} }
if not legacy then if not legacy then
submit = mp.command_native({name = "subprocess", capture_stdout = true, playback_only = false, args = args}) submit = mp.command_native({
name = "subprocess",
capture_stdout = true,
playback_only = false,
args = args
})
else else
submit = utils.subprocess({args = args}) submit = utils.subprocess({args = args})
end end
@ -445,14 +475,21 @@ function submit_segment()
create_chapter("Submitted segment end", end_time) create_chapter("Submitted segment end", end_time)
end end
elseif string.match(submit.stdout, "error") then elseif string.match(submit.stdout, "error") then
mp.osd_message("[sponsorblock] segment submission failed, server may be down. try again", 5) mp.osd_message(
"[sponsorblock] segment submission failed, server may be down. try again",
5)
elseif string.match(submit.stdout, "502") then elseif string.match(submit.stdout, "502") then
mp.osd_message("[sponsorblock] segment submission failed, server is down. try again", 5) mp.osd_message(
"[sponsorblock] segment submission failed, server is down. try again",
5)
elseif string.match(submit.stdout, "400") then elseif string.match(submit.stdout, "400") then
mp.osd_message("[sponsorblock] segment submission failed, impossible inputs", 5) mp.osd_message(
"[sponsorblock] segment submission failed, impossible inputs", 5)
segment = {a = 0, b = 0, progress = 0, first = true} segment = {a = 0, b = 0, progress = 0, first = true}
elseif string.match(submit.stdout, "429") then elseif string.match(submit.stdout, "429") then
mp.osd_message("[sponsorblock] segment submission failed, rate limited. try again", 5) mp.osd_message(
"[sponsorblock] segment submission failed, rate limited. try again",
5)
elseif string.match(submit.stdout, "409") then elseif string.match(submit.stdout, "409") then
mp.osd_message("[sponsorblock] segment already submitted", 3) mp.osd_message("[sponsorblock] segment already submitted", 3)
segment = {a = 0, b = 0, progress = 0, first = true} segment = {a = 0, b = 0, progress = 0, first = true}

File diff suppressed because it is too large Load diff

View file

@ -14,9 +14,11 @@ function M.blameVirtText()
local currFile = vim.fn.expand('%') local currFile = vim.fn.expand('%')
local line = api.nvim_win_get_cursor(0) local line = api.nvim_win_get_cursor(0)
local blame = vim.fn.system(string.format('git blame -c -L %d,%d %s', line[1], line[1], currFile)) local blame = vim.fn.system(string.format('git blame -c -L %d,%d %s',
line[1], line[1], currFile))
local hash = vim.split(blame, '%s')[1] local hash = vim.split(blame, '%s')[1]
local cmd = string.format("git show %s ", hash).."--format='%an | %ar | %s'" local cmd = string.format("git show %s ", hash) ..
"--format='%an | %ar | %s'"
if hash == '00000000' then if hash == '00000000' then
text = 'Not Committed Yet' text = 'Not Committed Yet'

View file

@ -1,15 +1,27 @@
local on_attach = function(client, bufnr) local on_attach = function(client, bufnr)
-- Keybindings for LSPs -- Keybindings for LSPs
-- Note these are in on_attach so that they don't override bindings in a non-LSP setting -- Note these are in on_attach so that they don't override bindings in a non-LSP setting
vim.fn.nvim_set_keymap("n", "gd", "<cmd>lua vim.lsp.buf.definition()<CR>", {noremap = true, silent = true}) vim.fn.nvim_set_keymap("n", "gd", "<cmd>lua vim.lsp.buf.definition()<CR>",
vim.fn.nvim_set_keymap("n", "gD", "<cmd>lua vim.lsp.buf.implementation()<CR>", {noremap = true, silent = true}) {noremap = true, silent = true})
vim.fn.nvim_set_keymap("n", "K", "<cmd>lua vim.lsp.buf.hover()<CR>", {noremap = true, silent = true}) vim.fn.nvim_set_keymap("n", "gD",
vim.fn.nvim_set_keymap("n", "gK", "<cmd>lua vim.lsp.buf.signature_help()<CR>", {noremap = true, silent = true}) "<cmd>lua vim.lsp.buf.implementation()<CR>",
vim.fn.nvim_set_keymap("n", "1gD", "<cmd>lua vim.lsp.buf.type_definition()<CR>", {noremap = true, silent = true}) {noremap = true, silent = true})
vim.fn.nvim_set_keymap("n", "gr", "<cmd>lua vim.lsp.buf.references()<CR>", {noremap = true, silent = true}) vim.fn.nvim_set_keymap("n", "K", "<cmd>lua vim.lsp.buf.hover()<CR>",
vim.fn.nvim_set_keymap("n", "g0", "<cmd>lua vim.lsp.buf.document_symbol()<CR>", {noremap = true, silent = true}) {noremap = true, silent = true})
vim.fn.nvim_set_keymap("n", "gW", "<cmd>lua vim.lsp.buf.workspace_symbol()<CR>", {noremap = true, silent = true}) vim.fn.nvim_set_keymap("n", "gK",
"<cmd>lua vim.lsp.buf.signature_help()<CR>",
{noremap = true, silent = true})
vim.fn.nvim_set_keymap("n", "1gD",
"<cmd>lua vim.lsp.buf.type_definition()<CR>",
{noremap = true, silent = true})
vim.fn.nvim_set_keymap("n", "gr", "<cmd>lua vim.lsp.buf.references()<CR>",
{noremap = true, silent = true})
vim.fn.nvim_set_keymap("n", "g0",
"<cmd>lua vim.lsp.buf.document_symbol()<CR>",
{noremap = true, silent = true})
vim.fn.nvim_set_keymap("n", "gW",
"<cmd>lua vim.lsp.buf.workspace_symbol()<CR>",
{noremap = true, silent = true})
end end
require'nvim_lsp'.pyls.setup {on_attach = on_attach} require'nvim_lsp'.pyls.setup {on_attach = on_attach}
@ -26,6 +38,6 @@ require('nlua.lsp.nvim').setup(require('nvim_lsp'), {
-- Include globals you want to tell the LSP are real :) -- Include globals you want to tell the LSP are real :)
globals = { globals = {
-- Colorbuddy -- Colorbuddy
"Color", "c", "Group", "g", "s", "Color", "c", "Group", "g", "s"
} }
}) })

View file

@ -2,12 +2,11 @@ local M = {}
function M.getCompletionItems(prefix) function M.getCompletionItems(prefix)
-- define your total completion items -- define your total completion items
local items = vim.api.nvim_call_function('pandoc#completion#Complete',{0, prefix}) local items = vim.api.nvim_call_function('pandoc#completion#Complete',
{0, prefix})
return items return items
end end
M.complete_item = { M.complete_item = {item = M.getCompletionItems}
item = M.getCompletionItems
}
return M return M

View file

@ -13,20 +13,22 @@ variable to the intended filetype.
local api = vim.api local api = vim.api
local M = {} local M = {}
local function isempty(s) local function isempty(s) return s == nil or s == '' end
return s == nil or s == ''
end
function M.create(split, ft) function M.create(split, ft)
-- should we create a new split or switch out the current buffer? -- should we create a new split or switch out the current buffer?
if isempty(split) then split = false else split = true end if isempty(split) then
split = false
else
split = true
end
-- which filetype to set for the scratchpad, defaults to pandoc -- which filetype to set for the scratchpad, defaults to pandoc
if isempty(ft) then ft = vim.b["scratchpad_ft"] or vim.g["scratchpad_ft"] or "pandoc" end if isempty(ft) then
ft = vim.b["scratchpad_ft"] or vim.g["scratchpad_ft"] or "pandoc"
end
local buf = api.nvim_create_buf(false, true) local buf = api.nvim_create_buf(false, true)
if buf == 0 then if buf == 0 then print("Error opening scratch buffer.") end
print("Error opening scratch buffer.")
end
api.nvim_buf_set_option(buf, "bufhidden", "hide") api.nvim_buf_set_option(buf, "bufhidden", "hide")
api.nvim_buf_set_option(buf, "buftype", "nofile") api.nvim_buf_set_option(buf, "buftype", "nofile")
api.nvim_buf_set_option(buf, "swapfile", false) api.nvim_buf_set_option(buf, "swapfile", false)

View file

@ -7,10 +7,8 @@ local function on_change(err, fname, status)
watch_file(fname) watch_file(fname)
end end
function watch_file(fname) function watch_file(fname)
local fullpath = vim.api.nvim_call_function( local fullpath = vim.api.nvim_call_function('fnamemodify', {fname, ':p'})
'fnamemodify', {fname, ':p'}) w:start(fullpath, {}, vim.schedule_wrap(function(...) on_change(...) end))
w:start(fullpath, {}, vim.schedule_wrap(function(...)
on_change(...) end))
end end
vim.api.nvim_command( vim.api.nvim_command(
"command! -nargs=1 Watch call luaeval('watch_file(_A)', expand('<args>'))") "command! -nargs=1 Watch call luaeval('watch_file(_A)', expand('<args>'))")