summaryrefslogtreecommitdiff
path: root/examples/tools/wc.lua
blob: f2bbcb4294c5852d70f324018a57132c81f30778 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
-- Single-tool form: a Lua file under `tools/` returns one registration
-- table, and panto registers it as if `panto.ext.register_tool` had been
-- called on the value. Drop this file into one of:
--   ${XDG_CONFIG_HOME:-$HOME/.config}/panto/tools/wc.lua  (user-global)
--   ./.panto/tools/wc.lua                                  (project-local)
--
-- Or use the directory form `<somewhere>/tools/wc/init.lua` if you want
-- to `require` sibling modules from the same directory.

return {
    name = "wc",
    description = "Count bytes, characters, words, and lines in a string. " ..
        "Like `wc`, but operates on text passed in directly rather than on files.",
    schema = {
        type = "object",
        properties = {
            text = {
                type = "string",
                description = "The text to measure.",
            },
        },
        required = { "text" },
    },
    handler = function(input)
        local text = input.text
        local bytes = #text
        -- UTF-8 character count: utf8.len returns nil on invalid sequences;
        -- fall back to byte count in that case so we always return something.
        local chars = utf8.len(text) or bytes
        local _, words = text:gsub("%S+", "")
        local _, newlines = text:gsub("\n", "")
        -- Match `wc -l` semantics: count newlines, not lines. A trailing
        -- non-newline-terminated line is *not* counted, matching wc(1).
        return string.format(
            "bytes=%d chars=%d words=%d lines=%d",
            bytes, chars, words, newlines
        )
    end,
}