#!/usr/bin/env python
"""
Launch a text editor from a carefully crafted link from Firefox.

This script is meant to be invoked from Firefox, with the Mozex plug-in, from
links that specify a filename and line number::

   edit://<filename>:<line-no>

Those links are shown by my web application framework in stack traces, when
there is an error.  This allows me to simply click on the links to open the
files in a running Emacs (with emacsclient).
"""
__version__ = "Revision: 1.6 "
__author__ = "Martin Blais <blais@furius.ca>"


# stdlib imports
import os, re
from subprocess import Popen


def main():
    import optparse
    parser = optparse.OptionParser(__doc__.strip())
    opts, args = parser.parse_args()

    if len(args) != 1:
        parser.error("You must specify a single argument, an URL.")
    uri, = args

    mo = re.match('(?:fileloc|edit)://(.*):(\\d+)$', uri)
    if not mo:
        parser.error("Invalid URL.")
    filename, line = mo.group(1), int(mo.group(2))

    # Launch emacsclient asynchronously.
    Popen( (os.environ['EDITOR'], '-e', cmd % (filename, line)) )

cmd = '''

(progn
 (find-file "%s")
 (goto-line %d)
 (push-mark (point))
 (forward-line 1)
 (exchange-point-and-mark)
 (recenter)
 )


'''

if __name__ == '__main__':
    main()

