views:

32

answers:

4

I don't think I'm alone in spending a fair amount of my programming time moving bits of code from place to place, often within the same file. However, in my experience thus far, every time I cut/copy and paste some code I need to manually realign the spacing so that the pasted code is corrected indented and aligned.

For example in the following code I have pasted the weight arrays to inside my for loop. The spacing is wrong.

weight[v1_t]=1;
weight[v2_t]=12;

if (connected(g)) {
    cout << "I'm connected";
        weight[v1_t]=1;
weight[v2_t]=12;
}

I have tried all combinations of where I highlight my selection from and where I position the cursor for pasting to, without success. I have not seen any difference in any editors.

Am I just unaware of the correct technique or are there specific editors that solve this problem or has this minor nuisance just gone under the radar?

A: 

Microsoft Visual Studio 2005/2008/2010 in my experience is pretty good at negotiating these kinds of situations.

Also, Emacs has a nice feature that if you hit tab than it automatically corrects the indenting - no thinking required (this was for C/C++ code, I don't know about other languages).

mj_
A: 

You didn't mention what platform you're on, but TextMate and Eclipse are both pretty good at handling this. In both editors, when I paste a block of code from a certain indentation level into a new block at a different indentation level, it does a good job of automatically adjusting the indentation of all the lines I pasted.

It might be dependent on the language and the editor's support for it, though. In Eclipse, for example, I work in Java. I don't know whether Eclipse is equally capable of figuring out indentation for C++ code.

Jeff
A: 

The issue may be with how your editor treats the tab character. Some use actual tab characters ("hard tab") for indentation, and some add a certain number of spaces ("soft tab").Due to differences in how editors display tab characters, the alignment can be wrong when code is moved around.

Depending on what editor you use, this may be an option in the settings.

Here is a Jeff Atwood blog post on this. Google "tabs versus spaces" for many more pages on the topic.

Ottawa
+1  A: 

The Zeus editor has a smart paste feature where by it tries to vertically align pasted code based on the surrounding code.

jussij