Sometimes I will copy a piece of code that someone has put up in answer to a question, then paste the code into MATLAB at the command prompt. Often I will need to make a change to the code before I hit return, such as fixing a typo. Usually this works fine, but sometimes the code executes as soon as I paste it, resulting in the expected error due to the typo. If the block of code is long I usually end up pasting it into the editor, making the change, then copying and pasting into the command window to execute the code.
This is annoying, so what causes this sometimes and not other times?
No products are associated with this question.
I believe this has to do with how the lines of code are selected. If you start selecting at the beginning of the line and simply drag your mouse down, you end up copying the "carriage return" characters along with your lines. So when you paste it, it simply evaluates everything. But if you take your mouse and make sure you select only to the last character, then it shouldn't execute.
However, I think different applications treat copying of text differently. For example, I found that some text editors try to do the "smart thing" and select the carriage return for you no matter what you do. But other times it does what you ask for.
I've also found that using shift-click to behave better sometimes. But I make sure I select the last character first, then shift-click at the beginning. Sometimes, if I do it the other way (click at beginning and shift-click at end), it automatically appends a carriage return. Grrr.
I'm using a small function to clean the contents of the clipboard:
function cv % reminds me to Ctrl-V Str = clipboard('paste'); Index = max(find(~isspace(Str))); clipboard('copy', Str(1:Index));
Afterwards I can user Ctrl-V without triggering the execution. It might be more convenient to use one of Yair's tricks, the java.awt.Robot or FEX:textInject to write directly to the command prompt. But I use it too seldom to need this.
A visual example:
In the first part, if you select down to the next line, you include a carriage return, and whenever you paste to the cmd windonw the code is executed.
The second part is the tedious end-of-line selection...which once pasted stays on the cmd window until you 'enter' it.
I desume from this example that Jiro is correct.