Is it possible to programmatically add a file extension for syntax highlighting?
2 views (last 30 days)
Show older comments
Hi,
Is it possible to programmatically add a file extension for syntax highlighting?
Just for the sake of argument, suppose I have a file with extension "xtn". It is possible to go into
preference-->editor/Debugger-->language
and from there add extension xtn under the block "file extensions". Then matlab will apply the same syntax coloring it uses for files with extension .m to all files with extension xtn.
Is there any way to do this programmatically instead of manually?
Thanks
0 Comments
Answers (1)
Jan
on 24 Oct 2015
Edited: Jan
on 24 Oct 2015
You can do it the hard way:
Open the file prefdir\matlab.prf. Search for the variable "Editor.Language.MATLAB.Extensions" and append 'xtn'.
Ext = 'xtn';
PrefFile = fullfile(prefdir, 'matlab.prf');
copyfile(PrefFile, [PrefFile, '.bak']); % To be secure
fid = fopen(PrefFile, 'r');
if fid == -1
error('Cannot open file for reading: %s', PrefFile);
end
C = textscan(fid, '%s', 'Delimiter', '\n');
Data = C{1};
fclose(fid);
key = 'Editor.Language.MATLAB.Extensions';
index = strncmp(Data, key, length(key));
if sum(index) ~= 1
error('Cannot identify key line.');
end
keyLine = Data{index};
keyData = keyLine(length(key) + 3:end); % <key>=S...
keyValue = regexp(keyData, ';', 'split');
if ~any(strcmpi(keyValue, Ext))
keyData = [keyData, ';', Ext];
end
Data{index} = [key, '=S', keyData];
% Save the file:
fid = fopen(PrefFile, 'w');
if fid == -1
error('Cannot open file for writing: %s', PrefFile);
end
fprintf(fid, '%s\n', Data{:});
fclose(fid);
Afterwards restart Matlab:
!matlab
quit
Or you use the smart, but undocumented methods:
key = 'Editor.Language.MATLAB.Extensions';
keyData = com.mathworks.services.Prefs.getPref(key);
keyValue = regexp(keyData, ';', 'split');
if ~any(strcmpi(keyValue, Ext))
keyData = [keyData, ';', Ext];
com.mathworks.services.Prefs.setStringPref(key, keyData);
end
This worked 2007 (see http://mathworks.com/matlabcentral/newsreader/view_thread/154608) and in R2011b. But as all undocumented methods this might change in the future.
Finally, let me mention, that this does not look like a useful method to me. I guess that it is easier to change the file extension from the concerned files.
2 Comments
Jan
on 24 Oct 2015
Edited: Jan
on 24 Oct 2015
Too complicated? I've posted 2 solutions already. So simply copy&paste one of them into a function called "add_extension". All you have to modify for "remove_extension" is:
match = strcmpi(keyValue, Ext);
if any(match)
keyValue(match) = [];
keyData = sprintf('%s;', keyValue{:});
keyData(end) = [];
com.mathworks.services.Prefs.setStringPref(key, keyData);
end
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!