Create an automator service for commenting selected code segment

At first my intention was to create an Xcode plugin that helps to comment a selected code segment with C style comment(like /*…*/) with some shortcuts. In current versions of Xcode, if we select a segment and press ⌘ + / then Xcode will comment the selected code segment with // in front of each line. Well, this is easy.. But not so clean, isn’t it? I think So, because if you comment a large number of lines together by putting // in front of each line, it is impossible to fold the commented code. But if you comment with /* … */, its possible to fold the commented code segment.

Ok… lets create an automator service for this. And you can assign  shortcut keys for this service. As a result you can use this service very easily.

Lets Start…

  • Open up automator and select New from file or press ⌘ and N keys together.
  • From the dialogue select service(See screenshot)

Select sevice

  • Then you can see a screen like followingScreen Shot 2014-09-08 at 11.52.27 am
    change the following entries in the window
  1. Service receives selected text – leave as is, because we are working on texts
  2. in Xcode (select other from the drop down and browse application folder then select Xcode) – we need our service only in Xcode
  3. Check the option output replaces selected text
  • Then add a Run Shell script from left actions area(you can search in the box for shell script), in that script area
  • Change the Pass input drop down to as arguments 
  • Change text in the script editor to echo "/*$@*/"
  • Save the service and click on play button.
  • Now switch to Xcode and select a portion of code then right click on it then the context menu may either like thiscontext menu 2                  Context menu 1

Thats it you have done it.

Lets assign a key shortcut to this service.

  • Open System Preferences
  • Select Keyboard preferences > Click  on Shortcuts tab > Then select services (See screenshot)Service Keyboard shortcut
  • Scroll to our service and click on add shortcut then press they keys that you like.

And… I know this service has lot of limitation from a user/developer perspective. This is just an example tat illustrates how you can make a Mac OSX service with automator. You can improve/extend the functionalities if you know shell script very well.