TheFile.Ninja

Automatisering med Lua

Små skript som får TheFile.Ninja att arbeta på ditt sätt. Vart och ett är kort nog att läsa innan du kör det: ta det som det är, eller som början på ett eget.

Så använder du ett

  1. Ladda ned dess .lua-fil.
  2. Välj Automatisering › Öppna skriptmappen i TheFile.Ninja, och lägg filen i mappen som dess kort anger.
  3. Ett skript i Scripts\ finns under Automatisering › Åtgärder och i kommandopaletten (Ctrl+Shift+P); de andra startar av sig själva.

TheFile.Ninja frågar innan ett skript ändrar filer, startar ett program, kör ett kommando, når nätverket eller skickar något till en AI. Du svarar: en gång, för sessionen eller alltid för det skriptet.

ProLua-skript ingår i Pro, och i varje dators första månad. Priser

Skripten och deras meddelanden är på engelska.

Varje dag

Kopiera kontrollsumman från nedladdningssidan, ställ markören på filen och kör det: MD5, SHA-1, SHA-256 eller SHA-512, som skiljs åt på längden. Utan något att jämföra med kopierar det filens SHA-256.

  • Läggs i: Scripts\ — kör det från Automatisering › Åtgärder
  • Behöver ingen behörighet
Koden · 53 rader
--@action Check a download's checksum
--@version 1.0.0
--@author TheFile.Ninja
--@id check-checksum
--@description Compares the file under the cursor with the checksum on the clipboard: MD5, SHA-1, SHA-256 or SHA-512.
--@tags files, security
--@requires none

-- Copy the checksum from the download page, put the cursor on the file and
-- run this. The checksum's length says which algorithm it is. With no
-- checksum on the clipboard, the file's SHA-256 is shown and copied.

local ALGORITHMS = {
  [32] = { "md5", "MD5" },
  [40] = { "sha1", "SHA-1" },
  [64] = { "sha256", "SHA-256" },
  [128] = { "sha512", "SHA-512" },
}

local f = pane.active():focused()
if not f or not f.is_file then
  ui.message("Put the cursor on the file to check.", "Checksum")
  return
end

-- The clipboard may hold more than the checksum ("SHA256: 9f86…  setup.exe"):
-- the first run of hex digits with a checksum's length is the one.
local expected, algorithm
for hex in (clipboard.get_text() or ""):gmatch("%x+") do
  if ALGORITHMS[#hex] then
    expected, algorithm = hex:lower(), ALGORITHMS[#hex]
    break
  end
end

local prog = ui.progress("Checksum of " .. f.name)
prog:update(-1)
local ok, actual = pcall(hash.file, f, algorithm and algorithm[1] or "sha256")
prog:finish()
if not ok then
  ui.message(tostring(actual), "Checksum", "error")
  return
end

if not expected then
  clipboard.set_text(actual)
  ui.message(f.name .. "\n\nSHA-256  " .. actual .. "\n\nNo checksum on the clipboard to compare with: this one is copied.", "Checksum")
elseif actual == expected then
  ui.message(f.name .. "\n\nThe " .. algorithm[2] .. " matches:\n" .. actual, "Checksum matches")
else
  ui.message(f.name .. "\n\nThe " .. algorithm[2] .. " does NOT match.\n\nExpected  " .. expected .. "\nThe file  " .. actual,
             "Checksum differs", "error")
end

De markerade objektens sökvägar i den form du behöver: en per rad, inom citattecken, för PowerShell, för WSL, som Markdown-länkar, eller bara namnen.

  • Läggs i: Scripts\ — kör det från Automatisering › Åtgärder
  • Behöver ingen behörighet
Koden · 37 rader
--@action Copy paths as…
--@version 1.0.0
--@author TheFile.Ninja
--@id copy-paths
--@description Copies the paths of the marked items (or the one under the cursor) in the form you need: quoted, for PowerShell, for WSL, as Markdown links.
--@tags clipboard, terminal
--@requires none

local items = pane.active():effective_selection()
if #items == 0 then
  ui.message("Mark something first, or put the cursor on it.", "Copy paths")
  return
end

-- Each form: its name, how one item is written, what goes between them.
-- shell.quote and shell.to_wsl only write text: nothing is started.
local FORMS = {
  { "One per line", function(f) return f.full_path end, "\n" },
  { "Quoted, on one line", function(f) return '"' .. f.full_path .. '"' end, " " },
  { "For PowerShell", function(f) return shell.quote(f.full_path, "pwsh") end, ", " },
  { "For WSL", function(f) return shell.quote(shell.to_wsl(f.full_path), "wsl") end, " " },
  { "Markdown links", function(f)
      return "[" .. f.name .. "](<file:///" .. f.full_path:gsub("\\", "/") .. ">)"
    end, "\n" },
  { "Names only", function(f) return f.name end, "\n" },
}

local names = {}
for i, form in ipairs(FORMS) do names[i] = form[1] end

local choice = ui.choose(#items == 1 and items[1].name or (#items .. " items"), names, "Copy paths as")
if not choice then return end

local form, out = FORMS[choice], {}
for i, f in ipairs(items) do out[i] = form[2](f) end
clipboard.set_text(table.concat(out, form[3]))
ui.status("Copied " .. #items .. " path(s): " .. form[1])

Ett kommando med en egen tangent: Ctrl+Alt+T visar bara det som ändrats i dag i den aktiva panelen, och en gång till visar allt. Med platt vy ser du ett helt projekts dag på en gång.

  • Läggs i: Scripts\Autostart\ — körs när appen startar, och igen när det sparas
  • Behöver ingen behörighet
Koden · 37 rader
--@action What changed today
--@version 1.0.0
--@author TheFile.Ninja
--@id changed-today
--@description Ctrl+Alt+T: the active pane shows only what changed today; again, everything. Put it in Scripts\Autostart\ to have the key from the start.
--@tags filters, keys
--@requires none

-- A command of your own with a key of its own. It is in the command palette
-- (Ctrl+Shift+P) and in Automation › Commands while the app runs. Combine it
-- with a flat view (every file below the folder in one list) to see what
-- changed anywhere in a project.

local KEY = "Ctrl+Alt+T"

cmd.register{
  id          = "script.changed_today",
  name        = "Show only what changed today",
  description = "The active pane shows what changed today; again: everything",
  category    = "Scripts",
  action      = function()
    local p = pane.active()
    for _, filter in ipairs(p:get_column_filters()) do
      if filter.column == "modified" then
        p:clear_column_filter("modified")
        ui.status("Showing everything again")
        return
      end
    end
    p:set_column_filter("modified", "today")
    ui.status("Only what changed today (" .. KEY .. " again: everything)")
  end,
}

if not cmd.set_shortcut("script.changed_today", KEY) then
  print(KEY .. " is taken: change KEY at the top of this script.")
end

Städa

Bevakar en mapp (Hämtade filer, till exempel) och flyttar varje ny fil till Pictures, Documents, Archives, Installers, Video eller Music. Det väntar tills en nedladdning är klar, och en fil du lägger tillbaka med Ctrl+Z blir kvar där den är.

  • Läggs i: Scripts\Autostart\ — körs när appen startar, och igen när det sparas
  • Frågar innan det: ändrar filer
Koden · 62 rader
--@action Tidy a folder as files arrive
--@version 1.0.0
--@author TheFile.Ninja
--@id tidy-as-they-arrive
--@description Watches a folder (your Downloads, say) and moves each new file into a subfolder for its kind: Pictures, Documents, Archives… Put it in Scripts\Autostart\.
--@tags cleanup, downloads, watcher
--@requires file_write

-- The first time it runs it asks which folder to watch (the active pane's is
-- offered) and remembers it. The moves go through the app's file operations:
-- the strip under the panes shows them, a clash is asked there, and Ctrl+Z
-- puts a file back (it is then left where it is).

-- Which subfolder each kind of file goes to. Change them as you like; a file
-- that matches none stays where it is.
local KINDS = {
  Pictures   = { "jpg", "jpeg", "png", "gif", "webp", "heic", "svg", "bmp" },
  Documents  = { "pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "odt", "ods", "txt", "md", "csv" },
  Archives   = { "zip", "7z", "rar", "gz", "tar" },
  Installers = { "exe", "msi", "msix" },
  Video      = { "mp4", "mkv", "mov", "webm", "avi" },
  Music      = { "mp3", "flac", "m4a", "wav", "ogg" },
}

-- Files a browser is still downloading: left alone until they get their name.
local UNFINISHED = { crdownload = true, part = true, partial = true, download = true, tmp = true }

local folder = script.data_get("folder")
if not folder or not fs.is_dir(folder) then
  folder = ui.input("Which folder should be tidied as files arrive?", "Tidy a folder", pane.active():path())
  if not folder or folder == "" or not fs.is_dir(folder) then return end
  script.data_set("folder", folder)
end

local kind_of = {}
for sub, exts in pairs(KINDS) do
  for _, ext in ipairs(exts) do kind_of[ext] = sub end
end

local moved = {}   -- what was moved once is left alone when it comes back (Ctrl+Z)

local function tidy(file)
  local sub = kind_of[path.ext(file):lower()]
  if not sub or UNFINISHED[path.ext(file):lower()] or moved[file:lower()] or not fs.is_file(file) then return end
  local dest = path.join(folder, sub)
  if not fs.is_dir(dest) then
    local ok, err = fs.create_dir(dest)
    if not ok then
      ui.log_error("Tidy: could not make " .. dest .. ": " .. tostring(err))
      return
    end
  end
  moved[file:lower()] = true
  file_ops.move(file, dest)
  ui.status(path.basename(file) .. " → " .. sub)
end

local w = watcher.create(folder, { recursive = false, debounce_ms = 1500 })
w:on("created", function(e) tidy(e.path) end)
w:on("renamed", function(e) tidy(e.path) end)   -- a browser's download that is done

print("Tidying " .. folder .. " as files arrive")

Filer med samma innehåll i en mapp och under den, i ett fönster som säger hur mycket plats de tar. En knapp markerar de extra kopiorna i en platt vy; att radera dem bestämmer du, och Ctrl+Z tar tillbaka dem.

  • Läggs i: Scripts\ — kör det från Automatisering › Åtgärder
  • Behöver ingen behörighet
Koden · 76 rader
--@action Find duplicate files
--@version 1.0.0
--@author TheFile.Ninja
--@id find-duplicates
--@description Finds files with the same content in the active pane's folder and below, lists them in a window, and marks the extra copies for you to delete.
--@tags cleanup, report, views
--@requires none

-- Nothing is deleted here: the button marks the extra copies in a flat view
-- of the folder, and Delete sends them to the Recycle Bin (Ctrl+Z brings them
-- back). Of each set of copies, the one with the shortest path is kept:
-- "photo.jpg" rather than "photo (1).jpg" or "Copy of photo.jpg".

local p = pane.active()
if p:is_virtual() then
  ui.message("This works on a folder on a disk or a share.", "Find duplicates")
  return
end
local root = p:path()

-- Sizes first, then the first 64 KB of big files, then whole checksums.
local prog = ui.progress("Looking for duplicates")
prog:update(-1, root)
local ok, sets = pcall(hash.find_duplicates, root, { recursive = true })
prog:finish()
if not ok then
  ui.message(tostring(sets), "Find duplicates", "error")
  return
end
if #sets == 0 then
  ui.message("No two files in " .. root .. " are the same.", "Find duplicates")
  return
end

local rows, extra, wasted = {}, {}, 0
for _, set in ipairs(sets) do
  table.sort(set.files, function(a, b)
    if #a ~= #b then return #a < #b end
    return a < b
  end)
  for i, file in ipairs(set.files) do
    local folder = path.dirname(file):sub(#root + 2)
    rows[#rows + 1] = { path.basename(file), folder ~= "" and folder or ".", set.size, i == 1 and "kept" or "extra copy", path = file }
    if i > 1 then extra[#extra + 1] = file end
  end
  wasted = wasted + set.size * (set.count - 1)
end

ui.window{
  id = "duplicates",
  title = "Duplicates in " .. path.basename(root),
  width = 860, height = 640,
  view = {
    { heading = #sets .. " files have copies" },
    { text = #extra .. " extra copies take " .. item.format_size(wasted) .. ". Double-click a row to show it in the pane.", muted = true, id = "note" },
    { table = {
        columns = { "Name", "Folder", { "Size", type = "size", width = 90 }, { "Status", width = 90 } },
        rows = rows,
      }, id = "rows" },
    { row = {
      { button = "Mark the extra copies", id = "mark", style = "primary" },
      { spacer = true },
      { button = "Close", action = { close = true } },
    } },
  },
  on_action = function(name, values, v)
    if name ~= "mark" then return end
    -- A flat view lists every file below the folder, so all the copies can be marked.
    if p:path() ~= root and not p:navigate_and_wait(root, 10000) then return end
    if not p.is_flattened then p:flatten_and_wait(60000) end
    p:unmark_all()
    p:mark(extra)
    p:focus()
    v:update("note", { text = "Marked the " .. #extra .. " extra copies: Delete sends them to the Recycle Bin, Ctrl+Z brings them back.", color = "ok" })
  end,
}

Mappar som inte rymmer något, eller bara andra tomma mappar, visas först och skickas sedan till papperskorgen i en enda operation: ett Ctrl+Z tar tillbaka alla.

  • Läggs i: Scripts\ — kör det från Automatisering › Åtgärder
  • Frågar innan det: ändrar filer
Koden · 65 rader
--@action Remove empty folders
--@version 1.0.0
--@author TheFile.Ninja
--@id remove-empty-folders
--@description Finds the folders below the active pane's that hold nothing, or only other empty folders, shows them, and sends them to the Recycle Bin.
--@tags cleanup
--@requires file_write

-- A folder with a single hidden file in it (desktop.ini, Thumbs.db) is not
-- empty: it is kept. One delete for all of them, so one Ctrl+Z brings them
-- all back.

local p = pane.active()
if p:is_virtual() then
  ui.message("This works on a folder on a disk or a share.", "Remove empty folders")
  return
end
local root = p:path()

-- Paths compared without case and without a trailing backslash.
local function key(s) return (s:gsub("[\\/]+$", "")):lower() end
local top = key(root)

local entries = fs.list(root, { recursive = true })
if #entries >= 100000 then
  -- fs.list stops at 100 000: a folder it did not get to could look empty.
  ui.message("There is too much below " .. root .. " to be sure. Run it in a smaller folder.", "Remove empty folders", "warning")
  return
end

-- Every folder above a file holds something.
local holds = {}
for _, e in ipairs(entries) do
  if not e.is_directory then
    local dir = path.parent(e.full_path)
    while dir ~= "" and key(dir) ~= top and not holds[key(dir)] do
      holds[key(dir)] = true
      dir = path.parent(dir)
    end
  end
end

-- The empty folders whose parent is not empty itself: deleting those takes the rest.
local empty = {}
for _, e in ipairs(entries) do
  if e.is_directory and not holds[key(e.full_path)] then
    local parent = key(path.parent(e.full_path))
    if parent == top or holds[parent] then empty[#empty + 1] = e.full_path end
  end
end

if #empty == 0 then
  ui.message("No empty folders below " .. root .. ".", "Remove empty folders")
  return
end
table.sort(empty)

local lines = {}
for i = 1, math.min(#empty, 25) do lines[i] = "  " .. empty[i]:sub(#root + 2) end
if #empty > 25 then lines[#lines + 1] = "  … and " .. (#empty - 25) .. " more" end

if ui.confirm(#empty .. " empty folder(s) to the Recycle Bin?\n\n" .. table.concat(lines, "\n"), "Remove empty folders") then
  file_ops.delete(empty)
  ui.status(#empty .. " empty folder(s) to the Recycle Bin; Ctrl+Z brings them back")
end

Kraftverktyg

Varje Git-projekt i en mapp som har något att committa eller pusha, i en egen mapp, lua://changes/: grenen och det som väntar i kolumnen Typ, och Enter går in i projektet.

  • Läggs i: Scripts\ — kör det från Automatisering › Åtgärder
  • Frågar innan det: startar ett program
Koden · 62 rader
--@action Projects with changes
--@version 1.0.0
--@author TheFile.Ninja
--@id git-changes
--@description Looks through the Git projects in the active pane's folder and lists those with uncommitted changes or unpushed commits in a folder of their own: lua://changes/.
--@tags git, script folders
--@requires shell

-- Run it in the folder that holds your projects (C:\src, say). Each project
-- with something to commit or push becomes a row in lua://changes/, which
-- opens in a new tab: the row is the project's folder (Enter goes in), its
-- Type column says the branch and what is waiting. Run it again to update.

if not shell.which("git") then
  ui.message("Git is not on the PATH.", "Projects with changes", "error")
  return
end

local p = pane.active()
local root = p:path()
local projects = {}
for _, e in ipairs(fs.list(root)) do
  if e.is_directory and fs.exists(path.join(e.full_path, ".git")) then projects[#projects + 1] = e end
end
if #projects == 0 then
  ui.message("No Git projects directly in " .. root .. ".", "Projects with changes")
  return
end

board.clear("vfs:changes")
local prog = ui.progress("Git status")
local waiting = 0
for i, project in ipairs(projects) do
  if prog:is_cancelled() then break end
  prog:update(math.floor((i - 1) * 100 / #projects), project.name)
  -- One line for the branch ("## main...origin/main [ahead 2]"), one per changed file.
  local r = shell.capture("git status --porcelain=v1 --branch", { working_dir = project.full_path, timeout_ms = 20000 })
  if r.exit_code == 0 then
    local first = r.stdout:match("^[^\n]*")
    local branch = first:match("^## No commits yet on (%S+)") or first:match("^## (.-)%.%.%.") or first:match("^## (%S+)")
    local ahead = tonumber(first:match("ahead (%d+)")) or 0
    local behind = tonumber(first:match("behind (%d+)")) or 0
    local _, lines = r.stdout:gsub("\n", "")
    local changed = math.max(0, lines - 1)
    if changed > 0 or ahead > 0 then
      waiting = waiting + 1
      board.set("vfs:changes", project.name, {
        target = project.full_path,
        branch = branch, changed = changed, ahead = ahead, behind = behind,
      })
    end
  else
    ui.log_warning(project.name .. ": " .. (r.stderr ~= "" and r.stderr or "git status failed"))
  end
end
prog:finish(waiting .. " of " .. #projects .. " have changes")

if waiting > 0 then
  p:new_tab("lua://changes/")
else
  ui.status("All " .. #projects .. " projects are committed and pushed")
end

En MP4-kopia bredvid varje markerad video, gjord av ffmpeg i bakgrunden, en i taget, med en förloppsindikator under panelerna. Originalen rörs aldrig. Kräver ffmpeg.

  • Läggs i: Scripts\ — kör det från Automatisering › Åtgärder
  • Frågar innan det: kör ett kommando
Koden · 87 rader
--@action MP4 copies of marked videos
--@version 1.0.0
--@author TheFile.Ninja
--@id mp4-copies
--@description Makes an MP4 copy (H.264 and AAC) beside each marked video with ffmpeg, in the background, one after the other, with a progress bar. Needs ffmpeg.
--@tags video, terminal, background
--@requires terminal

-- ffmpeg is not part of TheFile.Ninja: winget install Gyan.FFmpeg, then
-- start the app again so that it finds it. The originals are never touched;
-- a copy that is there already is skipped. Cancel in the strip under the
-- panes stops the one being made (its unfinished file is left) and the rest.

local ARGS = { "-c:v", "libx264", "-crf", "23", "-preset", "medium", "-c:a", "aac", "-b:a", "160k", "-movflags", "+faststart" }

if not shell.which("ffmpeg") then
  ui.message("ffmpeg is not on the PATH.\n\nwinget install Gyan.FFmpeg, then start TheFile.Ninja again.", "MP4 copies", "error")
  return
end

local videos = {}
for _, f in ipairs(pane.active():effective_selection()) do
  if f.is_file then videos[#videos + 1] = f end
end
if #videos == 0 then
  ui.message("Mark the videos first, or put the cursor on one.", "MP4 copies")
  return
end

local function seconds(h, m, s) return tonumber(h) * 3600 + tonumber(m) * 60 + tonumber(s) end

local prog = ui.progress("MP4 copies")
local done, failed = 0, 0
local index, job = 0, nil

local function next_video()
  index = index + 1
  local f = videos[index]
  if not f or prog:is_cancelled() then
    prog:finish(failed == 0 and (done .. " made") or (done .. " made, " .. failed .. " failed"))
    return
  end
  local name = path.stem(f.name) .. (f.extension:lower() == "mp4" and " (copy).mp4" or ".mp4")
  local out = path.join(path.parent(f.full_path), name)
  if fs.exists(out) then
    ui.log_warning("Already there: " .. out)
    return next_video()
  end
  prog:update(math.floor((index - 1) * 100 / #videos), f.name)

  local argv = { "ffmpeg", "-hide_banner", "-nostdin", "-n", "-progress", "pipe:1", "-i", f.full_path }
  for _, a in ipairs(ARGS) do argv[#argv + 1] = a end
  argv[#argv + 1] = out

  local duration
  job = terminal.run{
    argv = argv,
    cwd = path.parent(f.full_path),
    title = "ffmpeg " .. f.name,
    cols = 300,
    timeout_ms = 3600000,
    on_line = function(line)
      if prog:is_cancelled() then job:cancel() return end
      local h, m, s = line:match("Duration: (%d+):(%d+):([%d%.]+)")
      if h then duration = seconds(h, m, s) end
      -- -progress writes how far it is, in microseconds, a line at a time.
      local us = tonumber(line:match("^out_time_[mu]s=(%d+)"))
      if us and duration and duration > 0 then
        local part = math.min(1, us / 1e6 / duration)
        prog:update(math.floor((index - 1 + part) * 100 / #videos), f.name)
      end
    end,
    on_done = function(r)
      if r.ok then
        done = done + 1
      elseif r.cancelled then
        ui.log_warning("Stopped: " .. out .. " is unfinished")
      else
        failed = failed + 1
        ui.log_error(f.name .. ": ffmpeg ended with " .. tostring(r.exit_code) .. "\n" .. table.concat(r.lines, "\n", math.max(1, #r.lines - 5)))
      end
      next_video()
    end,
  }
end

next_video()

IMG_2041.jpg blir red-boat-in-the-harbour.jpg: din AI-tjänst (Inställningar › AI) namnger varje markerad bild, du ser varje nytt namn innan något byter namn, och Ctrl+Z ångrar dem ett i taget. Namnens språk väljer du överst i skriptet.

  • Läggs i: Scripts\ — kör det från Automatisering › Åtgärder
  • Frågar innan det: frågar din AI, ändrar filer
Koden · 86 rader
--@action Name pictures by what they show
--@version 1.0.0
--@author TheFile.Ninja
--@id ai-picture-names
--@description Asks your AI provider (Preferences › AI) for a short name for each marked picture, shows every new name, and renames them when you agree.
--@tags ai, rename, pictures
--@requires ai, file_write

-- For screenshots and phone photos called IMG_2041.jpg. The pictures go to
-- the provider set in Preferences › AI, shrunk, eight at a time; nothing is
-- renamed before you have seen the list. Ctrl+Z undoes each rename.

local LANGUAGE = "English"   -- the language of the new names
local PICTURES = { jpg = true, jpeg = true, png = true, webp = true, gif = true, bmp = true, heic = true }

local SYSTEM = "You name picture files. For each picture, in the order given, write a short file name that says what "
  .. "it shows: 2 to 6 words in " .. LANGUAGE .. ", lower case, joined by hyphens, no extension, no dates. "
  .. 'Answer with JSON only: {"names": ["first-name", "second-name"]}.'

if not ai.available() then
  ui.message("No AI provider is set up: Preferences › AI.", "Name pictures")
  return
end
if not ai.supports_images() then
  ui.message("The model chosen in Preferences › AI takes no pictures. Choose one that does.", "Name pictures")
  return
end

local pictures = {}
for _, f in ipairs(pane.active():effective_selection()) do
  if f.is_file and PICTURES[f.extension:lower()] then pictures[#pictures + 1] = f end
end
if #pictures == 0 then
  ui.message("Mark the pictures first, or put the cursor on one.", "Name pictures")
  return
end

-- Words joined by hyphens, without punctuation, at most 60 characters.
-- (Lua's patterns know ASCII only: letters of other languages are kept as they are.)
local function clean(name)
  name = tostring(name or ""):lower():gsub("%.%a+$", "")      -- an extension the answer added
  name = name:gsub("[%s_%-]+", " "):gsub("%p", ""):gsub("^%s+", ""):gsub("%s+$", ""):gsub("%s+", "-")
  local cut = utf8.offset(name, 61)
  if cut then name = name:sub(1, cut - 1):gsub("%-$", "") end
  return name
end

local prog = ui.progress("Naming pictures")
local proposals, taken = {}, {}
for first = 1, #pictures, 8 do
  if prog:is_cancelled() then return end
  prog:update(math.floor((first - 1) * 100 / #pictures))
  local batch = { table.unpack(pictures, first, math.min(first + 7, #pictures)) }
  local ok, answer = pcall(ai.extract, "Name these " .. #batch .. " pictures.", { system = SYSTEM, images = batch, temperature = 0.2 })
  if not ok then
    prog:finish()
    ui.message(tostring(answer), "Name pictures", "error")
    return
  end
  for i, f in ipairs(batch) do
    local base = clean(answer and answer.names and answer.names[i])
    if base ~= "" then
      -- Never two the same, and never a name the folder has already.
      local name, n = base .. f.ext:lower(), 1
      while taken[path.join(path.parent(f.full_path), name):lower()] or (name:lower() ~= f.name:lower() and fs.exists(path.join(path.parent(f.full_path), name))) do
        n = n + 1
        name = base .. "-" .. n .. f.ext:lower()
      end
      taken[path.join(path.parent(f.full_path), name):lower()] = true
      if name ~= f.name then proposals[#proposals + 1] = { item = f, name = name } end
    end
  end
end
prog:finish()

if #proposals == 0 then
  ui.message("Nothing to rename.", "Name pictures")
  return
end

local lines = {}
for i, pr in ipairs(proposals) do lines[i] = string.format("%-28s  %s", pr.item.name, pr.name) end
if ui.confirm("Rename " .. #proposals .. " picture(s)?\n\n" .. table.concat(lines, "\n"), "Name pictures") then
  for _, pr in ipairs(proposals) do file_ops.rename(pr.item, pr.name) end
  ui.status(#proposals .. " picture(s) renamed; Ctrl+Z undoes each")
end

Mer i panelerna

Antalet rader i kod- och textfiler, i en egen kolumn: välj Lines under Skriptkolumner i en panels rubrikmeny.

  • Läggs i: Scripts\Extensions\ — läses in när appen startar
  • Behöver ingen behörighet
Koden · 35 rader
--@action Lines column
--@version 1.0.0
--@author TheFile.Ninja
--@id lines-column
--@description A Lines column for source code and text files. Put it in Scripts\Extensions\, then choose Lines in a pane's header menu under Script columns.
--@tags columns, code
--@requires none

-- Extension scripts run in a sandbox of their own: they read, never write or
-- ask. The app asks for the rows on screen, 64 at a time, and keeps each
-- value until the file changes.

columns.register{
  id         = "line_count",
  header     = "Lines",
  type       = "number",
  width      = 70,
  extensions = { "txt", "md", "log", "csv", "lua", "rs", "py", "js", "ts", "tsx", "cs", "c", "h", "cpp", "hpp", "go",
                 "java", "kt", "swift", "rb", "php", "sql", "html", "css", "scss", "xml", "json", "toml", "yaml", "yml",
                 "ini", "ps1", "sh", "bat", "cmd" },
  max_size   = 2 * 1024 * 1024,   -- bigger files stay blank
  timeout_ms = 3000,
  value      = function(items)
    local out = {}
    for i, it in ipairs(items) do
      local text = fs.read_text(it.full_path)
      if text then
        local _, n = text:gsub("\n", "")
        if #text > 0 and text:sub(-1) ~= "\n" then n = n + 1 end   -- a last line without its line break
        out[i] = n
      end
    end
    return out
  end,
}

Förhandsvisningen visar .csv- och .tsv-filer som en tabell: kommatecken, semikolon eller tabbar, fält inom citattecken, och tal som sorteras som tal.

  • Läggs i: Scripts\Preview\ — läses in när appen startar
  • Behöver ingen behörighet
Koden · 124 rader
--@action CSV files as a table
--@version 1.0.0
--@author TheFile.Ninja
--@id csv-table
--@description Shows .csv and .tsv files as a table in the preview pane, a column for each field, numbers sorted as numbers. Put it in Scripts\Preview\.
--@tags preview, data
--@requires none

-- Commas, semicolons, tabs or bars, whichever the first line has most of;
-- quoted fields may hold any of them, line breaks and "" too. The table
-- shows the first 1 000 rows that fit in the file's first 256 KB.

local MAX_ROWS = 1000
local SEPARATORS = { [","] = "commas", [";"] = "semicolons", ["\t"] = "tabs", ["|"] = "bars" }

local function separator(text, ext)
  if ext == "tsv" then return "\t" end
  local first, best, most = text:match("^[^\r\n]*"), ",", 0
  for sep in pairs(SEPARATORS) do
    local _, n = first:gsub(sep, "")
    if n > most then best, most = sep, n end
  end
  return best
end

-- Rows of fields; true as well when there was more than max.
local function parse(text, sep, max)
  local rows, row, buf = {}, {}, {}
  local special = "[" .. sep .. '"\r\n]'
  local i, n = 1, #text
  local function field() row[#row + 1] = table.concat(buf); buf = {} end
  while i <= n do
    local j = text:find(special, i)
    if not j then buf[#buf + 1] = text:sub(i); break end
    buf[#buf + 1] = text:sub(i, j - 1)
    local c = text:sub(j, j)
    if c == '"' then
      local k = j + 1
      while true do   -- a quoted part ends at a lone quote ("" is one quote)
        local q = text:find('"', k, true)
        if not q then buf[#buf + 1] = text:sub(k); i = n + 1; break end
        buf[#buf + 1] = text:sub(k, q - 1)
        if text:sub(q + 1, q + 1) == '"' then
          buf[#buf + 1] = '"'
          k = q + 2
        else
          i = q + 1
          break
        end
      end
    elseif c == sep then
      field()
      i = j + 1
    else
      field()
      rows[#rows + 1] = row
      row = {}
      if c == "\r" and text:sub(j + 1, j + 1) == "\n" then j = j + 1 end
      i = j + 1
      if #rows > max then return rows, true end
    end
  end
  if #buf > 0 or #row > 0 then
    field()
    rows[#rows + 1] = row
  end
  return rows, false
end

-- "1 234,5" and "1234.5" alike; nil when it is no number.
local function number(s, sep)
  s = s:gsub("^%s+", ""):gsub("%s+$", "")
  if s == "" then return nil end
  return tonumber(s) or (sep ~= "," and tonumber((s:gsub("\194\160", ""):gsub("%s", ""):gsub(",", "."))) or nil)
end

preview.register{
  id         = "csv_table",
  title      = "CSV table",
  extensions = { "csv", "tsv" },
  wants      = { "file_head" },
  on_error   = "fallback",
  generate   = function(ctx)
    local text = ctx.head_text
    if not text or text == "" then return nil end
    text = text:gsub("^\239\187\191", "")   -- a UTF-8 byte order mark
    local sep = separator(text, ctx.ext)
    local rows, more = parse(text, sep, MAX_ROWS + 1)
    if ctx.head_truncated and not more then table.remove(rows) end   -- the last row may be cut
    local header = table.remove(rows, 1) or {}
    while #rows > MAX_ROWS do
      table.remove(rows)
      more = true
    end

    local width = #header
    for _, r in ipairs(rows) do width = math.max(width, #r) end

    -- A column whose every value is a number sorts as numbers.
    local columns = {}
    for c = 1, width do
      local all_numbers, any = true, false
      for _, r in ipairs(rows) do
        local v = r[c]
        if v and v ~= "" then
          any = true
          if not number(v, sep) then all_numbers = false break end
        end
      end
      local title = header[c] ~= nil and header[c] ~= "" and header[c] or ("Column " .. c)
      if any and all_numbers then
        columns[c] = { title, type = "number" }
        for _, r in ipairs(rows) do if r[c] then r[c] = number(r[c], sep) end end
      else
        columns[c] = title
      end
    end

    return {
      { text = #rows .. (more and "+" or "") .. (#rows == 1 and " row · " or " rows · ") .. width .. " columns · separated by " .. SEPARATORS[sep], muted = true, small = true },
      { table = { columns = columns, rows = rows } },
    }
  end,
}

Skriv egna

Action Studio (Automatisering › Action Studio…, Ctrl+Shift+E) har komplettering, kontroller medan du skriver, hela referensen och en assistent som skriver och rättar skript med dig.

▶ Action Studio: egna skript · 3 min