Ever wanted to programmatically insert something at the cursor in Google Docs (say, a “Sign Here” image) or read the user’s selection (maybe for an on-the-spot translation)? Starting today, you can.
Apps Scripts bound to Google Docs can now access the active user's Cursor and Selection by calling Document.getCursor() and Document.getSelection(), respectively. The returned objects provide useful information like the element the cursor is positioned in and an array of all of the elements contained in the selection.
Document.getCursor()
Document.getSelection()
This Google Doc contains a simple script that uses Apps Script’s Language Service to translate selected text from English to Spanish through a custom menu item.
Here, it uses the getSelectedElements() method of the Selection class to get an array of selected elements:
getSelectedElements()
Selection
var selection = DocumentApp.getActiveDocument().getSelection(); if (selection) { var elements = selection.getSelectedElements();
Next, it loops through each element, performs the translation, and replaces the original text:
var translatedText = LanguageApp.translate( element.asText().getText(), 'EN', 'ES'); element.asText().setText(translatedText);
At Google I/O this year, Apps Script engineer Jonathan Rascher demonstrated Bibstro, a bibliography sample app for Google Docs that inserts inline citations at the cursor. Today, we’re releasing the source code for Bibstro; you can also try it out by making of copy of this Google Doc.
To insert text, the script calls the aptly named insertText() method of the Cursor object:
insertText()
Cursor
var cursor = DocumentApp.getActiveDocument().getCursor(); if (cursor) { // Determine the text of the new inline citation to insert. var citation = bibStrategy.getInlineCitationText(...); var surroundingText = cursor.getSurroundingText().getText(); var surroundingTextOffset = cursor.getSurroundingTextOffset(); if (surroundingTextOffset > 0 && surroundingText.charAt(surroundingTextOffset - 1) != ' ') { // If the cursor follows a non-space character, insert a space // and then the citation. cursor.insertText(' ' + citation); } else { // Otherwise, just insert the citation. cursor.insertText(citation); } }
You’ll also notice that the script uses the Cursor class’s getSurroundingText() method to determine whether to insert a space before the new inline citation.
getSurroundingText()
To help you become familiar with how cursor and selection work, we've also created a Cursor Inspector sample script. As you navigate through a document, the script displays up-to-date information about your cursor or selection in a custom sidebar. We’re also releasing the source code for Cursor Inspector on GitHub.
These new APIs are available immediately. We’re excited to see what kind of scripts you come up with!
Flubaroo, a popular Apps Script application that helps teachers with grading, has just reached version 3.0. The new features and improvements include:
If you know any teachers who aren’t using Flubaroo yet, why not encourage them to try it out? It doesn’t cost a thing, and has helped thousands of teachers save time and gain insight into student performance — all through the power of Apps Script.
Ever look at the data returned when using the Drive API? A files.list call, even if just returning a single file, can yield upwards of 4kb of data. Drive has a rich set of metadata about files, but chances are your application only needs a small fraction of what’s available.
files.list
One of the simplest but most effective optimizations you can make when building apps with the Drive API is limiting the amount of data returned to only those fields needed for your particular use case. The fields query parameter gives you that control, and the results can be dramatic.
A simple example of this is using the files.list call to display a list of files to a user. The naive query, https://www.googleapis.com/drive/v2/files?maxResults=100, generated more than 380kb of data when I ran it against my own corpus. But to render this list nicely, an app only needs a few bits of information -- the document title, icon & thumbnail URLs, the mime type, and of course the file ID.
https://www.googleapis.com/drive/v2/files?maxResults=100
Using the fields query parameter, the results can be trimmed to just the necessary fields and those needed for fetching subsequent pages of data. The optimized query is https://www.googleapis.com/drive/v2/files?maxResults=100&fields=items(iconLink%2Cid%2Ckind%2CmimeType%2CthumbnailLink%2Ctitle)%2CnextPageToken.
https://www.googleapis.com/drive/v2/files?maxResults=100&fields=items(iconLink%2Cid%2Ckind%2CmimeType%2CthumbnailLink%2Ctitle)%2CnextPageToken
After modifying the query the resulting data was only 30k. That’s more than a 90% reduction in data size! Besides reducing the amount of data on the wire, these hints also enable us to further optimize how queries are processed. Not only is there less data to send, but also less time spent getting it in the first place.
Editor’s Note: Guest author Niels Buekers is a Google Apps consultant at Capgemini Belgium. — Arun Nagarajan
During a recent Google Apps migration project, we received several requests to create custom groups of contacts so that users could more easily email frequent collaborators. Before switching to Google Apps, users created their own private distribution lists — but this approach led to overlapping groups that quickly fell out of sync.
The problem was a perfect case for Google Apps Script. We built a great solution that gives users as much power as possible with just a quick administrator review.
The situation before: either manually adding each contact or using a private contacts group.
To start the process, a user adds a specific label to a Gmail message. A script that runs on a timed trigger then generates a request to create a group for all the addresses in the message. The script writes this data to a spreadsheet that tracks group names and administrator approval.
/** * Retrieves all 'group_request' threads and creates a request. */ function processInbox() { // Get threads that have the group_request label. var groupRequestLabel = GmailApp.getUserLabelByName('group_request'); var threads = groupRequestLabel.getThreads(0, 10); // For each thread, retrieve all recipients and create a group request. for (var i = 0; i < threads.length; i++) { var firstMessage = threads[i].getMessages()[0]; var sender = firstMessage.getFrom(); var recipients = []; // Add sender. recipients.push(parseAddresses(sender)); // Add recipients. if (threads[i].getMessages()[0].getTo()) { var toRecipients = parseAddresses(firstMessage.getTo()); recipients.push(toRecipients); } // Add CCs. if (threads[i].getMessages()[0].getCc()){ var ccRecipients = parseAddresses(firstMessage.getCc()); recipients.push(ccRecipients); } // Write all recipients to a cell in the spreadsheet // and send emails to ask for group name and approval. createGroupRequestForRecipients(recipients, Session.getActiveUser().getEmail()); // Remove label from this thread now that it has been processed. threads[i].removeLabel(groupRequestLabel); } };
Once the request has been processed and written to the spreadsheet, the script sends the user an email that asks her to suggest a name for the group in an Apps Script web app. A second email asks the administrator to visit the web app to approve or decline the request. The results are again stored in the spreadsheet.
The spreadsheet contains a second script, which is triggered for each modification. Once the script confirms that the request has been approved, it uses the Apps Script Domain Service to create the new group.
/** * Creates a new group in the Google Apps cPanel with the provided name * and members. */ function createGroupWithAddresses(addresses,groupName){ var group = GroupsManager.createGroup(groupName, groupName, groupName, GroupsManager.PermissionLevel.DOMAIN); var splitAddresses = addresses.split(','); for (var i = 0; i < splitAddresses.length; i++) { Logger.log('Adding ' + splitAddresses[i]); group.addMember(splitAddresses[i]); } };
The result after successfully running the script.
This solution provides a simple way for users to request new Google groups, without all the overhead of manually creating an admin-managed distribution list.
Editor’s Note: Guest author Jason Gordon is a co-founder of Beth Macri Designs — Arun Nagarajan
Beth Macri Designs creates jewelry from the point of view of a structural engineer. The forms are designed using generative 3D software systems and materialized using 3D printing technologies. Our company understands that to make beautiful fine jewelry, 3D printing is only the first step; traditional jewelry craft is then employed for final production. After our first product, The Hidden Message Necklace, was recently featured on The View as part of its Valentine's Day Gift Guide, we had a lot of orders to ship out. As soon as the mail leaves the building, though, the process is literally out of our hands: something unexpected was bound to happen to at least one or two packages. Several package-tracking services exist, but getting the names and tracking numbers into them was a cut-and-paste operation.
I knew that all of the tracking numbers were being delivered by email and I had already set up a Gmail filter to archive them and apply a label. With a little help from Google Apps Script, I knew I could automatically parse those emails and add them to my account on PackageTrackr (which syncs to their newer service, Fara).
The script supports reading emails from multiple shipping providers and is set up so one could easily add more. Every 30 minutes on a time-driven trigger, using the Gmail service, the script runs and looks through unread emails from the shipping provider label, then parses the name and tracking number out of each one. The provider, tracking number, and recipient are stored in a JavaScript array.
function getUSPSConversations(){ return GmailApp.search("in:usps is:unread subject:(Click-N-Ship)"); } function matchUSPSHTML(data){ var out = []; var track_num = data.match( /TrackConfirmAction\Winput\.action\WtLabels\=(\d+)/g); var to = data.match(/Shipped.to.*[\r\n]*.*>([a-zA-Z\s-_]*)<br>/g); for(i in track_num){ var o = new Object(); var track = track_num[i].match(/(\d+)/g); var person = to[i].match(/>([a-zA-Z\s-_]+)<br>/); var myPerson = person[1].replace(/(\r\n|\n|\r)/gm,"") o["number"]=track[0]; o["carrier"]="USPS"; o["person"]=myPerson; out.push(o); } return out; }
You can parse all of your different shipping providers in one run of the script. After all of the shipment emails are read, it composes an email to PackageTrackr to give it all of the tracking numbers it just harvested.
var user = Session.getActiveUser().getEmail(); if(data.length > 0){ for(d in data){ body += this["formatForPackageTrackr"](data[d]["number"], data[d]["carrier"], data[d]["person"]); } GmailApp.sendEmail("track@packagetrackr.com", "Add Packages", body, {bcc: user}); } function formatForPackageTrackr(tracking_num, service, person){ return "#:" + tracking_num + " " + service + " " + person + "\n"; }
Down the line, other shipping providers could be added such as UPS and Fedex. Additionally, more tracking services could be added instead of just PackageTrackr.