Thanks to Albert Retey and Rolf Mertig now we have an easy way to copy code from Mathematica. The source for the code copy palette is below (note that the core code is written by Albert Retey, not me).
Evaluate it to create the palette, pop it out from the notebook, and save it for permanent use with the Palettes -> Install Palette...
menu item. (When you do this, older versions of the same palette will be overwritten.)
The latest version will always be available in this post.
The palette copies code already indented (for pasting as a code block), with output cells commented out.
Please test this palette, evaluate its usability, and post suggestions, ideas, bug reports in the comments below.
PaletteNotebook[
Tooltip[Button["Copy for MSE",
If[MemberQ[Hold[{}, $Failed, NotebookRead[$Failed]],
NotebookRead[SelectedNotebook[]]],
Beep[],
FrontEndTokenExecute[SelectedNotebook[], "CopySpecial", "InputText"];
Map[
CreateDocument[
Cell[BoxData[#], "Code",
Evaluatable -> False, InitializationCell -> False,
Background -> White, CellMargins -> 10],
DockedCells -> Cell[BoxData@ToBoxes@Button["Copy all",
SelectionMove[EvaluationNotebook[], All, Notebook];
FrontEndTokenExecute[SelectedNotebook[], "Copy"]],
"DockedCell"],
WindowTitle -> "Code to copy (from " <> NotebookTools`NotebookName@SelectedNotebook[] <> ")",
Saveable -> False] &,
Cases[NotebookGet@ClipboardNotebook[],
Cell[c_String, ___] :> " " <>
StringReplace[
StringJoin@Riffle[
StringReplace[
StringTrim@StringSplit[c, ("In" | "Out") ~~ "[" ~~ DigitCharacter .. ~~ "]"],
{StartOfString ~~ ":=" ~~ WhitespaceCharacter ~~ input__ :> input,
StartOfString ~~ "=" ~~ WhitespaceCharacter ~~ output__ :>
If[StringFreeQ[output, "\n"],
"(* ==> " <> output <> " *)",
"(*\n==> " <> output <> "\n*)"]
}
],
"\n\n"],
{"\n" -> "\n ",
"\[Pi]" -> "Pi", "\[ExponentialE]" -> "E",
"\[ImaginaryI]" | "\[ImaginaryJ]" -> "I",
"\[UndirectedEdge]" -> "<->",
"\[Infinity]" -> "Infinity"}], Infinity]]
], Appearance -> "Palette"],
"Copy formatted for use on Mathematica.SE", TooltipDelay -> Automatic],
WindowTitle -> "Code Copy", Saveable -> False]
(* ==> 2 x *)
?