/ lsf / column.py
swadhin biswas feat: major v4.5.0 release with GNU ls compatibility and comprehensive documentation · 10/15/2025
20c1470
83 lines · 2.1 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/env python3
import re
import sys
import os

def get_terminal_width():
    try:
        return os.get_terminal_size().columns
    except OSError:
        return 80

def display_len(s):
    return len(re.sub(r'\x1b\[[0-9;]*m', '', s))

def main():
    items = [line.strip('\n') for line in sys.stdin]
    if not items:
        return

    layout = os.environ.get("LSF_LAYOUT", "columns").lower()
    if layout not in {"rows", "columns"}:
        layout = "columns"

    try:
        tabsize = int(os.environ.get("LSF_TABSIZE", "8"))
    except ValueError:
        tabsize = 8
    if tabsize <= 0:
        tabsize = 8

    width = get_terminal_width()
    if not items:
        return
    max_len = max(display_len(item) for item in items) if items else 0

    if max_len == 0:
        col_width = tabsize
    else:
        col_width = ((max_len + tabsize - 1) // tabsize) * tabsize
        if col_width <= max_len:
            col_width = max_len + tabsize

    cols = max(1, width // col_width)
    rows = (len(items) + cols - 1) // cols

    for i in range(rows):
        for j in range(cols):
            if layout == "rows":
                index = i * cols + j
            else:
                index = i + j * rows

            if index >= len(items):
                continue

            item = items[index]
            d_len = display_len(item)
            padding = ''

            has_next = False
            if layout == "rows":
                if j != cols - 1 and (index + 1) < len(items):
                    has_next = True
            else:
                if j != cols - 1 and (index + rows) < len(items):
                    has_next = True

            if has_next:
                offset = d_len % col_width
                if offset == 0:
                    padding_width = tabsize
                else:
                    padding_width = col_width - offset
                if padding_width < 1:
                    padding_width = tabsize
                padding = ' ' * padding_width

            sys.stdout.write(item + padding)
        sys.stdout.write('\n')

if __name__ == '__main__':
    main()