Advertisement

PopClip: Scripting Extensions

by

This Cyber Monday Tuts+ courses will be reduced to just $3 (usually $15). Don't miss out.

PopClip is a great utility program that, once you get used to it, is very hard to live without. This tutorial is going to show how to write a scripting extension by making an example extension.

In this tutorial I will show you how to create a PopClip extension by building an extension that will look for a Bible reference to be selected, lookup the reference in English or Thai using a Web API, and paste the appropriate verse(s) in place. You will learn to create a PopClip extension that uses a PHP script, regular expression for activation, setting preferences that the user can edit, and using hotkeys to override the preferences.


Defining Your Extension

The first thing that should be done is to decide what the extension is going to do. You should always create each extension with a single functionality in mind. Since I am a missionary, I write notes on Bible verses all the time. I would like to have an extension that will take a Bible reference and paste that verse or verses into my document in both Thai and English. Therefore, the extension will do just that!

But, sometimes I might just need one or the other language. Therefore, the extension needs to have a preference panel and hotkeys to override the preferences. That might sound like a lot of work, but PopClip makes it easy.

I found a great website, Ephesians 4:14, that allows for the downloading of verses from both the King James Bible in English and the Thai King James Bible. Since I work with the Thai language, these are the only Bibles I need. They also have many other languages. Therefore, you can add whatever language might interest you.


Popclip Resources

If you just recently installed PopClip, please read the PopClip User Guide first. The tutorial, Create Your Own Custom Extension for PopClip, gives a great introduction to PopClip and how to make extensions that do not call for any programming. This tutorial will focus on script programming extensions for PopClip.

Pilotmoon gives a complete list of plist configuration file options. Always refer to this for up to date documentation of the extensions interface for PopClip.

The extension will be written in PHP. If you do not know how to program in PHP, an excellent video course can be found on Tuts+: PHP Fundamentals.


The File Structure

Wherever you will be working on your computer, create a directory called popclipBible.popclipext. That directory will look like a normal file, but when you right click on it and select the popup menu Show Package Contents, it will show the contents of that directory. You need to create the files Config.plist, bible.php, and bible.png in to this directory.

Config.plist is the plist file described in the next section. bible.php will contain the PHP script to be executed. bible.png is the graphic file for the extension. All of these are in the download file at the top.


The Plist

All extensions for PopClip start with a plist file called Config.plist. This file tells PopClip how the extension fits in to the world of PopClip. The full plist for this extension is:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>Actions</key>
	<array>
		<dict>
			<key>After</key>
			<string>paste-result</string>
			<key>Image File</key>
			<string>bible.png</string>
			<key>Script Interpreter</key>
			<string>/usr/bin/php</string>
			<key>Shell Script File</key>
			<string>bible.php</string>
			<key>Title</key>
			<string>Bible</string>
		</dict>
	</array>
	<key>Options</key>
	<array>
		<dict>
			<key>Option Identifier</key>
			<string>biblekjv</string>
			<key>Option Type</key>
			<string>boolean</string>
			<key>Option Label</key>
			<string>KJB</string>
		</dict>
	<dict>
		<key>Option Identifier</key>
		<string>biblethaikjv</string>
		<key>Option Type</key>
		<string>boolean</string>
		<key>Option Label</key>
		<string>Thai KJV</string>
	</dict>
	</array>
	<key>Extension Description</key>
	<string>Lookup Bible verses in Popclip.</string>
	<key>Extension Identifier</key>
	<string>com.customct.popclip.extension.bible</string>
	<key>Extension Name</key>
	<string>Bible</string>
	<key>Long Running</key>
	<true/>
	<key>Regular Expression</key>
	<string>(.*\d+\:\d+(\-\d+)*)</string>
	<key>Required Software Version</key>
	<integer>701</integer>
</dict>
</plist>

As can be seen, it is a XML formated data file. This data file tells PopClip all it needs to know to run the extension.

This is the bare bones plist needed for this extension. The main dictionary has the keys Actions and Options. These are the main entries for providing the functionality of the extension. I will describe them in more detail below. The other keys are:

Extension Description
This key gives a description of what the extension will do. This needs to be short, but descriptive.

Extension Identifier
This key gives a unique identifier for your extension. I based it off of my website for complete uniqueness. It can by any alpha-numeric sequense, but something readable is always nice.

Extension Name
This key is the name of the extension. I simply call it Bible.

Long Running
This key is set to true since it will be making a Web API call that take a while to finish due to net speed. This simply has PopClip display a wait icon while performing the action.

If the extension does not take long, it should be false.

Regular Expression
This key's value is a regular expression that will allow the launching of the extension only if it asserts true for the currently selected text. By writing a regular expression that will only match a bible reference, it will not show the Bible extension on just any text selection.

Make good use of this feature. Showing up with any text selection makes it harder on the user of the extension. Think about how someone would want to use the extension and create a good regular expression for that case.

If you are a little rusty on writing regular expressions, then you should read this article on Net Tuts+.

Required Software Version
This key specifies the version of PopClip that this extension needs.


Actions

The Action keys are for defining the action that the extension will perform. There are a lot of possibilities, but this tutorial will only focus on the items needed. They are as follows:

After
This specifies the action to take after running the script. paste-result will paste into the top most application whatever text the script echos out.

Image File
This key specifies the icon used for this extension. Since the icon in the same area as the extension, you can simply refer to the file: bible.png. If you wanted to keep the icons in a sub-directory of the extension, you would use a relative reference to that file.

Script Interpreter
This key defines the interpreter will be used to process the script. Since I am doing this program in PHP, it needs to reference the default PHP interpreter on all Macs: /usr/bin/php. You can place the full path to any interpreter you want to use to write extensions.

Shell Script File
This key defines the file in the directory of the extension to run. The filename is: bible.php.

Title
This key is the title of the extension: Bible.


Options

The Options key contains an array of dictionaries. One dictionary for each option in the preference panel for the extension. For this extension, the user should have the option of pasting from the KJV Bible or the Thai KJV Bible. Since I have two options for this extension, I will describe each key in the Options dictionary and tell what I used for each option.

Option Identifier
This key give PopClip a unique name for the option you need for your extension. This is used in the environment variable that is passed to your program. For the two options, these ids will be used: biblekjv and biblethaikjv.

Option Type
This key defines what type of option it is. It can be either boolean (yes or no), string (any string), or multiple (You give a list of options and the user can pick from them). The boolean type is what is needed for this extension.

Option Label
This key defines the text to use in the options panel for the extension. For this extension, the labels KJB and Thai KJV will work.

With these options defined in the plist, a preference panel will be created for editing the preferences. This is what it will look like:

Bible Extension Preferences

Bible Extension Preferences

The Script

Now, the script needs to be written. The full script is:

<?php
//
// Array for converting English Bible book names 
// to thai. Not eloquent, but works.
//
$book = array();
$book['Genesis']='ปฐมกาล';
$book['Exodus']='อพยพ';
$book['Leviticus']='เลวีนิติ';
$book['Numbers']='กันดารวิถี';
$book['Deuteronomy']='เฉลยธรรมบัญญัติ';
$book['Joshua']='โยชูวา';
$book['Judges']='ผู้วินิจฉัย';
$book['Ruth']='นางรูธ';
$book['1Samuel']='1ซามูเอล';
$book['2Samuel']='2ซามูเอล';
$book['1Kings']='1พงศ์กษัตริย์';
$book['2Kings']='2พงศ์กษัตริย์';
$book['1Chronicles']='1พงศาวดาร';
$book['2Chronicles']='2พงศาวดาร';
$book['Ezra']='เอสรา';
$book['Nehemiah']='เนหะมีย์';
$book['Esther']='เอสเธอร์';
$book['Job']='โยบ';
$book['Psalms']='สดุดี';
$book['Proverbs']='สุภาษิต';
$book['Ecclesiastes']='ปัญญาจารย์';
$book['SongofSongs']='เพลงซาโลมอน';
$book['Isaiah']='อิสยาห์';
$book['Jeremiah']='เยเรมีย์';
$book['Lamentations']='เพลงคร่ำครวญ';
$book['Ezekiel']='เอเสเคียล';
$book['Daniel']='ดาเนียล';
$book['Hosea']='โฮเชยา';
$book['Joel']='โยเอล';
$book['Amos']='อาโมส';
$book['Obadiah']='โอบาดีย์';
$book['Jonah']='โยนาห์';
$book['Micah']='มีคาห์';
$book['Nahum']='นาฮูม';
$book['Habakkuk']='ฮาบากุก';
$book['Zephaniah']='เศฟันยาห์';
$book['Haggai']='ฮักกัย';
$book['Zechariah']='เศคาริยาห์';
$book['Malachi']='มาลาคี';
$book['Matthew']='มัทธิว';
$book['Mark']='มาระโก';
$book['Luke']='ลูกา';
$book['John']='ยอห์น';
$book['Acts']='กิจการของอัครทูต';
$book['Romans']='โรม';
$book['1Corinthians']='1โครินธ์';
$book['2Corinthians']='2โครินธ์';
$book['Galatians']='กาลาเทีย';
$book['Ephesians']='เอเฟซัส';
$book['Philippians']='ฟีลิปปี';
$book['Colossians']='โคโลสี';
$book['1Thessalonians']='1เธสะโลนิกา';
$book['2Thessalonians']='2เธสะโลนิกา';
$book['1Timothy']='1ทิโมธี';
$book['2Timothy']='2ทิโมธี';
$book['Titus']='ทิตัส';
$book['Philemon']='ฟีเลโมน';
$book['Hebrews']='ฮีบรู';
$book['James']='ยากอบ';
$book['1Peter']='1เปโตร';
$book['2Peter']='2เปโตร';
$book['1John']='1ยอห์น';
$book['2John']='2ยอห์น';
$book['3John']='3ยอห์น';
$book['Jude']='ยูดา';
$book['Revelation']='วิวรณ์';

//
// Send a GET requst using cURL
// @param string $url to request
// @param array $get values to send
// @param array $options for cURL
// @return string
//
function curl_get($url, array $options = array())
{
    $defaults = array(
        CURLOPT_URL => $url,
        CURLOPT_HEADER => 0,
        CURLOPT_RETURNTRANSFER => TRUE,
        CURLOPT_TIMEOUT => 4
    );

    $ch = curl_init();
    curl_setopt_array($ch, ($options + $defaults));
    if( ! $result = curl_exec($ch))
    {
        trigger_error(curl_error($ch));
    }
    curl_close($ch);
    return $result;
}

//
// Function:          getBibleVerse
//
// Description:      This function is for retrieving a Bible
//                   verse from the api.preachingcentral.com
//                   web site.
//
// Inputs:
//          $verse       The verses to be searched for.
//          $version     The version of the bible to use.
//
function getBibleVerse($verse, $version) {
	global $book;

	$result = "";
	$raw = urlencode($verse);
	$xml = curl_get("http://api.preachingcentral.com/bible.php?passage=$raw&version=$version");
	$xml_parser = xml_parser_create();
	xml_parse_into_struct($xml_parser, $xml, $vals, $index);
	xml_parser_free($xml_parser);

	$first = 0;
	$quote = 0;

	foreach ($vals as $xml_elem) {
		if(strcmp($xml_elem['tag'],"TEXT") === 0) {
			if($quote == 0) {
				$result = $result . ' "' . $xml_elem['value'];
				$quote = 1;
			} else {
				$result = $result . " " . $xml_elem['value'];
			}
		}
		if(strcmp($xml_elem['tag'],"RESULT") === 0) {
			if($first == 0) {
				if(strcmp($version, "thai") === 0) {
					//
					// The site only return book names in English. Translate them
					// to Thai.
					//
					$blist = explode(" ", $xml_elem['value']);
					$bname = '';
					$bver = '';
					if(count($blist) == 3) {
						$bname = $blist[0] . $blist[1];
						$bver = $blist[2];
					} elseif (count($blist) == 4) {
						$bname = $blist[0] . $blist[1] . $blist[2];
						$bver = $blist[3];
					} else {
						$bname = $blist[0];
						$bver = $blist[1];
					}
					$result = $book[$bname] . " " . $bver;
				} else {
					//
					// English is fine here.
					//
					$result = $xml_elem['value'];
				}
				$first = 1;
			} else {
				$result = $result . '"' . "\n\n" . $xml_elem['value'];
			}
			$quote = 0;
		}
	}
	return $result . '"';
}

//
// Get the PopClip Environment variables for the
// extension.
//
$verse = trim(getenv('POPCLIP_TEXT'));
$qKJV = getenv('POPCLIP_OPTION_BIBLEKJV');
$qThaiKJV = getenv("POPCLIP_OPTION_BIBLETHAIKJV");
$keycode = intval(getenv('POPCLIP_MODIFIER_FLAGS'));
$results = "";


//
// If the preference is set to KJV or the command key
// is pressed, then get the verse from the English KJV
// and add it to the result. If both the command key
// and the control key is pressed, then get the KJV also.
//
if(($qKJV[0] == '1')||($keycode == 1048576)||($keycode == 1310720)) {
	$results .= getBibleVerse($verse, "kjv") . "\n" ;
}

//
// If the preference is set to the Thai KJV or the
// control key is press then get the verse from the
// Thai KJV and add it to the result. If both the
// command key and the control key is pressed,
// then get the Thai version also.
//
if(($qThaiKJV[0] == '1')||($keycode == 262144)||($keycode == 1310720)) {
	$results .= getBibleVerse($verse, "thai") . "\n";
}

//
// Anything echoed from the script will be pasted in
// to the top most application by PopClip. If the results
// is nothing, then return the verse.
//
if(strcmp($results,"")===0) {
	echo $verse;
} else {
	echo $results;
}

?>

The first thing in the script is an array of the names of the books in the Bible. This array is for translating the English book names to their Thai equivalent. The web api that the extension uses only gives references in English. So, the English Bible book names needs to be translated to Thai.

The first function is a helper function. It is a PHP routine for requesting information from a web site using curl and returning the results to the calling program. The input is the url of the request.

The second function is the main function for processing the Bible verse. It will request the Bible verse and process the resulting XML to a more readable format for pasting into the text editor or what ever program is currently active. The parameters are the actual Bible verse and the designator for which Bible to request. For the King James Bible, it is kjv. For the Thai Bible, it is thai. You can get other codes from the site link above.


Getting Information From the Environment

PopClip sends information to the script through environment variables. It is a simple way to communicate. This is how you access that information.

//
// Get the PopClip Environment variables for the
// extension.
//
$verse = trim(getenv('POPCLIP_TEXT'));
$qKJV = getenv('POPCLIP_OPTION_BIBLEKJV');
$qThaiKJV = getenv("POPCLIP_OPTION_BIBLETHAIKJV");
$keycode = intval(getenv('POPCLIP_MODIFIER_FLAGS'));
$results = "";

The PHP function getenv() will retrieve the environment variable given in the string for the function call. All of the environment variables are strings and need to be used as such. The different environment variables are:

POPCLIP_TEXT
This variable is the selection when PopClip was invoked. Since the user of the extension could select extra white space, I always like to use the trim() function to remove any extra white space.

POPCLIP_OPTION_BIBLEKJV
This variable is the option about getting the verse from the King James version. It is a string containing the character 1 if true, otherwise it contains the character 0.

POPCLIP_OPTION_BIBLETHAIKJV
This variable is the option about getting the verse from the Thai King James version. It is a string containing the character 1 if true, otherwise it contains the character 0.

POPCLIP_MODIFIER_FLAGS
This tells use what keys were pressed while the PopClip action was selected. Everything passed in an environment variable is a string. Therefore, the strings need to be translated to an easy to use format as well. I use the intval() function to convert the string to an integer.

All the different key code values are shown in the PopClip Extensions GitHub.

As can be seen, every option in the preferences for the extension has it’s own corresponding environment variable.

The $result variable is also set to an empty string for the next two sections to fill up.


Processing the Environment Variables

The main part of any PopClip extension is to take the variables passed in the environment and make something useful with it.

//
// If the preference is set to KJV or the command key
// is pressed, then get the verse from the English KJV
// and add it to the result.
//
if(($qKJV[0] == '1')||($keycode == 1048576)||($keycode == 1310720)) {
	$results .= getBibleVerse($verse, "kjv") . "\n" ;
}

This section of code will fetch the verse from the King James version if it was set in the preferences (the $qKJV variable) or the command key was pressed while selecting the PopClip action ($keycode is 1048576). It will also request it if both control and command keys are pressed ($keycode is 1310720). Since the $qKJV variable is a string that is 1 or 0, you can check for the first character to be a character 1. That way, it does not have to process to a number. That can save some time!

If the condition is true, then the verses are retrieved using the getBibleVerse() function and appended to the $result string.

//
// If the preference is set to the Thai KJV or the
// control key is press then get the verse from the
// Thai KJV and add it to the result.
//
if(($qThaiKJV[0] == '1')||($keycode == 262144)||($keycode == 1310720)) {
	$results .= getBibleVerse($verse, "thai") . "\n";
}

Here, it is similar. If the Thai King James version was selected in the preferences ($qThaiKJV) or the control key was pressed while selecting the PopClip action ($keycode is 262144), then the Thai King James version will be requested. It will also request it if both control and command keys are pressed ($keycode is 1310720).

If the condition is true, then the verses are retrieved using the getBibleVerse() function and appended to the $result string.

//
// Anything echoed from the script will be pasted in
// to the top most application by PopClip. If the results
// is nothing, then return the verse.
//
if(strcmp($results,"")===0) {
	echo $verse;
} else {
	echo $results;
}

Here, the results need to be echoed. But, if the results buffer is empty, then the verse should be echoed. If an empty string is echoed, it effectively deletes what was selected. Since everything is an option, it is possible to get here with the $results variable empty. Good programming practices tells us to always take each possibility into account.


Usage

Once the extension is loaded into PopClip and the preferences are set, then the extension is easy to use. Just select some text that is a Bible reference.

Selecting a verse

Selecting a verse

When the PopClip bar appears, select the white bible and the selection will be changed into the verse. Here, the preferences were set up for both KJV and ThaiKJV versions to be printed.

Replaced Verse

Replaced Verse

If the text does not match the regular expression for a Bible reference, then the Bible icon will not be shown.

Selection not a Verse

Selection not a Verse

This helps to save real-estate on the PopClip bar. Whenever you create an extension, think about how to minimize unnecessary appearances of your extension.


Summary

Now you have a neat little PopClip extension for getting verses from a web site and pasting them in to your application. Even better than that, you now know how to create a preferences panel for your extension, get to that information from your extension, manipulate the selected text, and paste it back into the top most application. You can take this code and expand it or use it as a skeleton for your own PopClip extension. Let everyone know how you use it in the comments!

Advertisement