Extension listings (latex) et asymptote

Tout ce qui concerne le langage Asymptote. Ce langage est utilisable sur le forum via les balises asy.
[participation réservée aux utilisateurs inscrits]
Règles du forum
Merci de soigner la rédaction de vos messages et de consulter ce sujet avant de poster. Pensez également à utiliser la fonction recherche du forum.
Francky
Utilisateur éprouvé
Utilisateur éprouvé
Messages : 681
Inscription : dimanche 11 avril 2010, 14:01

Extension listings (latex) et asymptote

Message non lu par Francky »

Ph. Ivaldi a écrit :L'idéal serait d'utiliser l'extension listing mais elle ne connait pas Asymptote.
On peut définir un nouveau langage pour asymptote, j'ai fait une mini ébauche à deux balles.
Je voulais faire un mini papier d'intro (genre encore plus simple que ce qui est dispo), mais j'ai pas encore assez de recul avec asymptote.
Si quelqu'un se lance dans l'entreprise asymptote-listings, il pourra en faire profiter tout le monde. Un simple envoi à l'auteur de listings d'une bonne version, et ce sera inclus dans la prochaine mouture. Ce serait bien qu'un 'cardor' le fasse ; je veux bien participer, mais je sais que j'ai pas le niveau.

Code : Tout sélectionner

\lstdefinelanguage{asymptote}{%
keywords=[1]{import, unitsize, add, shift, label, draw, dot,
 show, arc}, %pour asymptote + geometry
keywords=[2]{geometry, grid, triangleabc, perpendicularmark},% pour les autres extensions
keywords=[3]{pair, triangle, path}, % pour les classes
keywords=[4]{lightgray, black, gray, red}, %pour les couleurs
keywords=[5]{bp, pt, cm,  % unités
 N, E, S, W, NE, SE, SW, NW,
 NNE, ENE, ESE, SSE, SSW, WSW, WNW, NNW},% points cardinaux
comment=[l]{//},
otherkeywords={ -- , .. , :: , \^\^},
sensitive=true,
%morecomment=[s]{/*}{*/},
%string=[d]",
moredelim=*[s][\color{purple}]{"}{"},
moredelim=**[s][\color{OliveGreen}]{{$}{$}}
}


\lstset{%
language=asymptote,
keywordstyle=[1]\ttfamily\bfseries\color{red},
keywordstyle=[2]\ttfamily\color{cyan},
keywordstyle=[3]\ttfamily\bfseries,
keywordstyle=[4]\ttfamily\color{Bittersweet},
keywordstyle=[5]\ttfamily\bfseries\color{brown},
identifierstyle=\ttfamily\color{black!75},
firstnumber=5
}% à compléter au besoin
%
%
J'espère que cet embryon de code va susciter une vocation.
Je vais aussi voir si je peux étoffer mon papier.
Linux Mint | TeXLive - TexMaker - asymptote | Python3 & C - Geany - Project Euler - SPOJ
Entia non sunt multiplicanda praeter necessitatem
GMaths
Utilisateur chevronné
Utilisateur chevronné
Messages : 2042
Inscription : lundi 01 octobre 2007, 10:20

Re: listings[latex] et asymptote

Message non lu par GMaths »

Je n'avais pas vu le doublon. J'ai répondu ici.
GMaths
Utilisateur chevronné
Utilisateur chevronné
Messages : 2042
Inscription : lundi 01 octobre 2007, 10:20

Re: listings[latex] et asymptote

Message non lu par GMaths »

... et les listes déjà faites, sont évidemment celles-ci fournies avec Asymptote :

Code : Tout sélectionner

(defvar asy-keyword-name '(
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 ))

(defvar asy-type-name '(
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 ))

(defvar asy-function-name '(
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 ))

(defvar asy-variable-name '(
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 ))
Alors bien sûr... on peut tenter de personnaliser davantage... mais une fois que l'on a ajouté en plus des couleurs spécifiques pour les commentaires, les parenthèses, accolades, les chiffres, etc ... cela fait déjà très coloré. Moi j'avais juste ajouté des groupes pour mes propres définitions enfin de les distinguer des 4 listes officielles qui sont alors plus simples à mettre à jour à chaque mise à jour d'Asymptote, sans avoir de tri à faire.
OG
Modérateur honoraire
Modérateur honoraire
Messages : 2293
Inscription : lundi 12 mars 2007, 11:20
Localisation : Rouen

Re: listings[latex] et asymptote

Message non lu par OG »

Et listings (ou LaTeX) est-il capable d'avaler tous ces mots clefs ?

O.G.
GMaths
Utilisateur chevronné
Utilisateur chevronné
Messages : 2042
Inscription : lundi 01 octobre 2007, 10:20

Re: listings[latex] et asymptote

Message non lu par GMaths »

OG a écrit :Et listings (ou LaTeX) est-il capable d'avaler tous ces mots clefs ?
Aucun problème chez moi.

J'ai ressorti ce vieux fichier de coloration (dans un état pitoyable tellement mes tests de listings étaient partis dans tous les sens... en me promettant à l'époque, après des essais rapides, d'y revenir après pour mettre les choses au propre... sans tenir la promesse jusqu'à aujourd'hui) et donc je vais le retoucher un peu avant de copier-coller ici un exemple.
GMaths
Utilisateur chevronné
Utilisateur chevronné
Messages : 2042
Inscription : lundi 01 octobre 2007, 10:20

Re: listings[latex] et asymptote

Message non lu par GMaths »

Un exemple qui devrait compiler :

Code : Tout sélectionner

% !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,.8,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{couleurk3}{rgb}{1,.5,0}                % asy-keyword-name
    \definecolor{couleurk4}{rgb}{.8,0.1,0.1}           % asy-type-name
    \definecolor{couleurk5}{rgb}{0,0,1}               % asy-function-name
    \definecolor{couleurk6}{rgb}{0,.5,1}             % asy-variable-name
    \definecolor{couleurk7}{rgb}{.8,0.1,0.1}        % types oubliés ou nouveau (rouge)

\lstdefinelanguage{Asymptote} {
morekeywords=[3]{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=[4]{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=[5]{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=[6]{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=[7]{Noeud,skeleton,GRAPHEchr(32),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     = {[3]\color{couleurk3}},
    keywordstyle     = {[4]\color{couleurk4}\underbar},
    keywordstyle     = {[5]\color{couleurk5}},
    keywordstyle     = {[6]\color{couleurk6}},
    keywordstyle     = {[7]\color{couleurk7}},
    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]
/* Ce qui suit n'est plus utile depuis la révision 4127, où ont été 
   implémentés : factorial(Int n) et choose(Int n, Int k) mais cela reste 
   un exemple intéressant du point de vue des possibilités de programmation.
*/
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}
\end{document}
test_asy_listings.pdf
(48.34 Kio) Téléchargé 596 fois
alors bien sûr... les couleurs sont à revoir suivant les goûts... et il faudra voir s'il n'y a pas de mauvaises "détections".
Dernière modification par GMaths le vendredi 01 juillet 2011, 00:46, modifié 1 fois.
projetmbc
Utilisateur chevronné
Utilisateur chevronné
Messages : 2303
Inscription : samedi 29 décembre 2007, 00:58

Re: listings[latex] et asymptote

Message non lu par projetmbc »

Bonsoir.

Pour éviter les soucis d'accents en français sans passer par XeLaTeX, voici un code complété avec des paramètres proposés par nicollivier.

Code : Tout sélectionner

% Sources
%
%   1) Coloration pour Asymptote :
%       http://forum.mathematex.net/asymptote-f34/listings-et-asymptote-t13260.html#p127643
%
%   2) Gestion des accents :
%       http://forum.mathematex.net/latex-f6/mettre-un-titre-a-ses-boites-t12446-20.html#p120797

\documentclass[11pt]{article}
	\usepackage[utf8x]{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}   

	\usepackage{listings}

	\setlength{\parindent}{0pt}


% Hack pour forcer la compatibilité avec UTF8
% (pour le français uniquement)
	\lstset{
		extendedchars = true,
		literate =
%	* Lettres a et A
		{à}{{\`a}}1 {â}{{\^a}}1 
		{À}{{\`A}}1 {Â}{{\^A}}1
%	* Lettres c et C
		{ç}{{\c{c}}}1
		{Ç}{{\c{C}}}1
%	* Lettres e et E
		{é}{{\'e}}1 {è}{{\`e}}1 {ê}{{\^e}}1 {ë}{{\"e}}1
		{É}{{\'E}}1 {È}{{\`E}}1 {Ê}{{\^E}}1 {Ë}{{\"E}}1
%	* Lettres i et I
		{î}{{\^i}}1 {ï}{{\"i}}1
		{Î}{{\^I}}1 {Ï}{{\"I}}1
%	* Lettres o et O
		{ô}{{\^o}}1
		{Ô}{{\^O}}1
%	* Lettres oe et OE
		{œ}{{\oe}}1
		{Œ}{{\OE}}1
%	* Lettres u et U
		{ù}{{\`u}}1 {û}{{\^u}}1 {ü}{{\"u}}1
		{Ù}{{\`U}}1 {Û}{{\^U}}1 {Ü}{{\"U}}1
%	* Caractères spéciaux
		{°}{{\textdegree}}1
		{±}{{\textpm}}1
		{'}{{\textquotesingle}}1
		{§}{{\S}}1
	}


% Coloration des codes Asymptote

	\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,.8,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{couleurk3}{rgb}{1,.5,0}                  % asy-keyword-name
	\definecolor{couleurk4}{rgb}{.8,0.1,0.1}              % asy-type-name
	\definecolor{couleurk5}{rgb}{0,0,1}                   % asy-function-name
	\definecolor{couleurk6}{rgb}{0,.5,1}                  % asy-variable-name
	\definecolor{couleurk7}{rgb}{.8,0.1,0.1}              % types oubliés ou nouveau (rouge)

	\lstdefinelanguage{Asymptote}{
		morekeywords=[3]{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=[4]{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=[5]{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=[6]{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=[7]{Noeud,skeleton,GRAPHEchr(32),stylegraphe,envelope},
%
		sensitive=true,
		morecomment=[l]{//},
		morecomment=[s]{/*}{*/},
		morestring=[b]",
		morestring=[d]'
	}[strings,keywords,comments]

% UN joli environnement
	\lstdefinestyle{AsyCode} {
		language         = Asymptote,
		backgroundcolor  = \color{couleurfond},
		basicstyle       = \bf\small\ttfamily\color{couleurdebase},
		identifierstyle  = \color{couleuridentifier},
		stringstyle      = \color{couleurstring},
		commentstyle     = \color{couleurcomments},
		keywordstyle     = {[3]\color{couleurk3}},
		keywordstyle     = {[4]\color{couleurk4}\underbar},
		keywordstyle     = {[5]\color{couleurk5}},
		keywordstyle     = {[6]\color{couleurk6}},
		keywordstyle     = {[7]\color{couleurk7}},
		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}

\section{Test}

\hfill

\begin{lstlisting}[title=Test de coloration]
/* Ce qui suit n'est plus utile depuis la révision 4127, où ont été
   implémentés : factorial(Int n) et choose(Int n, Int k) mais cela reste
   un exemple intéressant du point de vue des possibilités de programmation.
*/
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}
\end{document}
GMaths
Utilisateur chevronné
Utilisateur chevronné
Messages : 2042
Inscription : lundi 01 octobre 2007, 10:20

Re: listings[latex] et asymptote

Message non lu par GMaths »

projetmbc a écrit :Pour éviter les soucis d'accents en français sans passer par XeLaTeX, ...
Quels soucis ?
Dans mon exemple, les quelques accents que j'ai mis dans les commentaires passent sans problème chez moi.
GMaths
Utilisateur chevronné
Utilisateur chevronné
Messages : 2042
Inscription : lundi 01 octobre 2007, 10:20

Re: listings[latex] et asymptote

Message non lu par GMaths »

Une version modifiée avec :
  • les catégorie de keywords numérotées à partir de 1 (au lieu de 3);
  • un vert un peu moins flashi ;
  • un deuxième exemple, pour tester la coloration d'un type que l'on a créé... avec une difficulté non réglée : comment fait-on pour faire la différence entre le type GRAPHE et la fonction GRAPHE ?
  • la non prise en compte de ce qui a été suggéré un peu plus haut... car pour l'instant, j'arrive à mettre des lettres accentuées sans que cela pose problème... et je n'ai pas compris où est le problème qui pourrait se poser.

Code : Tout sélectionner

% !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]
/* Ce qui suit n'est plus utile depuis la révision 4127, où ont été 
   implémentés : factorial(Int n) et choose(Int n, Int k) mais cela reste 
   un exemple intéressant du point de vue des possibilités de programmation.
*/
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}
test_asy_listings.pdf
(56.42 Kio) Téléchargé 499 fois
projetmbc
Utilisateur chevronné
Utilisateur chevronné
Messages : 2303
Inscription : samedi 29 décembre 2007, 00:58

Re: listings[latex] et asymptote

Message non lu par projetmbc »

Bonjour.
GMaths a écrit :...la non prise en compte de ce qui a été suggéré un peu plus haut... car pour l'instant, j'arrive à mettre des lettres accentuées sans que cela pose problème... et je n'ai pas compris où est le problème qui pourrait se poser.
Comment ? Pardon ! Mais c'est un vrai scandale ! :lol:

En fait sous Mac, avec un fichier encodé en utf8 et déclaré en utf8 dans le préambule LaTeX, ton code ne fonctionnait pas chez moi.
GMaths a écrit :Un problème demeure : être capable de faire la distinction entre le type GRAPHE et la fonction GRAPHE.
Pas possible de faire cela avec listings car il colore des mots (que quelqu'un me contredise si je dis une grosse bêtise). Je ne pense pas non plus que Pygments puisse faire cela.

Il faudrait avoir un outil de coloration basée sur une grammaire. En existe-t-il ? En tout cas, de mon côté, je bosse sur un truc de ce type en Python (j'ai enfin réglé un problème de définition de règle pour le XML).
OG
Modérateur honoraire
Modérateur honoraire
Messages : 2293
Inscription : lundi 12 mars 2007, 11:20
Localisation : Rouen

Re: listings[latex] et asymptote

Message non lu par OG »

projetmbc a écrit :
GMaths a écrit :Un problème demeure : être capable de faire la distinction entre le type GRAPHE et la fonction GRAPHE.
Pas possible de faire cela avec listings car il colore des mots (que quelqu'un me contredise si je dis une grosse bêtise). Je ne pense pas non plus que Pygments puisse faire cela.
Même si ce n'est pas parfait, Pygments sait faire la différence (sujet déjà abordé).
Ce n'est pas à jour et je me rappelle plus là où Pygments se trompe (voir http://math.mad.free.fr/depot/asysvn/essai.html)

Une partie du code du lexer.

Code : Tout sélectionner

 (r'(and|controls|tension|atleast|curl|if|else|while|for|do|'
             r'return|break|continue|struct|typedef|new|access|import|'
             r'unravel|from|include|quote|static|public|private|restricted|'
             r'this|explicit|true|false|null|cycle|newframe|operator)\b', Keyword),
            # Since an asy-type-name can be also an asy-function-name,
            # in the following we test if the string "  [a-zA-Z]" follows
            # the Keyword.Type.
            # Of course it is not perfect !
            (r'(Braid|FitResult|Label|Legend|TreeNode|abscissa|arc|arrowhead|'
             r'binarytree|binarytreeNode|block|bool|bool3|bounds|bqe|circle|'
             r'conic|coord|coordsys|cputime|ellipse|file|filltype|frame|grid3|'
             r'guide|horner|hsv|hyperbola|indexedTransform|int|inversion|key|'
             r'light|line|linefit|marginT|marker|mass|object|pair|parabola|path|'
             r'path3|pen|picture|point|position|projection|real|revolution|'
             r'scaleT|scientific|segment|side|slice|splitface|string|surface|'
             r'tensionSpecifier|ticklocate|ticksgridT|tickvalues|transform|'
             r'transformation|tree|triangle|trilinear|triple|vector|'
             r'vertex|void)(?=([ ]{1,}[a-zA-Z]))', Keyword.Type),
            # Now the asy-type-name which are not asy-function-name
            # except yours !
            # Perhaps useless
            (r'(Braid|FitResult|TreeNode|abscissa|arrowhead|block|bool|bool3|'
             r'bounds|coord|frame|guide|horner|int|linefit|marginT|pair|pen|'
             r'picture|position|real|revolution|slice|splitface|ticksgridT|'
             r'tickvalues|tree|triple|vertex|void)\b', Keyword.Type),
            ('[a-zA-Z_][a-zA-Z0-9_]*:(?!:)', Name.Label),
            ('[a-zA-Z_][a-zA-Z0-9_]*', Name),
            ],

O.G.
Ph. Ivaldi

Re: listings[latex] et asymptote

Message non lu par Ph. Ivaldi »

projetmbc a écrit :
GMaths a écrit :Un problème demeure : être capable de faire la distinction entre le type GRAPHE et la fonction GRAPHE.
Pas possible de faire cela avec listings car il colore des mots (que quelqu'un me contredise si je dis une grosse bêtise). Je ne pense pas non plus que Pygments puisse faire cela.
Ça limite énormément l'intérêt du coup.
projetmbc a écrit :Il faudrait avoir un outil de coloration basée sur une grammaire. En existe-t-il ?.
Emacs mais il sort du html. J'ai un script bash pas très joli qui le converti en latex, si ça t'intéresse.
Sinon Pygment.
Ph. Ivaldi

Re: listings[latex] et asymptote

Message non lu par Ph. Ivaldi »

OG a écrit :Une partie du code du lexer.
Ha oui, je me souviens maintenant !
J'avais oublié que tu étais l'auteur du lexer d'Asymptote pour Pygment :oops:
projetmbc
Utilisateur chevronné
Utilisateur chevronné
Messages : 2303
Inscription : samedi 29 décembre 2007, 00:58

Re: listings[latex] et asymptote

Message non lu par projetmbc »

Bonjour.
Ph. Ivaldi a écrit :Ça limite énormément l'intérêt du coup.
Cela se discute. Par exemple, quand on demande de colorer différemment le type GRAPHE et la fonction GRAPHE, j'aurais tendance à me dire qu'il y a là un problème de noms : deux objets différents du point de vue informatique portent le même nom.

Par contre, sur un autre post, quelqu'un souhaitait colorer par exemple les attributs principaux d'une classe, ceux définis lors de la création ou de l'initialisation d'une classe. Moi même, j'aimerais colorer en Python les modules importés. Pour le coup, avec listings, je vais être bloqué.
Ph. Ivaldi a écrit :
projetmbc a écrit :Il faudrait avoir un outil de coloration basée sur une grammaire. En existe-t-il ?.
Emacs mais il sort du html. J'ai un script bash pas très joli qui le converti en latex, si ça t'intéresse.
Sinon Pygment.
Pour Emacs, peut-on ajouter soit même des colorations en mettant un peu les mains dans le cambouis ? Si oui, aurais-tu un exemple de ce type de lexer pour par exemple les fichiers XML ?

Concernant Pygments, je trouve ce projet peu Pythonique en fait, d'où ma décision de me faire un outil de coloration qui se baserait sur une déclaration "simple" des lexers.

Par exemple, pour le XML, on pourrait imaginer quelque chose du type suivant (je n'ai pas encore arrêté mes choix) :

Code : Tout sélectionner

lexer::
    context::
        METHOD::
            < ??? >

        DOC_TYPE::
            <?xml ??? ?>

    comment::
        all::
            <!--
            ...
            -->

    string::
        METHOD::
            "..."

    keyword::
        type::
            DOC_TYPE::
                version encoding

        constant::
            METHOD::
                {{word in {{word =}} }}

        function::
            all::
                <?xml
                ?>
    
                <{{word}}
                </{{word}}
                >

        symbol::
            METHOD::
                =

    group::
        all::
            <{{ONE_ID is word}}...>
            ...
            </{{ONE_ID}}>
Ph. Ivaldi

Re: listings[latex] et asymptote

Message non lu par Ph. Ivaldi »

projetmbc a écrit :quand on demande de colorer différemment le type GRAPHE et la fonction GRAPHE, j'aurais tendance à me dire qu'il y a là un problème de noms : deux objets différents du point de vue informatique portent le même nom.
Ça se discute. Je trouve agréable de pouvoir coder line d = line(A, B) même si j'aurai préféré Line d = line(A, B).
projetmbc a écrit :Pour Emacs, peut-on ajouter soit même des colorations en mettant un peu les mains dans le cambouis ?
Bien sûr, Emacs est codé dans cet esprit.
J'ai bossé récemment sur la coloration de php-mode, tu peux voir comment ça se passe ici vers les lignes 1281 à 1465.
projetmbc a écrit : Si oui, aurais-tu un exemple de ce type de lexer pour par exemple les fichiers XML ?
Jette un zyeux à cette documentation. C'est quand même ce qu'il peut y avoir de plus difficile à comprendre dans Emacs… Bon courage !
projetmbc
Utilisateur chevronné
Utilisateur chevronné
Messages : 2303
Inscription : samedi 29 décembre 2007, 00:58

Re: Extension listings (latex) et asymptote

Message non lu par projetmbc »

Merci, c'est bien ce que je craignais. ceci étant des choses comme ceci se comprennent bien.

Je vais donc continuer mon projet de lexer "facile" à définir...
Ph. Ivaldi

Re: Extension listings (latex) et asymptote

Message non lu par Ph. Ivaldi »

projetmbc a écrit :des choses comme ceci se comprennent bien.
Je veux bien mais c'est un cas d'école.
Si tu regardes comment est implémentée la coloration dans asy-mode, tu verras que c'est très simple, un peu comme pour listing. Cette simplicité apparente est due au fait que asy-mode hérite de cc-mode et c'est lui qui fait tout le boulot difficile finalement.
projetmbc a écrit :Je vais donc continuer mon projet de lexer "facile" à définir...
Je ne veux pas te décourager mais je pense qu'il y a des cas où il sera impossible de proposer quelque chose de simple. Les expressions rationnelles par exemple ne suffisent pas toujours, il faut au moins pouvoir recourir à l'injection de fonctions. C'est ce qui est fait par exemple pour la fontification de la notation here-document sous Emacs. Je parle de celle-là parce que j'ai bossé dessus récemment mais il doit y avoir pire ;)
projetmbc
Utilisateur chevronné
Utilisateur chevronné
Messages : 2303
Inscription : samedi 29 décembre 2007, 00:58

Re: Extension listings (latex) et asymptote

Message non lu par projetmbc »

Ph. Ivaldi a écrit :Je ne veux pas te décourager mais je pense qu'il y a des cas où il sera impossible de proposer quelque chose de simple.
Pas de souci, je suis le spécialiste des causes perdues.
Ph. Ivaldi a écrit :Les expressions rationnelles par exemple ne suffisent pas toujours, il faut au moins pouvoir recourir à l'injection de fonctions.
On est d'accord. Mon système de définition des lexers utilise une grammaire CONTEXTE+MOT A COLORER, avec un petit langage de programmation très réduit (test, mise en mémoire pour la création dynamique de mots clés...). Je pense que cela suffira.

As-tu un exemple de coloration où l'injection de fonction, comme tu dis, est indispensable ?

Par exemple, un cas pénible pour moi est le XML où par exemple les guillemets sont à colorier dans <personne id="bidon"> et non dans <personne>Du "texte"</personne>.
Ph. Ivaldi

Re: Extension listings (latex) et asymptote

Message non lu par Ph. Ivaldi »

projetmbc a écrit :As-tu un exemple de coloration où l'injection de fonction, comme tu dis, est indispensable ?
http://www.piprime.fr/files/tmp/file.sh.html
projetmbc
Utilisateur chevronné
Utilisateur chevronné
Messages : 2303
Inscription : samedi 29 décembre 2007, 00:58

Re: Extension listings (latex) et asymptote

Message non lu par projetmbc »

Dans le bout de code ci-dessous, le fait que les lignes 2 à 3 sont en jaune est dû au fait que ce ne sont pas des instructions valides. C'est ça.

Code : Tout sélectionner

[1]   cat >toto.txt<<EOF
[2]   Bla "${truc}" <<TRUC
[3]   TRUC
[4]   EOF
[5]
[6]   echo "pass"
Sinon, l'injection est-elle utilisée pour les lignes 1 et 2 ?