Drag and Drop files into Lyx to create links

It’s sometimes handy to drag and drop files into Lyx and have it do something of value. This works pretty well for images but not at all for generic files. You can add something like the same functionality using a simple python script and the lyx pipe.

Dropping a file on the drop target generates the code above (it even adds the right image if there is one)

Make sure the Lyx server is switched on http://wiki.lyx.org/LyX/LyXServer#toc4, and restart Lyx to make sure it is running.

Create a python file called dropper.py and copy in the source. You also need python 2.6ish and wxPython installed.

import wx, os

# perform the appropriate operations in lyx with the
def dealFile(file):
 #the adequately escaped lyx pipe
 lyxServer = "\\\\.\pipe\lyxserver.in"

 aFile = file.split('.')
 if(len(aFile) == 1):#it's a folder
 aFile = [aFile[-1], 'fld']
 print aFile

 #insert a picture with an image of ext.png
 command = "echo LYXCMD:dropper:inset-insert:graphics lyxscale 10 width 1.2em height 1.2em keepAspectRatio filename $DROPPER_IMAGES$/image/"+aFile[1]+".png>>"+lyxServer

 # put in a space
 command = "echo LYXCMD:dropper:self-insert: >>"+lyxServer
 #print it for debugging and send it to the os

 # insert the hyperlink
 aFile = file.split('\\')
 command = "echo LYXCMD:dropper:inset-insert:href LatexCommand href name "+aFile[-1]+" target \""+file+"\" type \"file:\" \end_inset>>"+lyxServer
 #print it for debugging and send it to the os

# the drop target
class MyFileDropTarget(wx.FileDropTarget):
 def __init__(self, window):
 self.window = window

 # when a file is dropped print its name and hand it to dealFile()
 def OnDropFiles(self, x, y, filenames):
 for file in filenames:
 self.window.AppendText("%s\n" % file)

# the application frame
class MyFrame(wx.Frame):
 def __init__(self):
 #set it all up
 wx.Frame.__init__(self, None, title="Drop Target",size=(200,200))
 p = wx.Panel(self)

 label = wx.StaticText(p, -1, "Drop some files here:")
 text = wx.TextCtrl(p, -1, "",style=wx.TE_MULTILINE)

 sizer = wx.BoxSizer(wx.VERTICAL)
 sizer.Add(label, 0, wx.ALL, 5)
 sizer.Add(text, 1, wx.EXPAND|wx.ALL, 5)

 #put in the drop target
 dt = MyFileDropTarget(text)

# run the windowed script
app = wx.PySimpleApp()
frm = MyFrame()

Make sure you replace $DROPPER_IMAGES$ by a path to an image directory with thumbnails in. These need to be in the form extension.png.

There is a bug in Lyx before 1.6.8 which duplicates the final character of an image when it is inserted by the dropper. All images end up being called extension.pngg.

Note: The basis for this script is from an example site, can’t remember which one though… The Lyx code is the interesting part (as far as it goes).

Leave a Reply