Changes
Cprintf
,Created page with "<p>% For displaying string to red color using "cprintf"</p> <p>% Reference: https://kr.mathworks.com/matlabcentral/fileexchange/24093-cprintf-display-formatted-colored..."
<p>% For displaying string to red color using "cprintf"</p>
<p>% Reference: https://kr.mathworks.com/matlabcentral/fileexchange/24093-cprintf-display-formatted-colored-text-in-the-command-window</p>
<p>function count = cprintf(style,format,varargin)<br />
% CPRINTF displays styled formatted text in the Command Window<br />
%<br />
% Syntax:<br />
% count = cprintf(style,format,...)<br />
%<br />
% Description:<br />
% CPRINTF processes the specified text using the exact same FORMAT<br />
% arguments accepted by the built-in SPRINTF and FPRINTF functions.<br />
%<br />
% CPRINTF then displays the text in the Command Window using the<br />
% specified STYLE argument. The accepted styles are those used for<br />
% Matlab's syntax highlighting (see: File / Preferences / Colors / <br />
% M-file Syntax Highlighting Colors), and also user-defined colors.<br />
%<br />
% The possible pre-defined STYLE names are:<br />
%<br />
% 'Text' - default: black<br />
% 'Keywords' - default: blue<br />
% 'Comments' - default: green<br />
% 'Strings' - default: purple<br />
% 'UnterminatedStrings' - default: dark red<br />
% 'SystemCommands' - default: orange<br />
% 'Errors' - default: light red<br />
% 'Hyperlinks' - default: underlined blue<br />
%<br />
% 'Black','Cyan','Magenta','Blue','Green','Red','Yellow','White'<br />
%<br />
% STYLE beginning with '-' or '_' will be underlined. For example:<br />
% '-Blue' is underlined blue, like 'Hyperlinks';<br />
% '_Comments' is underlined green etc.<br />
%<br />
% STYLE beginning with '*' will be bold (R2011b+ only). For example:<br />
% '*Blue' is bold blue;<br />
% '*Comments' is bold green etc.<br />
% Note: Matlab does not currently support both bold and underline,<br />
% only one of them can be used in a single cprintf command. But of<br />
% course bold and underline can be mixed by using separate commands.<br />
%<br />
% STYLE also accepts a regular Matlab RGB vector, that can be underlined<br />
% and bolded: -[0,1,1] means underlined cyan, '*[1,0,0]' is bold red.<br />
%<br />
% STYLE is case-insensitive and accepts unique partial strings just<br />
% like handle property names.<br />
%<br />
% CPRINTF by itself, without any input parameters, displays a demo<br />
%<br />
% Example:<br />
% cprintf; % displays the demo<br />
% cprintf('text', 'regular black text');<br />
% cprintf('hyper', 'followed %s','by');<br />
% cprintf('key', '%d colored', 4);<br />
% cprintf('-comment','& underlined');<br />
% cprintf('err', 'elements\n');<br />
% cprintf('cyan', 'cyan');<br />
% cprintf('_green', 'underlined green');<br />
% cprintf(-[1,0,1], 'underlined magenta');<br />
% cprintf([1,0.5,0],'and multi-\nline orange\n');<br />
% cprintf('*blue', 'and *bold* (R2011b+ only)\n');<br />
% cprintf('string'); % same as fprintf('string') and cprintf('text','string')<br />
%<br />
% Bugs and suggestions:<br />
% Please send to Yair Altman (altmany at gmail dot com)<br />
%<br />
% Warning:<br />
% This code heavily relies on undocumented and unsupported Matlab<br />
% functionality. It works on Matlab 7+, but use at your own risk!<br />
%<br />
% A technical description of the implementation can be found at:<br />
% <a href="http://undocumentedmatlab.com/blog/cprintf/">http://UndocumentedMatlab.com/blog/cprintf/</a><br />
%<br />
% Limitations:<br />
% 1. In R2011a and earlier, a single space char is inserted at the<br />
% beginning of each CPRINTF text segment (this is ok in R2011b+).<br />
%<br />
% 2. In R2011a and earlier, consecutive differently-colored multi-line<br />
% CPRINTFs sometimes display incorrectly on the bottom line.<br />
% As far as I could tell this is due to a Matlab bug. Examples:<br />
% >> cprintf('-str','under\nline'); cprintf('err','red\n'); % hidden 'red', unhidden '_'<br />
% >> cprintf('str','regu\nlar'); cprintf('err','red\n'); % underline red (not purple) 'lar'<br />
%<br />
% 3. Sometimes, non newline ('\n')-terminated segments display unstyled<br />
% (black) when the command prompt chevron ('>>') regains focus on the<br />
% continuation of that line (I can't pinpoint when this happens). <br />
% To fix this, simply newline-terminate all command-prompt messages.<br />
%<br />
% 4. In R2011b and later, the above errors appear to be fixed. However,<br />
% the last character of an underlined segment is not underlined for<br />
% some unknown reason (add an extra space character to make it look better)<br />
%<br />
% 5. In old Matlab versions (e.g., Matlab 7.1 R14), multi-line styles<br />
% only affect the first line. Single-line styles work as expected.<br />
% R14 also appends a single space after underlined segments.<br />
%<br />
% 6. Bold style is only supported on R2011b+, and cannot also be underlined.<br />
%<br />
% Change log:<br />
% 2015-06-24: Fixed a few discoloration issues (some other issues still remain)<br />
% 2015-03-20: Fix: if command window isn't defined yet (startup) use standard fprintf as suggested by John Marozas<br />
% 2012-08-09: Graceful degradation support for deployed (compiled) and non-desktop applications; minor bug fixes<br />
% 2012-08-06: Fixes for R2012b; added bold style; accept RGB string (non-numeric) style<br />
% 2011-11-27: Fixes for R2011b<br />
% 2011-08-29: Fix by Danilo (FEX comment) for non-default text colors<br />
% 2011-03-04: Performance improvement<br />
% 2010-06-27: Fix for R2010a/b; fixed edge case reported by Sharron; CPRINTF with no args runs the demo<br />
% 2009-09-28: Fixed edge-case problem reported by Swagat K<br />
% 2009-05-28: corrected nargout behavior suggested by Andreas G?b<br />
% 2009-05-13: First version posted on <a href="http://www.mathworks.com/matlabcentral/fileexchange/authors/27420">MathWorks File Exchange</a><br />
%<br />
% See also:<br />
% sprintf, fprintf<br />
% License to use and modify this code is granted freely to all interested, as long as the original author is<br />
% referenced and attributed as such. The original author maintains the right to be solely associated with this work.<br />
% Programmed and Copyright by Yair M. Altman: altmany(at)gmail.com<br />
% $Revision: 1.10 $ $Date: 2015/06/24 01:29:18 $<br />
persistent majorVersion minorVersion<br />
if isempty(majorVersion)<br />
%v = version; if str2double(v(1:3)) <= 7.1<br />
%majorVersion = str2double(regexprep(version,'^(\d+).*','$1'));<br />
%minorVersion = str2double(regexprep(version,'^\d+\.(\d+).*','$1'));<br />
%[a,b,c,d,versionIdStrs]=regexp(version,'^(\d+)\.(\d+).*'); %#ok unused<br />
v = sscanf(version, '%d.', 2);<br />
majorVersion = v(1); %str2double(versionIdStrs{1}{1});<br />
minorVersion = v(2); %str2double(versionIdStrs{1}{2});<br />
end<br />
% The following is for debug use only:<br />
%global docElement txt el<br />
if ~exist('el','var') || isempty(el), el=handle([]); end %#ok mlint short-circuit error ("used before defined")<br />
if nargin<1, showDemo(majorVersion,minorVersion); return; end<br />
if isempty(style), return; end<br />
if all(ishandle(style)) && length(style)~=3<br />
dumpElement(style);<br />
return;<br />
end<br />
% Process the text string<br />
if nargin<2, format = style; style='text'; end<br />
%error(nargchk(2, inf, nargin, 'struct'));<br />
%str = sprintf(format,varargin{:});<br />
% In compiled mode<br />
try useDesktop = usejava('desktop'); catch, useDesktop = false; end<br />
if isdeployed | ~useDesktop %#ok<OR2> - for Matlab 6 compatibility<br />
% do not display any formatting - use simple fprintf()<br />
% See: http://undocumentedmatlab.com/blog/bold-color-text-in-the-command-window/#comment-103035<br />
% Also see: https://mail.google.com/mail/u/0/?ui=2&shva=1#all/1390a26e7ef4aa4d<br />
% Also see: https://mail.google.com/mail/u/0/?ui=2&shva=1#all/13a6ed3223333b21<br />
count1 = fprintf(format,varargin{:});<br />
else<br />
% Else (Matlab desktop mode)<br />
% Get the normalized style name and underlining flag<br />
[underlineFlag, boldFlag, style, debugFlag] = processStyleInfo(style);<br />
% Set hyperlinking, if so requested<br />
if underlineFlag<br />
format = ['<a href="">' format '</a>'];<br />
% Matlab 7.1 R14 (possibly a few newer versions as well?)<br />
% have a bug in rendering consecutive hyperlinks<br />
% This is fixed by appending a single non-linked space<br />
if majorVersion < 7 || (majorVersion==7 && minorVersion <= 1)<br />
format(end+1) = ' ';<br />
end<br />
end<br />
% Set bold, if requested and supported (R2011b+)<br />
if boldFlag<br />
if (majorVersion > 7 || minorVersion >= 13)<br />
format = ['<strong>' format '</strong>'];<br />
else<br />
boldFlag = 0;<br />
end<br />
end<br />
% Get the current CW position<br />
cmdWinDoc = com.mathworks.mde.cmdwin.CmdWinDocument.getInstance;<br />
lastPos = cmdWinDoc.getLength;<br />
% If not beginning of line<br />
bolFlag = 0; %#ok<br />
%if docElement.getEndOffset - docElement.getStartOffset > 1<br />
% Display a hyperlink element in order to force element separation<br />
% (otherwise adjacent elements on the same line will be merged)<br />
if majorVersion<7 || (majorVersion==7 && minorVersion<13)<br />
if ~underlineFlag<br />
fprintf('<a href=""> </a>'); %fprintf('<a href=""> </a>\b');<br />
elseif format(end)~=10 % if no newline at end<br />
fprintf(' '); %fprintf(' \b');<br />
end<br />
end<br />
%drawnow;<br />
bolFlag = 1;<br />
%end<br />
% Get a handle to the Command Window component<br />
mde = com.mathworks.mde.desk.MLDesktop.getInstance;<br />
cw = mde.getClient('Command Window');<br />
% Fix: if command window isn't defined yet (startup), use standard fprintf()<br />
if (isempty(cw))<br />
count1 = fprintf(format,varargin{:});<br />
if nargout<br />
count = count1;<br />
end<br />
return;<br />
end<br />
<br />
xCmdWndView = cw.getComponent(0).getViewport.getComponent(0);<br />
% Store the CW background color as a special color pref<br />
% This way, if the CW bg color changes (via File/Preferences), <br />
% it will also affect existing rendered strs<br />
com.mathworks.services.Prefs.setColorPref('CW_BG_Color',xCmdWndView.getBackground);<br />
% Display the text in the Command Window<br />
% Note: fprintf(2,...) is required in order to add formatting tokens, which<br />
% ^^^^ can then be updated below (no such tokens when outputting to stdout)<br />
count1 = fprintf(2,format,varargin{:});<br />
% Repaint the command window<br />
%awtinvoke(cmdWinDoc,'remove',lastPos,1); % TODO: find out how to remove the extra '_'<br />
drawnow; % this is necessary for the following to work properly (refer to Evgeny Pr in FEX comment 16/1/2011)<br />
xCmdWndView.repaint;<br />
%hListeners = cmdWinDoc.getDocumentListeners; for idx=1:numel(hListeners), try hListeners(idx).repaint; catch, end, end<br />
docElement = cmdWinDoc.getParagraphElement(lastPos+1);<br />
if majorVersion<7 || (majorVersion==7 && minorVersion<13)<br />
if bolFlag && ~underlineFlag<br />
% Set the leading hyperlink space character ('_') to the bg color, effectively hiding it<br />
% Note: old Matlab versions have a bug in hyperlinks that need to be accounted for...<br />
%disp(' '); dumpElement(docElement)<br />
setElementStyle(docElement,'CW_BG_Color',1+underlineFlag,majorVersion,minorVersion); %+getUrlsFix(docElement));<br />
%disp(' '); dumpElement(docElement)<br />
el(end+1) = handle(docElement); % #ok used in debug only<br />
end<br />
% Fix a problem with some hidden hyperlinks becoming unhidden...<br />
fixHyperlink(docElement);<br />
%dumpElement(docElement);<br />
end<br />
% Get the Document Element(s) corresponding to the latest fprintf operation<br />
while docElement.getStartOffset < cmdWinDoc.getLength<br />
% Set the element style according to the current style<br />
if debugFlag, dumpElement(docElement); end<br />
specialFlag = underlineFlag | boldFlag;<br />
setElementStyle(docElement,style,specialFlag,majorVersion,minorVersion);<br />
if debugFlag, dumpElement(docElement); end<br />
docElement2 = cmdWinDoc.getParagraphElement(docElement.getEndOffset+1);<br />
if isequal(docElement,docElement2), break; end<br />
docElement = docElement2;<br />
end<br />
if debugFlag, dumpElement(docElement); end<br />
% Force a Command-Window repaint<br />
% Note: this is important in case the rendered str was not '\n'-terminated<br />
xCmdWndView.repaint;<br />
% The following is for debug use only:<br />
el(end+1) = handle(docElement); %#ok used in debug only<br />
%elementStart = docElement.getStartOffset;<br />
%elementLength = docElement.getEndOffset - elementStart;<br />
%txt = cmdWinDoc.getText(elementStart,elementLength);<br />
end<br />
if nargout<br />
count = count1;<br />
end<br />
return; % debug breakpoint<br />
% Process the requested style information<br />
function [underlineFlag,boldFlag,style,debugFlag] = processStyleInfo(style)<br />
underlineFlag = 0;<br />
boldFlag = 0;<br />
debugFlag = 0;<br />
% First, strip out the underline/bold markers<br />
if ischar(style)<br />
% Styles containing '-' or '_' should be underlined (using a no-target hyperlink hack)<br />
%if style(1)=='-'<br />
underlineIdx = (style=='-') | (style=='_');<br />
if any(underlineIdx)<br />
underlineFlag = 1;<br />
%style = style(2:end);<br />
style = style(~underlineIdx);<br />
end<br />
% Check for bold style (only if not underlined)<br />
boldIdx = (style=='*');<br />
if any(boldIdx)<br />
boldFlag = 1;<br />
style = style(~boldIdx);<br />
end<br />
if underlineFlag && boldFlag<br />
warning('YMA:cprintf:BoldUnderline','Matlab does not support both bold & underline')<br />
end<br />
% Check for debug mode (style contains '!')<br />
debugIdx = (style=='!');<br />
if any(debugIdx)<br />
debugFlag = 1;<br />
style = style(~debugIdx);<br />
end<br />
% Check if the remaining style sting is a numeric vector<br />
%styleNum = str2num(style); %#ok<ST2NM> % not good because style='text' is evaled!<br />
%if ~isempty(styleNum)<br />
if any(style==' ' | style==',' | style==';')<br />
style = str2num(style); %#ok<ST2NM><br />
end<br />
end<br />
% Style = valid matlab RGB vector<br />
if isnumeric(style) && length(style)==3 && all(style<=1) && all(abs(style)>=0)<br />
if any(style<0)<br />
underlineFlag = 1;<br />
style = abs(style);<br />
end<br />
style = getColorStyle(style);<br />
elseif ~ischar(style)<br />
error('YMA:cprintf:InvalidStyle','Invalid style - see help section for a list of valid style values')<br />
% Style name<br />
else<br />
% Try case-insensitive partial/full match with the accepted style names<br />
matlabStyles = {'Text','Keywords','Comments','Strings','UnterminatedStrings','SystemCommands','Errors'};<br />
validStyles = [matlabStyles, ...<br />
'Black','Cyan','Magenta','Blue','Green','Red','Yellow','White', ...<br />
'Hyperlinks'];<br />
matches = find(strncmpi(style,validStyles,length(style)));<br />
% No match - error<br />
if isempty(matches)<br />
error('YMA:cprintf:InvalidStyle','Invalid style - see help section for a list of valid style values')<br />
% Too many matches (ambiguous) - error<br />
elseif length(matches) > 1<br />
error('YMA:cprintf:AmbigStyle','Ambiguous style name - supply extra characters for uniqueness')<br />
% Regular text<br />
elseif matches == 1<br />
style = 'ColorsText'; % fixed by Danilo, 29/8/2011<br />
% Highlight preference style name<br />
elseif matches <= length(matlabStyles)<br />
style = ['Colors_M_' validStyles{matches}];<br />
% Color name<br />
elseif matches < length(validStyles)<br />
colors = [0,0,0; 0,1,1; 1,0,1; 0,0,1; 0,1,0; 1,0,0; 1,1,0; 1,1,1];<br />
requestedColor = colors(matches-length(matlabStyles),:);<br />
style = getColorStyle(requestedColor);<br />
% Hyperlink<br />
else<br />
style = 'Colors_HTML_HTMLLinks'; % CWLink<br />
underlineFlag = 1;<br />
end<br />
end<br />
% Convert a Matlab RGB vector into a known style name (e.g., '[255,37,0]')<br />
function styleName = getColorStyle(rgb)<br />
intColor = int32(rgb*255);<br />
javaColor = java.awt.Color(intColor(1), intColor(2), intColor(3));<br />
styleName = sprintf('[%d,%d,%d]',intColor);<br />
com.mathworks.services.Prefs.setColorPref(styleName,javaColor);<br />
% Fix a bug in some Matlab versions, where the number of URL segments<br />
% is larger than the number of style segments in a doc element<br />
function delta = getUrlsFix(docElement) %#ok currently unused<br />
tokens = docElement.getAttribute('SyntaxTokens');<br />
links = docElement.getAttribute('LinkStartTokens');<br />
if length(links) > length(tokens(1))<br />
delta = length(links) > length(tokens(1));<br />
else<br />
delta = 0;<br />
end<br />
% fprintf(2,str) causes all previous '_'s in the line to become red - fix this<br />
function fixHyperlink(docElement)<br />
try<br />
tokens = docElement.getAttribute('SyntaxTokens');<br />
urls = docElement.getAttribute('HtmlLink');<br />
urls = urls(2);<br />
links = docElement.getAttribute('LinkStartTokens');<br />
offsets = tokens(1);<br />
styles = tokens(2);<br />
doc = docElement.getDocument;<br />
% Loop over all segments in this docElement<br />
for idx = 1 : length(offsets)-1<br />
% If this is a hyperlink with no URL target and starts with ' ' and is collored as an error (red)...<br />
if strcmp(styles(idx).char,'Colors_M_Errors')<br />
character = char(doc.getText(offsets(idx)+docElement.getStartOffset,1));<br />
if strcmp(character,' ')<br />
if isempty(urls(idx)) && links(idx)==0<br />
% Revert the style color to the CW background color (i.e., hide it!)<br />
styles(idx) = java.lang.String('CW_BG_Color');<br />
end<br />
end<br />
end<br />
end<br />
catch<br />
% never mind...<br />
end<br />
% Set an element to a particular style (color)<br />
function setElementStyle(docElement,style,specialFlag, majorVersion,minorVersion)<br />
%global tokens links urls urlTargets % for debug only<br />
global oldStyles<br />
if nargin<3, specialFlag=0; end<br />
% Set the last Element token to the requested style:<br />
% Colors:<br />
tokens = docElement.getAttribute('SyntaxTokens');<br />
try<br />
styles = tokens(2);<br />
oldStyles{end+1} = cell(styles);<br />
% Correct edge case problem<br />
extraInd = double(majorVersion>7 || (majorVersion==7 && minorVersion>=13)); % =0 for R2011a-, =1 for R2011b+<br />
%{<br />
if ~strcmp('CWLink',char(styles(end-hyperlinkFlag))) && ...<br />
strcmp('CWLink',char(styles(end-hyperlinkFlag-1)))<br />
extraInd = 0;%1;<br />
end<br />
hyperlinkFlag = ~isempty(strmatch('CWLink',tokens(2)));<br />
hyperlinkFlag = 0 + any(cellfun(@(c)(~isempty(c)&&strcmp(c,'CWLink')),cell(tokens(2))));<br />
%}<br />
jStyle = java.lang.String(style);<br />
if numel(styles)==4 && isempty(char(styles(2)))<br />
% Attempt to fix discoloration issues - NOT SURE THAT THIS IS OK! - 24/6/2015<br />
styles(1) = jStyle;<br />
end<br />
styles(end-extraInd) = java.lang.String('');<br />
styles(end-extraInd-specialFlag) = jStyle; % #ok apparently unused but in reality used by Java<br />
if extraInd<br />
styles(end-specialFlag) = jStyle;<br />
end<br />
oldStyles{end} = [oldStyles{end} cell(styles)];<br />
catch<br />
% never mind for now<br />
end<br />
<br />
% Underlines (hyperlinks):<br />
%{<br />
links = docElement.getAttribute('LinkStartTokens');<br />
if isempty(links)<br />
%docElement.addAttribute('LinkStartTokens',repmat(int32(-1),length(tokens(2)),1));<br />
else<br />
%TODO: remove hyperlink by setting the value to -1<br />
end<br />
%}<br />
% Correct empty URLs to be un-hyperlinkable (only underlined)<br />
urls = docElement.getAttribute('HtmlLink');<br />
if ~isempty(urls)<br />
urlTargets = urls(2);<br />
for urlIdx = 1 : length(urlTargets)<br />
try<br />
if urlTargets(urlIdx).length < 1<br />
urlTargets(urlIdx) = []; % '' => []<br />
end<br />
catch<br />
% never mind...<br />
a=1; %#ok used for debug breakpoint...<br />
end<br />
end<br />
end<br />
<br />
% Bold: (currently unused because we cannot modify this immutable int32 numeric array)<br />
%{<br />
try<br />
%hasBold = docElement.isDefined('BoldStartTokens');<br />
bolds = docElement.getAttribute('BoldStartTokens');<br />
if ~isempty(bolds)<br />
%docElement.addAttribute('BoldStartTokens',repmat(int32(1),length(bolds),1));<br />
end<br />
catch<br />
% never mind - ignore...<br />
a=1; %#ok used for debug breakpoint...<br />
end<br />
%}<br />
<br />
return; % debug breakpoint<br />
% Display information about element(s)<br />
function dumpElement(docElements)<br />
%return;<br />
disp(' ');<br />
numElements = length(docElements);<br />
cmdWinDoc = docElements(1).getDocument;<br />
for elementIdx = 1 : numElements<br />
if numElements > 1, fprintf('Element #%d:\n',elementIdx); end<br />
docElement = docElements(elementIdx);<br />
if ~isjava(docElement), docElement = docElement.java; end<br />
%docElement.dump(java.lang.System.out,1)<br />
disp(docElement)<br />
tokens = docElement.getAttribute('SyntaxTokens');<br />
if isempty(tokens), continue; end<br />
links = docElement.getAttribute('LinkStartTokens');<br />
urls = docElement.getAttribute('HtmlLink');<br />
try bolds = docElement.getAttribute('BoldStartTokens'); catch, bolds = []; end<br />
txt = {};<br />
tokenLengths = tokens(1);<br />
for tokenIdx = 1 : length(tokenLengths)-1<br />
tokenLength = diff(tokenLengths(tokenIdx+[0,1]));<br />
if (tokenLength < 0)<br />
tokenLength = docElement.getEndOffset - docElement.getStartOffset - tokenLengths(tokenIdx);<br />
end<br />
txt{tokenIdx} = cmdWinDoc.getText(docElement.getStartOffset+tokenLengths(tokenIdx),tokenLength).char; %#ok<br />
end<br />
lastTokenStartOffset = docElement.getStartOffset + tokenLengths(end);<br />
try<br />
txt{end+1} = cmdWinDoc.getText(lastTokenStartOffset, docElement.getEndOffset-lastTokenStartOffset).char; %#ok<br />
catch<br />
txt{end+1} = ''; %#ok<AGROW><br />
end<br />
%cmdWinDoc.uiinspect<br />
%docElement.uiinspect<br />
txt = strrep(txt',sprintf('\n'),'\n');<br />
try<br />
data = [cell(tokens(2)) m2c(tokens(1)) m2c(links) m2c(urls(1)) cell(urls(2)) m2c(bolds) txt];<br />
if elementIdx==1<br />
disp(' SyntaxTokens(2,1) - LinkStartTokens - HtmlLink(1,2) - BoldStartTokens - txt');<br />
disp(' ==============================================================================');<br />
end<br />
catch<br />
try<br />
data = [cell(tokens(2)) m2c(tokens(1)) m2c(links) txt];<br />
catch<br />
disp([cell(tokens(2)) m2c(tokens(1)) txt]);<br />
try<br />
data = [m2c(links) m2c(urls(1)) cell(urls(2))];<br />
catch<br />
% Mtlab 7.1 only has urls(1)...<br />
data = [m2c(links) cell(urls)];<br />
end<br />
end<br />
end<br />
disp(data)<br />
end<br />
% Utility function to convert matrix => cell<br />
function cells = m2c(data)<br />
%datasize = size(data); cells = mat2cell(data,ones(1,datasize(1)),ones(1,datasize(2)));<br />
cells = num2cell(data);<br />
% Display the help and demo<br />
function showDemo(majorVersion,minorVersion)<br />
fprintf('cprintf displays formatted text in the Command Window.\n\n');<br />
fprintf('Syntax: count = cprintf(style,format,...); click <a href="matlab:help cprintf">here</a> for details.\n\n');<br />
url = 'http://UndocumentedMatlab.com/blog/cprintf/';<br />
fprintf(['Technical description: <a href="' url '">' url '</a>\n\n']);<br />
fprintf('Demo:\n\n');<br />
boldFlag = majorVersion>7 || (majorVersion==7 && minorVersion>=13);<br />
s = ['cprintf(''text'', ''regular black text'');' 10 ...<br />
'cprintf(''hyper'', ''followed %s'',''by'');' 10 ...<br />
'cprintf(''key'', ''%d colored'',' num2str(4+boldFlag) ');' 10 ...<br />
'cprintf(''-comment'',''& underlined'');' 10 ...<br />
'cprintf(''err'', ''elements:\n'');' 10 ...<br />
'cprintf(''cyan'', ''cyan'');' 10 ...<br />
'cprintf(''_green'', ''underlined green'');' 10 ...<br />
'cprintf(-[1,0,1], ''underlined magenta'');' 10 ...<br />
'cprintf([1,0.5,0], ''and multi-\nline orange\n'');' 10];<br />
if boldFlag<br />
% In R2011b+ the internal bug that causes the need for an extra space<br />
% is apparently fixed, so we must insert the sparator spaces manually...<br />
% On the other hand, 2011b enables *bold* format<br />
s = [s 'cprintf(''*blue'', ''and *bold* (R2011b+ only)\n'');' 10];<br />
s = strrep(s, ''')',' '')');<br />
s = strrep(s, ''',5)',' '',5)');<br />
s = strrep(s, '\n ','\n');<br />
end<br />
disp(s);<br />
eval(s);<br />
%%%%%%%%%%%%%%%%%%%%%%%%%% TODO %%%%%%%%%%%%%%%%%%%%%%%%%<br />
% - Fix: Remove leading space char (hidden underline '_')<br />
% - Fix: Find workaround for multi-line quirks/limitations<br />
% - Fix: Non-\n-terminated segments are displayed as black<br />
% - Fix: Check whether the hyperlink fix for 7.1 is also needed on 7.2 etc.<br />
% - Enh: Add font support</p>
<p>% Reference: https://kr.mathworks.com/matlabcentral/fileexchange/24093-cprintf-display-formatted-colored-text-in-the-command-window</p>
<p>function count = cprintf(style,format,varargin)<br />
% CPRINTF displays styled formatted text in the Command Window<br />
%<br />
% Syntax:<br />
% count = cprintf(style,format,...)<br />
%<br />
% Description:<br />
% CPRINTF processes the specified text using the exact same FORMAT<br />
% arguments accepted by the built-in SPRINTF and FPRINTF functions.<br />
%<br />
% CPRINTF then displays the text in the Command Window using the<br />
% specified STYLE argument. The accepted styles are those used for<br />
% Matlab's syntax highlighting (see: File / Preferences / Colors / <br />
% M-file Syntax Highlighting Colors), and also user-defined colors.<br />
%<br />
% The possible pre-defined STYLE names are:<br />
%<br />
% 'Text' - default: black<br />
% 'Keywords' - default: blue<br />
% 'Comments' - default: green<br />
% 'Strings' - default: purple<br />
% 'UnterminatedStrings' - default: dark red<br />
% 'SystemCommands' - default: orange<br />
% 'Errors' - default: light red<br />
% 'Hyperlinks' - default: underlined blue<br />
%<br />
% 'Black','Cyan','Magenta','Blue','Green','Red','Yellow','White'<br />
%<br />
% STYLE beginning with '-' or '_' will be underlined. For example:<br />
% '-Blue' is underlined blue, like 'Hyperlinks';<br />
% '_Comments' is underlined green etc.<br />
%<br />
% STYLE beginning with '*' will be bold (R2011b+ only). For example:<br />
% '*Blue' is bold blue;<br />
% '*Comments' is bold green etc.<br />
% Note: Matlab does not currently support both bold and underline,<br />
% only one of them can be used in a single cprintf command. But of<br />
% course bold and underline can be mixed by using separate commands.<br />
%<br />
% STYLE also accepts a regular Matlab RGB vector, that can be underlined<br />
% and bolded: -[0,1,1] means underlined cyan, '*[1,0,0]' is bold red.<br />
%<br />
% STYLE is case-insensitive and accepts unique partial strings just<br />
% like handle property names.<br />
%<br />
% CPRINTF by itself, without any input parameters, displays a demo<br />
%<br />
% Example:<br />
% cprintf; % displays the demo<br />
% cprintf('text', 'regular black text');<br />
% cprintf('hyper', 'followed %s','by');<br />
% cprintf('key', '%d colored', 4);<br />
% cprintf('-comment','& underlined');<br />
% cprintf('err', 'elements\n');<br />
% cprintf('cyan', 'cyan');<br />
% cprintf('_green', 'underlined green');<br />
% cprintf(-[1,0,1], 'underlined magenta');<br />
% cprintf([1,0.5,0],'and multi-\nline orange\n');<br />
% cprintf('*blue', 'and *bold* (R2011b+ only)\n');<br />
% cprintf('string'); % same as fprintf('string') and cprintf('text','string')<br />
%<br />
% Bugs and suggestions:<br />
% Please send to Yair Altman (altmany at gmail dot com)<br />
%<br />
% Warning:<br />
% This code heavily relies on undocumented and unsupported Matlab<br />
% functionality. It works on Matlab 7+, but use at your own risk!<br />
%<br />
% A technical description of the implementation can be found at:<br />
% <a href="http://undocumentedmatlab.com/blog/cprintf/">http://UndocumentedMatlab.com/blog/cprintf/</a><br />
%<br />
% Limitations:<br />
% 1. In R2011a and earlier, a single space char is inserted at the<br />
% beginning of each CPRINTF text segment (this is ok in R2011b+).<br />
%<br />
% 2. In R2011a and earlier, consecutive differently-colored multi-line<br />
% CPRINTFs sometimes display incorrectly on the bottom line.<br />
% As far as I could tell this is due to a Matlab bug. Examples:<br />
% >> cprintf('-str','under\nline'); cprintf('err','red\n'); % hidden 'red', unhidden '_'<br />
% >> cprintf('str','regu\nlar'); cprintf('err','red\n'); % underline red (not purple) 'lar'<br />
%<br />
% 3. Sometimes, non newline ('\n')-terminated segments display unstyled<br />
% (black) when the command prompt chevron ('>>') regains focus on the<br />
% continuation of that line (I can't pinpoint when this happens). <br />
% To fix this, simply newline-terminate all command-prompt messages.<br />
%<br />
% 4. In R2011b and later, the above errors appear to be fixed. However,<br />
% the last character of an underlined segment is not underlined for<br />
% some unknown reason (add an extra space character to make it look better)<br />
%<br />
% 5. In old Matlab versions (e.g., Matlab 7.1 R14), multi-line styles<br />
% only affect the first line. Single-line styles work as expected.<br />
% R14 also appends a single space after underlined segments.<br />
%<br />
% 6. Bold style is only supported on R2011b+, and cannot also be underlined.<br />
%<br />
% Change log:<br />
% 2015-06-24: Fixed a few discoloration issues (some other issues still remain)<br />
% 2015-03-20: Fix: if command window isn't defined yet (startup) use standard fprintf as suggested by John Marozas<br />
% 2012-08-09: Graceful degradation support for deployed (compiled) and non-desktop applications; minor bug fixes<br />
% 2012-08-06: Fixes for R2012b; added bold style; accept RGB string (non-numeric) style<br />
% 2011-11-27: Fixes for R2011b<br />
% 2011-08-29: Fix by Danilo (FEX comment) for non-default text colors<br />
% 2011-03-04: Performance improvement<br />
% 2010-06-27: Fix for R2010a/b; fixed edge case reported by Sharron; CPRINTF with no args runs the demo<br />
% 2009-09-28: Fixed edge-case problem reported by Swagat K<br />
% 2009-05-28: corrected nargout behavior suggested by Andreas G?b<br />
% 2009-05-13: First version posted on <a href="http://www.mathworks.com/matlabcentral/fileexchange/authors/27420">MathWorks File Exchange</a><br />
%<br />
% See also:<br />
% sprintf, fprintf<br />
% License to use and modify this code is granted freely to all interested, as long as the original author is<br />
% referenced and attributed as such. The original author maintains the right to be solely associated with this work.<br />
% Programmed and Copyright by Yair M. Altman: altmany(at)gmail.com<br />
% $Revision: 1.10 $ $Date: 2015/06/24 01:29:18 $<br />
persistent majorVersion minorVersion<br />
if isempty(majorVersion)<br />
%v = version; if str2double(v(1:3)) <= 7.1<br />
%majorVersion = str2double(regexprep(version,'^(\d+).*','$1'));<br />
%minorVersion = str2double(regexprep(version,'^\d+\.(\d+).*','$1'));<br />
%[a,b,c,d,versionIdStrs]=regexp(version,'^(\d+)\.(\d+).*'); %#ok unused<br />
v = sscanf(version, '%d.', 2);<br />
majorVersion = v(1); %str2double(versionIdStrs{1}{1});<br />
minorVersion = v(2); %str2double(versionIdStrs{1}{2});<br />
end<br />
% The following is for debug use only:<br />
%global docElement txt el<br />
if ~exist('el','var') || isempty(el), el=handle([]); end %#ok mlint short-circuit error ("used before defined")<br />
if nargin<1, showDemo(majorVersion,minorVersion); return; end<br />
if isempty(style), return; end<br />
if all(ishandle(style)) && length(style)~=3<br />
dumpElement(style);<br />
return;<br />
end<br />
% Process the text string<br />
if nargin<2, format = style; style='text'; end<br />
%error(nargchk(2, inf, nargin, 'struct'));<br />
%str = sprintf(format,varargin{:});<br />
% In compiled mode<br />
try useDesktop = usejava('desktop'); catch, useDesktop = false; end<br />
if isdeployed | ~useDesktop %#ok<OR2> - for Matlab 6 compatibility<br />
% do not display any formatting - use simple fprintf()<br />
% See: http://undocumentedmatlab.com/blog/bold-color-text-in-the-command-window/#comment-103035<br />
% Also see: https://mail.google.com/mail/u/0/?ui=2&shva=1#all/1390a26e7ef4aa4d<br />
% Also see: https://mail.google.com/mail/u/0/?ui=2&shva=1#all/13a6ed3223333b21<br />
count1 = fprintf(format,varargin{:});<br />
else<br />
% Else (Matlab desktop mode)<br />
% Get the normalized style name and underlining flag<br />
[underlineFlag, boldFlag, style, debugFlag] = processStyleInfo(style);<br />
% Set hyperlinking, if so requested<br />
if underlineFlag<br />
format = ['<a href="">' format '</a>'];<br />
% Matlab 7.1 R14 (possibly a few newer versions as well?)<br />
% have a bug in rendering consecutive hyperlinks<br />
% This is fixed by appending a single non-linked space<br />
if majorVersion < 7 || (majorVersion==7 && minorVersion <= 1)<br />
format(end+1) = ' ';<br />
end<br />
end<br />
% Set bold, if requested and supported (R2011b+)<br />
if boldFlag<br />
if (majorVersion > 7 || minorVersion >= 13)<br />
format = ['<strong>' format '</strong>'];<br />
else<br />
boldFlag = 0;<br />
end<br />
end<br />
% Get the current CW position<br />
cmdWinDoc = com.mathworks.mde.cmdwin.CmdWinDocument.getInstance;<br />
lastPos = cmdWinDoc.getLength;<br />
% If not beginning of line<br />
bolFlag = 0; %#ok<br />
%if docElement.getEndOffset - docElement.getStartOffset > 1<br />
% Display a hyperlink element in order to force element separation<br />
% (otherwise adjacent elements on the same line will be merged)<br />
if majorVersion<7 || (majorVersion==7 && minorVersion<13)<br />
if ~underlineFlag<br />
fprintf('<a href=""> </a>'); %fprintf('<a href=""> </a>\b');<br />
elseif format(end)~=10 % if no newline at end<br />
fprintf(' '); %fprintf(' \b');<br />
end<br />
end<br />
%drawnow;<br />
bolFlag = 1;<br />
%end<br />
% Get a handle to the Command Window component<br />
mde = com.mathworks.mde.desk.MLDesktop.getInstance;<br />
cw = mde.getClient('Command Window');<br />
% Fix: if command window isn't defined yet (startup), use standard fprintf()<br />
if (isempty(cw))<br />
count1 = fprintf(format,varargin{:});<br />
if nargout<br />
count = count1;<br />
end<br />
return;<br />
end<br />
<br />
xCmdWndView = cw.getComponent(0).getViewport.getComponent(0);<br />
% Store the CW background color as a special color pref<br />
% This way, if the CW bg color changes (via File/Preferences), <br />
% it will also affect existing rendered strs<br />
com.mathworks.services.Prefs.setColorPref('CW_BG_Color',xCmdWndView.getBackground);<br />
% Display the text in the Command Window<br />
% Note: fprintf(2,...) is required in order to add formatting tokens, which<br />
% ^^^^ can then be updated below (no such tokens when outputting to stdout)<br />
count1 = fprintf(2,format,varargin{:});<br />
% Repaint the command window<br />
%awtinvoke(cmdWinDoc,'remove',lastPos,1); % TODO: find out how to remove the extra '_'<br />
drawnow; % this is necessary for the following to work properly (refer to Evgeny Pr in FEX comment 16/1/2011)<br />
xCmdWndView.repaint;<br />
%hListeners = cmdWinDoc.getDocumentListeners; for idx=1:numel(hListeners), try hListeners(idx).repaint; catch, end, end<br />
docElement = cmdWinDoc.getParagraphElement(lastPos+1);<br />
if majorVersion<7 || (majorVersion==7 && minorVersion<13)<br />
if bolFlag && ~underlineFlag<br />
% Set the leading hyperlink space character ('_') to the bg color, effectively hiding it<br />
% Note: old Matlab versions have a bug in hyperlinks that need to be accounted for...<br />
%disp(' '); dumpElement(docElement)<br />
setElementStyle(docElement,'CW_BG_Color',1+underlineFlag,majorVersion,minorVersion); %+getUrlsFix(docElement));<br />
%disp(' '); dumpElement(docElement)<br />
el(end+1) = handle(docElement); % #ok used in debug only<br />
end<br />
% Fix a problem with some hidden hyperlinks becoming unhidden...<br />
fixHyperlink(docElement);<br />
%dumpElement(docElement);<br />
end<br />
% Get the Document Element(s) corresponding to the latest fprintf operation<br />
while docElement.getStartOffset < cmdWinDoc.getLength<br />
% Set the element style according to the current style<br />
if debugFlag, dumpElement(docElement); end<br />
specialFlag = underlineFlag | boldFlag;<br />
setElementStyle(docElement,style,specialFlag,majorVersion,minorVersion);<br />
if debugFlag, dumpElement(docElement); end<br />
docElement2 = cmdWinDoc.getParagraphElement(docElement.getEndOffset+1);<br />
if isequal(docElement,docElement2), break; end<br />
docElement = docElement2;<br />
end<br />
if debugFlag, dumpElement(docElement); end<br />
% Force a Command-Window repaint<br />
% Note: this is important in case the rendered str was not '\n'-terminated<br />
xCmdWndView.repaint;<br />
% The following is for debug use only:<br />
el(end+1) = handle(docElement); %#ok used in debug only<br />
%elementStart = docElement.getStartOffset;<br />
%elementLength = docElement.getEndOffset - elementStart;<br />
%txt = cmdWinDoc.getText(elementStart,elementLength);<br />
end<br />
if nargout<br />
count = count1;<br />
end<br />
return; % debug breakpoint<br />
% Process the requested style information<br />
function [underlineFlag,boldFlag,style,debugFlag] = processStyleInfo(style)<br />
underlineFlag = 0;<br />
boldFlag = 0;<br />
debugFlag = 0;<br />
% First, strip out the underline/bold markers<br />
if ischar(style)<br />
% Styles containing '-' or '_' should be underlined (using a no-target hyperlink hack)<br />
%if style(1)=='-'<br />
underlineIdx = (style=='-') | (style=='_');<br />
if any(underlineIdx)<br />
underlineFlag = 1;<br />
%style = style(2:end);<br />
style = style(~underlineIdx);<br />
end<br />
% Check for bold style (only if not underlined)<br />
boldIdx = (style=='*');<br />
if any(boldIdx)<br />
boldFlag = 1;<br />
style = style(~boldIdx);<br />
end<br />
if underlineFlag && boldFlag<br />
warning('YMA:cprintf:BoldUnderline','Matlab does not support both bold & underline')<br />
end<br />
% Check for debug mode (style contains '!')<br />
debugIdx = (style=='!');<br />
if any(debugIdx)<br />
debugFlag = 1;<br />
style = style(~debugIdx);<br />
end<br />
% Check if the remaining style sting is a numeric vector<br />
%styleNum = str2num(style); %#ok<ST2NM> % not good because style='text' is evaled!<br />
%if ~isempty(styleNum)<br />
if any(style==' ' | style==',' | style==';')<br />
style = str2num(style); %#ok<ST2NM><br />
end<br />
end<br />
% Style = valid matlab RGB vector<br />
if isnumeric(style) && length(style)==3 && all(style<=1) && all(abs(style)>=0)<br />
if any(style<0)<br />
underlineFlag = 1;<br />
style = abs(style);<br />
end<br />
style = getColorStyle(style);<br />
elseif ~ischar(style)<br />
error('YMA:cprintf:InvalidStyle','Invalid style - see help section for a list of valid style values')<br />
% Style name<br />
else<br />
% Try case-insensitive partial/full match with the accepted style names<br />
matlabStyles = {'Text','Keywords','Comments','Strings','UnterminatedStrings','SystemCommands','Errors'};<br />
validStyles = [matlabStyles, ...<br />
'Black','Cyan','Magenta','Blue','Green','Red','Yellow','White', ...<br />
'Hyperlinks'];<br />
matches = find(strncmpi(style,validStyles,length(style)));<br />
% No match - error<br />
if isempty(matches)<br />
error('YMA:cprintf:InvalidStyle','Invalid style - see help section for a list of valid style values')<br />
% Too many matches (ambiguous) - error<br />
elseif length(matches) > 1<br />
error('YMA:cprintf:AmbigStyle','Ambiguous style name - supply extra characters for uniqueness')<br />
% Regular text<br />
elseif matches == 1<br />
style = 'ColorsText'; % fixed by Danilo, 29/8/2011<br />
% Highlight preference style name<br />
elseif matches <= length(matlabStyles)<br />
style = ['Colors_M_' validStyles{matches}];<br />
% Color name<br />
elseif matches < length(validStyles)<br />
colors = [0,0,0; 0,1,1; 1,0,1; 0,0,1; 0,1,0; 1,0,0; 1,1,0; 1,1,1];<br />
requestedColor = colors(matches-length(matlabStyles),:);<br />
style = getColorStyle(requestedColor);<br />
% Hyperlink<br />
else<br />
style = 'Colors_HTML_HTMLLinks'; % CWLink<br />
underlineFlag = 1;<br />
end<br />
end<br />
% Convert a Matlab RGB vector into a known style name (e.g., '[255,37,0]')<br />
function styleName = getColorStyle(rgb)<br />
intColor = int32(rgb*255);<br />
javaColor = java.awt.Color(intColor(1), intColor(2), intColor(3));<br />
styleName = sprintf('[%d,%d,%d]',intColor);<br />
com.mathworks.services.Prefs.setColorPref(styleName,javaColor);<br />
% Fix a bug in some Matlab versions, where the number of URL segments<br />
% is larger than the number of style segments in a doc element<br />
function delta = getUrlsFix(docElement) %#ok currently unused<br />
tokens = docElement.getAttribute('SyntaxTokens');<br />
links = docElement.getAttribute('LinkStartTokens');<br />
if length(links) > length(tokens(1))<br />
delta = length(links) > length(tokens(1));<br />
else<br />
delta = 0;<br />
end<br />
% fprintf(2,str) causes all previous '_'s in the line to become red - fix this<br />
function fixHyperlink(docElement)<br />
try<br />
tokens = docElement.getAttribute('SyntaxTokens');<br />
urls = docElement.getAttribute('HtmlLink');<br />
urls = urls(2);<br />
links = docElement.getAttribute('LinkStartTokens');<br />
offsets = tokens(1);<br />
styles = tokens(2);<br />
doc = docElement.getDocument;<br />
% Loop over all segments in this docElement<br />
for idx = 1 : length(offsets)-1<br />
% If this is a hyperlink with no URL target and starts with ' ' and is collored as an error (red)...<br />
if strcmp(styles(idx).char,'Colors_M_Errors')<br />
character = char(doc.getText(offsets(idx)+docElement.getStartOffset,1));<br />
if strcmp(character,' ')<br />
if isempty(urls(idx)) && links(idx)==0<br />
% Revert the style color to the CW background color (i.e., hide it!)<br />
styles(idx) = java.lang.String('CW_BG_Color');<br />
end<br />
end<br />
end<br />
end<br />
catch<br />
% never mind...<br />
end<br />
% Set an element to a particular style (color)<br />
function setElementStyle(docElement,style,specialFlag, majorVersion,minorVersion)<br />
%global tokens links urls urlTargets % for debug only<br />
global oldStyles<br />
if nargin<3, specialFlag=0; end<br />
% Set the last Element token to the requested style:<br />
% Colors:<br />
tokens = docElement.getAttribute('SyntaxTokens');<br />
try<br />
styles = tokens(2);<br />
oldStyles{end+1} = cell(styles);<br />
% Correct edge case problem<br />
extraInd = double(majorVersion>7 || (majorVersion==7 && minorVersion>=13)); % =0 for R2011a-, =1 for R2011b+<br />
%{<br />
if ~strcmp('CWLink',char(styles(end-hyperlinkFlag))) && ...<br />
strcmp('CWLink',char(styles(end-hyperlinkFlag-1)))<br />
extraInd = 0;%1;<br />
end<br />
hyperlinkFlag = ~isempty(strmatch('CWLink',tokens(2)));<br />
hyperlinkFlag = 0 + any(cellfun(@(c)(~isempty(c)&&strcmp(c,'CWLink')),cell(tokens(2))));<br />
%}<br />
jStyle = java.lang.String(style);<br />
if numel(styles)==4 && isempty(char(styles(2)))<br />
% Attempt to fix discoloration issues - NOT SURE THAT THIS IS OK! - 24/6/2015<br />
styles(1) = jStyle;<br />
end<br />
styles(end-extraInd) = java.lang.String('');<br />
styles(end-extraInd-specialFlag) = jStyle; % #ok apparently unused but in reality used by Java<br />
if extraInd<br />
styles(end-specialFlag) = jStyle;<br />
end<br />
oldStyles{end} = [oldStyles{end} cell(styles)];<br />
catch<br />
% never mind for now<br />
end<br />
<br />
% Underlines (hyperlinks):<br />
%{<br />
links = docElement.getAttribute('LinkStartTokens');<br />
if isempty(links)<br />
%docElement.addAttribute('LinkStartTokens',repmat(int32(-1),length(tokens(2)),1));<br />
else<br />
%TODO: remove hyperlink by setting the value to -1<br />
end<br />
%}<br />
% Correct empty URLs to be un-hyperlinkable (only underlined)<br />
urls = docElement.getAttribute('HtmlLink');<br />
if ~isempty(urls)<br />
urlTargets = urls(2);<br />
for urlIdx = 1 : length(urlTargets)<br />
try<br />
if urlTargets(urlIdx).length < 1<br />
urlTargets(urlIdx) = []; % '' => []<br />
end<br />
catch<br />
% never mind...<br />
a=1; %#ok used for debug breakpoint...<br />
end<br />
end<br />
end<br />
<br />
% Bold: (currently unused because we cannot modify this immutable int32 numeric array)<br />
%{<br />
try<br />
%hasBold = docElement.isDefined('BoldStartTokens');<br />
bolds = docElement.getAttribute('BoldStartTokens');<br />
if ~isempty(bolds)<br />
%docElement.addAttribute('BoldStartTokens',repmat(int32(1),length(bolds),1));<br />
end<br />
catch<br />
% never mind - ignore...<br />
a=1; %#ok used for debug breakpoint...<br />
end<br />
%}<br />
<br />
return; % debug breakpoint<br />
% Display information about element(s)<br />
function dumpElement(docElements)<br />
%return;<br />
disp(' ');<br />
numElements = length(docElements);<br />
cmdWinDoc = docElements(1).getDocument;<br />
for elementIdx = 1 : numElements<br />
if numElements > 1, fprintf('Element #%d:\n',elementIdx); end<br />
docElement = docElements(elementIdx);<br />
if ~isjava(docElement), docElement = docElement.java; end<br />
%docElement.dump(java.lang.System.out,1)<br />
disp(docElement)<br />
tokens = docElement.getAttribute('SyntaxTokens');<br />
if isempty(tokens), continue; end<br />
links = docElement.getAttribute('LinkStartTokens');<br />
urls = docElement.getAttribute('HtmlLink');<br />
try bolds = docElement.getAttribute('BoldStartTokens'); catch, bolds = []; end<br />
txt = {};<br />
tokenLengths = tokens(1);<br />
for tokenIdx = 1 : length(tokenLengths)-1<br />
tokenLength = diff(tokenLengths(tokenIdx+[0,1]));<br />
if (tokenLength < 0)<br />
tokenLength = docElement.getEndOffset - docElement.getStartOffset - tokenLengths(tokenIdx);<br />
end<br />
txt{tokenIdx} = cmdWinDoc.getText(docElement.getStartOffset+tokenLengths(tokenIdx),tokenLength).char; %#ok<br />
end<br />
lastTokenStartOffset = docElement.getStartOffset + tokenLengths(end);<br />
try<br />
txt{end+1} = cmdWinDoc.getText(lastTokenStartOffset, docElement.getEndOffset-lastTokenStartOffset).char; %#ok<br />
catch<br />
txt{end+1} = ''; %#ok<AGROW><br />
end<br />
%cmdWinDoc.uiinspect<br />
%docElement.uiinspect<br />
txt = strrep(txt',sprintf('\n'),'\n');<br />
try<br />
data = [cell(tokens(2)) m2c(tokens(1)) m2c(links) m2c(urls(1)) cell(urls(2)) m2c(bolds) txt];<br />
if elementIdx==1<br />
disp(' SyntaxTokens(2,1) - LinkStartTokens - HtmlLink(1,2) - BoldStartTokens - txt');<br />
disp(' ==============================================================================');<br />
end<br />
catch<br />
try<br />
data = [cell(tokens(2)) m2c(tokens(1)) m2c(links) txt];<br />
catch<br />
disp([cell(tokens(2)) m2c(tokens(1)) txt]);<br />
try<br />
data = [m2c(links) m2c(urls(1)) cell(urls(2))];<br />
catch<br />
% Mtlab 7.1 only has urls(1)...<br />
data = [m2c(links) cell(urls)];<br />
end<br />
end<br />
end<br />
disp(data)<br />
end<br />
% Utility function to convert matrix => cell<br />
function cells = m2c(data)<br />
%datasize = size(data); cells = mat2cell(data,ones(1,datasize(1)),ones(1,datasize(2)));<br />
cells = num2cell(data);<br />
% Display the help and demo<br />
function showDemo(majorVersion,minorVersion)<br />
fprintf('cprintf displays formatted text in the Command Window.\n\n');<br />
fprintf('Syntax: count = cprintf(style,format,...); click <a href="matlab:help cprintf">here</a> for details.\n\n');<br />
url = 'http://UndocumentedMatlab.com/blog/cprintf/';<br />
fprintf(['Technical description: <a href="' url '">' url '</a>\n\n']);<br />
fprintf('Demo:\n\n');<br />
boldFlag = majorVersion>7 || (majorVersion==7 && minorVersion>=13);<br />
s = ['cprintf(''text'', ''regular black text'');' 10 ...<br />
'cprintf(''hyper'', ''followed %s'',''by'');' 10 ...<br />
'cprintf(''key'', ''%d colored'',' num2str(4+boldFlag) ');' 10 ...<br />
'cprintf(''-comment'',''& underlined'');' 10 ...<br />
'cprintf(''err'', ''elements:\n'');' 10 ...<br />
'cprintf(''cyan'', ''cyan'');' 10 ...<br />
'cprintf(''_green'', ''underlined green'');' 10 ...<br />
'cprintf(-[1,0,1], ''underlined magenta'');' 10 ...<br />
'cprintf([1,0.5,0], ''and multi-\nline orange\n'');' 10];<br />
if boldFlag<br />
% In R2011b+ the internal bug that causes the need for an extra space<br />
% is apparently fixed, so we must insert the sparator spaces manually...<br />
% On the other hand, 2011b enables *bold* format<br />
s = [s 'cprintf(''*blue'', ''and *bold* (R2011b+ only)\n'');' 10];<br />
s = strrep(s, ''')',' '')');<br />
s = strrep(s, ''',5)',' '',5)');<br />
s = strrep(s, '\n ','\n');<br />
end<br />
disp(s);<br />
eval(s);<br />
%%%%%%%%%%%%%%%%%%%%%%%%%% TODO %%%%%%%%%%%%%%%%%%%%%%%%%<br />
% - Fix: Remove leading space char (hidden underline '_')<br />
% - Fix: Find workaround for multi-line quirks/limitations<br />
% - Fix: Non-\n-terminated segments are displayed as black<br />
% - Fix: Check whether the hyperlink fix for 7.1 is also needed on 7.2 etc.<br />
% - Enh: Add font support</p>