How do Ctrl+C and Ctrl+V work?

99

17

I was always wondering what happens under the hood (in the operating system) when I copy an image (selecting it and using Ctrl+C) into a Word file (pasting it with Ctrl+V), for example.

Inter Sys

Posted 2019-05-14T10:51:21.297

Reputation: 589

42What level of detail do you expect? – user1686 – 2019-05-14T11:49:55.780

11

Let begin with this https://docs.microsoft.com/en-us/windows/desktop/dataxchg/clipboard.

– Biswapriyo – 2019-05-14T11:58:10.570

4@Biswapriyo doesn't linux also support this kind of functionality? grawity: I said in terms of operating systems, I guess the information is stored in a temporary pipe? I'm more intrigued with images, how can they be copied so easily – Inter Sys – 2019-05-14T12:04:21.513

6@InterSys: Indeed, this differs a lot between different operating systems. The link given by Biswapriyo gives the details on the Microsoft Windows platform. – Andreas Rejbrand – 2019-05-14T14:20:01.200

1@InterSys BTW, if providing additional details about your question, you may/should incorporate them into a question itself if you consider them vital; comments can/will be pruned occasionally by mods, so the information you provided there are often lost. – None – 2019-05-15T13:42:10.627

The question is horribly nebulous, but attracted an excellent answer, which demonstrates that it can be well-answered with an in-scope answer. Voting to reopen only to ensure that the answer is preserved. – fixer1234 – 2019-05-17T23:17:47.193

Answers

163

In Windows, the clipboard API and storage buffer are provided by the OS at kernel level. (The clipboard belongs to the "window station" kernel object.)

  • Ctrl+C tells the program to store the "copied" data using the Win32 API function SetClipboardData(), which also corresponds to NtUserSetClipboardData() in the Native API.

    Normally, the copied data is immediately stored in the OS-managed clipboard buffer and no longer depends on the source program. The program can provide several different formats – e.g. text copied from MS Word can come in HTML, RTF, and plaintext formats simultaneously.

    (However, the program may store 'null' data and defer conversion until a paste is requested using WM_RENDERFORMAT. In this case data is lost when the program is closed. I'm not sure how common this method is.)

  • Ctrl+V tells the program to choose the desired format and retrieve it using GetClipboardData(). Some programs, e.g. WordPad or Paint, have a "Paste as" feature that lets you choose the preferred format (e.g. if you copied HTML but don't want formatting).

  • See also "NT Debugging: How the clipboard works" blog post.

In Linux, there is no system-wide clipboard, instead it is provided by whatever graphical environment you're using (that is, X11, Wayland, none):

In X11 (not necessarily limited to Linux), clipboard transfer is deferred. That is, the storage is provided by the 'source' program. The exchange is done via X11 messages according to the ICCCM protocol (therefore the clipboard is isolated to the X server):

  • Ctrl+C tells the source program to reserve the "copied" data in its own memory, and to claim the X11 selection called 'CLIPBOARD'. This is done using XSetSelectionOwner(), and the ownership is tracked by the X server (Xorg).

    If you had copied something previously, the previous selection owner is informed about this and discards the now-unneeded data.

    If you close the program, the copied data is lost. (Clipboard managers can be used to avoid this by watching and duplicating the current selection.)

  • Ctrl+V tells the destination program to look up the current owner of the 'CLIPBOARD' selection using XGetSelectionOwner(), then directly asks it for the preferred type using XConvertSelection(). The source program then returns the data via another X11 message, converted on-demand to the type that was requested. (There is also a special type which returns a list of possible types.)

  • See this link for a practical example.

(Note: When you "copy" text by selecting it and paste it using middle-click, the mechanism is the same but the 'PRIMARY' selection is used instead. This is where the term 'X11 selection' comes from.)

In Wayland – I don't actually understand how it works, all I have is the protocol docs:

Traditional text editors (Vim, emacs, nano) often have their own internal clipboards (aka registers/killrings). They might, or might not, also integrate with the X11 clipboard.

In macOS, something called a "pasteboard server" appears to be used (which I think means that programs communicate with it through Mach APIs). Other than that, it behaves like the Windows clipboard and stores the currently copied data itself.

I'm more intrigued with images, how can they be copied so easily

Images are just chunks of binary data, like text or audio. The clipboard will usually hold an image in formats common to the OS, e.g. BMP on Windows, image/png on Linux.

And on Linux, the X11 clipboard protocol actually allows one X client to offer different "encodings" of the selection to other clients, and the receiving X client can choose the encoding, so the sending X client gets to convert the selection into whatever format both clients understand. At least in theory; not sure if modern toolkit libraries like GTK or Qt do offer much choice.

user1686

Posted 2019-05-14T10:51:21.297

Reputation: 283 655

1Do X11 clipboard managers request all the available formats when they steal ownership from the original owner? – Ruslan – 2019-05-14T15:57:45.607

1@Ruslan It probably depends on the clipboard manager. For example, I think the one I use, parcellite, only watches for text data. If I copy an image and kill the source program, I can't paste it anymore. – JoL – 2019-05-14T16:21:05.673

Can you clarify, in Windows, is this something that program has explicitly to support, or is it an operating system feature that works across the board? I personally never use Ctrl-C and Ctrl-V and use Ctrl-Ins Shift-Ins instead, this is automatic for me. To my dismay, some programs do not copy/paste with Ctrl-Ins / Shift-Ins, But Ctrl-C / Ctrl-V works fine (I try to avoid those programs). So this must be for each particular program to support individually, is this right? – Andrew Savinykh – 2019-05-14T21:56:47.770

I'd note some Linux programs will support Ctrl-C and Ctrl-V for compatibility with Windows standards, but other Linux programs may have other meanings for those keys, or just not support them. An older Linux alternative which also often works is to highlight text with the mouse to "copy" (become the selection source), then click the middle mouse button or the left and right mouse buttons at once to paste. – aschepler – 2019-05-14T22:17:04.023

3Re: I'm not sure how common this method is, I have only ever noticed it in Word, Powerpoint and Publisher (suggesting that perhaps only Microsoft ever bothers to implement it). When you click close on the application, it asks if you wish to save the clipboard. I've only seen it happen when there's a large (>1MB) image on the clipboard. – Tim – 2019-05-14T22:36:29.353

10

@AndrewSavinykh Technically these keyboard shortcuts must be interpreted by the specific application which must then call the appropriate API to fetch the data. But most applications rely on standard frameworks which provide widgets that implement these "standard" keyboard shortcuts, e.g. the basic Win32 Edit Control implements its own handling for Ctrl+C/Ctrl+V. So: applications that draw "from scratch" must implement shortcut handling, while applications that use existing frameworks often get it "for free".

– Bob – 2019-05-15T01:02:52.560

@AndrewSavinykh As Bob says. For example both the Windows Console in Quickedit mode and the Windows port of mintty, the default cygwin terminal emulator, use idiosyncratic methods (select/enter resp. select only for mintty, to emulate X11 behavior). Some Windows programs offer "Copy to clipboard" buttons in situations where selecting would be awkward. So it's entirely up to the program which event it uses to put something in the copy buffer. – Peter - Reinstate Monica – 2019-05-15T05:36:53.967

3Also note, that in Linux, CTRL+C does not necessarily copy a text. In text terminals, which also holds for terminals in GUIs, CTRL+C usually treated as terminating the currently running process. – rexkogitans – 2019-05-15T06:01:10.397

Modern terminals usually have Ctrl+Shift+C/V for the clipboard. (Some also have Shift+Ins, but it's a dice roll on whether that'll paste from clipboard, or from primary, or even from a legacy "cutbuffer".) – user1686 – 2019-05-15T06:07:07.800

I have seen at least one 3rd party application which lets you paste application-specific data into a Word document as a live control rather than a mere screenshot. (I believe the technology behind this is an OLE embedded control.) So this stuff is occasionally implemented by 3rd parties other than Microsoft. – MathematicalOrchid – 2019-05-15T11:44:33.697

@MathematicalOrchid: I'm not sure whether that's the same thing as "conversion on demand", though. It could still easily be a predefined data type, merely one that informs the destination how to fully embed the object. (Note that the clipboard conversion, whether deferred or not, is still one-time and cannot result in interactive embedding all by itself – OLE involves another layer of communications beyond that.) – user1686 – 2019-05-15T11:49:00.357

notably; the windows clipboard also only works for images; animated items, like .gif files, only capture one frame. – Erin B – 2019-05-15T13:26:07.200

2@ErinB: That very much depends on what type is common between the two programs... there is nothing that would stop e.g. a video editor from including all frames in its own format, but usually it'll only be understood by that same program, everyone else must resort to pasting generic single-frame formats. Same goes for MS Office data, for example. – user1686 – 2019-05-15T16:58:03.210

Note that X11 actually has a second clipboard-like feature: cut buffers. Unlike selections, those are stored in the X server (as a property on the root window). Also, there is a third selection ("SECONDARY"), though it sees little use. I suggest you mention these and send anyone interested to [unix.se] for details. E.g., https://unix.stackexchange.com/questions/254740/who-stores-copy-paste-buffers-in-x11 and https://unix.stackexchange.com/questions/139191/whats-the-difference-between-primary-selection-and-clipboard-buffer

– derobert – 2019-05-15T20:55:13.900

1On Windows, if a program uses delayed rendering it would normally render the clipboard data before closing, instead of just losing the data. You wouldn’t notice this when using that program. – roeland – 2019-05-15T23:11:56.337

@rexkogitans that's no different on Windows. Ctrl+C or Ctrl+Break on the console terminates the current command – phuclv – 2019-05-18T04:04:21.660