How can I use Python to create a customized Eclipse IDE?
Eclipse is a powerful framework that supports multiple extension methods through the built-in plug-in mechanism. However, if you want to add a few additional features, you will inevitably need to write and deploy new plug-ins, which is obviously a headache. With the help of pipeline, we can accomplish this task in a better way-and the entire process does not need to involve any generation of Java code. Pipeline allows us to easily use Python, JavaScript, and other scripting languages to implement automated workbench functions.
In this article, we will learn how to use Python and idea to set up the Eclipse environment and consider multiple feasible ways to use Python to enhance the IDE solution.
Set and run "Hello World"
The examples in this article are based on the Python Java implementation scheme, that is, Jython. You can directly install idea into the existing Eclipse IDE. However, in this example, we use Eclipse Mars and install the runtime ontology, its modules, and the Jython engine.
In the Eclipse installation dialog box, Install idea: http://download.eclipse.org/ease/update/nightly
Next, select the following components:
- EASE Core featureEASE Core functions)
- EASE core UI featureEASE core UI functions)
- Using Python Developer ResourcesEASE Python Developer resources)
- EASE modules (Incubation) Incubator Module)
In this way, we can use the token and Its modules. Here we mainly need to use the resource module, which allows us to access the Eclipse work zone, project, and file API.
After the preceding entries are successfully installed, install the mongojython engine: https://dl.bintray.com/pontesegger/ease-jython /. Once the plug-ins are installed, You need to test the plugin below. Create a new project and run the following command to add a file named hello. py:
- print "hello world"
Right-click the file and choose "Run as-> scripts script ". In this case, the console displays "Hellp World ".
Now you can write Python scripts that can access the workspace and project. From here on, we have adjusted the IDE based on the following goals.
Improve code Quality
Ensuring good code quality is a very difficult task, especially when the code library is large or involves multiple developers. Some of these difficulties can be easily solved by introducing scripts, such as batch format adjustment for certain types of files, or removing unix end lines in source code control systems such as git to simplify file content comparison. It is also worth noting that we can use scripts to generate Eclipse tags, so as to improve functions by highlighting code. The following script example can be used to add the task tag mechanism to all "printStackTrace" methods to implement internal Java file detection. Click this link to view the source code: markers. py
Copy the file in the workspace, right-click the corresponding file, and select "Run as-> prepare script ".
- loadModule('/System/Resources')
-
- from org.eclipse.core.resources import IMarker
-
- for ifile in findFiles("*.java"):
- file_name = str(ifile.getLocation())
- print "Processing " + file_name
- with open(file_name) as f:
- for line_no, line in enumerate(f, start=1):
- if "printStackTrace" in line:
- marker = ifile.createMarker(IMarker.TASK)
- marker.setAttribute(IMarker.TRANSIENT, True)
- marker.setAttribute(IMarker.LINE_NUMBER, line_no)
- marker.setAttribute(IMarker.MESSAGE, "Fix in Sprint 2: " + line.strip())
If you already have some Java files that contain printStackTraces, you can view the newly created tag in the task view at the edge of the editor.
Automated processing of tedious tasks
When you deal with multiple projects at the same time, you may want to automate some tedious and repetitive tasks. You may need to add a copyright title at the beginning of each source file or update the source file when a new framework is used. For example, when we switch to Tycho and Maven for the first time, we need to add a pom. xml file for each project. Just a few lines of Python code can be easily completed. However, because Tycho currently supports building without pom, we need to remove unnecessary pom files. Similarly, several lines of Python scripts can fulfill this requirement. For example, here we use the following script to add a README. md file to each open project in the workspace -- if they belong to a Java or Python project, of course. Click the following link to view the source code: add_readme.py.
To Run this script, copy the file to the workspace, right-click the file and choose "Run as-> scripts script ".
- loadModule('/System/Resources')
-
- for iproject in getWorkspace().getProjects():
- if not iproject.isOpen():
- continue
-
- ifile = iproject.getFile("README.md")
-
- if not ifile.exists():
- contents = "# " + iproject.getName() + "\n\n"
- if iproject.hasNature("org.eclipse.jdt.core.javanature"):
- contents += "A Java Project\n"
- elif iproject.hasNature("org.python.pydev.pythonNature"):
- contents += "A Python Project\n"
- writeFile(ifile, contents)
The result is that each opened project will have a README. md file, while the Java and Python projects have additional description lines.
New function prototype design
You can also use the Python script to quickly fix most of the required features, or use it as a prototype to help team members or users understand how to use this new feature. For example, Eclipse IDE does not currently support automatic saving of files being processed. Although this feature will certainly be available in future versions, you can still manually Save the current file every 30 seconds or when the editor is disabled. The following is a code snippet in the main method. Click the following link to view the complete source code: autosave. py
- def save_dirty_editors():
- workbench = getService(org.eclipse.ui.IWorkbench)
- for window in workbench.getWorkbenchWindows():
- for page in window.getPages():
- for editor_ref in page.getEditorReferences():
- part = editor_ref.getPart(False)
- if part and part.isDirty():
- print "Auto-Saving", part.getTitle()
- part.doSave(None)
Before running this script, you also need to check "Allow Scripts to run code in UI thread" in the dialog box in Window> Preferences> Scripting to Allow the script to run code in the UI thread). In this way, you can add the file to your work, right-click it, and select "Run as-> scripts ". Each time the editor is saved, a save message is output in the console view. To disable the Automatic save function, you only need to click the "Terminate" red button in the console view to stop the script.
Use buttons, menus, and other entries to quickly expand the user interface
One of the best features of idea is to allow everyone to use their own scripts and quickly hook them into the UI elements in the IDE-as new buttons or new menu entries. You don't need to write Java code or use a new plug-in. You just need to add a few lines of content to the script title-that's easy.
The following example uses a simple script to create three new projects for us:
- # name : Create fruit projects
- # toolbar : Project Explorer
- # description : Create fruit projects
-
- loadModule("/System/Resources")
-
- for name in ["banana", "pineapple", "mango"]:
- createProject(name)
The comment line pointing to the toolbar adds a new button to the toolbar of the Project Manager. The following shows another set of scripts, which are used to add another button in the same toolbar to completely delete the three items. Click the following link to view its source code: createProjects. py and deleteProjects. py.
- # name :Delete fruit projects
- # toolbar : Project Explorer
- # description : Get rid of the fruit projects
-
- loadModule("/System/Resources")
-
- for name in ["banana", "pineapple", "mango"]:
- project = getProject(name)
- project.delete(0, None)
To display these buttons correctly, we also need to add two script files to the new project-here we call the new project "ScriptsProject ". Next, open Windows> Preference> Scripting> Script Locations step by step. Click "Add Workspace" and select ScriptsProject. This project is now the default location for storing script files. In this case, you can directly view these buttons in the project manager without restarting the IDE. With these new buttons, we can quickly create and delete these three corresponding projects.
Integration with third-party tools
You may need to use tool options other than the Eclipse ecosystem at any time, and you must admit that although Eclipse is very powerful, it is still quite powerful ). For such scenarios, you can easily add packet requests and tool calls to scripts. The following example allows you to integrate javaser.exe and add it to the content menu. In this way, you can use the existing options to open the file browser at any time. Click the following link to view its source code: explorer. py
- # name : Explore from here
- # popup : enableFor(org.eclipse.core.resources.IResource)
- # description : Start a file browser using current selection
- loadModule("/System/Platform")
- loadModule('/System/UI')
-
- selection = getSelection()
- if isinstance(selection, org.eclipse.jface.viewers.IStructuredSelection):
- selection = selection.getFirstElement()
-
- if not isinstance(selection, org.eclipse.core.resources.IResource):
- selection = adapt(selection, org.eclipse.core.resources.IResource)
-
- if isinstance(selection, org.eclipse.core.resources.IFile):
- selection = selection.getParent()
-
- if isinstance(selection, org.eclipse.core.resources.IContainer):
- runProcess("explorer.exe", [selection.getLocation().toFile().toString()])
To make the menu correctly displayed, we need to add the script to a new project-we still call it "ScriptsProject ". Next, go to Windows> Preference> Scripting> Script Locations. Click "Add Workspace" and select ScriptsProject. Now, you should be able to right-click a file and see that the new menu entry is displayed in the pop-up menu. Click to open the file browser. Note that this feature already exists in Eclipse, but here we just use it as an example to explain how other third-party tools integrate .)
This Eclipse advanced script environment can give full play to the powerful potential of Python, so that we can use Eclipse IDE flexibly. At present, this project is in its infancy, so we can look forward to more exciting functions and features in the future. If you are interested, you can click here to view the project description or click here to participate in the original English version of the relevant forum ).
We will give a more detailed introduction to the idea at the Eclipsecon North America Conference in 2016. In the subsequent Keynote Speech "using Python to implement Eclipse scripting", in addition to the existing Jython, I will also discuss C-Python and how to extend its functions to scientific use cases. Coming soon!
Original article title: How to use Python to hack your Eclipse IDE
Bkjia translation. if the site is reprinted, indicate the original translator and the source is bkjia.com]