287

I might just be lazy, but do you ever find it tiresome to select all the source code from a large post on Stack Overflow to copy it?

I would like a feature, possibly a Firefox extension, but preferably a JavaScript script, for automatically copying source examples to the clipboard. It's no big deal for a small snippet, but a 1000+ line posting is cumbersome to copy.

Do you guys have a better way of copying large source posts? I'm using Firefox 3.5.5 on Windows 7.

24
  • 63
    Even copying 25 lines of code can be annoying sometimes. A simple "Copy" link would be really useful.
    – Noam Gal
    Commented Jul 18, 2010 at 14:36
  • 2
    Cut/paste versus copy button - I'll take a copy button, hands down, for a number of reasons.
    – IAbstract
    Commented Dec 9, 2010 at 12:57
  • Related: “Unformatting” a code block which uses a Greasemonkey script ("pre select") to copy the contents of a pre block.
    – Arjan
    Commented Dec 9, 2010 at 16:30
  • See also File attachments
    – bobobobo
    Commented Dec 9, 2010 at 16:47
  • 5
    When displaying code, it seems it's becoming more and more common on other sites to present the user with a quick option (button) that copies all the code in the code block. I don't understand the reason why stackexchange sites would not also implement this feature?
    – mg1075
    Commented Jul 9, 2011 at 19:04
  • 40
    Getting close to 2 years that this feature-request was submitted - is anyone even looking at this?
    – IAbstract
    Commented Oct 6, 2011 at 16:18
  • On top of this, when you do finally select all and copy it, the code you paste is all unformatted and appear in one line. Is there a way to copy the formatted code with all the spacing?
    – Jay
    Commented Dec 14, 2011 at 18:01
  • 13
    It's not the copying which is a pain, it's the selecting. I've seen a "select" or "select all" button in many other sites which involve source codes, such as JavaScript minifiers and I think either or both of jsfiddle and the YQL console. Scroll-selecting sucks, and it sucks worse on a netbook )-: Commented Aug 12, 2012 at 7:17
  • 2
    So was this idea taken in consideration for future performing? Commented Feb 7, 2013 at 9:39
  • 4
    I love this idea! But why just one button? I've suggested a list of possible buttons: meta.stackexchange.com/questions/169119/code-block-tools Commented Feb 26, 2013 at 13:01
  • @PeterAjtai 2 whole extra seconds while answering questions is a quite reasonable argument
    – X.Jacobs
    Commented Mar 24, 2013 at 11:12
  • 3
    How can we bump this feature request so it gets a final answer? I also would like to have such a button and the implementation is probably easy to do. So, why isn't it there already (after 4 years since this request came up)? Commented Mar 9, 2014 at 10:18
  • 3
    @MikeLischke "How can we bump this feature request so it gets a final answer?" It seems like there was nothing we could do to bump this feature enough. However, a final answer wasn't really needed, just not implementing the feature for many years and not putting a status on it either is also an answer I would say. Commented Jun 10, 2020 at 10:51
  • 2
    It has been over a decade since this question was asked. We had some pushback when I first answered back in '10. Will anyone put this thing on the ToDo list?
    – IAbstract
    Commented Jan 27, 2021 at 22:18
  • 3
    @IAbstract you mean over 12 years. And I bet we'll be here in 8 years as well, and it won't be done yet. ;-) Commented Nov 2, 2022 at 12:59

21 Answers 21

144
+450

I think something along these lines would be an excellent option:

a copy button above right corner in code block

Having a copy button means:

  • I get all the text in the code block
  • I don't have to click/drag the full length of the text
  • Automatically copied to clipboard

I don't know why people would be against this small piece of added functionality. It makes sense to have a copy button. I certainly don't expect this comfort control to take priority but an official word on whether it will be considered would be nice.

Update & Alternative
I have learned that this functionality simply will not be implemented due to security concerns.

An alternative that I would not mind having would be an "Email me teh codez" button. One click, done! Now I have a somewhat permanent record of the code which I can organize in mail folders and copy at any time.

21
  • 25
    I must be honest, the button is so 90's, but the idea is good. Commented Feb 5, 2012 at 14:51
  • 2
    I couldn't agree more ...but there is a certain convenience about it.
    – IAbstract
    Commented Feb 5, 2012 at 23:09
  • 3
    Copying code (especially long ones) from SO is a pain the ass!!! Commented Jan 1, 2013 at 4:42
  • The button could appear only if the mouse hovers near the right-top of a code block. By the way, I'm not sure if it's technically possible to place code on the clipboard in a clean way. As I remember, you had to abuse a Flash control, which would be a no-go for any sane website.
    – Andomar
    Commented Feb 7, 2013 at 10:27
  • 1
    ZeroClipboard seems to do a nice job of abstracting the actual "copy to clipboard" code. Commented Feb 25, 2013 at 22:52
  • I agree with Camilo Martin lol! It's definitely possible with pure js @Andomar as Syntax Highlighter does it: code.google.com/p/syntaxhighlighter
    – Adam B
    Commented Feb 26, 2013 at 5:24
  • 2
    FWIW, I agree. We were just having a discussion in chat.stackexchange.com/rooms/41/tex-latex-and-friends about the pros and cons of adding various plugin features. The proposer noted that latex-community.org/forum/viewtopic.php?f=37&t=22340 has them -- but it starts with the "copy" feature. In short this might open a can of worms but that could be powerful/cool. Commented Mar 7, 2013 at 0:06
  • @Shimmy: There shouldn't be any "long ones". Commented Jul 18, 2013 at 9:22
  • @LightnessRacesinOrbit, U got my vote, but I said sometimes. There are those who paste in huge code with no source. Commented Jul 19, 2013 at 12:49
  • 1
    @Shimmy: Those posts should be downvoted and then deleted. Commented Jul 19, 2013 at 12:52
  • 3
    I completely disagree. Sometimes they are useful, just not formatted the right way. Commented Jul 19, 2013 at 15:49
  • 3
    What kind of security concerns? Any source for that?
    – Stijn
    Commented Jul 4, 2014 at 14:11
  • @Stijn: since the copy functionality must copy to the client clipboard, there are security concerns. I can't recall the details that I was given specifically.
    – IAbstract
    Commented Jul 5, 2014 at 6:49
  • 3
    Can this be done now in 2020 atleast? Are there still security issues? Commented Jun 30, 2020 at 12:25
  • 4
    Even if there is security issue for Copy button then at least it should be no security issue to make Select All button, copying selected text ourselves is trivial.
    – Arty
    Commented Jan 11, 2021 at 8:51
40

Simple and unobtrusive. ZeroClipboard and sytaxhighlighter both seem to do a nice job of abstracting the actual "copy to clipboard" code.

copy box

36

There are some cases in which all the code is in one line and is very long like answers to this post. These lines are hard to copy, and it would be nice to have a Copy code button.

4
  • CTRL+C works fine. I believe the line breaks must have been added by the original poster, because by default you will get a horizontal scrollbar instead.
    – bobobobo
    Commented Dec 9, 2010 at 16:50
  • Why add breaks? You should be able to copy from the IDE and have the line breaks added automatically or propertly formatted or if it is no posible then the line breaks are ok. Similarly you should be able to copy code from an answer or question in an easy way. Commented Dec 11, 2010 at 5:19
  • @bobobobo: CTRL+C might work fine, the issue is with the selection of the code sample block; not always easy to get right, especially with long code blocks.
    – casperOne
    Commented Aug 11, 2011 at 13:14
  • 6
    If you're finding it difficult to select an entire line because it's so long, just triple click and it'll select the entire line.
    – JBurace
    Commented May 30, 2012 at 14:32
22

I don't understand people's aversion to usability. (Looking over some of the Q&A on MSO, it seems like some people have an aversion to any kind of change.)

Code snippets don't have to be 1000+ lines to create a vertical scrollbar. Worse still are code snippets on one long line with a horizontal scrollbar. Those are a real pain to copy.

How can anything that makes things a little easier be a bad thing? Today, it should be fairly simple to implement in jQuery. SE already uses jQeury anyway. I think it's worth looking into.

7
  • 2
    The thing is that you would have to add the clutter of an additional UI element for relatively little gain. As long as copying code is just a bit hard (and not impossible, say, through line numbers) I'm opposed to adding this
    – Pekka
    Commented Sep 16, 2011 at 10:01
  • 8
    But it's a fairly standard UI element for code snippits. I'd hardly call it clutter.
    – Herbert
    Commented Oct 12, 2011 at 9:01
  • 5
    It would be no more clutter than the Share|Edit|Flag links. This is such as basic and useful feature that is very standard on many coding sites and should be there on Stack Overflow. Commented Feb 15, 2013 at 12:48
  • 1
    @Herbert: Changing software is not the default action. It's not a general aversion to any change -- it's that you need to present a solid use case for spending expensive man hours implementing a new software feature, and that has not been done here. Commented Jul 18, 2013 at 9:24
  • Copying and pasting code out of answers is an uncommon scenario. And in the case it's not, we'd like to discourage copy-and-paste programming.
    – Cody Gray
    Commented Aug 4, 2013 at 10:29
  • 2
    @LightnessRacesinOrbit I disagree about man hours, that's ridiculous. The number of man hours that were spent on less useful SO features go way beyond what it would take to add this. When a suggestion gets 148 upvotes on a meta site, and you still see some categorical yet unexplained "no"s, that's called stubbornness.
    – Oliver
    Commented Apr 24, 2014 at 5:19
  • @Schollii: Not everybody agrees with you that this should be done. "Less useful SO features" is subjective and debatable. Commented Apr 24, 2014 at 9:19
19

I'd like to see the copy feature as well. I do more answering than questioning - and a lot of the PHP questions that I look at are written by newer users. They aren't familiar with the culture and have a tendency to post blocks of code followed by "what did I do wrong?" For these scenarios, it's often much easier to copy into an IDE and take a look at it the way I would look at my own code. (Especially if the lines extend past the codeblock width.)

SO shouldn't be a snippet site, but it is devoted to helping coders share knowledge. Such a feature facilitates that transaction.

17

I can't understand why people would object to taking one single click (to select all and copy) instead of many steps (as Shog9 suggested).

And w.r.t. Ether's answer, I don't think it matters how many lines of code you want to copy. I'd say it's particularly painful if there are only a few lines.

I've run into many sites with "copy code" button. phpBB has Select All.

2
  • 2
    Selecting a block of text and hitting control/command-C is "painful"?
    – Ether
    Commented Sep 17, 2010 at 16:22
  • 7
    Infinitely more painful than hitting one "Copy Code" button? YES. More painful than being stuck at 11 rep? NO. Commented Sep 22, 2010 at 14:14
12

I struggle with the same thing so I decided to create a browser extension that adds a copy to clipboard button on every code snippet.

It works with all StackExchange sites, including StackOverflow.

If you're interested, you can use it on Chrome or Firefox.

preview

The source code is available on GitHub.

2
  • 1
    The Chrome link is broken so here's another.
    – Shub
    Commented Mar 10 at 9:56
  • @Shub does it only function on StackOverflow?
    – raf
    Commented Jun 23 at 13:17
10

Select code block buttons.

H.B. on StackApps has written a script to do exactly this.

A user-installable script lets anyone who wants this feature have it without running afoul of any of the objections raised in other answers.

See also this question for some further discussion of similar tools.

8

The Stack Overflow Extras (SOX) userscript includes this feature, along with loads of other useful enhancements.

The setting is called "Add a button to code in posts to let you copy it".

Here's what it looks like:

enter image description here

Just click the button to save the code to your clipboard.

You'll need to install Tampermonkey (Chrome, Microsoft Edge, Safari, Opera Next, and Firefox) or Greasemonkey (Firefox) first (see above link for details).

6

I really would like this feature, and it would make it easy to test out code.

Like today, I wanted to copy the following:

enter image description here

1
  • 1
    For single-line code: just double-click it to select-all.
    – Alex
    Commented Aug 12, 2016 at 23:39
3

If all those "selecting" and "clipboard" functions are not possible/secure, then what about a simple link to the raw content, just like GitHub does?

Enter image description here

The "raw" button links to a new page that contains the code snippet as plain text. This allows to save or copy/paste it easily.


Disclaimer: I'm no UX expert ;)

1
  • 1
    By now on GitHub there is a copy button for every code chunk in the issue comments. Commented Sep 10, 2021 at 13:12
3

Actually, I've created a chrome extension to solve exactly this problem. You can try it here.

Basically, whenever you double click a code snippet, it's automatically copied to your clipboard.

enter image description here

3

The two people who said no, gave the following reasons:

  • Security concern
  • Ethically unpleasant

One alternative that would take care of both of them: override codeblock behaviour to select-all text within that codeblock when double-clicked.

This way, there is no additional button to be ethically unpleasant; and since you have to press CTRL+C manually, it is not a security concern.

2

If there is so much source code in a question that it is onerous to copy it, and especially that you feel a need to paste it all in your response, then both the questioner and you the answerer are doing things wrong. There is rarely a need for a huge amount of source, and you shouldn't have to repeat it in your response. If you do, I figure you deserve to go through a few extra steps to do so. It's not something we want to encourage.

2
  • 16
    I shudder to think that he's not copying a huge block of code to paste it into a response, but into his IDE. Commented Sep 17, 2010 at 15:38
  • 6
    I don't think the primary purpose of the copy button is to simply copy question code blocks to a response. It would be for copying code snippets to clipboard and pasted in an editor.
    – IAbstract
    Commented Dec 9, 2010 at 13:11
2

Do you guys have a better way of copying large source posts?

One of my primary use cases is to download C++ code directly to a file so that I can compile it and try to reproduce the problem. So I wrote this simple one-liner to download code blocks from questions:

curl -sL https://stackoverflow.com/q/11227809/72178|xmllint --html --xpath "(//pre/code)[1]/text()" - 2>/dev/null|recode html..ascii

The code block number can be specified in square brackets in an XPath expression. For me I find this more useful than a "Copy" button. Here are examples of a one-liner in action for Why is it faster to process a sorted array than an unsorted array?.

First code block:

[ ~]$ curl -sL https://stackoverflow.com/q/11227809/72178|xmllint --html --xpath "(//pre/code)[1]/text()" - 2>/dev/null|recode html..ascii
#include <algorithm>
#include <ctime>
#include <iostream>

int main()
{
    // Generate data
    const unsigned arraySize = 32768;
    int data[arraySize];

    for (unsigned c = 0; c < arraySize; ++c)
        data[c] = std::rand() % 256;

    // !!! With this, the next loop runs faster
    std::sort(data, data + arraySize);

    // Test
    clock_t start = clock();
    long long sum = 0;

    for (unsigned i = 0; i < 100000; ++i)
    {
        // Primary loop
        for (unsigned c = 0; c < arraySize; ++c)
        {
            if (data[c] >= 128)
                sum += data[c];
        }
    }

    double elapsedTime = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;

    std::cout << elapsedTime << std::endl;
    std::cout << "sum = " << sum << std::endl;
}

Second code block:

[ ~]$ curl -sL https://stackoverflow.com/q/11227809/72178|xmllint --html --xpath "(//pre/code)[2]/text()" - 2>/dev/null|recode html..ascii
import java.util.Arrays;
import java.util.Random;

public class Main
{
    public static void main(String[] args)
    {
        // Generate data
        int arraySize = 32768;
        int data[] = new int[arraySize];

        Random rnd = new Random(0);
        for (int c = 0; c < arraySize; ++c)
            data[c] = rnd.nextInt() % 256;

        // !!! With this, the next loop runs faster
        Arrays.sort(data);

        // Test
        long start = System.nanoTime();
        long sum = 0;

        for (int i = 0; i < 100000; ++i)
        {
            // Primary loop
            for (int c = 0; c < arraySize; ++c)
            {
                if (data[c] >= 128)
                    sum += data[c];
            }
        }

        System.out.println((System.nanoTime() - start) / 1000000000.0);
        System.out.println("sum = " + sum);
    }
}
2

Considering all of the source code is wrapped around a <pre><code> block, I suspect it would be easy enough to write a Greasemonkey snippet to find those code blocks and copy them to the clipboard for you.

Or similarly, I've been using EverNote as of late and I've found that highlighting the code in a question/answer and then hitting CTRL+ALT+V will grab the selected text and put in into a new note entry for me. Then I can easily take it where I need it.

3
  • 5
    As you have stated it is easy enough. Easy enough for the dev team at stackexchange to implement it. Commented Sep 26, 2010 at 18:02
  • It's not that easy, because unless you get to it before the prettyprint script, the code as a simple block of text is no longer there...
    – Benjol
    Commented Dec 9, 2010 at 13:43
  • See “Unformatting” a code block which uses a Greasemonkey script ("pre select") to copy the contents of a pre block, but shows that this needs some tweaking to get rid of the Google Prettify stuff.
    – Arjan
    Commented Dec 9, 2010 at 16:31
2

For now, use Click Copy {Code}. It's a Chrome extension that simplifies your workflow by copying the content of code blocks on any website with a double-click. Check out the project's source on GitHub: Click-Copy-Code.

1

What about something along the lines of how LaTeX-Community.org allow users to open code in writeLaTeX (an online collaborative LaTeX editor/compiler)? For details and examples of how it works, see the announcement:

http://latex-community.org/forum/viewtopic.php?f=37&t=22340

This type of integration has been proposed for TeX SX, and with the recent integration of CircuitLabs into Electronics SX, it seems like there are some precedents (and models) for how this could work.

1
  • I should add that I'm one of the developers at writeLaTeX, so happy to discuss how we could work on an integration along these lines for SX Commented Mar 7, 2013 at 0:19
0

If you are struggling to select all of the code in a question/answer then the correct action is to EDIT THE POST to remove the extraneous code. There should never be so much code in a post as to pose a useability problem.

Adding auto-copy functionality will promote behemothic walls of crappy code that we simply do not want.

0
-2

Nah. Jeff specifically said somewhere on his blog that SO was not for posting "huge swathes of code." And how.

What code blocks should be is 1. easy to highlight with the mouse and CTRL+C, which they are. As you can see:

Code code code
Oh more code

The other part is 2: when you paste it somewhere, annoying line numbers don't spill into your code which so far, doesn't happen.

I'd say SO has got codeblocks right, and they shouldn't be touched. I'd shudder if they ever look like the code blocks here.

I've always hated the "copy" button on sites that sites have, mostly for the reason if you can write to my clipboard, you also read it. And people don't usually like that. See the need for Flash to do this.

5
  • 2
    I would hope that line numbers would not be inserted. In addition, does MSDN use flash to copy code snippets from it's site? I don't believe Flash is the only way for this to be worked out.
    – IAbstract
    Commented Dec 9, 2010 at 17:50
  • The above example works but copying and pasting doesn't work with context colored code samples in IE8. It does work in Chrome. In IE8 the samples are pasted all in one line. See this code sample stackoverflow.com/questions/4308828/…
    – Ed Greaves
    Commented Jun 2, 2011 at 14:48
  • 3
    I actually love the code blocks you linked, shudderingly, to :)
    – sehe
    Commented Jul 4, 2011 at 13:45
  • 1
    can't find ctrl-c on my iPad... :(
    – cormullion
    Commented Aug 19, 2012 at 9:54
  • 1
    Hold your finger down and select "Copy".
    – bobobobo
    Commented Oct 8, 2012 at 15:07
-3

Do you guys have better way of copying large source post?

Edit -> Select all -> Copy -> Paste -> Edit out non-source portions.

But then, the only time I'm copying 1000+ line posts is to edit them anyway. That's really a bit much for SO...

7
  • I want to respond this: Suggestion to implement a Copy To Clipboard button on the code snippet inclusion tag You misunderstood what I mean in my request to implement a "COPY to Clipboard" button. Commented Dec 23, 2010 at 22:34
  • The purpose is to ease testing process when somebody answers with code inclusion. It is very useful in tex.stackexchange.com. There we intensively provide minimal code snippet for testing purpose. For the production, adjustment might be needed. Commented Dec 23, 2010 at 22:41
  • EDIT->Select All ->Copy -> Paste will not work because if you choose Select All, the whole page get highlighted. You need to copy the whole page including the banner, related links, and other unnecessary things? Commented Dec 23, 2010 at 22:43
  • 2
    @xport: the point of the edit step is to allow you to select all within the textbox - that is, just the text of the post itself, not the page chrome. And again, if someone's posting 1K LoC, there is no "easy" solution - that's quite a few pages of code, far too much to even comprehend without at least a bit of time invested. Worrying about a few extra clicks to get it into your clipboard seems a bit like complaining that you have to walk all the way to the end of the pier before swimming across the Atlantic...
    – Shog9
    Commented Dec 23, 2010 at 23:52
  • How to SELECT ALL a single code snippet region (or textbox in your terminology) that a person submit in his/her answer? Commented Dec 24, 2010 at 0:42
  • Double the killer delete select all
    – bobobobo
    Commented Aug 19, 2012 at 13:52
  • Maybe time to reject this poor feature request then and bring it to eternal rest? :) Commented Nov 19, 2013 at 7:54

You must log in to answer this question.