Is there a shortcut to make a block comment in Xcode?

XcodeComments

Xcode Problem Overview


I'm writing ANSI-compatible C code, and hence I can't use the line (//) comment. I'm using Xcode. In Sublime Text and Eclipse, and I think most other IDEs, there are separate keyboard shortcuts for line comments and block comments (/**/). However, I don't see that in Xcode - in fact, I don't even see a menu option to add a block comment. Is it simply not supported in Xcode? That would certainly seem to be a lame decision if so.

Xcode Solutions


Solution 1 - Xcode

Try command + /.

So, you just highlight the block of code you want to comment out and press those two keys.

Solution 2 - Xcode

UPDATE Xcode 12 / macOS Big Sur:

Currently the Mac App Store version of the BlockComment for Xcode doesn't show up under Xcode > Preferences > Key Bindings. This issue has been resolved and GitHub version can be used instead.

UPDATE June 2017:

Since I was lazy, and didn't fully implement my solution, I searched around and found BlockComment for Xcode, a recently released plugin (June 2017). Don't bother with my solution, this plugin works beautifully, and I highly recommend it.

ORIGINAL ANSWER:

None of the above worked for me on Xcode 7 and 8, so I:

  1. Created Automator service using AppleScript

  2. Make sure "Output replaces selected text" is checked

  3. Enter the following code:

    on run {input, parameters}
    return "/*\n" & (input as string) & "*/"
    end run
    

enter image description here

Now you can access that service through Xcode - Services menu, or by right clicking on the selected block of code you wish to comment, or giving it a shortcut under System Preferences.

Solution 3 - Xcode

Now with xCode 8 you can do:

+ + /

to auto-generate a doc comment.

Source: https://twitter.com/felix_schwarz/status/774166330161233920

Solution 4 - Xcode

There is now an Xcode plugin that allows this: [CComment][1].

The easiest way to install this is to use the amazing [Alcatraz plugin manager for Xcode][2].

EDIT Apple has sadly (and wrongly, IMHO) retired the old plugin model with Xcode 8. The new plugin system is quite limited, but should allow development of a plugin like this again. For anyone interested in doing this, watch [WWDC 2016 session 414][3]. Also, please [file radars][4] for API for plugins you'd like to write or see.

[1]: https://github.com/flexih/Xcode-CComment "CComment" [2]: http://alcatraz.io/ [3]: https://developer.apple.com/videos/play/wwdc2016/414/ [4]: https://bugreport.apple.com/

Solution 5 - Xcode

UPDATE: Xcode 8 Update

Now with xcode 8 you can do:

+ + /

Note: Below method will not work in xcode version => 8

Very simple steps to add Block Comment functionality to any editor of mac OS X

  1. Open Automator
  2. Choose Services
  3. Search Run Shell Script and double click it

> Add the below applescript in textarea

awk 'BEGIN{print "/*"}{print $0}END{print "*/"}'

apple script for block comment

  1. Save script as Block Comment

> Add a keyboard shortcut

Open System Preference > Keyboard > Shortcuts, add new shortcut by clicking + and right the same name i.e. Block Comment as you given to applescript in the 4th step. Add your Keyboard Shortcut and click Add button.

New keyboard shortcut

Now you should be able to use block comment in Xcode or any other editor, select some text, use your shortcut key to block comment any line of code or right click, the context menu, and the name you gave to this script should show near the bottom.

Solution 6 - Xcode

It looks that on macOS Monterey the Xcode block comment toggle key combination has been changed to command ⌘ + '

Edit: Xcode 13.2 has returned to the previous key combination. command ⌘ + + 7

Solution 7 - Xcode

I modified the code of Nikola Milicevic a little bit so it also remove comment block if code is already commented:

on run {input, parameters}
	repeat with anInput in input
		if "/*" is in anInput then
			set input to replaceText("/*", "", input as string)
			set input to replaceText("*/", "", input as string)
			
			return input
			exit repeat
		end if
	end repeat
	return "/*" & (input as string) & "*/"
end run

on replaceText(find, replace, textString)
	set prevTIDs to AppleScript's text item delimiters
	set AppleScript's text item delimiters to find
	set textString to text items of textString
	set AppleScript's text item delimiters to replace
	set textString to "" & textString
	set AppleScript's text item delimiters to prevTIDs
	return textString
end replaceText

Hope this will help someone.enter image description here

Solution 8 - Xcode

In XCode 10 (and up) use Option + Command + Slash (that is ⌥ + ⌘ + /)

to write a beautiful comment for your function or class like below:

XCode screenshot of doc comment

Solution 9 - Xcode

You can assign this yourself very easily, here goes a step by step explaination.

1.) In you xCode .m file type the following, it does not matter where you type as long as it's an empty area.

/*
*/

2.)Highlight that two lines of code then drag and drop onto 'code snippet library panel' area (it's at the bottom part of Utilities panel). A light blue plus sign will show up if you do it right.

enter image description here

3.) After you let go of your mouse button, a new window will pop up and will ask you to add name, short cut etc; as shown. As you can see I added my shortcut to //. So every time I want a block comment I will type //. Hope this helps

enter image description here

Solution 10 - Xcode

i managed to get this working well via an automator task and have used shortcut to bind it to key combination ctrl+option+command+b. all i have to do is highlight the code i want block commented in xcode and press the above keys and the selected text is block commented out using /* ... */.

i use code folding a fair bit so the reason i wanted this functionality was so i could easily fold down a block of commented code ... code commented the usual way using // wont fold.

im not familiar with using mac automator but i simply followed the instrux in the following wwdc video

in the WWDC 2012 video Session 402 - Working Efficiently with Xcode ( from around 6 minutes in) there's a description of how to use the Mac OSX Automator to add a service to manipulate selected text. The example shown in the video is to remove duplicates in a selection of text using the shell commands sort and uniq. Using this approach you do the same but you enter the following command instead of what he does in the video

awk 'BEGIN{print "/"}{print $0}END{print "/"}'

(note there are meant to be 2 asterisks in the previous line that for some reason are not showing .... they do show up in the screenshot below so copy that as the correct command to enter)

you should end up running a shell script like this

screenshot

this will, for any given selected text, put the comment delimiters before and after.

when you save it you should get options to name it (i called it blockcomment) and also to assign a keyboard shortcut

then you should be able to open xcode, select some text, right click, the context menu, and the name you gave to this script should show near the bottom

simply click the name and the script will run and block comment the selected code or use the keyboard shortcut you assigned.

hope this helps

Solution 11 - Xcode

If you have a keyboard layout that requires you to also press the shift key (i.e. cmd + shift + 7 on a German keyboard), the shortcut won't work and open the help menu, instead.

Apple's "Think Different" in its fullest extent ...

You can define your own shortcut to make it work, if you go to Xcode > Preferences > Key Bindings:

Changing comment selection key map in Xcode

Solution 12 - Xcode

Based on Baig's reply, I created a shortcut to comment and uncomment part of a line. This works on Xcode 13.2.1 and MacOS 12.0.

  1. Open Automator
  2. select Quick Action
  3. Search for Run AppleScript
  4. Select text on Workflow receives current dropdown
  5. Check Output replaces selected text
  6. Add this script
on run {input, parameters}
	set s to (input as string)
	if s contains "/*" then
		return text 3 thru -3 of s
	else
		return "/*" & s & "*/"
	end if
end run
  1. Tap play and save as Block Comment
  2. On Settings -> Keyboard -> Shortcuts, select App Shortcuts and tap +
  3. Use title of script as Menu Title (ie "Block Comment")
  4. Choose desired shortcut (I did command+option+shift+/)
  5. On Xcode select text to comment and press shortcut keys
  6. To uncomment, select text from /* to */ and press shortcut keys

Solution 13 - Xcode

Cmd + Shift + 7 will comment the selected lines.

Solution 14 - Xcode

There is a symbol before help menu on xcode which has Edit user script. On Un/Comment Selection under comments section change my $cCmt = "//"; to my $cCmt = "#"; or whatever your IDE works with. Then by selecting lines and command + / (It's my xcode default) you can comment and uncomment the selected lines.

Solution 15 - Xcode

@Nikola Milicevic

Here is the screenshot of the indentation issue. This is very minor, but it is strange that it seems to work so well, in your example visual.

I am also adding a screenshot of my Automator set-up...

Thanks

enter image description here

enter image description here

Update:

If I change the script slightly to:

enter image description here

And then select full lines in XCode, I get the desired outcome:

enter image description here

enter image description here

Solution 16 - Xcode

If you're looking a way to convert autogenerated comment from Add Documentation action (available under cmd-shift-/) you might find it useful too:

function run(input, parameters) {
  var lines = input[0].split('\n');
  var line1 = lines[0];
  var prefixRe = /^( *)\/\/\/?(.*)/gm;
  var prefix = prefixRe.test(line1) ? line1.replace(prefixRe, "$1") : ""
  
  var result = prefix + "/*\n";  
  lines.forEach(function(line) {
    result += prefix + line.replace(prefixRe, "$2") + '\n';
  });
  result += '\n' + prefix + ' */';
  return result;
}

Rest the same as in @Charles Robertson answer:

Automator

Services

Solution 17 - Xcode

in Macbooks, you can use shift + cmd + 7 to comment a previously highlighted block

Solution 18 - Xcode

In xcode 11.1 swift 5.0

select the code you would like to add block comment then press + + /

enter image description here

Solution 19 - Xcode

Seems like already a lot of people answers this question.

in Swift 3.0, single line comment is to put double forward slashes upfront : "//" ; multiline is put "/* .... */".

Hope this helps.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionlimp_chimpView Question on Stackoverflow
Solution 1 - XcodeStefan VasiljevicView Answer on Stackoverflow
Solution 2 - XcodeNikola MilicevicView Answer on Stackoverflow
Solution 3 - XcodeBeninho85View Answer on Stackoverflow
Solution 4 - XcodefzwoView Answer on Stackoverflow
Solution 5 - XcodeBaigView Answer on Stackoverflow
Solution 6 - XcoderockdaswiftView Answer on Stackoverflow
Solution 7 - XcodeA. BukshaView Answer on Stackoverflow
Solution 8 - XcodeParas GuptaView Answer on Stackoverflow
Solution 9 - XcodeOhmyView Answer on Stackoverflow
Solution 10 - XcodelozflanView Answer on Stackoverflow
Solution 11 - XcodeMartin BraunView Answer on Stackoverflow
Solution 12 - XcodeDiogo SouzaView Answer on Stackoverflow
Solution 13 - XcodeJulioView Answer on Stackoverflow
Solution 14 - XcodeFatiView Answer on Stackoverflow
Solution 15 - XcodeCharles RobertsonView Answer on Stackoverflow
Solution 16 - XcodeDaniel BaukeView Answer on Stackoverflow
Solution 17 - XcodeArthur C. ClarkeView Answer on Stackoverflow
Solution 18 - XcodeAshim DahalView Answer on Stackoverflow
Solution 19 - XcodeDil AzatView Answer on Stackoverflow