📄 teximage.m
字号:
function out=teximage(s,varargin)
%TEXIMAGE display a LaTeX string as a bitmap image
% H = TEXIMAGE(S) creates an image of the LaTeX string S and
% displays it in the current figure. Click and drag to
% move the image and use the context menu to change properties.
% The image handle is returned in H, if specified. If S is a cell
% array of strings then each is made into a separate image and
% the resulting handles are returned as a vector. S can also be a
% symbolic expression (see SYM).
%
% H = TEXIMAGE(S,PARAM1,VALUE1,PARAM2,VALUE2,...) creates the image
% with options given by the parameter-value pairs. The argument S
% can be a string or the image handle H returned by a previous
% call to TEXIMAGE or a cell array of strings or vector of handles.
% The legal parameter strings and values are:
%
% 'antialias' one of the strings 'on' or 'off'
% antialiasing will produce more readable text on-screen
% but will sacrifice printout quality (default on)
%
% 'convolution' an integer
% the size of the convolution matrix for antialiasing (default 7)
% smaller numbers will result in sharper text
%
% 'background' a colorspec
% specifies the background color (default white)
% background color 'none' means no background (requires OpenGL renderer)
%
% 'scale' a double
% multiplies the image size by specified scale (default 1)
%
% 'resolution' a double
% the font resolution to use (default 600)
%
% 'displaymode' one of the strings 'math', 'text' or 'none'
% specifies the TeX display mode to use (default 'math')
% The 'none' displaymode will put the string S directly into
% the TeX file without any surrounding $ or $$.
%
% 'rotation' a multiple of 90
% rotates the image counterclockwise in degrees (default 0)
%
% 'position' a 2 element vector
% specifies the position of the center of the bitmap on the
% figure (default [.5 .5])
%
% 'units' an HG units string ('normalized','inches',...)
% specifies the units for the position property (default 'normalized')
%
% 'parent' a figure handle
% specifies the figure to use (default current figure)
%
% When the input S is a handle a new TeX string can be specified
% with the parameter 'texstring'. To get the current parameter
% value for a given handle call GETAPPDATA with the handle and
% the name of the parameter. eg,
% scale = getappdata(h,'scale');
%
% The default parameter values can be set in R12(or later) by calling
% SETPREF. eg,
% setpref('teximage','resolution',300);
% setpref('teximage','background',get(0,'DefaultFigureColor'));
% and in R11 by modifying STARTUP.M to call setappdata as follows:
% setappdata(0,'teximage',struct(...
% 'resolution',300,'background',get(0,'DefaultFigureColor'));
%
% H = TEXIMAGE('-noHG',S,PARAM1,VALUE1,...) generates the bitmap
% but does not create an HG image object. The bitmap is return in
% H as a height x width x 3 matrix of doubles.
%
% Important note: LaTeX must be installed before running this
% function. To obtain a LaTeX distribution see your system
% administrator or go to the web site http://www.tug.org
% This function was tested with MikTeX on PCs and Web2c7.2 on Unix.
%
% Examples:
% h = teximage('\dot{x} = \sqrt{x+1}','scale',2);
% teximage(h,'antialias','off');
% h2 = teximage('\lim_{n \rightarrow \infty} \left(1+\frac{1}{n}\right)^n')
% h3 = teximage('Math $x^2+1$ inline.','displaymode','none');
%
% See also: TEXT, SYM, LATEX
% Version 1.1. Copyright 2002 Ben Hinkle
% Email bug reports and comments to bhinkle@mathworks.com
%TODO:
% better text with transparent backgrounds - need darken/lighten?
% support arbitrary rotation angles
% support user-specified tex file template
% better support on old TeX versions and old MATLAB versions
% test more PC distributions and add them to the registry query
if isunix
exe_ext = '';
else
exe_ext = '.exe';
end
noHG = logical(0);
% first handle the callbacks
if isa(s,'char')
switch(lower(s))
case {'startmove','mousemove','endmove','figuremoved'}
feval(lower(s),varargin{:});
return;
case '-nohg'
noHG = logical(1);
s = varargin{1};
varargin(1) = [];
% note no return
case '-setup'
texbin = locateTeX;
if isequal(texbin,0)
texbin = promptForTeX(exe_ext);
if isequal(texbin,0)
error(['No TeX installed. See www.tug.org for' ...
'a list of distributions.']);
end
end
if ~isempty(texbin)
Lsetpref('teximage','texpath',texbin);
end
return;
case {'increasesize','decreasesize','whitecolor','transparent',...
'figurecolor','togglealias','sharpentex','blurtex',...
'rotclockwise','rotcounterclock'}
docallback(s,varargin{:});
return;
end
end
% handle vectorized inputs
if isa(s,'cell') | (ishandle(s) & length(s) > 1)
iscell = isa(s,'cell');
y = zeros(1,length(s));
for n=1:length(s)
if iscell
y(n) = teximage(s{n},varargin{:});
else
y(n) = teximage(s(n),varargin{:});
end
end
if nargout > 0
out = y;
end
return;
elseif isa(s,'sym') % handle symbolic expressions
s = latex(s);
end
% get the default values for the options
ishndl = ishandle(s);
antialias = getdefault(ishndl,s,'antialias','on');
convolution = getdefault(ishndl,s,'convolution',7);
resolution = getdefault(ishndl,s,'resolution',600);
background = getdefault(ishndl,s,'background',[1 1 1]);
scale = getdefault(ishndl,s,'scale',1);
displaymode = getdefault(ishndl,s,'displaymode','math');
rotation = getdefault(ishndl,s,'rotation',0);
position = getdefault(ishndl,s,'position',[.5 .5]);
units = getdefault(ishndl,s,'units','normalized');
parent = getdefault(ishndl,s,'parent','gcf');
if ishndl
oldHandle = s;
s = getappdata(s,'texstring');
end
%process param-value pairs
while length(varargin) > 0
if isa(varargin{1},'char') & (length(varargin) > 1)
switch lower(varargin{1})
case 'antialias'
antialias = lower(varargin{2});
case 'convolution'
convolution = varargin{2};
case 'resolution'
resolution = varargin{2};
case 'background'
background = varargin{2};
case 'scale'
scale = varargin{2};
case 'displaymode'
displaymode = lower(varargin{2});
case 'rotation'
rotation = varargin{2};
case 'texstring'
s = varargin{2};
case 'position'
position = varargin{2};
case 'units'
units = lower(varargin{2});
case 'parent'
parent = varargin{2};
otherwise
error(['Unrecognized parameter:' varargin{1} '.']);
end
end
varargin(1:2) = [];
end
if convolution < 1
convolution = 1;
end
rotation90 = round(rotation/90);
if ishndl & canreusebits(oldHandle,resolution,displaymode,s)
bits = getappdata(oldHandle,'texbitmap');
else
olddir = pwd;
file = tempname;
cd(tempdir);
try
tex(file,s,displaymode,exe_ext);
dvips(file,resolution,exe_ext);
bits = ghostscript(file,resolution,exe_ext);
catch
delete([file '*']);
cd(olddir);
error(deblank(lasterr));
end
delete([file '*']);
cd(olddir);
end
y = makeimage(bits,background,antialias,convolution,rotation90);
if noHG
out = y;
return;
end
% make an image in the current figure and set up callbacks
if isa(parent,'char')
parent = eval(parent);
end
fig = parent;
fpos = convertUnits(get(fig,'units'),get(fig,'position'),'inches');
center = convertUnits(units,[position 10 10],'inches',fpos,'inches');
ys = [size(y,2) size(y,1)] * scale / resolution;
if ishndl
h = oldHandle;
ax = get(h,'parent');
set(ax,'position',[center(1)-ys(1)*.5 center(2)-ys(2)*.5 ys(1) ...
ys(2)]);
set(h,'cdata',y);
try
if isequal(background,'none')
set(h,'alphadata',1-y(:,:,1));
if ~isequal(get(fig,'renderer'),'opengl')
set(fig,'renderer','opengl');
end
else
set(h,'alphadata',1);
end
end
set(ax,'xlim',[1 size(y,2)],'ylim',[1 size(y,1)]);
else
ax = axes('parent',fig,'visible','off',...
'handlevis','off','units','inch','tag','teximage_axes');
set(ax,'position',[center(1)-ys(1)*.5 center(2)-ys(2)*.5 ys(1) ...
ys(2)]);
h = image('cdata',y,'parent',ax,'tag','teximage');
try
if isequal(background,'none')
set(h,'alphadata',1-y(:,:,1));
if ~isequal(get(fig,'renderer'),'opengl')
set(fig,'renderer','opengl');
end
else
set(h,'alphadata',1);
end
end
set(ax,'xlim',[1 size(y,2)],'ylim',[1 size(y,1)],...
'xtick',[],'ytick',[],'ydir','reverse');
set(h,'uicontextmenu',makecontextmenu(h));
set(h,'buttondownfcn','teximage(''startmove'',gcbo)');
oldResize = get(fig,'resizefcn');
newResize = 'teximage(''figuremoved'',gcbo);';
if ~isempty(oldResize) & ~isequal(oldResize,newResize)
warning('Overwriting existing ResizeFcn property of figure.');
end
set(fig,'resizefcn',newResize);
end
setappdata(h,'resolution',resolution);
setappdata(h,'antialias',antialias);
setappdata(h,'convolution',convolution);
setappdata(h,'background',background);
setappdata(h,'scale',scale);
setappdata(h,'displaymode',displaymode);
setappdata(h,'texstring',s);
setappdata(h,'texbitmap',bits);
setappdata(h,'rotation',rotation);
setappdata(h,'position',position);
setappdata(h,'units',units);
setappdata(h,'parent',parent);
setantialiasmenu(h,antialias);
if nargout > 0
out = h;
end
function tex(file,s,displaymode,exe_ext)
tex_file = [file '.tex'];
tex_fid = fopen (tex_file, 'w');
if (tex_fid < 0)
error('Unable to create temporary file')
end
% write out the TeX file
fprintf(tex_fid, '%%&latex\n'); % this tells the TeX to use latex.fmt
fprintf(tex_fid, '\\documentclass{minimal}\n');
fprintf(tex_fid, '\\begin{document}\n');
if isequal(displaymode,'math')
fprintf(tex_fid, '$$');
fwrite(tex_fid, s);
fprintf(tex_fid, '$$ \n');
elseif isequal(displaymode,'text')
fprintf(tex_fid, '$');
fwrite(tex_fid, s);
fprintf(tex_fid, '$ \n');
else
fwrite(tex_fid, s);
fprintf(tex_fid, '\n');
end
fprintf(tex_fid, '\\end{document}\n');
fclose(tex_fid);
%now run TeX
if Lispref('teximage','texpath')
texbin = Lgetpref('teximage','texpath');
else
texbin = locateTeX;
if isequal(texbin,0)
error(['Cannot automatically locate TeX installation. ' ...
'Run ''teximage -setup'' to manually locate TeX. ']);
end
if ~isempty(texbin)
Lsetpref('teximage','texpath',texbin);
end
end
[s,r] = run_system_cmd(['echo X | "' fullfile(texbin,['tex' exe_ext]) ...
'" "' tex_file '"']);
if ~exist([file '.dvi'])
ind1 = findstr('!',r);
if ~isempty(ind1)
ind2 = findstr(sprintf('\n'),r(ind1+1:end));
r = r(ind1-1:ind1+ind2(3)-1);
end
error(['Error running TeX: ' r]);
end
function dvips(file,res,exe_ext)
dvi_file = [file '.dvi'];
ps_file = [file '.ps'];
if Lispref('teximage','texpath')
texbin = Lgetpref('teximage','texpath');
else
texbin = '';
end
[s,r] = run_system_cmd(['"' fullfile(texbin,['dvips' exe_ext]) ...
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -