tags:

views:

52

answers:

1

I've inherited some code where the author had an aversion to semicolons. Is it possible to fix all the mlint messages in one go (at least all the ones with an automatic fix), rather than having to click each one and press ALT+ENTER?

+3  A: 

I don't know of a way in general to automatically fix code based on MLINT messages. However, in your specific case there is an automated way for you to add semicolons to lines that throw an MLINT warning.

First, let's start with this sample script junk.m:

a = 1
b = 2;
c = 'a'
d = [1 2 3]
e = 'hello';

The first, third, and fourth lines will give you the MLINT warning message "Terminate statement with semicolon to suppress output (within a script).". Using the functional form of MLINT, we can find the lines in the file where this warning occurs. Then, we can read all the lines of code from the file, add a semicolon to the ends of the lines where the warning occurs, and write the lines of code back to the file. Here's the code to do so:

%# Find the lines where a given mlint warning occurs:

fileName = 'junk.m';
mlintID = 'NOPTS';                       %# The ID of the warning
mlintData = mlint(fileName,'-id');       %# Run mlint on the file
index = strcmp({mlintData.id},mlintID);  %# Find occurrences of the warnings...
lineNumbers = [mlintData(index).line];   %#   ... and their line numbers

%# Read the lines of code from the file:

fid = fopen(fileName,'rt');
linesOfCode = textscan(fid,'%s','Delimiter',char(10));  %# Read each line
fclose(fid);

%# Modify the lines of code:

linesOfCode = linesOfCode{1};  %# Remove the outer cell array encapsulation
linesOfCode(lineNumbers) = strcat(linesOfCode(lineNumbers),';');  %# Add ';'

%# Write the lines of code back to the file:

fid = fopen(fileName,'wt');
fprintf(fid,'%s\n',linesOfCode{1:end-1});  %# Write all but the last line
fprintf(fid,'%s',linesOfCode{end});        %# Write the last line
fclose(fid);

And now the file junk.m should have semicolons at the end of every line. If you want, you can put the above code in a function so that you can easily run it on every file of your inherited code.

gnovice
If you replace '-struct' with '-id' in your call to mlint the structure which is returned contains an additional field called 'id' which is a short id for the mlint message. That might be easier to match against than the full text of the message. The structure also contains a field called 'fix' which is 0 for all warnings in my test file and I haven't figured out what it is for yet -- it is not documented.
High Performance Mark
@High Performance Mark: The `'fix'` field must be a newer feature, as it does not appear in MATLAB R2009a.
gnovice
@gnovice: yes, I'm running 2010a here.
High Performance Mark

related questions