How can I use Python to create a customized Eclipse IDE?

Source: Internet
Author: User

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:

 
 
  1. 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 ".

 
 
  1. loadModule('/System/Resources') 
  2.   
  3. from org.eclipse.core.resources import IMarker 
  4.   
  5. for ifile in findFiles("*.java"): 
  6.     file_name = str(ifile.getLocation()) 
  7.     print "Processing " + file_name 
  8.     with open(file_name) as f: 
  9.         for line_no, line in enumerate(f, start=1): 
  10.             if "printStackTrace" in line: 
  11.                 marker = ifile.createMarker(IMarker.TASK) 
  12.                 marker.setAttribute(IMarker.TRANSIENT, True) 
  13.                 marker.setAttribute(IMarker.LINE_NUMBER, line_no) 
  14.                 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 ".

 
 
  1. loadModule('/System/Resources') 
  2.   
  3. for iproject in getWorkspace().getProjects(): 
  4.     if not iproject.isOpen(): 
  5.         continue 
  6.   
  7.     ifile = iproject.getFile("README.md") 
  8.   
  9.     if not ifile.exists(): 
  10.         contents = "# " + iproject.getName() + "\n\n"  
  11.         if iproject.hasNature("org.eclipse.jdt.core.javanature"): 
  12.             contents += "A Java Project\n" 
  13.         elif iproject.hasNature("org.python.pydev.pythonNature"): 
  14.             contents += "A Python Project\n" 
  15.         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

 
 
  1. def save_dirty_editors(): 
  2.     workbench = getService(org.eclipse.ui.IWorkbench) 
  3.     for window in workbench.getWorkbenchWindows(): 
  4.         for page in window.getPages(): 
  5.             for editor_ref in page.getEditorReferences(): 
  6.                 part = editor_ref.getPart(False) 
  7.                 if part and part.isDirty(): 
  8.                     print "Auto-Saving", part.getTitle() 
  9.                     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:

 
 
  1. # name      : Create fruit projects 
  2. # toolbar   : Project Explorer 
  3. # description   : Create fruit projects 
  4.   
  5. loadModule("/System/Resources") 
  6.   
  7. for name in ["banana", "pineapple", "mango"]: 
  8.     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.

 
 
  1. # name            :Delete fruit projects 
  2. # toolbar        : Project Explorer 
  3. # description    : Get rid of the fruit projects 
  4.   
  5. loadModule("/System/Resources") 
  6.   
  7. for name in ["banana", "pineapple", "mango"]: 
  8.     project = getProject(name) 
  9.     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

 
 
  1. # name      : Explore from here 
  2. # popup     : enableFor(org.eclipse.core.resources.IResource) 
  3. # description   : Start a file browser using current selection 
  4. loadModule("/System/Platform") 
  5. loadModule('/System/UI') 
  6.   
  7. selection = getSelection() 
  8. if isinstance(selection, org.eclipse.jface.viewers.IStructuredSelection): 
  9.     selection = selection.getFirstElement() 
  10.   
  11. if not isinstance(selection, org.eclipse.core.resources.IResource): 
  12.     selection = adapt(selection, org.eclipse.core.resources.IResource) 
  13.   
  14. if isinstance(selection, org.eclipse.core.resources.IFile): 
  15.     selection = selection.getParent() 
  16.   
  17. if isinstance(selection, org.eclipse.core.resources.IContainer): 
  18.     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]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.