Sublime Forum

"Open function"-functionality for Matlab plugin

#1

Hello,

While working with Matlab files, I missed the function to open the file of a selected function. If this is already possible, I would be glad to get told how this can be done. Nevertheless, I wrote a plugin for the Matlab package, which allows to open a function according to the selection within the text. Here is the code of the file “openmatlabfunction.py”, which has to be added to the Packages/Matlab folder:

import sublime
import sublime_plugin
import os


class OpenmatlabfunctionCommand(sublime_plugin.TextCommand):
	def run(self, edit):

		for sels in self.view.sel():
			if sels.empty():
				fileToFind = self.view.word(sels)

			fileToFind = self.view.substr(sels)
			
			didFind = False
			fileDir = os.path.dirname(self.view.file_name())
			fileName, fileExtension = os.path.splitext(self.view.file_name());

			# traverse the directory of the current file and look for the corresponding .m file
			for fname in os.listdir(fileDir):
				tempfileName, tempfileExtension = os.path.splitext(fname);

				# if the .m file is found, open it and set syntax
				if tempfileExtension==".m" and fileToFind==tempfileName:
					didFind = True
				 	print "Opening "+fileToFind+tempfileExtension
				 	currentSyntax = self.view.settings().get('syntax')
				 	newView = sublime.active_window().open_file(fileToFind+tempfileExtension)
				 	newView.settings().set('syntax', currentSyntax)

	 	# if we did not find the .m file, print a message
	 	if not didFind:
	 		print "Did not find "+fileToFind+".m in current directory."
	 		

The plugin can easily be added to the context menu by adding the file “Context.sublime-menu” to the Packages/Matlab folder with the following content:


    {
        "command": "openmatlabfunction",
        "caption": "Open selected Matlab function"
    }
]

Regards,
Florian

0 Likes