⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 highlight.m

📁 Matlab开发环境中编辑程序文本时的高亮工具代码。
💻 M
📖 第 1 页 / 共 2 页
字号:
function highlight(mfile,options,outfile)%HIGHLIGHT - Syntax Highlighting of Matlab M-files in HTML, LaTeX, RTF and XML.%  HIGHLIGHT(MFILE) takes an M-file MFILE in input and writes on disk an HTML%  file with the same basename ('foo.m' => 'foo.html') adding colored syntax %  highlighting on comment, string and Matlab keyword elements.%  HIGHLIGHT(MFILE,OPTIONS) with OPTIONS being string 'html', 'xhtml', 'tex', %  'rtf' or 'xml', allows to choose the output format between HTML, XHTML, LaTeX%  RTF or XML. The same rule is used to determine the name of the output file.%  HIGHLIGHT(MFILE,OPTIONS) allows to specify some options in a structure:%     options.type - Output file type %             [ {'html'} | 'tex' | 'rtf' | 'xml' | 'xhtml']%     options.tabs - Replace '\t' in source code by n white space%                           [ 0 ... {4}  ... n]%     options.linenb - Display line number in front of each line [ 0 | {1} ]%  HIGHLIGHT(MFILE,OPTIONS,OUTFILE) allows to specify the name of the output %  file. OUTFILE can also be a file handle. In that case, no header will be %  written, only the highlighted Matlab code will be sent to the OUTFILE stream.%  Output file can be customized (font style, font color, font size, ...):%     o HTML: use CSS (Cascading Style Sheets) to define 'comment', 'string', %       'keyword', 'cont' and 'code' SPAN elements and 'mcode' PRE tag.%     o LaTeX: packages 'alltt' and 'color' are required, you can modify colors%       in defining colors 'string', 'comment' and 'keyword' using command%                      \definecolor{mycolor}{rgb}{a,b,c}%     o RTF: Colors are defined in the Color Table at the beginning of the%       document. See Rich Text Format Specifications for more details:%       <http://msdn.microsoft.com/library/en-us/dnrtfspec/html/rtfspec.asp>%     o XML: you will find the DTD of the resulting XML file in matlab.dtd%       You can then use XSL to transform your XML file in what you want.%       For example, mat2html.xsl transforms your XML file in HTML as it would%       be if you would have used highlight.m to to so.%       On Matlab 6.5, the command is:%               xslt highlight.xml mat2html.xsl highlight.html%       On Linux, using libxslt <http://xmlsoft.org/XSLT/>, the command is: %               xsltproc -o highlight.html mat2html.xsl highlight.xml%  Copyright (C) 2003 Guillaume Flandin <Guillaume@artefact.tk>%  $Revision: 1.1 $Date: 2003/09/07 15:39:33 $%  This program is free software; you can redistribute it and/or%  modify it under the terms of the GNU General Public License%  as published by the Free Software Foundation; either version 2%  of the License, or any later version.% %  This program is distributed in the hope that it will be useful,%  but WITHOUT ANY WARRANTY; without even the implied warranty of%  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the%  GNU General Public License for more details.% %  You should have received a copy of the GNU General Public License%  along with this program; if not, write to the Free Software%  Foundation Inc, 59 Temple Pl. - Suite 330, Boston, MA 02111-1307, USA.% Suggestions for improvement and fixes are always welcome, although no% guarantee is made whether and when they will be implemented.% Send requests to Guillaume@artefact.tk% TODO % Improve distinction between 'end' keyword and array subscript% TODO % Smart indentation is *very* buggy (unusable => undocumented)% TODO % Handle wrap mode for long lines in LaTeX mode (and in HTML)% TODO % Improve the XSL transformer from XML to LaTeX%- Set up optionserror(nargchk(1,3,nargin));opt = struct('type',   'html', ...			 'tabs',   4, ...             'linenb', 1, ...			 'indent', 0);if nargin >= 2	if isstruct(options)		names = fieldnames(options);		for i=1:length(names)			opt = setfield(opt,names{i},getfield(options,names{i}));		end	elseif ischar(options)		opt.type = options;	else		error('Bad input argument.');	endendif strcmp(lower(opt.type),'latex'), opt.type = 'tex'; endif strcmp(lower(opt.type),'xml'), opt.linenb = 1; end%- If no output filename is provided, one is chosen according to mfileif nargin < 3	[pathstr, name, ext] = fileparts(mfile);	outfile = fullfile(pathstr, [name, '.' lower(opt.type)]);end%- If an output filename is provided, a standard header is createdif ischar(outfile)	outfid = fopen(outfile,'wt');	if outfid == -1		error(sprintf('Cannot open ',outfile));	end	feval([lower(opt.type) '_file_start'],outfid,mfile);%- Otherwise a file handle is providedelse	outfid = outfile;end%- Open the Matlab mfile to be highlightedmfid = fopen(mfile,'rt');if mfid == -1	error(sprintf('Cannot open ',mfile));end%- Write the syntax highlighted mfile code in the output filewrite_highlighted_code(mfid,outfid,opt)%- Close the Matlab mfile and potentially the output filefclose(mfid);if ischar(outfile), 	feval([lower(opt.type) '_file_end'],outfid);	fclose(outfid); end%===============================================================================function write_highlighted_code(mfid,outfid,opt)	matlabKeywords = getMatlabKeywords;	mKeySort       = getMatlabKeywordsSorted;	out_format     = feval([lower(opt.type) '_format']);	strtok_delim   = sprintf(' \t\n\r(){}[]<>+-*~!|\\@&/.,:;="''%');		fprintf(outfid,out_format.pre_start);	nbline = 1;	nbblanks = 0;	flagnextline = 0;	while 1		tline = fgetl(mfid);		if ~ischar(tline), break, end		tline = feval([lower(opt.type) '_special_char'],horztab(tline,opt.tabs));		%- Display the line number at each line		if opt.linenb			fprintf(outfid,out_format.nb_line,nbline);			nbline = nbline + 1;		end		%- Remove blanks at the beginning of the line		if opt.indent			tline = fliplr(deblank(fliplr(tline)));		end		nbblanks = nbblanks + flagnextline;		flagnextline = 0;		%- Split code into meaningful chunks		splitc = splitcode(tline);		newline = '';		for i=1:length(splitc)			if isempty(splitc{i})			elseif splitc{i}(1) == ''''				newline = [newline sprintf(out_format.string,splitc{i})];			elseif splitc{i}(1) == '%'				newline = [newline sprintf(out_format.comment,splitc{i})];			elseif ~isempty(strmatch('...',splitc{i}))				newline = [newline sprintf(out_format.cont,'...')];				if ~isempty(splitc{i}(4:end))					newline = [newline sprintf(out_format.comment,splitc{i}(4:end))];				end			else				%- Look for Matlab keywords				r = splitc{i};				stringcode = '';				while 1					[t,r,q] = strtok(r,strtok_delim);					stringcode = [stringcode q];					if isempty(t), break, end;					isNextIncr  = any(strcmp(t,mKeySort.nextincr));					isNextIncr2 = any(strcmp(t,mKeySort.nextincr2));					isCurrDecr  = any(strcmp(t,mKeySort.currdecr));					isNextDecr  = any(strcmp(t,mKeySort.nextdecr));					isOther     = any(strcmp(t,mKeySort.other));					if isNextDecr % if strcmp(t,'end')						% 'end' is keyword or array subscript ?						rr = fliplr(deblank(fliplr(r)));						icomma = strmatch(',',rr);						isemicolon = strmatch(';',rr);						if ~(isempty(rr) | ~isempty([icomma isemicolon]))							isNextDecr = 0;						else							nbblanks = nbblanks - 1;							flagnextline = flagnextline + 1;						end						% TODO % false detection of a([end,1])					end					if isNextIncr, flagnextline = flagnextline + 1; end					if isNextIncr2, flagnextline = flagnextline + 2; end					if isNextDecr, flagnextline = flagnextline - 1; end					if isCurrDecr, nbblanks = nbblanks - 1; end					% if any(strcmp(t,matlabKeywords))					if isNextIncr | isNextIncr2 |isCurrDecr | isNextDecr | isOther						if ~isempty(stringcode)							newline = [newline sprintf(out_format.code,stringcode)];							stringcode = '';						end						newline = [newline sprintf(out_format.keyword,t)];					else						stringcode = [stringcode t];					end				end				if ~isempty(stringcode)					newline = [newline sprintf(out_format.code,stringcode)];				end			end		end		if ~opt.indent, nbblanks = 0; end		%- Print the syntax highlighted line		fprintf(outfid,out_format.line,[blanks(nbblanks*opt.tabs) newline]);	end	fprintf(outfid,out_format.pre_end);%===============================================================================%                                  HTML FORMAT                                 %%===============================================================================function html_file_start(fid,mfile)	fprintf(fid,[ ...	'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"\n' ...    '\t"http://www.w3.org/TR/REC-html40/loose.dtd">\n' ...	'<html>\n<head>\n<title>%s</title>\n' ...	'<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">\n' ...	'<meta name="generator" content="highlight.m &copy; 2003 Guillaume Flandin">\n' ...	'<style type="text/css">\n' ...	'  .comment {color: #228B22;}\n' ...	'  .string {color: #B20000;}\n' ...	'  .keyword, .cont {color: #0000FF;}\n' ...	'  .cont {text-decoration: underline;}\n' ...	'  .code {color: #000000;}\n' ...	'</style>\n' ...	'</head>\n<body>\n'],mfile);%-------------------------------------------------------------------------------function html_file_end(fid)	fprintf(fid,'\n</body>\n</html>');%-------------------------------------------------------------------------------function format = html_format	format.string    = '<span class="string">%s</span>';	format.comment   = '<span class="comment">%s</span>';	format.code      = '%s'; %'<span class="code">%s</span>';	format.keyword   = '<span class="keyword">%s</span>';	format.cont      = '<span class="cont">%s</span>';	format.pre_start = '<pre class="mcode">';	format.pre_end   = '</pre>\n';	format.nb_line   = '%04d ';	format.line      = '%s\n';%-------------------------------------------------------------------------------function str = html_special_char(str)	%- See http://www.w3.org/TR/html4/charset.html#h-5.3.2	str = strrep(str,'&','&amp;');	str = strrep(str,'<','&lt;');	str = strrep(str,'>','&gt;');	str = strrep(str,'"','&quot;');%===============================================================================%                                  XHTML FORMAT                                %%===============================================================================function xhtml_file_start(fid,mfile)	fprintf(fid,[ ...	'<?xml version="1.0"?>\n' ...	'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" ' ...	'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n' ...	'<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">\n' ...	'<head>\n<title>%s</title>\n' ...	'<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />\n' ...	'<meta name="generator" content="highlight.m &copy; 2003 Guillaume Flandin" />\n' ...	'<style type="text/css">\n' ...	'  .comment {color: #228B22;}\n' ...	'  .string {color: #B20000;}\n' ...	'  .keyword, .cont {color: #0000FF;}\n' ...	'  .cont {text-decoration: underline;}\n' ...	'  .code {color: #000000;}\n' ...	'</style>\n' ...	'</head>\n<body>\n'],mfile);%-------------------------------------------------------------------------------function xhtml_file_end(fid)	fprintf(fid,'\n</body>\n</html>');%-------------------------------------------------------------------------------function format = xhtml_format	format.string    = '<span class="string">%s</span>';	format.comment   = '<span class="comment">%s</span>';	format.code      = '%s'; %'<span class="code">%s</span>';	format.keyword   = '<span class="keyword">%s</span>';	format.cont      = '<span class="cont">%s</span>';	format.pre_start = '<pre class="mcode">';	format.pre_end   = '</pre>\n';	format.nb_line   = '%04d ';	format.line      = '%s\n';%-------------------------------------------------------------------------------function str = xhtml_special_char(str)	%- See http://www.w3.org/TR/html4/charset.html#h-5.3.2	str = strrep(str,'&','&amp;');	str = strrep(str,'<','&lt;');

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -