tommsch
tommsch

Reputation: 688

Get name of code section in Matlab script

I have a script (actually a test script used for script based unit tests) which is divided into sections of the type

%% test foo
code

%% test bar
more code

How do I retrieve the name of a section (in any form, e.g. foo, test foo, TestFoo or whatever Matlab makes out of a section name) from inside my script (i.e. the place where I have written code).

Upvotes: 0

Views: 118

Answers (2)

Christian
Christian

Reputation: 749

Sorry, I have no Matlab on this computer. So the code is untested. But I guess with the code snippet below you should be able to do what you are trying.

It's a little bit hacky, but it's Matlab.

function section_name = get_current_section_name()

ds = dbstack();

execution_file = ds(2).file;
execution_line = ds(2).line;

fid = fopen(execution_file);

section_name = "";
current_line_number = 1;

tline = fgetl(fid);
while ischar(tline)
    if startsWith(tline, "%%")
        section_name = tline;
    end

    if execution_line == current_line_number
        return
    end
    tline = fgetl(fid);
    current_line = current_line + 1;
end

fclose(fid)

% case: not found
section_name = "";

end

And on your desired position you should be fine if you just call

section_name = get_current_section_name()

Upvotes: 3

Paolo
Paolo

Reputation: 26064

Here's a possible solution. Given the following code:

%% test foo
code


%% test bar
more code

%% test baz
other code

You can obtain the comment of the active live script as follows:

>> X = matlab.desktop.editor.getActive; % Get MATLAB editor
>> editorText = X.Text; % Get editor text
>> n = X.Selection(1); % Get line number on which cursor is
>> all_lines = regexp(editorText,'\n','split'); % Get all lines of editor
>> for line = all_lines(n:-1:1) % Iterate backwards from starting lne
>>   if contains(line,'%%') % If the line contains a comment, extract string and exit loop
>>     match = regexp(line,'%% (.+)$','tokens','once')
>>     break
>>   end
>> end

match is a cell with the desired content. If your cursor is in the first code section, match{1} contains test foo. If the cursor is in the second block, test bar and finally test baz for the last block.


How it works:

First we get the active MATLAB editor and the position of the cursor. Then, we split on newline \n to obtain all of the lines in the editor. From the current line, we iterate backwards to identify the first line which has the comment, which contains the desired string.

Upvotes: 2

Related Questions