Skip to main content
Protein Science : A Publication of the Protein Society logoLink to Protein Science : A Publication of the Protein Society
. 2020 Nov 30;30(1):262–269. doi: 10.1002/pro.3997

Templates for writing PyMOL scripts

Blaine H M Mooers 1,2,3,, Marina E Brown 1
PMCID: PMC7737772  PMID: 33179363

Abstract

PyMOL commands are used to exert exquisite control over the appearance of a molecular model. This control has made PyMOL popular for making images of protein structures for publications and presentations. However, many users have poor recall of the commands due to infrequent use of PyMOL. This poor recall hinders the writing of new code in scripts. One solution is to build the new script by using code fragments as templates for modular parts of the task at hand. The code fragments can be accessed from a library while writing the code from inside a text editor (e.g., Visual Studio Code, Vim, and Emacs). We developed a library of PyMOL code templates or snippets called pymolsnips to ease the writing of PyMOL code in scripts. We made pymolsnips available on GitHub in formats for 18 popular text editors. Most of the supported text editors are available for Mac, Windows, and Linux operating systems. The GitHub site includes animations that complement the instructions for installing the library for each text editor. We expect that the library will help many PyMOL users to be more productive when writing PyMOL script files.

Keywords: computer artwork, computer graphics, molecular artwork, molecular graphics, molecular illustration, molecular visualization, reproducible research, scientific illustration, scripting


Abbreviations

GUI

graphical user interface

IDE

integrated development environment

pml

PyMOL macro language

VSC

visual studio code

1. INTRODUCTION

Many molecular biologists aspire to make stunning molecular artwork. 1 , 2 Such artwork helps the reader comprehend the significance of the molecular structure that is being presented. Molecular artwork is generally made with one or more molecular computer graphics programs such as UCSF Chimera, 3 UCSF ChimeraX, 4 CCP4mg, 5 VMD, 6 YASARA, 7 JMOL, 8 RasMOL, 9 and PyMOL. 10 PyMOL is popular for making images of proteins because it provides the user with exquisite control over the appearance of the final image. This control comes from a vast set of parameters that can be customized with high precision. Often one to several dozen parameters are optimized to make a publication‐quality figure. The tedium of setting numerous parameters by using pull‐down menus in the graphical user interface (GUI) can be avoided by setting the parameters in a script file. PyMOL provides a macro language (pml, PyMOL macro or command language) that has a simple syntax. Many beginning PyMOL users have trouble recalling the commands due to inexperience. The reuse of existing code is an efficient approach to this problem. In fact, the reuse of existing code fragments is rule 6 in the 10 rules for biologists learning to program. 11 The recycling of code fragments is also a productivity‐enhancement practice with deep roots in software engineering. 12 A library stores the code fragments, templates, or snippets that are to be reused in a text editor. The user accesses the snippets in the library by a pull‐down menu or a special keyboard shortcut known as a tab trigger. The names of these tab triggers are autocompleted by some text editors. Although snippet libraries for over 100 other programming languages are available, we found no snippet libraries for PyMOL code in a format ready for use in popular text editors.

The objective of this project was to supply a snippet library of PyMOL code that can be used to build new scripts. The pymolsnips library has over 200 snippets. The code fragments are designed to be modular units that perform a single role in the script. The snippets vary in length from 1 to dozens of lines and span 22 categories to cover a wide range of applications. To encourage the use of the library, we formatted pymolsnips for 18 popular text editors. Odds are that most users currently use at least one of these text editors. We supply instructions about the installation and use of the library for each text editor on the public repository for the library (http://github.com/MooersLab/pymolsnips). Users of PyMOL will find that snippets in pymolsnips ease the assembly of new scripts and aid self‐directed learning about the PyMOL commands.

2. RESULTS

To ease the re‐use of pml code, we assembled a library of code templates written in pml. The contents of the snippets were drawn from lecture notes on molecular graphics, scripts used to make figures for presentations and publications, on‐line tutorials, the PyMOL Wiki (http://pymolwiki.org), and the PyMOL mailing list archive. There is about a 60% overlap in functionality with the shortcuts that we developed for use at the PyMOL prompt in interactive PyMOL sessions. 13 Code fragments or snippets consist of one or more complete lines of code. About 60% of snippets lack lines of Python code and could be run with old versions of PyMOL that use Python2. The Python3 code in the remaining snippets may have to be rewritten for use with versions of PyMOL that depend on Python2. A snippet is inserted into a script file by entering the tab trigger name and pressing the tab key or by selecting the snippet from a pull‐down menu. We describe below the role of tab triggers and tab stops when using the snippet library to write a new script file. We clustered the snippets into 22 categories to ease their lookup. A web page for this project has animations that show how to install the library for each supported text editor. Collectively, these user‐friendly features of pymolsnips should promote its adoption by those workers seeking to become more efficient at writing PyMOL scripts.

2.1. Tab triggers to insert the code

Tab triggers are the most efficient means of retrieving a snippet from the snippet library. Entering the tab‐trigger name and hitting tab inserts the corresponding code fragment into the script file to the right of the current position of the mouse cursor (Figure 2a). The user often does not need to know the full name of the tab trigger because many text editors support autocompletion of the name of the tab trigger (see Table 1). The user enters the first letters of the tab trigger name. Then the editor suggests the full name of the tab trigger in a pop‐up menu (Figure 2a). The user selects the correct snippet from the pop‐up menu.

FIGURE 2.

FIGURE 2

Insertion of the threeMaps snippet in a PyMOL script file using the text editor Visual Studio Code (VSC). This code generates three contours from two electron density maps for the structure of influenza neuraminidase (PDB‐ID 4dgr) reported by Reference 14. (a) Automated word completion in VSC suggests the closest tab trigger name. VSC also provides a preview of the code with a scroll bar on the right. (b) After insertion of the code by entering tab, the tab stops are highlighted with gray boxes. The default parameter values are shown. The user hits tab to advance through the tab stops from the top of the code toward the bottom. The cursor (marked by vertical heavy line) is currently at the second tab stop. This tab stop is mirrored at three additional sites. The word “glycan” is being replaced with “sugar” at all four sites simultaneously by typing “sugar” at the first site. (c) The final tab stop is below the snippet and at the start of a new line

TABLE 1.

Features of the text editors supported by the PyMOL snippet library. Autocompletion refers to autosuggestion of the tab trigger name at the cursor. Pull‐down menu refers to another form of access to the snippets. Tab stops are located inside the inserted snippet. Syntax highlighting applies to all of the pml code in the script file or electronic notebook

Editor Tab trigger Autocompletion Pull‐down menu Tab stops Syntax highlighting
Atom
BBedit
Brackets
Cuda Text
Emacs
Expresso
Geany
Gedit
Kate
Komodo Edit
Light Table
Micro
Neovim
Spacemacs
Sublime Text 3
TextMate
Vim
Visual Studio Code

2.2. In‐line lookup of tab trigger names

To ease the lookup of snippet names, a table with the names of the tab triggers and a description of the snippet can be inserted into the file by entering the tab trigger lsSnips. This table can be commented out with hash marks at the start of each line of the table. Commenting out of the table of snippets prevents the table from interfering with the execution of the script. The table can be placed at the top or bottom of the script file for quick reference by navigating up or down in the script file. Visual Studio Code (VSC) provides a preview of the table in the lsSnips snippet (Figure 1). This preview negates the need to insert the table and eases the look‐up of the snippet names while writing in a pml script file.

FIGURE 1.

FIGURE 1

The lsSnip tabtrigger and preview of the table of snippets in VSC text editor. The user can find the tabtrigger of interest without finishing the execution of the lsSnip tab trigger and thus without inserting the table of snippets into the script file

Several text editors display the snippet names in the pull‐down menus (Table 1). These menus enable the insertion of the code fragment by selection with a mouse cursor. Several text editors have snippets organized into sub‐menus by snippet category. These sub‐menus limit the length of the search for a snippet. Pull‐down menus of snippets are useful when first learning about the pymolsnips library, although they are not as efficient nor as ergonomic as the use of tab‐triggers.

Text editors with the pymolsnips library installed will recognize the pml file extension of PyMOL script files. The pml file extension verifies the scope is correct for the pymolsnips library. The pymolsnips library will not work in files with other file extensions. The scope prevents name conflicts between different libraries of snippets.

2.3. Tab stops within snippets

Tab stops are sites of parameter values in the snippet code. The snippet provides a placeholder value at each tab stop. The user may need to change this placeholder value to customize the code. The user's cursor advances to the first tab stop after inserting the snippet. The default parameter value will be highlighted (Figure 2b). The user can change this parameter value by typing over it, or they can leave it unchanged.

The user advances to the next tab stop by pressing the tab key again, makes an edit if needed, and then advances to the next tab stop. The user repeats this cycle until all tab stops have been visited. The tab stops ensure that the user edits all the relevant parameter values in one pass.

Some tab stops have the same default parameter value. A change at one site will be propagated to all other sites (Figure 2b). This propagation is called mirroring. Mirroring ensures that all identical sites retain identical parameter values. The overlooking the need to make changes at some identical sites is a common source of bugs. The mirroring of tab stops reduces the need for later debugging of the script file. Of course, the user can override the mirroring by manually entering different parameter values at each of the mirrored sites. The last tab stop is at the beginning of a new line below the snippet (Figure 2c). The presence of tab stops reduces coding errors.

2.4. Adding new snippets

Users can use existing snippets as templates to create new snippets for their personal library. Users can also submit requests on the Issues tab of the GitHub Site for the addition of new snippets to the library. We plan to add new snippets to the library as the need for them emerges.

2.5. Updating the library

Users may want to update their copy of the library as new snippets are added to pymolsnips on GitHub. The date of the last update and its nature is recorded in the GitHub repository. GitHub has only experimental support for downloading part of a repository. In the meantime, users must download the entire repository either via the “code → download zip” pull‐down menu or by “git clone https://github.com/MooersLab/pymolsnips.git” if they have git on their computer. The second option enables subsequent updating of the library by simply entering “git pull ” . Detailed instructions are provided in the README.md file at the GitHub site for pymolsnips.

2.6. Snippet lengths

The lengths of the snippets varied from one to many lines. Short snippets are easily reused in numerous new contexts. Some long snippets are applicable to any molecular scene like those snippets that make a special effect that is not available through a command in one of the pull‐down menus in the GUI of PyMOL. Other long snippets are more context‐dependent and require extensive editing to adapt them to a new molecular scene.

2.7. Categories of snippets

A number of categories of snippets were defined based on the function of each snippet (Table 2). Tallies show one or more snippets for each category. The distribution of the number of snippets across the categories is uneven because some categories may be used more frequently in scripts and because some categories have a large number of snippets with similar functionality.

TABLE 2.

Frequency of snippets by category

Category Number of snippets
Alternate locators 1
Change orientation 3
Color scheme 5
Electron density 10
File input/output 14
H‐bonds 3
Help 9
Labels 14
List snippets 1
Measurements 2
Molecular representations 36
Nucleic acids 13
Objects 9
Print 19
Programming 13
Pymolrc 6
Selection 16
Settings 2
Stereo 3
Trajectories 1
Unit cell display 30

2.8. Running a script in PyMOL

The user's PyMOL script can be tested in PyMOL by selecting the “File” pull‐down menu and then the “run script …” menu option. A file‐selection GUI will open to help the user navigate to their script file. The script is executed when the user selects it. Alternatively, the user can enter “@scriptname.pml” at the PyMOL prompt to run their script if it is in the current working directory of PyMOL. If not, the user needs to supply the appropriate file path or move the file to the working directory of PyMOL.

2.9. Conversion of a vertical script into a horizontal script

Because the snippets were written in pml, they can be entered at the PyMOL prompt in the GUI, but this is tedious and error‐prone. Instead, a semicolon can be added to the end of each line, and then the commands can be placed on one line by removing the end‐of‐line control character (i.e., \n). These edits are automated by using the regular expression %s/\n/;/g in a text editor like Vim. Before or after removing the end‐of‐line control characters, the user can use the tab stops to find and change the parameter values. The resulting single line of commands can be copied and pasted at the PyMOL prompt.

The horizontal script can be further edited at the PyMOL prompt. A subset of readline commands works on the PyMOL command line. These commands can be used to shift rapidly the mouse cursor to right and left on the command line. The final code fragment can then be copied and pasted back into the script file. The semicolons do not need to be removed; the script will still run with them present. If the user wants to convert the horizontal script into a vertical script, the regex %s/;/\r/g will replace the semicolons with the newline character. (Note that while the newline \n character was sought for replacement with a semicolon, the carriage return \r character has to substitute for the semicolon in the reverse operation).

2.10. Gallery of thumbnail images

Some users of the pymolsnips library need a visual method to find the snippet of interest. To meet this need, we made a gallery of thumbnail images of the output from the corresponding snippet (Figure 3). The gallery includes the snippet's tab trigger and category and is located near the top of the README.md file on the pymolsnips GitHub repository.

FIGURE 3.

FIGURE 3

Two example entries in the gallery of images representing the output of the snippets. The gallery eases discovery of the appropriate snippet. The RNA structure in the top row is a 27‐nucleotide hairpin (PDB‐ID 5d99), and the RNA structure in the bottom row is the 16‐base pair double helix (PDB‐ID 3nd3)

2.11. Text editors

Although the use of many text editors is relatively intuitive, it is still time‐consuming to master a new text editor. To address this issue, we made the pymolsnips library available for 18 text editors. It is likely that a user will find a supported text editor that they already know well. If a user's favorite text editor is missing, they can request support for it via the Issues pull‐down menu on the pymolnsips GitHub site.

2.12. Snippet library installation

The README.md file at the GitHub site for pymolsnips (http://www.github.com/MooersLab/pymolsnips) documents the installation of the text editors and the snippet library for each text editor. The CudaText editor is exceptional in that it comes primed for the automated installation of the pymolnsips library, but the remaining text editors require installation of the snippet library. The documentation also explains how to install any extra software that may be required. The README.md has links to the download sites for the text editors. Animated gifs in the README.md file show in 15–20 seconds how to install the snippet libraries and use them. The documentation in the README.md file is also valuable to users interested in trying a new text editor.

3. DISCUSSION

Easing the writing of the PyMOL scripts via the pymolsnips library can have a number of benefits for the field of structural biology. Experience gained by writing scripts for PyMOL can build confidence and interest in writing scripts for other scientific software. 15 Other benefits include building the script‐writing and data science skills of junior scientists, thereby improving their job prospects.

The reasons for using a snippet library may or may not be obvious depending on one's prior experience with snippet libraries. Reasons include accelerating the retrieval of code for recycling, reducing internal barriers to starting a coding project, reducing time required to assemble a new script, reducing the time spent on debugging by using tab stops to ensure that all parameters that need to be changed are changed, and facilitating the use of snippets in new combinations.

Snippets are one of several code writing aids that are widely used in modern text editors. Other aids include syntax highlighting, word completion (or autocompletion), and libraries of functions.

Syntax highlighting colors words with a color scheme that is mapped to the words' roles as commands, parameter names, parameter values, constants, and so on. Rules of syntax highlighting are specified in a lexer that is language‐specific. The format of the lexer is not standardized and varies between text editors. PyMOL lexers are available for several text editors. 16 If a PyMOL lexer is unavailable, the Python lexer works modestly well with the pymolsnips library.

Text editors support autocompletion. The user enters the first letters of a word and hits the tab key to obtain the remaining letters. Autocompletion seems to overlap with the role of snippet libraries by easing the writing of new code. Autocompletion is currently limited to single words on the command line in PyMOL. Some text editors autocomplete small blocks of template code in other programming languages. This would be the next logical step for autocompletion in PyMOL. Autocompleted lines of code still need to be customized. Some autocompletion systems facilitate this with the use of default values and tab stops. In general, autocompleted lines are shorter than the code fragments found in the pymolsnips library, so the snippet library complements autocompletion systems.

One common approach to recycling code fragments is to cast them as functions that are stored in a private Python library. This in‐house library is set up as a module that can be imported into the current Python session. The function is called by entering its name and providing any needed arguments. This approach could work well with code fragments that require no or few arguments. However, PyMOL code is often densely populated with parameters that need to customized when applying the code fragment to a new molecule. It would be tedious to enter numerous settings as function arguments: The user would still have to look at the code to determine the context for the parameter setting. In addition, the use of the private library complicates sharing the script with collaborators. The library would have to be sent with the script. Less‐computer literate collaborators may not be comfortable with installing and using the library. When compared to the use of the code fragments as functions, the snippets from the pymolsnips library should be more efficient.

The ability to insert code fragments from tab triggers overcomes the need to search for PyMOL commands online or in old script files. Online searches can be deceptively time‐consuming. These searches also expose the user to tempting distractions. Likewise, the searches of hard drives for old script files can be time‐consuming. The user can also be tempted to linger on interesting but unfinished projects. The fingertip access to PyMOL code fragments eliminates expensive searches and reduces the risk of being lured into an off‐task activity.

When we started this project, no snippet libraries for PyMOL were available to the public in a format ready for use in a text editor. Some individuals have shared collections of code fragments on the PyMOL wiki pages, on personal web pages, in articles, and in books (e.g., References 17, 18). These collections could be called snippet libraries. A user can copy code fragments from these collections where the source's software license permits copying. However, the copy operations are fraught with the danger of mis‐translation of the pasted text. For example, a hyphen might be copied as an emdash. The resulting bug can take hours to find. Users can avoid problems with such bugs by using the pymolsnips library.

4. MATERIALS AND METHODS

4.1. Snippet library construction

Each text editor had generally unique format requirements, so a separate library was developed for each text editor. The snippet libraries were kept under version control with git. 19 The libraries were posted on the GitHub repository called pymolsnips. The README.md file of the repository has extensive documentation about the snippet library and how to install it for each text editor.

4.2. Formatting of snippets

There is no universal format for snippet files. Some text editors store all of the snippets for all programming languages in one file, others store the snippets for one language in one file, and other editors store one snippet per file. Text editors also differ in the code used to mark tab stops. Snippets were written with appropriate tab stop codes and file formats as required for each text editor.

4.3. Avoidance of conflicting global variables

Some older PyMOL code fragments use the module pymol.stored to define the global variables as members of the stored module. The user's script may call other scripts that rely on the pymol.stored module and those that use the same stored member names. The use of the same member names by two or more scripts will cause conflicts. We rewrote the code fragments that used pymol.stored to use instead the space argument of the cmd.iterate and the cmd.alter functions. These functions generate unique global variables that should not conflict with older scripts.

4.4. Future proofing

The pymolsnip library was initially developed with versions of PyMOL that used a Python2 interpreter, but PyMOL has since migrated to Python3. Snippets were tested in PyMOL version 2.4.1. 20 Snippets with print statements were rewritten as print functions to be in compliance with the syntax in Python3. Math equations with division involving integers in the divisor had the divisor converted to a float prior to division. The format of the code was checked with pylint. 21

4.5. Animated tutorials

Animations were constructed to promote understanding of how the snippets can be operated. These animations were made with Giphy Capture 22 and can be run in the README.md file of the pymolsnips GitHub site.

AUTHOR CONTRIBUTIONS

Blaine Mooers: Conceptualization; funding acquisition; methodology; project administration; resources; software; supervision; validation; visualization; writing‐original draft; writing‐review and editing. Marina Brown: Conceptualization; data curation; methodology; software; validation; visualization; writing‐review and editing.

Mooers BHM, Brown ME. Templates for writing PyMOL scripts. Protein Science. 2021;30:262–269. 10.1002/pro.3997

Funding information National Cancer Institute, Grant/Award Number: R01 CA242845; National Institute of Allergy and Infectious Diseases, Grant/Award Number: R01 AI088011; National Institute of General Medical Sciences, Grant/Award Number: P20 GM103640; National Science Foundation, Grant/Award Number: MCB‐1616845; Oklahoma Center for the Advancement of Science and Technology, Grant/Award Number: HR20‐002; Schrodinger, Inc, Grant/Award Number: Warren Delano Memorial PyMOL Open‐Source Software Fellowship

REFERENCES

  • 1. Mura C, Mccrimmon C, Vertrees J, Sawaya M. An introduction to biomolecular graphics. PLoS Comput Biol. 2010;6:e1000918. [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 2. Goodsell D, Jenkinson J. Molecular illustration in research and education: Past, present, and future. J Mol Biol. 2018;430:3969–3981. [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 3. Pettersen EF, Goddard TD, Huang CC, et al. UCSF chimera–A visualization system for exploratory research and analysis. J Comput Chem. 2004;25:1605–1612. [DOI] [PubMed] [Google Scholar]
  • 4. Goddard TD, Huang CC, Meng EC, et al. UCSF ChimeraX: Meeting modern challenges in visualization and analysis. Protein Sci. 2018;27:14–25. [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 5. McNicholas S, Potterton E, Wilson KS, Noble MEM. Presenting your structures: The CCP4mg molecular‐graphics software. Acta Crystallogr D Biol Crystallogr. 2011;67:386–394. [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 6. Humphrey W, Dalke A, Schulten K. VMD: Visual molecular dynamics. J Mol Graph. 1996;14:33–38. [DOI] [PubMed] [Google Scholar]
  • 7. Krieger E, Koraimann G, Vriend G. Increasing the precision of comparative models with YASARA NOVA–A self‐parameterizing force field. Proteins: Struct Funct Bioinf. 2002;47:393–402. [DOI] [PubMed] [Google Scholar]
  • 8. Hanson RM. Jmol – A paradigm shift in crystallographic visualization. J App Cryst. 2010;43:1250–1260. [Google Scholar]
  • 9. Sayle RA, Milner‐White EJ. RASMOL: Biomolecular graphics for all. Trends Biochem Sci. 1995;20:374–376. [DOI] [PubMed] [Google Scholar]
  • 10. Delano W. Use of PyMOL as a communications tool for molecular science. Abstracts of Papers of the American Chemical Society, Amer Chemical Soc, 16th St, NW Washington, DC; 2004, Volume 228, p. U228–U230.
  • 11. Carey MA, Papin JA. Ten simple rules for biologists learning to program. PLoS Comput Biol. 2018;14:e1005871. [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 12. McIlroy, MD . Mass produced software components, In P. Naur & B. Randell, eds, ‘Proceedings of NATO Software Engineering Conference’, Vol. 1, pp. 138–150; 1969, NATO Science Committee. Presented at the NATO Conference on Software Engineering, Garmisch, Germany, 7‐11 October, 1968.
  • 13. Mooers BHM. Shortcuts for faster image creation in PyMOL. Protein Sci. 2020;29:268–276. [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 14. Venkatramani L, Johnson ES, Kolavi G, Air GM, Brouillette WJ, Mooers BH. Crystal structure of a new benzoic acid inhibitor of influenza neuraminidase bound with a new tilt induced by overpacking subsite C6. BMC Struct Biol. 2012;12:7. [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 15. Wilson G. Software carpentry: Getting scientists to write better code by making them more productive. Comput Sci & Eng. 2006;8:66–69. [Google Scholar]
  • 16. Babaian A, Ebou A, Fegen A, et al. bioSyntax: Syntax highlighting for computational biology. BMC Bioinf. 2018;19:303. [DOI] [PMC free article] [PubMed] [Google Scholar]
  • 17. Via A, Rother K, Tramontano A. Managing your biological data with python, Boca Raton, FL: CRC Press, 2014. [Google Scholar]
  • 18. Skern T. Exploring protein structure: principles and practice, Cham, Switzerland: Springer, 2018. [Google Scholar]
  • 19. git, version 2.92.2. 2020. San Franciso, CA: GitHub. [Google Scholar]
  • 20. PyMOL, version 2.4.0. New York: Schrodinger Inc., 2020. [Google Scholar]
  • 21. PyTest, version 5.4.3. Wilmington, DE: Python Software Foundation, 2020. [Google Scholar]
  • 22. Giphy capture, Verison 4.1. New York, NY: Giphy Inc., 2020. [Google Scholar]

Articles from Protein Science : A Publication of the Protein Society are provided here courtesy of The Protein Society

RESOURCES