102

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.

Worthwelle
  • 4,538
  • 11
  • 21
  • 32
Inter Sys
  • 628
  • 2
  • 5
  • 7
  • 42
    What level of detail do you expect? – u1686_grawity May 14 '19 at 11:49
  • 11
    Let begin with this https://docs.microsoft.com/en-us/windows/desktop/dataxchg/clipboard. – Biswapriyo May 14 '19 at 11:58
  • 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 May 14 '19 at 12:04
  • 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 May 14 '19 at 14:20
  • 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. –  May 15 '19 at 13:42
  • 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 May 17 '19 at 23:17

1 Answers1

168

One thing in common across all systems is that keyboard shortcuts such as CtrlC are not system-level – they are handled by each program individually, just like the "Copy" or "Paste" menu items are specific to each program. So it's not the OS itself that "copies" something, but rather it's the app (Word) that uses some OS-specific function to put data in the global clipboard.

Windows

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.)

  • When you "copy" something, the program will 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 Word can simultaneously come in HTML, RTF, and plain-text formats in addition to Word's own format.

    However, the program may store 'null' data and defer conversion until a paste is requested using WM_RENDERFORMAT, e.g. if the copied data is large. In this case the data is lost when the program is closed. You might've seen Word or Photoshop ask about this when exiting the program.

    (Note that when you "cut" or "copy" a whole file through Explorer, this doesn't put the entire file's contents in the clipboard, but only a file reference that Explorer itself will understand when it's pasted.)

  • When you ask the program to "paste", the program chooses the desired format and retrieves 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 from a web browser but want to paste without formatting).

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

Linux, BSD, Solaris, OpenVMS

In Linux and other similar systems, the clipboard is provided by the graphical environment you're using (that is, an X11 server or a Wayland compositor) – there is no shared clipboard for programs running outside such an environment.

X11

X11 handles the clipboard a little bit differently – the X server doesn't provide storage at all, it only facilitates communications between the copy-source program (which announces that it has something "copied") and the paste-target program.

Both the initial "copy" announcement and the later "paste" transfer are done via X11 messages according to the ICCCM protocol. (Each X display therefore has a separate clipboard

  • Upon pressing CtrlC, the source program will keep track of "copied" data in its own memory and will claim ownership of the X11 "selection" called 'CLIPBOARD', which is done using XSetSelectionOwner().

    This ownership is tracked centrally by the X server (e.g. Xorg). Whenever you "copy" something new, the previous app that owned the 'CLIPBOARD' selection is informed about losing its ownership so that it can discard the now-unneeded data.

    Because clipboard transfer is always deferred, the copied data is usually lost as soon as you close the "source" program (unless you're running a "clipboard manager" which proactively stores everything that is copied). So if you copy something from Firefox and then close Firefox, you cannot paste it anymore.

  • When pasting, the program will look up the current owner of the 'CLIPBOARD' selection using XGetSelectionOwner(). Similar to Windows, it is possible for X11 clipboard to hold data in several alternative types so the destination program will ask the source for the preferred type using XConvertSelection().

    (Usually a special type named 'TARGETS' is available, which has the source program return an ASCII list of data types that are currently available.)

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.

Wayland

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

Non-graphical programs

Traditional text editors (Vim, emacs, nano) often have their own internal clipboards (aka registers/killrings).

Terminal-based apps may access X11 or Wayland clipboards if running inside a graphical terminal emulator, e.g. Vim's "+ register will paste from the X11 clipboard (whereas other Vim registers are internal to the program).

macOS (Mac OS X)

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

There is nothing special about images – they're still just chunks of binary data that can be represented as bytes, so if they can be saved in a file (e.g. in PNG or JPEG format), they can also be stored in the clipboard using the same format.

Windows apps typically store copied images in BMP/DIB formats (the same as in a .bmp file), while on Linux it is common for apps to offer PNG (i.e. "image/png" target).

u1686_grawity
  • 426,297
  • 64
  • 894
  • 966
  • 1
    Do X11 clipboard managers request all the available formats when they steal ownership from the original owner? – Ruslan May 14 '19 at 15:57
  • 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 May 14 '19 at 16:21
  • 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 May 14 '19 at 21:56
  • 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 May 14 '19 at 22:17
  • 3
    Re: *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 May 14 '19 at 22:36
  • 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](https://docs.microsoft.com/en-us/windows/desktop/controls/about-edit-controls) 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 May 15 '19 at 01:02
  • @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 May 15 '19 at 05:36
  • 3
    Also 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 May 15 '19 at 06:01
  • 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".) – u1686_grawity May 15 '19 at 06:07
  • 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 May 15 '19 at 11:44
  • @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.) – u1686_grawity May 15 '19 at 11:49
  • notably; the windows clipboard also only works for images; animated items, like .gif files, only capture one frame. – Erin B May 15 '19 at 13:26
  • 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. – u1686_grawity May 15 '19 at 16:58
  • 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 May 15 '19 at 20:55
  • 1
    On 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 May 15 '19 at 23:11
  • @rexkogitans that's no different on Windows. Ctrl+C or Ctrl+Break on the console terminates the current command – phuclv May 18 '19 at 04:04