python -c 'import sys; v=eval(sys.stdin.read().strip()); v.sort(); print(v)'
It's hard to generalize these kinds of things, like if you have a list split across lines with different indentations, single/double quotes, trailing/non-trailing commas on the last value, etc. Probably best to just do the easiest thing to get them sorted and then use a keyboard macro or multiple-cursors to massage the output to your desired format. (defun sort-symbols (reverse beg end)
"Sort symbols in region alphabetically, in REVERSE if negative.
See `sort-words'."
(interactive "*P\nr")
(sort-regexp-fields reverse "\\(\\sw\\|\\s_\\)+" "\\&" beg end))
[1]: https://www.emacswiki.org/emacs/SortWordsFascinating to think how that doesn't mean it's bad advice. That is, unless your threat model includes targeted attacks by three-letter-scale adversaries — and then you maybe just don't open untrusted files in Emacs or use advice from strangers on HN.
Using Python's eval with empty globals and locals dicts (consult the docs) could make this safer, though I've only ever had to use that for defending against accidents rather than malice. And now this quick thing is becoming increasingly complicated, and maybe you'd be better off engineering it properly.
python-shell-send-statement, it's built into Emacs's python mode.
(defun my-sort-list ()
(interactive)
(when (not (looking-at (rx "[")))
(search-backward "[" nil t))
(when-let* ((line (thing-at-point 'sexp t))
(items (split-string (substring line 1 -1) (rx ",") t (rx blank)))
(sorted (string-join (sort items #'string-lessp) ", ")))
(kill-sexp)
(insert "[" sorted "]")))
I don't think I am using any non-builtin function here, though I think a few exceptions like s.el, f.el and dash.el can make things much easier. (let ((list (treesit-thing-at-point "list" 'nested))
(query "(list (string (string_content) @item))"))
(cl-loop for (_ . item) in (treesit-query-capture list query)
collect (treesit-node-text item t))) C-u M-| jq -c sortIt feels great when you can use narrow-to-region² to perfect a complex address or write a custom function with all your editor's power at your fingertips. With the sad, but obvious, drawback that the changes aren't linked in your disjoint shell and editor history.
¹ https://manpages.debian.org/jessie/moreutils/vipe.1.en.html
² Nowadays, that is more likely https://github.com/chrisbra/NrrwRgn for me.
I usually insert newlines between the elements, use a line-based sort, then recombine the lines. That works but is more tedious than I’d like. I’ve never taken the time to wrap that logic it in a function because it’s infrequent and it seems like it’s always slightly different.