Can you programmatically delete text in the editor window?
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Matthew Pepich
el 27 de Jul. de 2022
Editada: Matthew Pepich
el 9 de Ag. de 2022
I have a tool that edits files directly in the editor window (see below). It relies on the JavaEditor to overwrite text, which is no longer supported in R2021b+. There are other ways to edit files and make the final results appear in the editor, but I thought this method of live editing (without saving to file first) was very neat and I would like to retain it.
Is there any other way to overwrite or delete text directly in the editor window? I can add text using "insertTextAtPositionInLine", but cannot figure out how to remove any. Thanks!
% /`````````````\
% ( Countdown: 00 ) <-- Press F5 to run this function and watch the number count down from 10 to 0
% \_____________/
function AutoType( fName, iRow, ijCol, newTxt )
%% Test Case
if nargin==0
for n=10:-1:0
AutoType( mfilename(), 2, [16 18], sprintf('%02d',n) );
pause(1);
end
return
end
%% Replace Text
matlab.desktop.editor.openDocument( which(fName) );
activeFile = matlab.desktop.editor.getActive;
activeFile.Selection = [ iRow ijCol(1) iRow ijCol(2) ];
activeFile.JavaEditor.insertTextAtCaret(newTxt); % <---No longer works in R2021b+
% activeFile.insertTextAtPositionInLine( newTxt, iRow, ijCol(1) ) % <---Adds but doesn't overwrite!
activeFile.Selection = [ iRow ijCol(1) iRow ijCol(1)+numel(newTxt) ];
end
2 comentarios
Rik
el 4 de Ag. de 2022
Just out of curiosity: what are you using this for? Most use cases I can image work just fine if you write the m file as text and let the editor reload the changed file (although, as you point out, that does require saving first).
Respuesta aceptada
Yair Altman
el 9 de Ag. de 2022
You can simply update the activeFile.Text property based on your code logic. For example:
activeFile.Text = [activeFile.Text(1:pos1-1) replacementText activeFile.Text(pos2+1:end)];
activeFile.Text(pos1:pos2) = replacementText; %equivalent alternative
or:
activeFile.Text = strrep(activeFile.Text, textToReplace, selectedText);
1 comentario
Matthew Pepich
el 9 de Ag. de 2022
Editada: Matthew Pepich
el 9 de Ag. de 2022
Más respuestas (0)
Ver también
Categorías
Más información sobre Environment and Settings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!