开发者

How to get the first line of text of a Matlab M-file?

开发者 https://www.devze.com 2023-04-07 11:57 出处:网络
I am using Matlab R2011b. I want to get the text of the firs开发者_开发百科t line of the active mfile in the Editor. I know I can use the following code to get all the text of the mfile as a 1xn chara

I am using Matlab R2011b. I want to get the text of the firs开发者_开发百科t line of the active mfile in the Editor. I know I can use the following code to get all the text of the mfile as a 1xn character array (not broken into lines). However I only want the first line.

activeEditor = matlab.desktop.editor.getActive ;    
activeEditor.Text ;

Any suggestions?


You can search for the first "newline" character, and return everything from the beginning to that position:

activeEditor = matlab.desktop.editor.getActive;
pos = find(activeEditor.Text==char(10), 1, 'first');
firstLineStr = activeEditor.Text(1:pos-1)


One way to do this is to select all of the text on the first line and then access the SelectedText property:

>> activeEditor = matlab.desktop.editor.getActive ;
>> activeEditor.Selection = [1 1 1 Inf];
>> activeEditor.SelectedText

ans =

This is the first line of this file

You could improve on this by storing the current selection before selecting the entire first line and then restoring the selection after the selected text is accessed. This way the cursor position is not lost.

0

精彩评论

暂无评论...
验证码 换一张
取 消