Keyboard shortcut to evaluate current line?

I often use a keyboard shortcut to evaluate highlighted selections of a script I'm working on. But often, I will add a single line to a script and want to evaluate it right away. To do this I highlight the line and hit F9, but it would be a smoother process if I could simply hit F10 to evaluate the line my cursor is on without needing to highlight the line. I've checked the Preferences and I don't see this option available. Are there any clever hacks to allow this?
I'm using R2012b on a Mac.

 Accepted Answer

Eric
Eric on 27 Mar 2015
Edited: Eric on 27 Mar 2015
Create a Quick Access Toolbar shortcut for doing this and call it "Run line". Here's the code:
currentEditor = matlab.desktop.editor.getActive;
originalSelection = currentEditor.Selection;
assert(originalSelection(1)==originalSelection(3));%Check that multiple lines are not selected
currentEditor.Selection = [originalSelection(1) 1 originalSelection(1) Inf];%Select the whole line
eval(currentEditor.SelectedText);%Run the whole line
currentEditor.Selection = originalSelection;%Reset selection to original state
clear currentEditor originalselection
Now, press and hold the Alt key (at least in Windows) to see the mnemonics for the Quick Access Toolbar items. On my system a little "5" shows for the "Run line" shortcut.
Hence I can press Alt+5 to run the current line and leave my selection unchanged. Alternatively I could use the mouse to click the "Run line" button on the Quick Access Toolbar.
-Eric

27 Comments

You could modify this to run multiple selected lines by removing the assert statement and using
currentEditor.Selection = [originalSelection(1) 1 originalSelection(3) Inf];%Select all lines
-Eric
While we're on the topic, I miss the old "Evaluate entire file" button that used to exist. It was the same as the "Run" button but it didn't require that you change directories. This functionality can be done with a shortcut as well. The code for this is just:
activeEditor = matlab.desktop.editor.getActive ;
eval(activeEditor.Text);
-Eric
Very cool, Eric! The shortcut is working almost exactly how I want it to. I can click on my newly-created Run Line button, but I'm having trouble assigning a keyboard shortcut to this button on my Mac. Does anybody know how to add an action name to the list of Keyboard Shortcut preferences on a Mac?
Eric
Eric on 30 Mar 2015
Edited: Eric on 30 Mar 2015
I haven't been able to come up with a workaround. Apparently you're right that mnemonics are not supported on Macs for some reason ( e.g., http://www.mathworks.com/help/symbolic/mupad_ug/use-mnemonics.html ). I can't imagine why not, though admittedly I know very little about the Mac environment.
I also tried Yair's EditorMacro ( http://www.mathworks.com/matlabcentral/fileexchange/24615-editormacro-assign-a-macro-to-a-keyboard-key-stroke-in-the-matlab-editor-and-command-window ). I could not get it to work on R2014b or R2015a on Windows. One commenter on that page seems to indicate it worked for him on R2014b, though. Maybe this works on a Mac? It might be worth trying.
Good luck,
Eric
Good answer but you'll run into problems when a selection is broken up into multiple lines by ellipse ("..."). Here's my work-around:
currentEditor = matlab.desktop.editor.getActive;
originalSelection = currentEditor.Selection;
currentEditor.Selection = [originalSelection(1) 1 originalSelection(3) Inf];%Select the whole line
selected = currentEditor.SelectedText;
while ~isempty(strfind(currentEditor.SelectedText,'...'))
currentEditor.Selection = [currentEditor.Selection(3)+1 1 currentEditor.Selection(3)+1 Inf]
selected = [selected, currentEditor.SelectedText];
end
eval(strrep(selected,'...','')); % remove ellipse and evaluate
currentEditor.Selection = [currentEditor.Selection(3)+1 1 currentEditor.Selection(3)+1 1]; % Advance 1 line
clear currentEditor originalselection
Notice that I've chosen to allow multiple lines selected as well as lines broken up by ellipse and I also call to automatically advance to the next line so that you can efficiently run through your script line-by-line.
- Kevin
Kevin, Thank you! This is a perfect solution. It even goes to the next line just like it is supposed** to. How has nobody else commented?
**This is how Ctrl+<Enter> works in R and that's the functionality I was looking for.
For everyone that has come here and not used this answer: All you have to do is click the "new shortcut" button (arrow with +) in the toolbar and copy Kevin's code into the "Callback" window underneath the commented line.
Edit: For reasons beyond me at the moment, the script does not like to execute lines with the command "save".
It gives the error: "Warning: com.mathworks.mde.editor.MatlabEditor@2665bc62 is not serializable"
-Thomas
Thanks Kevin and Thomas. I like this a lot. Can a keyboard shortcut be made to execute this function?
Eric answered that already. Once you have it in the tool bar, hold down 'alt' to see what number is assigned to the button then press that number while still holding down 'alt'. So, if you put your new button first in the shortcut bar, the combination will be the alt key and the number key 1.
Minor detail. Last line should be
clear currentEditor originalSelection
Capital S in Selection.
Thanks Eric, this method works very well. I use AHK to send the Quick Access Toolbar shortcut, so I can simply use a customized F7 key to excute a line.
Hi Amy, a naive question: What is AHK, and how to customize a F7 key to execute a line.
In RStudio, I also customize F4 to the Run Current Line or selection. The beauty of RStudio is that it can automatically move the cursor to the next line. Can we do it in Matlab as well?
Thank you Walter! I will try if I can customize it to one key.
puff dragon
puff dragon on 11 May 2018
Edited: puff dragon on 14 May 2018
Now Matlab is changing to Favorite Command Editor.
Currently, "All the statements in the Code field of the Favorite Command Editor execute as if you ran those statements from the Command Window, although they do not appear in the Command History window."
I set some favorite command to and Keyboard shortcut to evaluate current line, as stated here.
Is there a way to let the "current/selected line" appear in the Command History window after it is executed. It will be easier to track it.
There is a similar solution here: https://github.com/GavriYashar/Matlab-Editor-Plugin
It allows you to customize your shortcut key. However, after execute the current line, the current line remains selected and the mouse cursor won't move to the next line.
It's possible to add a command to the Matlab command history by calling:
com.mathworks.mlservices.MLCommandHistoryServices.add("Text_of_Matlab_Command");
So my favorite commands contains only one call to the appropriate favorite help function which includes this Java command to add the used favorite help function to the Command History.
Could anyone go into a little bit more detail on where this code needs to be inserted? I do not see a place to create a shortcut in Preference>Keyboard Shortcuts
I've been using R lately and I love the Shift+Enter command. When I switch back to MATLAB I'm lost without it.
Apologize for the introductory nature of the question. Googled and was not able to get a clear answer
It is very easy. If you haven't changed anything in the original environment, you will find it as an icon in the toolbar. It looks like a curved arrow pointing northeast and it has a small plus sign on the bottom right corner.
Once you click it, the "Shortcut Editor" will open. You can define the label (name) of the shortcut ("Run line" in this case) and in the field "Callback" you can insert Eric's code. You can also choose an icon for it (I went for the "R").
Hope that helps.
In current releases, you need to click on the downward arrow under "Favorites" in the toolbar, and then in the area that pops up, click on the bottom left one, "New Favorite", which looks like a blue star with a yellow plus sign at the bottom right.
Hey all, just for ease of access for others that don't initally find the thing: The toolbar is on the upper right, next to the close "X". I never used it and totally missed it.
Other than that, I have augmented this a little such that it selects all lines that are selected somehow (no need to restrict to one line imho), then jumps to the next line that has code in it. If an error happens, the selection that generated the error will persist. the code is:
% Evaluates selected lines of code (no need to highlight the entire lines) and jumps
% to the next line that has code in it. Errors will be rethrown and the line won't
% jump in that case.
currentEditor = matlab.desktop.editor.getActive;
% Selections are of the format:
% [start_line start_element_in_line end_line end_element_in_line]
originalSelection = currentEditor.Selection;
% Select the whole line
% The selection with the Inf-th element will automatically select the last one
current_selection = [originalSelection(1) 1 originalSelection(3) Inf];
currentEditor.Selection = current_selection;
% Try to evaluate the selection, if error, reset to original state and rethrow it
try
% Run the whole line
eval(currentEditor.SelectedText);
catch ME
% Reset selection to original state
currentEditor.Selection = originalSelection;
clear currentEditor originalselection
% Throw the original error
rethrow(ME)
end
% Check if the line is empty, if yes, advance one line
% Pretend the current length is 0, to initialize the first jump to the next line
line_length = 0;
while line_length == 0
% Jump to the line after selection and select all
currentEditor.Selection = [current_selection(3)+1 1 current_selection(3)+1 Inf];
current_selection = currentEditor.Selection;
line_length = current_selection(4) - current_selection(2);
end
% Undo the selection of the whole line again
currentEditor.Selection = [current_selection(3) 1 current_selection(3) 1];
clear currentEditor originalselection
Enjoy!
Thanks, Marius! Works nicely
Did anyone have any issues with this code being very slow? I'm running an i7 with 24GB of RAM. When I run this solution in MATLAB R2019a it freezes.
Thanks
I cant believe this! I cant believe that I need to write a complex script to get the most basic functionality in the free languages, Python and R. Where is the awesome productivity that MATLAB promise? False marketing!
Very helpful, thank you Eric and all other contributors!
I have chosen Marius Klug's code see above (which also needs a capital s in "originalselection" I think) and I have painted some an amateurish 16x16 icon for the Quick Access Toolbar:
Now when I insert it here it looks as if the quality and transparency of the png file are not preserved....
Where do I save this code?
Save it in the Favorite commands option under Home

Sign in to comment.

More Answers (6)

Anybody knows how to get the keyboard mnemonics for Mac?

2 Comments

I am not certain I understand what you are asking, but have you looked Preferences -> Keyboard -> Shortcuts ?
On Mac, select the lines to run; then press:
fn + shift + F7

Sign in to comment.

I don't know of this option but I do understand the use-case and agree that it would be valuable. Here's how I do it right now:
When writing a script, I always use lots of code sections.
Since you can evaluate a section from keyboard or from the "run section" button there is always the option to evaluate the section. If you intelligently name your variables so that they don't overwrite previous ones, then you will never have trouble running the whole section versus just the line of code. I'll also put computationally expensive lines of code in their own section so that it only needs to be rerun if the higher-level sections have changed.
This mimics the functionality you desire and actually expands it to multiple lines at once.

1 Comment

Indeed, I also use sectioning quite a bit. I was hoping for a single-line equivalent. I effectively want a new cell for each line of code without actually adding the %% between each line. It's only a minor inconvenience to highlight some new xlim line and hit F9 after data have already been plotted, but it would be less clunky if the current line could be evaluated with a single keystroke.

Sign in to comment.

Unfortunately I don't have a answer, but I'd be interested too. Did you find a way?

3 Comments

Still nothing. But I would use such a feature every day if I could.
I'll add my vote for this feature too. It's perhaps a minor inconvenience to have to highlight a line, but it's one of those little things I repeat dozens of times each day.
I agree wholeheartedly and would love to see this feature request completed! How do we go about getting our request known?

Sign in to comment.

Joseph Cheng
Joseph Cheng on 19 Aug 2014
Edited: Joseph Cheng on 19 Aug 2014
This is not entirely 1 button press but you can use the documentation here http://blogs.mathworks.com/community/2009/09/28/configurable-keyboard-shortcuts-have-arrived/ and configure a shortcut to do this. My test (in windows R2011A and R2013b) was to assign "evaluate selection" to F8 and "Selection End Line" to F8. I kept the "limit" keystroke selection to 1.
So by doing this F8 now either:
  1. if something is selected runs the selection
  2. with nothing selected the first F8 press highlights from my cursor to the end of line then upon second F8 press it runs selection.
I see now that i could have just mapped it to F9 as its performance is conditional to what is selected.
Not entirely sure how much faster this is. Normal keyboard way would be home->shift+end->F9 which is just 4 presses. My method would save you a key press as its home->F8->F8.

1 Comment

I can't get this to work in R2015A. They list a possible conflict between the two actions and F8 ends up only evaluating, it does not perform selection end line.
BUT, I did discover that single clicking the white margin to the left of your text (between the grey debug "-" (after the line number) and the first letter on your line) will select the entire line. Thus, clicking that margin and then pressing F9 completes what we are trying to accomplish... still wish we could just have one keybind for evaluating the current line.

Sign in to comment.

Matt J
Matt J on 3 May 2025
Edited: Matt J on 4 May 2025
I have created this File Exchange submission,
to make this kind of thing easier. To evaluate the line of code where the cursor is located, you can do simply,
eval(editorExtract(1))
and of course you can make this into a Quick Access button or hotkey as discussed.

Categories

Find more on Scripts in Help Center and File Exchange

Products

Asked:

on 2 Jun 2014

Edited:

on 4 May 2025

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!