4.89655

4.9 | 29 ratings Rate this file 129 Downloads (last 30 days) File Size: 7.2 KB File ID: #24093
image thumbnail

cprintf - display formatted colored text in the Command Window

by Yair Altman

 

12 May 2009 (Updated 27 Nov 2011)

Displays sprintf-formatted strings in the Command Window using the specified color/underline style

| Watch this File

File Information
Description

Syntax:
     count = cprintf(style,format,...)
 
Description:
CPRINTF processes the specified text using the exact same FORMAT arguments accepted by the built-in SPRINTF and FPRINTF functions.
 
CPRINTF then displays the text in the Command Window using the specified STYLE argument. The accepted styles are those used for Matlab's syntax highlighting (see: File / Preferences / Colors / M-file Syntax Highlighting Colors), and also user-defined colors.
 
The possible pre-defined STYLE names are:
 
   'Text' - default: black
   'Keywords' - default: blue
   'Comments' - default: green
   'Strings' - default: purple
   'UnterminatedStrings' - default: dark red
   'SystemCommands' - default: orange
   'Errors' - default: light red
   'Hyperlinks' - default: underlined blue
 
   'Black','Cyan','Magenta','Blue','Green','Red','Yellow','White'
 
Note: styles beginning with '-' will be underlined. For example:
   '-Blue' => underlined blue, like 'Hyperlinks'
   '-Comments' => underlined green
 
STYLE also accepts a regular Matlab RGB vector, that can be negated for underlining. For example: -[0,1,1] means underlined cyan.
 
STYLE is case-insensitive and accepts unique partial strings just like handle property names.
 
Examples (see results in the attached screenshot):
   cprintf; % displays the demo
   cprintf('text', 'regular black text');
   cprintf('hyper', 'followed %s','by');
   cprintf('k', '%d colored', 4);
   cprintf('-comment','& underlined');
   cprintf('err', 'elements\n');
   cprintf('cyan', 'cyan');
   cprintf('-green', 'underlined green');
   cprintf(-[1,0,1], 'underlined magenta');
   cprintf([1,0.5,0],'and multi-\nline orange\n');
 
Bugs and suggestions:
Please send to Yair Altman (altmany at gmail dot com)
 
Warning:
This code heavily relies on undocumented and unsupported Matlab functionality. It works on Matlab 7+, but use at your own risk!
 
A technical description of the implementation can be found at: http://UndocumentedMatlab.com/blog/cprintf/

See details & current limitations in the main help section

Acknowledgements
This submission has inspired the following:
setPrompt - Set the Command Window prompt
MATLAB release MATLAB 7.5 (R2007b)
Other requirements tested on Matlab 7.1, 7.5-7.12 (with a few version-specific quirks detailed in the help section). Should work on all Matlab 7 versions, but I haven't tested this.
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (46)
13 May 2009 Albert

Great, thanks!

13 May 2009 MATLABician

A while ago, a colleague asked me if it was possible to display in a color other than the default, in the Command Window, the values violating some thresholds in an optimization problem. My response was, "That must be doable, because MATLAB does that for, say, error messages. I will look into it." Well, you looked into it alright, Yair!

14 May 2009 Aurelien Queffurust

Tested successfully with the current release R2009a under Windows and with R2008b under Linux 64-bits. Just a great submission!

15 May 2009 Petter

I did not know this was possible

27 May 2009 Petter

The function prints an extra white space after each string. Example:

str = 'Welcome!';
n = length(str);
for k = 1:n
    col = [k/n 0 0];
    cprintf(col,str(k));
end
fprintf('\n');

results in:
 W e l c o m e !

27 May 2009 Petter

OK, I now think that may be required.

27 May 2009 Yair Altman

yes Petter - this is a known limitation of CPRINTF that is mentioned in its help section as well as the TODO list (at the bottom of the file). Unfortunately, it seems that if there is no space separator, then Matlab attempts to combine the adjacent style segments, thereby overrunning the first segment's style with the second's. Adding a separator solves this. If anyone finds a workaround I'll be happy to hear. Until then it's a small price to pay...

03 Jun 2009 Alan B  
04 Jun 2009 Karl

This is great! I wish Matlab documented its Java innards better. Anyway, there seems to be another small bug.

fprintf('Here: ')
cprintf('blue', 'Blue\n');

results in a blue underscore followed by the word 'Blue' in white (invisible on white background of my command window - but shows up when highlighted).

However, the same code as above, only using '-blue' instead of 'blue', works fine (gives the expected underlined blue text).

I'm using Matlab 2007b on a Linux box.

04 Jun 2009 Yair Altman

@Karl - this is a corollary of the known issue with non-newline-terminated strings. In this case, the initial fprintf() was non-newline-terminated, getting cprintf confused...

A workaround for this case is to simply use cprintf for the initial black text, instead of fprintf:

cprintf('text', 'Here: ');
cprintf('blue', 'Blue\n');

18 Jun 2009 Mike

There seems to be another bug, this one involving the '%' character. For example,

cprintf( 'keyword', '%% keyword\n' )

merely turns the command prompt (double chevron) blue, rather than printing '% keyword' and a newline character.

fprintf( '%% keyword\n' ), on the other hand, prints just what you would expect.

18 Jun 2009 Mike  
29 Sep 2009 LeFlaux

This is a great little tool! Thank You!

03 Nov 2009 A Millo  
17 Nov 2009 bocovp  
02 Dec 2009 Rahul PN  
30 Jan 2010 Rob Campbell

Nice! Although I run almost exclusively on Unix using the -nodesktop flag. Without the Mathworks command window this function doesn't work. In fact, it generates an error. Perhaps it ought to fail gracefully?

10 May 2010 André  
25 Jun 2010 Sharron

This is a great tool!.
However I think the command doesn't work well in printing the back slash, for example

cprintf('Errors', '\\abc\n')

does not generate output \abc

Thanks.

28 Jun 2010 Yair Altman

Sharron - I uploaded a new version that fixed the edge-case that you have reported

29 Jun 2010 Zachary Danziger  
06 Aug 2010 Yair Altman

read the description: cprintf prints to the command prompt - NOT TO A FILE !

03 Nov 2010 Evgeny Pr  
18 Dec 2010 Bijit Banik

Is it possible to change the text color of a GUI dialog box text with this cprintf function? For example:

title='ANALYTICAL SOLUTIONS';
author='bijit,yair';
Help_str=char(title,author);
helpdlg(Help_str,'Title and Authors');

Now I want to see 'bijit, yair' in different color.

with thanks.

18 Dec 2010 Yair Altman

Bijit - you cannot do that with cprintf, but you can do it via the text properties of the dialog box:

hDlg=helpdlg(Help_str,'Title and Authors');
hText = findall(hDlg,'type','text');
set(hText,'interpreter','tex','string','\color{red}Red text')

18 Dec 2010 Bijit Banik

Thanks a lot.

16 Jan 2011 Evgeny Pr

Hi!

CPRINTF in ~45 times more slowly than FPRINTF.
There is an opportunity to get rid of calling DRAWNOW in CPRINTF? This greatly reduces the performance.

05 Mar 2011 James Tursa

Great work. Of course, that means I want more! Is it possible to have blinking text? I know this is generally obnoxious to use, but that is exactly what I want when I put up a warning message and a pause in a piece of code that is about to potentially crash MATLAB (a bug demonstration code).

05 Mar 2011 Yair Altman

@James - unfortunately, blinking text is difficult to implement.

If this is sufficiently important to you, I'll be willing to develop it for you for a fee - contact me by email if this is the case.

12 Apr 2011 Cedric Wannaz

This function is great! It is in my todo list to use it, so I know almost nothing about it at this point. However, couldn't you replace the white space on line 145 with a \r for (at least partly) solving your white space issue?

fprintf('<a href="">\r</a>');

Just had a sneaky look, so I have no idea how it impacts the rest.

Best regards,

Cedric

17 May 2011 Ben

This helps me a lot.

However, it cannot cooperate with fprintf.
When using

cprintf('Text', '3D distance error (max):');
cprintf('Keywords', '%f\n', max(EVert));

it produces

 3D distance error (max): 0.226647

Since I do not want the leading space, when trying

fprintf('3D distance error (max):');
cprintf('Keywords', '%f\n', max(EVert));

it produced

3D distance error (max):_

There is underline with the right color, but the number is in WHITE.

Could you help me out, Yair?

Best regards,
Ben

20 May 2011 Reza Farrahi Moghaddam  
27 May 2011 Paul Macey  
28 May 2011 Matthias  
19 Jun 2011 Andrey Kan  
12 Jul 2011 Henry

This function is great. I've got only one problem. If I run it on a remote machine by ssh but without X (say via Cygwin), then it reports error:

<a href=""> </a>??? Attempt to reference field of non-structure array.

Error in ==> cprintf at 156
  xCmdWndView = cw.getComponent(0).getViewport.getComponent(0);

Obviously, I don't expect to see color when no display is specified. But I do want to my code platform independent. That is, if there is display, then show the colors. Otherwise, please just behave in the same way as fprintf(1, ...) (ie, please don't return error/failure).

17 Aug 2011 Chandrakanth  
29 Aug 2011 Danilo Zanatta

@Yair - I've found one bug:

Since I use black background and gray text for the command window, cprintf('text', 'Hello World!\n') was showing the string in black, i.e. invisible with my configurations.

By watching around a little bit, I figured out that the text color is "saved" in the 'ColorsText' preference, so I changed the code around line 242 to:

      % Regular text
      elseif matches == 1
          style = 'ColorsText';

Noew, when I use 'text' as style, I get *exactly* the color I have set in the preferences.

30 Aug 2011 mohammad  
06 Sep 2011 Jon  
15 Sep 2011 Mark Morehead

I have been using the cprintf function and find it very useful.

I just installed Matlab V 2011b (64bit) and cprintf is no longer working properly.

When I run it, I get:
>> cprintf('text', 'regular black text');
_ t>>
>>

If I highlight it, I get:
>> cprintf('text', 'regular black text');
regular black text>>
>>

So the text is printing in white. There must be a color inversion problem caused by something in the update in Matlab.

19 Sep 2011 Szilárd

A very useful function. Stopped working under R2011b (as Mark Morehead pointed it out).

Yair, do you plan to update it so that we can have this great stuff in future releases?

18 Nov 2011 Jerry Zhou  
23 Nov 2011 Rory Adams

You might find that changing the fprintf command on line 164 to use the standard output instead of standard error may solve your problem with the text colour

i.e. use
fprintf(1,format,varargin{:})
inplace of
fprintf(2,format,varargin{:})

28 Nov 2011 Yair Altman

For all the people who have noted about cprintf's issues with R2011b, the new version that was just uploaded fixes those problems, as well as the issue of the space (on R2011b only)

12 Dec 2011 Martin Lechner  
Please login to add a comment or rating.
Updates
28 Sep 2009

Fixed some problems reported by Andreas G & Swagat K

28 Sep 2009

Fixed some problems reported by Andreas G, Swagat K

26 Jun 2010

Minor fix for R2010a/b; fixed edge case reported by Sharron; CPRINTF with no args runs the demo

04 Mar 2011

Performance improvement

27 Nov 2011

Fixes for R2011b; fix by Danilo (FEX comment) for non-default text colors

Tag Activity for this File
Tag Applied By Date/Time
java Yair Altman 13 May 2009 09:23:03
desktop Yair Altman 13 May 2009 09:23:03
gui Yair Altman 13 May 2009 09:23:03
undocumented Yair Altman 13 May 2009 09:23:03

Contact us at files@mathworks.com