This responds to your general question, but not particularly to the use case you mention (moving bits of code around).
Emacs now has what it calls a noncontiguous region, which is the kind of selection that you are asking about. Vanilla Emacs does not provide any special way to create a noncontiguous region, except if it is a rectangle. But library Zones does.
Library Zones lets you define multiple zones in your buffer. A list of zones is a noncontiguous region. You can also think of it as multiple regions, depending on how you want to make use of it. You can have multiple zone lists defined at any time, each assigned to a different zones variable, and you can switch among them.
If you also use library Bookmark+ then you can save lists of zones persistently and restore them in later Emacs sessions. Bookmark+ also lets you assign arbitrary tags to a bookmark. This means that you can tag a list of zones.
The zones in a given zone list are typically in the same buffer, but they need not be. In this, a zone list is more general than a noncontiguous region. It is also more general in that each zone can contain additional information, besides just the zone limits, and it can have an identifier.
There are several ways to create a zone. One of the easiest is to use
C-x n a: it defines a zone from the active region, and adds it to the current zone set. (
C-x n n (
narrow-to-region) also does this, in addition to narrowing.)
These are some of the things you can do with a set (list) of zones:
- Sort them.
- Unite (coalesce) adjacent or overlapping zones (which includes sorting them).
- Intersect them.
- Narrow the buffer to a zone in the list. Cycle among narrowings. See Multiple Narrowings.
- Select a zone in the list as the active region. Cycle among regions.
- Search them (they are automatically united first). For this
you need library Isearch+.
- Query-replace over them.
- Highlight and unhighlight them. (For this you need library Highlight or library
See also Narrow Indirect, which lets you create indirect buffers that are clones of a given buffer and that are narrowed to different portions of it.
multiple-cursorsmay give you a solution.