选自:http://forum.mathematex.net/asymptote-f34/extension-listings-latex-et-asymptote-t13260.html代码节选:

% !TEX TS-program = latexmk
% !TEX encoding = Latin1
\documentclass[11pt]{article}
%\usepackage[latin1]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[a4paper,%
 
hmargin={1cm,1cm},%
 
vmargin={1cm,1cm},%
 
headheight=15pt,%
 
nohead,nofoot]{geometry}

\usepackage{lmodern,fourier}
\usepackage[francais]{babel}
\usepackage{graphicx}
\usepackage[svgnames]{xcolor}
\usepackage{amsmath,amsfonts}

\setlength{\parindent}{0pt}

\usepackage{listings}

\definecolor{couleurfond}{rgb}{0.97,0.97,1} 
% couleur du fond du cadre
\definecolor{couleurdebase}{rgb}{0,0,0} 
% couleur d'écriture par défaut (noir)
\definecolor{couleuridentifier}{rgb}{0,.5,0} 
% identifier (variables)
\definecolor{couleurstring}{rgb}{0.39, 0.22,
0.13} % string
\definecolor{couleurcomments}{rgb}{0.37, 0.37, 0.56} % comments
(bleu)
\definecolor{couleurk1}{rgb}{1,.5,0} 
% asy-keyword-name
\definecolor{couleurk2}{rgb}{.8,0.1,0.1} 
% asy-type-name
\definecolor{couleurk3}{rgb}{0,0,1} 
% asy-function-name
\definecolor{couleurk4}{rgb}{0,.5,1} 
% asy-variable-name
\definecolor{couleurk5}{rgb}{.8,0.1,0.1} 
% types oubliés ou nouveau (rouge)

\lstdefinelanguage{Asymptote} {
morekeywords=[1]{and,controls,tension,atleast,curl,if,else,while,for,do,return,break,continue,struct,typedef,

new,access,import,unravel,from,include,quote,static,public,private,restricted,this,explicit,

true,false,null,cycle,newframe,operator},
%
morekeywords=[2]{Braid,FitResult,Label,Legend,Segment,Solution,TreeNode,abscissa,arc,arrowhead,binarytree,

binarytreeNode,block,bool,bool3,bounds,bqe,circle,conic,coord,coordsys,cputime,ellipse,file,

filltype,frame,grid3,guide,horner,hsv,hyperbola,indexedTransform,int,inversion,key,light,

line,linefit,marginT,marker,mass,object,pair,parabola,path,path3,pen,picture,point,position,

projection,real,revolution,scaleT,scientific,segment,side,slice,solution,splitface,string,

surface,tensionSpecifier,ticklocate,ticksgridT,tickvalues,transform,transformation,tree,

triangle,trilinear,triple,vector,vertex,void},
%
morekeywords=[3]{AND,Arc,ArcArrow,ArcArrows,Arrow,Arrows,Automatic,AvantGarde,BBox,BWRainbow,BWRainbow2,

Bar,Bars,BeginArcArrow,BeginArrow,BeginBar,BeginDotMargin,BeginMargin,BeginPenMargin,Blank,

Bookman,Bottom,BottomTop,Bounds,Break,Broken,BrokenLog,CLZ,CTZ,Ceil,Circle,

CircleBarIntervalMarker,Cos,Courier,CrossIntervalMarker,DOSendl,DOSnewl,DefaultFormat,

DefaultLogFormat,Degrees,Dir,DotMargin,DotMargins,Dotted,Draw,Drawline,Embed,EndArcArrow,

EndArrow,EndBar,EndDotMargin,EndMargin,EndPenMargin,Fill,FillDraw,Floor,Format,Full,

Gaussian,Gaussrand,Gaussrandpair,Gradient,Grayscale,Helvetica,Hermite,HookHead,InOutTicks,

InTicks,Jn,Label,Landscape,Left,LeftRight,LeftTicks,Legend,Linear,Link,Log,LogFormat,Margin,

Margins,Mark,MidArcArrow,MidArrow,NOT,NewCenturySchoolBook,NoBox,NoMargin,NoModifier,NoTicks,

NoTicks3,NoZero,NoZeroFormat,None,OR,OmitFormat,OmitTick,OmitTickInterval,OmitTickIntervals,

OutTicks,Ox,Oy,Palatino,PaletteTicks,Pen,PenMargin,PenMargins,Pentype,Portrait,RadialShade,

RadialShadeDraw,Rainbow,Range,Relative,Right,RightTicks,Rotate,Round,SQR,Scale,ScaleX,ScaleY,

ScaleZ,Seascape,Segment,Shift,Sin,Slant,Spline,StickIntervalMarker,Straight,Symbol,Tan,TeXify,

Ticks,Ticks3,TildeIntervalMarker,TimesRoman,Top,TrueMargin,UnFill,UpsideDown,Wheel,X,XEquals,

XOR,XY,XYEquals,XYZero,XYgrid,XZEquals,XZZero,XZero,XZgrid,Y,YEquals,YXgrid,YZ,YZEquals,YZZero,

YZero,YZgrid,Yn,Z,ZX,ZXgrid,ZYgrid,ZapfChancery,ZapfDingbats,_begingroup3,_cputime,_draw,_eval,

_image,_labelpath,_projection,_strokepath,_texpath,aCos,aSin,aTan,abort,abs,accel,acos,acosh,

acot,acsc,activatequote,add,addArrow,addMargins,addSaveFunction,addpenarc,addpenline,adjust,

alias,align,all,altitude,angabscissa,angle,angpoint,animate,annotate,anticomplementary,antipedal,

apply,approximate,arc,arcarrowsize,arccircle,arcdir,arcfromcenter,arcfromfocus,arclength,

arcnodesnumber,arcpoint,arcsubtended,arcsubtendedcenter,arctime,arctopath,array,arrow,arrow2,

arrowbase,arrowbasepoints,arrowsize,asec,asin,asinh,ask,assert,asy,asycode,asydir,asyfigure,

asyfilecode,asyinclude,asywrite,atan,atan2,atanh,atbreakpoint,atexit,attach,attract,atupdate,

autoformat,autoscale,autoscale3,axes,axes3,axialshade,axis,axiscoverage,azimuth,babel,

background,bangles,bar,barmarksize,barsize,basealign,baseline,bbox,beep,begin,beginclip,

begingroup,beginpoint,between,bevel,bezier,bezierP,bezierPP,bezierPPP,bezulate,bibliography,

bibliographystyle,binarytree,binarytreeNode,binomial,binput,bins,bisector,bisectorpoint,

bispline,blend,blockconnector,boutput,box,bqe,breakpoint,breakpoints,brick,buildRestoreDefaults,

buildRestoreThunk,buildcycle,bulletcolor,byte,calculateScaling,canonical,canonicalcartesiansystem,

cartesiansystem,case1,case2,case3,case4,cbrt,cd,ceil,center,centerToFocus,centroid,cevian,change2,

changecoordsys,checkSegment,checkconditionlength,checker,checkincreasing,checklengths,checkposition,

checktriangle,choose,circle,circlebarframe,circlemarkradius,circlenodesnumber,circumcenter,

circumcircle,clamped,clear,clip,clipdraw,close,cmyk,code,colatitude,collect,collinear,color,

colorless,colors,colorspace,comma,compassmark,complement,complementary,concat,concurrent,cone,

conic,conicnodesnumber,conictype,conj,connect,connected,connectedindex,containmentTree,contains,

contour,contour3,contouredges,controlSpecifier,convert,coordinates,coordsys,copy,copyPairOrTriple,

cos,cosh,cot,countIntersections,cputime,crop,cropcode,cross,crossframe,crosshatch,crossmarksize,

csc,cubicroots,curabscissa,curlSpecifier,curpoint,currentarrow,currentexitfunction,currentmomarrow,

currentpolarconicroutine,curve,cut,cutafter,cutbefore,cyclic,cylinder,deactivatequote,debugger,

deconstruct,defaultdir,defaultformat,defaultpen,defined,degenerate,degrees,delete,deletepreamble,

determinant,diagonal,diamond,diffdiv,dir,dirSpecifier,dirtime,display,distance,divisors,do_overpaint,

dot,dotframe,dotsize,downcase,draw,drawAll,drawDoubleLine,drawFermion,drawGhost,drawGluon,

drawMomArrow,drawPRCcylinder,drawPRCdisk,drawPRCsphere,drawPRCtube,drawPhoton,drawScalar,drawVertex,

drawVertexBox,drawVertexBoxO,drawVertexBoxX,drawVertexO,drawVertexOX,drawVertexTriangle,

drawVertexTriangleO,drawVertexX,drawarrow,drawarrow2,drawline,drawpixel,drawtick,duplicate,elle,

ellipse,ellipsenodesnumber,embed,embed3,empty,enclose,end,endScript,endclip,endgroup,endgroup3,

endl,endpoint,endpoints,eof,eol,equation,equations,erase,erasestep,erf,erfc,error,errorbar,

errorbars,eval,excenter,excircle,exit,exitXasyMode,exitfunction,exp,expfactors,expi,expm1,

exradius,extend,extension,extouch,fabs,factorial,fermat,fft,fhorner,figure,file,filecode,

fill,filldraw,filloutside,fillrule,filltype,find,finite,finiteDifferenceJacobian,firstcut,

firstframe,fit,fit2,fixedscaling,floor,flush,fmdefaults,fmod,focusToCenter,font,fontcommand,

fontsize,foot,format,frac,frequency,fromCenter,fromFocus,fspline,functionshade,gamma,

generate_random_backtrace,generateticks,gergonne,getc,getint,getpair,getreal,getstring,

gettriple,gluon,gouraudshade,graph,graphic,gray,grestore,grid,grid3,gsave,halfbox,hatch,

hdiffdiv,hermite,hex,histogram,history,hline,hprojection,hsv,hyperbola,hyperbolanodesnumber,

hyperlink,hypot,identity,image,incenter,incentral,incircle,increasing,incrementposition,

indexedTransform,indexedfigure,initXasyMode,initdefaults,input,inradius,insert,inside,

integrate,interactive,interior,interp,interpolate,intersect,intersection,intersectionpoint,

intersectionpoints,intersections,intouch,inverse,inversion,invisible,is3D,isCCW,isDuplicate,

isogonal,isogonalconjugate,isotomic,isotomicconjugate,isparabola,italic,item,jobname,key,

kurtosis,kurtosisexcess,label,labelaxis,labelmargin,labelpath,labels,labeltick,labelx,labelx3,

labely,labely3,labelz,labelz3,lastcut,latex,latitude,latticeshade,layer,layout,ldexp,leastsquares,

legend,legenditem,length,lexorder,lift,light,limits,line,linear,linecap,lineinversion,linejoin,

linemargin,lineskip,linetype,linewidth,link,list,lm_enorm,lm_evaluate_default,lm_lmdif,lm_lmpar,

lm_minimize,lm_print_default,lm_print_quiet,lm_qrfac,lm_qrsolv,locale,locate,locatefile,location,

log,log10,log1p,logaxiscoverage,longitude,lookup,makeNode,makedraw,makepen,map,margin,markangle,

markangleradius,markanglespace,markarc,marker,markinterval,marknodes,markrightangle,markuniform,

mass,masscenter,massformat,math,max,max3,maxAfterTransform,maxbezier,maxbound,maxcoords,maxlength,

maxratio,maxtimes,mean,medial,median,midpoint,min,min3,minAfterTransform,minbezier,minbound,

minipage,minratio,mintimes,miterlimit,mktemp,momArrowPath,momarrowsize,monotonic,multifigure,

nativeformat,natural,needshipout,newl,newpage,newslide,newton,newtree,nextframe,nextnormal,

nextpage,nib,nodabscissa,none,norm,normalvideo,notaknot,nowarn,numberpage,nurb,object,offset,

onpath,opacity,opposite,orientation,origin,orthic,orthocentercenter,outformat,outline,outname,

outprefix,output,overloadedMessage,overwrite,pack,pad,pairs,palette,parabola,parabolanodesnumber,

parallel,parallelogram,partialsum,path,path3,pattern,pause,pdf,pedal,periodic,perp,perpendicular,

perpendicularmark,phantom,phi1,phi2,phi3,photon,piecewisestraight,point,polar,polarconicroutine,

polargraph,polygon,postcontrol,postscript,pow10,ppoint,prc,prc0,precision,precontrol,prepend,

printBytecode,print_random_addresses,project,projection,purge,pwhermite,quadrant,quadraticroots,

quantize,quarticroots,quotient,radialshade,radians,radicalcenter,radicalline,radius,rand,randompath,

rd,readline,realmult,realquarticroots,rectangle,rectangular,rectify,reflect,relabscissa,relative,

relativedistance,reldir,relpoint,reltime,remainder,remark,removeDuplicates,rename,replace,report,

resetdefaultpen,restore,restoredefaults,reverse,reversevideo,rf,rfind,rgb,rgba,rgbint,rms,rotate,

rotateO,rotation,round,roundbox,roundedpath,roundrectangle,same,samecoordsys,sameside,sample,save,

savedefaults,saveline,scale,scale3,scaleO,scaleT,scaleless,scientific,search,searchindex,searchtree,

sec,secondaryX,secondaryY,seconds,section,sector,seek,seekeof,segment,sequence,setcontour,setpens,

sgn,sgnd,sharpangle,sharpdegrees,shift,shiftless,shipout,shipout3,show,side,simeq,simpson,sin,sinh,

size,size3,skewness,skip,slant,sleep,slope,slopefield,solve,solveBVP,sort,sourceline,sphere,split,

sqrt,square,srand,standardizecoordsys,startScript,stdev,step,stickframe,stickmarksize,

stickmarkspace,stop,straight,straightness,string,stripdirectory,stripextension,stripfile,

stripsuffix,strokepath,subdivide,subitem,subpath,substr,sum,surface,symmedial,symmedian,system,

tab,tableau,tan,tangent,tangential,tangents,tanh,tell,tensionSpecifier,tensorshade,tex,texcolor,

texify,texpath,texpreamble,texreset,texshipout,texsize,textpath,thick,thin,tick,tickMax,tickMax3,

tickMin,tickMin3,ticklabelshift,ticklocate,tildeframe,tildemarksize,tile,tiling,time,times,title,

titlepage,topbox,transform,transformation,transpose,trembleFuzz,triangle,triangleAbc,triangleabc,

triangulate,tricoef,tridiagonal,trilinear,trim,truepoint,tube,uncycle,unfill,uniform,unique,unit,

unitrand,unitsize,unityroot,unstraighten,upcase,updatefunction,uperiodic,upscale,uptodate,usepackage,

usersetting,usetypescript,usleep,value,variance,variancebiased,vbox,vector,vectorfield,verbatim,

view,vline,vperiodic,vprojection,warn,warning,windingnumber,write,xaxis,xaxis3,xaxis3At,xaxisAt,

xequals,xinput,xlimits,xoutput,xpart,xscale,xscaleO,xtick,xtick3,xtrans,yaxis,yaxis3,yaxis3At,

yaxisAt,yequals,ylimits,ypart,yscale,yscaleO,ytick,ytick3,ytrans,zaxis3,zaxis3At,zero,zero3,

zlimits,zpart,ztick,ztick3,ztrans},
%
morekeywords=[4]{AliceBlue,Align,Allow,AntiqueWhite,Apricot,Aqua,Aquamarine,Aspect,Azure,BeginPoint,Beige,

Bisque,Bittersweet,Black,BlanchedAlmond,Blue,BlueGreen,BlueViolet,Both,Break,BrickRed,Brown,

BurlyWood,BurntOrange,CCW,CW,CadetBlue,CarnationPink,Center,Centered,Cerulean,Chartreuse,

Chocolate,Coeff,Coral,CornflowerBlue,Cornsilk,Crimson,Crop,Cyan,Dandelion,DarkBlue,DarkCyan,

DarkGoldenrod,DarkGray,DarkGreen,DarkKhaki,DarkMagenta,DarkOliveGreen,DarkOrange,DarkOrchid,

DarkRed,DarkSalmon,DarkSeaGreen,DarkSlateBlue,DarkSlateGray,DarkTurquoise,DarkViolet,DeepPink,

DeepSkyBlue,DefaultHead,DimGray,DodgerBlue,Dotted,Down,Draw,E,ENE,EPS,ESE,E_Euler,E_PC,E_RK2,

E_RK3BS,Emerald,EndPoint,Euler,Fill,FillDraw,FireBrick,FloralWhite,ForestGreen,Fuchsia,Gainsboro,

GhostWhite,Gold,Goldenrod,Gray,Green,GreenYellow,Honeydew,HookHead,Horizontal,HotPink,I,

IgnoreAspect,IndianRed,Indigo,Ivory,JOIN_IN,JOIN_OUT,JungleGreen,Khaki,LM_DWARF,LM_MACHEP,

LM_SQRT_DWARF,LM_SQRT_GIANT,LM_USERTOL,Label,Lavender,LavenderBlush,LawnGreen,Left,LeftJustified,

LeftSide,LemonChiffon,LightBlue,LightCoral,LightCyan,LightGoldenrodYellow,LightGreen,LightGrey,

LightPink,LightSalmon,LightSeaGreen,LightSkyBlue,LightSlateGray,LightSteelBlue,LightYellow,

Lime,LimeGreen,Linear,Linen,Log,Logarithmic,Magenta,Mahogany,Mark,MarkFill,Maroon,Max,

MediumAquamarine,MediumBlue,MediumOrchid,MediumPurple,MediumSeaGreen,MediumSlateBlue,

MediumSpringGreen,MediumTurquoise,MediumVioletRed,Melon,MidPoint,MidnightBlue,Min,MintCream,

MistyRose,Moccasin,Move,MoveQuiet,Mulberry,N,NE,NNE,NNW,NW,NavajoWhite,Navy,NavyBlue,

NoAlign,NoCrop,NoFill,NoSide,OldLace,Olive,OliveDrab,OliveGreen,Orange,OrangeRed,Orchid,Ox,

Oy,PC,PaleGoldenrod,PaleGreen,PaleTurquoise,PaleVioletRed,PapayaWhip,Peach,PeachPuff,Periwinkle,

Peru,PineGreen,Pink,Plum,PowderBlue,ProcessBlue,Purple,RK2,RK3,RK3BS,RK4,RK5,RK5DP,RK5F,

RawSienna,Red,RedOrange,RedViolet,Rhodamine,Right,RightJustified,RightSide,RosyBrown,RoyalBlue,

RoyalPurple,RubineRed,S,SE,SSE,SSW,SW,SaddleBrown,Salmon,SandyBrown,SeaGreen,Seashell,Sepia,

Sienna,Silver,SimpleHead,SkyBlue,SlateBlue,SlateGray,Snow,SpringGreen,SteelBlue,Suppress,

SuppressQuiet,Tan,TeXHead,Teal,TealBlue,Thistle,Ticksize,Tomato,Turquoise,UnFill,Up,VERSION,

Value,Vertical,Violet,VioletRed,W,WNW,WSW,Wheat,White,WhiteSmoke,WildStrawberry,XYAlign,YAlign,

Yellow,YellowGreen,YellowOrange,addpenarc,addpenline,align,allowstepping,angularsystem,

animationdelay,appendsuffix,arcarrowangle,arcarrowfactor,arrow2sizelimit,arrowangle,arrowbarb,

arrowdir,arrowfactor,arrowhookfactor,arrowlength,arrowsizelimit,arrowtexfactor,authorpen,

axis,axiscoverage,axislabelfactor,background,backgroundcolor,backgroundpen,barfactor,

barmarksizefactor,basealign,baselinetemplate,beveljoin,bigvertexpen,bigvertexsize,black,

blue,bm,bottom,bp,brown,bullet,byfoci,byvertices,camerafactor,chartreuse,circlemarkradiusfactor,

circlenodesnumberfactor,circleprecision,circlescale,cm,codefile,codepen,codeskip,colorPen,

coloredNodes,coloredSegments,conditionlength,conicnodesfactor,count,cputimeformat,

crossmarksizefactor,currentcoordsys,currentlight,currentpatterns,currentpen,currentpicture,

currentposition,currentprojection,curvilinearsystem,cuttings,cyan,darkblue,darkbrown,darkcyan,

darkgray,darkgreen,darkgrey,darkmagenta,darkolive,darkred,dashdotted,dashed,datepen,dateskip,

debuggerlines,debugging,deepblue,deepcyan,deepgray,deepgreen,deepgrey,deepmagenta,deepred,

default,defaultControl,defaultS,defaultbackpen,defaultcoordsys,defaultexcursion,defaultfilename,

defaultformat,defaultmassformat,defaultpen,diagnostics,differentlengths,dot,dotfactor,dotframe,

dotted,doublelinepen,doublelinespacing,down,duplicateFuzz,edge,ellipsenodesnumberfactor,eps,

epsgeo,epsilon,evenodd,expansionfactor,extendcap,exterior,fermionpen,figureborder,figuremattpen,

file3,firstnode,firststep,foregroundcolor,fuchsia,fuzz,gapfactor,ghostpen,gluonamplitude,

gluonpen,gluonratio,gray,green,grey,hatchepsilon,havepagenumber,heavyblue,heavycyan,heavygray,

heavygreen,heavygrey,heavymagenta,heavyred,hline,hwratio,hyperbola,hyperbolanodesnumberfactor,

identity4,ignore,inXasyMode,inch,inches,includegraphicscommand,inf,infinity,institutionpen,intMax,

intMin,interior,invert,invisible,itempen,itemskip,itemstep,labelmargin,landscape,lastnode,left,

legendhskip,legendlinelength,legendmargin,legendmarkersize,legendmaxrelativewidth,legendvskip,

lightblue,lightcyan,lightgray,lightgreen,lightgrey,lightmagenta,lightolive,lightred,lightyellow,

line,linemargin,lm_infmsg,lm_shortmsg,longdashdotted,longdashed,magenta,magneticRadius,mantissaBits,

markangleradius,markangleradiusfactor,markanglespace,markanglespacefactor,mediumblue,mediumcyan,

mediumgray,mediumgreen,mediumgrey,mediummagenta,mediumred,mediumyellow,middle,minDistDefault,

minblockheight,minblockwidth,mincirclediameter,minipagemargin,minipagewidth,minvertexangle,

miterjoin,mm,momarrowfactor,momarrowlength,momarrowmargin,momarrowoffset,momarrowpen,monoPen,

morepoints,nCircle,newbulletcolor,ngraph,nil,nmesh,nobasealign,nodeMarginDefault,nodesystem,

nomarker,nopoint,noprimary,nullpath,nullpen,numarray,ocgindex,oldbulletcolor,olive,orange,

origin,overpaint,page,pageheight,pagemargin,pagenumberalign,pagenumberpen,pagenumberposition,

pagewidth,paleblue,palecyan,palegray,palegreen,palegrey,palemagenta,palered,paleyellow,

parabolanodesnumberfactor,perpfactor,phi,photonamplitude,photonpen,photonratio,pi,pink,

plain,plain_bounds,plain_scaling,plus,preamblenodes,pt,purple,r3,r4a,r4b,randMax,realDigits,

realEpsilon,realMax,realMin,red,relativesystem,reverse,right,roundcap,roundjoin,royalblue,

salmon,saveFunctions,scalarpen,sequencereal,settings,shipped,signedtrailingzero,solid,

springgreen,sqrtEpsilon,squarecap,squarepen,startposition,stdin,stdout,stepfactor,

stepfraction,steppagenumberpen,stepping,stickframe,stickmarksizefactor,stickmarkspacefactor,

swap,textpen,ticksize,tildeframe,tildemarksizefactor,tinv,titlealign,titlepagepen,

titlepageposition,titlepen,titleskip,top,trailingzero,treeLevelStep,treeMinNodeWidth,

treeNodeStep,trembleAngle,trembleFrequency,trembleRandom,undefined,unitcircle,unitsquare,

up,urlpen,urlskip,version,vertexpen,vertexsize,viewportmargin,viewportsize,vline,white,wye,

xformStack,yellow,ylabelwidth,zerotickfuzz,zerowinding},
% Des mots-clefs oubliés ou persos :
morekeywords=[5]{Noeud,skeleton,GRAPHE,stylegraphe,envelope},
%
sensitive=true,
morecomment=[l]{//},
morecomment=[s]{},
morestring=[b]",
morestring=[d]'
}[strings,keywords,comments]

\lstdefinestyle{AsyCode} {
 
language 
= Asymptote,
 
backgroundcolor = \color{couleurfond},
 
basicstyle 
= \bf\small\ttfamily\color{couleurdebase},
 
identifierstyle =
\color{couleuridentifier},
 
stringstyle 
= \color{couleurstring},
 
commentstyle 
= \color{couleurcomments},
 
keywordstyle 
= {[1]\color{couleurk1}},
 
keywordstyle 
= {[2]\color{couleurk2}\underbar},
 
keywordstyle 
= {[3]\color{couleurk3}},
 
keywordstyle 
= {[4]\color{couleurk4}},
 
keywordstyle 
= {[5]\color{couleurk5}},
 
extendedchars 
= true,
 
tabsize 
= 4,
 
showtabs 
= false,
 
showspaces 
= false,
 
showstringspaces = false,
 
breakautoindent = true,
 
breaklines 
= true,
 
flexiblecolumns = true,
 
keepspaces 
= true,
 }
\lstset{
 style =
AsyCode,
 
numbers=left,
 
numberstyle=\small\color{blue},
 
stepnumber=1,
 
xleftmargin=20mm, xrightmargin=20mm,
 
numbersep=10mm, framexleftmargin=5mm, rulesep=1mm,
 
caption=\lstname,
 
firstnumber=last,
 
rulesepcolor=\color{couleurcomments},
 
frame=trBL
}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{document}

Test

\hfil
\begin{lstlisting}[title=Test de coloration]

usepackage("siunitx", "locale=DE");
size(7cm,7cm,IgnoreAspect);

// Fonction donnant la factorielle de n de fa??on
itérative
int factorielle_ite(int n) {
 if
(n<=1) return 1;
 else {
 
int f=1;
 
for(int i=2;i<=n;++i) f=f*i;
 
return f;
 }
}
// Fonction donnant la factorielle de n de fa??on récursive
int factorielle_rec(int n) {
 if (n == 0)
return 1;
 else return
n * factorielle_rec(n-1);
}
int x=0,y=0;
label("n",(x,y)); label("factorielle\_ite(n)",(++x,y+1));
 
label("factorial(n)",(x+=2,y+1));
for (int k=0; k<10; ++k) {
 x=0;
--y;
 
label(format(k),(x,y));
 
label(format("\num{%i}",factorielle_ite(k)),(++x,y));
 
label(format("\num{%i}",factorielle_rec(k)),(++x,y));
 
label(format("\num{%i}",factorial(k)),(++x,y));
}
label("factorielle\_rec(n)",(--x,y-=2));
shipout(bbox(.2cm,Fill(palegreen)));}
\end{lstlisting}

Test

\begin{lstlisting}[frame=simple,title=Deuxième test avec un type
d'objet perso]
import gm_graphes;
import gm_graphes_styles;
size(7cm,0);
pair sA=(0,0), sB=(4,3), sC=(5,-2), sD=(-1,3),
 
sE=(-2,1), sF=(1,-3), sG=(-2,-2);
pair[] 
sommets={sA,sB,sC,sD,sE,sF,sG};
string[] noms={"$A$","$B$","$C$","$D$","$E$"};
real[][] matadj={{1,1,0,0,0,1},
 
{0,0,0,1,0,0},
 
{1,3,0,0,0,1},
 
{0,2,0,0,1,0}};
GRAPHE gr=GRAPHE(sommets,
 
noms,
 
matadj,
 
style_boule_1
 
);
// On a adopté d'abord le style "style_boule_1" pour l'objet/graphe
gr
// puis on en modifie le style d'une arête particulière avant
tra??age.
modif_a(gr,0,1,a_ang=0,a_pen=1.5bp+.5blue, // arête qui relie les
sommets 0 et 1
 
a_penbelow=2.5bp+paleblue);
draw(gr,aff_a_lab=true);
\end{lstlisting}

Un problème demeure : être capable de faire la distinction entre
le type GRAPHE et la fonction GRAPHE.
\end{document}

发布时间:2012-06-03 00:54:41文章类别:小技巧原文地址:QQ群:91940767/145316219/141877998/80300084/194770436淘宝店:http://latexstudio.taobao.com

点赞(0)

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部