Search code examples
macosawkgedit

Using awk with gedit external tools


I have used gedit with Ubuntu a lot and now transitioning on Macos. I noticed that some of the plugins in the Macos version are missing. For instance, there is no (AFAIK) an out-of-the-box option to comment/uncomment code. However, there is the possibility to define an external tool to basically have whatever you want.

I want to just comment the text selection in R/python style (prepending a # before each line of the input). I went to Tools -> Manage External Tools and defined a "Comment Code" tool in this way:

#!/bin/bash
awk '{print "#" $0}'

and set Input as "Current Selection" and output as "Replace Current Selection".

It works if you select a text; however if you don't select anything, it stalls forever, since (for what I understood) awk is waiting for an input.

How can I avoid this problem? Of course I don't need a awk (or whatever) solution, whatever works is fine. I'm not much expert of bash tools like awk or sed, so very likely I'm missing something very simple.


Solution

  • See https://www.gnu.org/software/gawk/manual/html_node/Read-Timeout.html for how to implement a read timeout with GNU awk.

    With input from stdin (enter 7 then Enter/Return then Control-D):

    $ gawk 'BEGIN{PROCINFO["-", "READ_TIMEOUT"]=5000} {print "#" $0}'
    7
    #7
    

    or with input from a pipe:

    $ seq 2 | gawk 'BEGIN{PROCINFO["-", "READ_TIMEOUT"]=5000} {print "#" $0}'
    #1
    #2
    

    or from a file:

    $ seq 2 > file
    $ gawk 'BEGIN{PROCINFO["-", "READ_TIMEOUT"]=5000} {print "#" $0}' file
    #1
    #2
    

    but if you don't provide any input and wait 5 seconds:

    $ gawk 'BEGIN{PROCINFO["-", "READ_TIMEOUT"]=5000} {print "#" $0}'
    gawk: cmd. line:1: fatal: error reading input file `-': Connection timed out
    $
    

    You can always redirect stderr the usual way if you don't want to see the timeout message:

    $ gawk 'BEGIN{PROCINFO["-", "READ_TIMEOUT"]=5000} {print "#" $0}' 2>/dev/null
    $
    

    but of course that would mask ALL error messages so you might want to do this instead to just mask that one message:

    { gawk 'BEGIN{PROCINFO["-", "READ_TIMEOUT"]=5000} {print "#" $0}' 2>&1 >&3 |
        grep -v 'fatal: error reading input file'; } 3>&1
    

    e.g.:

    $ { gawk 'BEGIN{print "other error" >"/dev/stderr";
            PROCINFO["-", "READ_TIMEOUT"]=5000} {print "#" $0}' 2>&1 >&3 |
        grep -v 'fatal: error reading input file'; } 3>&1
    other error
    $
    

    Obviously change the 5000 to however many milliseconds you want the script to wait for input.