Re: Text wrapping Python docstrings

Yannick Gingras <[email protected]>
Newsgroups gmane.comp.kde.devel.kwrite
Message-ID <[email protected]>
I got it to work exactly the way I want with the External Tools plugin.
This plugin makes is really easy to bind the script to a keyboard
shortcut. For reference, I'm attaching the quick and dirty script I use
to re-format the text.

On Tue, 2022-02-01 at 22:35 -0800, Yannick Gingras wrote:
> On Wed, 2022-02-02 at 11:11 +0500, Waqar Ahmed wrote:
> > I don't think there is an easy way atm, but maybe you can use the
> > "script" api to write a script that adjust the indent for you?
> 
> My javascript is not really good, but it would be really easy for me
> to
> do a Python command line and to pass the fragment to "filter through
> command". Is there a way I could bind that to a keyboard shortcut?
> Let's say rebind ALT-W to "filter throught re-fill.py" without
> opening
> the command prompt?
> 

-- 
Yannick Gingras
http://ygingras.net
refill.py (text/x-python3, 944 B)
#!/bin/env python3

""" Re-indent the text passed on sys.stdin as a paragrath at most MAX_WIDTH 
wide, perserving the initial indentation. """

import re
import sys

LOGFILE = "/tmp/refill.log"
MAX_WIDTH = 79
INDENT_PAT = r"^(\s*)"


def reindent(text):
    indent = re.match(INDENT_PAT, text).group()
    words = text.split()
    lines = []
    cur_line = [indent]
    cur_length = len(indent)

    for word in words:
        if cur_length + len(word) > MAX_WIDTH:
            lines.append("".join(cur_line))
            cur_line = [indent, word, " "]
            cur_length = sum(map(len, cur_line))
        else:
            cur_line += [word, " "]
            cur_length += len(word) + 1

    if cur_line:
        if cur_line[-1] == " ":
            cur_line.pop()
        lines.append("".join(cur_line))
    return "\n".join(lines)


def main():
    data = sys.stdin.read()
    print(reindent(data))

if __name__ == "__main__":
    main()
signature.asc (application/pgp-signature, 659 B)
-----BEGIN PGP SIGNATURE-----

iQGzBAABCgAdFiEEQBAbmQFumbsYmkRfiKQ8CLil3UMFAmH6ngMACgkQiKQ8CLil
3UOeGwv/QJ7R8nPMKsa6qiz0hpJQuqYnb5tZsjRwGP3m+inMcY3wGXyfoCD94+XU
G04b6SWqdtTphnBALaZD4axYbE4gN95u6ta9h2B3JJXpha58D5nKmPPV67QFsN9j
gxo82g9TyUUUvacIkYtAEVJ2PnTPOPU6eePDLIPYQALxnx7ODaqe3RP9Ut+TRwA5
AIe3wQC9Q9bRSxiG/1ecwUB/PlC/Nj0rt/HE46rGWZSffQk/qPN38OxCjJhcDZxm
uQ24kWZsuZFJyB4dXXmjKfqKVwYLZ+IA7Bse8iqbCGqvNWW0LuhJ7PRt4P6E7nX2
WIQcbEE+OSiPW+2TdeELN+72zYsxTBQs0oiVyrFyWxuiOpCaKjF+pzFawMG4X6iS
IdYo42bCA9mF0U9CMcx2z/HjgH5cAjKSQ83/6CLwqwOvpEDXIqNeafJaPHyD2fxs
M2L6mXS3S21Ds0nPLOSCSb+3Y6HV9k2l0dWbcRo+Rw+0cowp8NSNRZgjMUQaMhrX
9mNbX209
=pigs
-----END PGP SIGNATURE-----
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.