This article is an introduction to searching for a string in a file using ag or pt and specify the matching line to open in JetBrains IDE.

The way to open a file from the command line in the JetBrains IDE is the same for all of them, so will use Goland as an example. You can configure it on Windows, macOS, and Linux that are supported by the JetBrains IDE, but in this article, the only introduction to macOS.

Create a shell script

Enables Goland to be run as a command.
Place the following files in a location where your PATH environment variable can find it(e.g. /usr/local/bin).

#!/bin/sh

open -na "GoLand.app" --args "${@}"

Grant the execute permissions.

$ chmod +x /usr/local/bin/goland

You can rewrite the "Goland.app" to "IntelliJ IDEA.app" and change /usr/local/bin/goland to /usr/local/bin/idea to make the settings for IntelliJ IDEA. If you want to use a different IDE, change it accordingly.

Refer to the manual for instructions if you are using the Toolbox App.

Open files from the command line

The following command will open the file in Goland.

$ goland nosplash /path/to/file

nosplash is an option to prevent the splash screen from appearing when Goland is loaded.

The command to open a file by specifying a line is as follows:

$ goland nosplash --line NUMBER /path/to/file

Search for strings and open matching lines

Use peco for the command line selector and ag for string search (skip the details usage of each). If you want to use pt, replace ag with pt.
Add the following function to your .bashrc or .zshrc and reload it.

ag-goland() {
    local selected_line=$(ag "${@}" | peco --query "$LBUFFER")
    if [ "${selected_line}" != "" ]; then
        if [ -f "${2}" ]; then
            goland nosplash --line $(echo ${selected_line} | awk -F':' '{print $1}') ${2}
        else
            goland nosplash --line $(echo ${selected_line} | awk -F':' '{print $2, $1}')
        fi
    fi
}

If no file matches the string search, or if you stop the execution with Ctrl-C while selecting with peco, nothing will be done. The second argument of ag is made to work with both directories and files, but the implementation is designed to specify only one file, so please be careful about that.

The usage is as follows:

$ ag-goland PATTERN /path/to/dir
$ ag-goland PATTERN /path/to/file

Conclusion

This article was an introduction to searching for a string in a file and specify the matching line to open in Goland.
If you want to open a file within a project, you may not need to use it since you can do the same thing with the IDE functionality, but if you want to open a file by searching across various projects, you may be able to use it.

References