Many code editors allow automatic reformatting of the code while typing, without losing the cursor position. I often use that feature to quickly correct indentation, so that I don't need to do it by hand, or to verify that braces and parantheses are correctly placed and balanced. Unfortunately, it seems that the only option to reformat C code in geany is to select all the text (CTRL+A) and then to pass it to the external command (astyle or indent) via CTRL+1 (or via Edit->Format->Send selection to in menu), after the command is properly defined. It would be nice, if geany allowed repositioning the cursor to the original position (or at list to line with the same number if reformatting breaks or combines lines). Is it possible to write a macro or script that first stores the current line number, then selects all text, passes it to the external command, and finally attempts to put the cursor to the line with the stored number?
I have prepared a script in Lua, that is able to implement the behavior described in my previous post:
--[[ Script that reformats the C source code passing it via external command defined in variable "flt" --]] local flt = "astyle --indent-classes -Y" line, column = geany.rowcol() local fn=os.tmpname() local fo=assert(io.open(fn,'w')) assert(fo:write(geany.text())) fo:close() local cmd = "cat ".. fn .. " | " .. flt local f = assert(io.popen(cmd, 'r')) local s = assert(f:read('*a')) f:close() os.remove(fn) geany.text(s) position=geany.rowcol(line,column) geany.caret(position)
The cursor remains in the original location, or near to it. The only problem is that the position of the text on the screen may be changed (Usually after the processing, the line with the cursor is near to the bottom of the window). Of course you must activate the "Lua Script" plugin to use the above script. The script should be placed in `~/.config/geany/plugins/geanylua` directory or `~/.geany/plugins/geanylua` directory (depending on distribution). You may also create a `hotkeys.cfg` file in the same directory, and put the filename of the above script in a line in that file. That allows you to assign a keyboard shortcut (e.g., CTRL+ALT+F) to that autoformatting script via `Edit->Preferences->Key bindings->Lua Script` .
Closed #1913.
Reopened #1913.
github-comments@lists.geany.org