% # -*- coding: utf-8 -*-
% \input{ctex4xetex.cfg}
% \documentclass{ctexart}
\documentclass[11pt]{article}
\usepackage[CJKtextspaces]{xeCJK}                                      
% \usepackage[CJKnumber]{xeCJK}
%\setCJKmainfont[BoldFont=Adobe Heiti Std,ItalicFont=Adobe Kaiti Std]{Adobe Song Std}
%\setCJKsansfont{Adobe Heiti Std}         
%\setCJKmonofont{Adobe Fangsong Std}  
\setCJKmainfont[BoldFont=SimHei,ItalicFont=KaiTi_GB2312]{SimSun}
\setCJKsansfont{SimHei}         
\setCJKmonofont{FangSong_GB2312}  
\usepackage{framed}

\usepackage[a4paper,centering,
left=1cm,right=1cm,
top=2cm,bottom=2cm,
nohead,nomarginpar]{geometry}

\usepackage{graphicx}


\usepackage[hyperref]{xcolor}
\definecolor{bg-color}{rgb}{0.96,1,0.95}
\definecolor{shadecolor}{rgb}{0.96,1,0.95}
\definecolor{txt-color}{HTML}{000000}
\definecolor{builtin}{HTML}{DA70D6}
\definecolor{comment}{HTML}{B22222}
\definecolor{comment-delimiter}{HTML}{B22222}
\definecolor{constant}{HTML}{5F9EA0}
\definecolor{function-name}{HTML}{0000FF}
\definecolor{keyword}{HTML}{a020F0}
\definecolor{string}{HTML}{BC8F8F}
\definecolor{type}{HTML}{228B22}
\definecolor{variable-name}{HTML}{B8860B}
\definecolor{brick}{HTML}{7B0C00}

\usepackage{hyperref}
\hypersetup{%
  a4paper,
  colorlinks=true,
  filecolor=blue,
  linkcolor=brick,urlcolor=red,
  pdfstartview=Fit,
  pdfauthor={goodluck@bbs.ctex.org},
  pdfsubject={Asymptote},
  pdftitle={绘图语言 Asymptote 初步},
  pdfkeywords={FAQ,绘图,3D,latex,编程语言,asymptote,metapost},
  pdfcreator={引擎:XeTeX, 编辑器:Vim}}

% keywords 对应 asy-keyword-name
% keywords=[2] 对应 asy-type-name
% keywords=[3] 对应 asy-function-name
% keywords=[4] 对应 asy-variable-name 
\usepackage{listings}
% 语言定义
\lstdefinelanguage{Asymptote}{alsoletter={},
  sensitive=true,% 大小写
  keywords={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},
  keywords=[2]{Braid,Label,Legend,Rmf,TreeNode,arrowhead,binarytree,binarytreeNode,block,bool,bounds,coord,cputime,file,frame,grid3,guide,guide3,horner,hsv,indexedTransform,int,key,line,linefit,marginT,marker,object,pair,path,path3,pen,picture,position,projection,real,revolution,scaleT,scientific,segment,side,slice,splitface,string,surface,tensionSpecifier,ticklocate,ticksgridT,tickvalues,transform,transform3,transformation,tree,triple,vertex,void},
  keywords=[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,Ceil,Circle,CircleBarIntervalMarker,Cos,Courier,CrossIntervalMarker,DefaultFormat,DefaultLogFormat,Degrees,Dir,DotMargin,DotMargins,Dotted,Draw,Embed,EndArcArrow,EndArrow,EndBar,EndDotMargin,EndMargin,EndPenMargin,Fill,FillDraw,Floor,Format,Full,Gaussian,Gaussrand,Gaussrandpair,Gradient,Grayscale,Helvetica,Hermite,HookHead,InOutTicks,InTicks,J,Label,Landscape,Left,LeftRight,LeftTicks,Linear,Link,Log,LogFormat,Margin,Margins,Mark,MidArcArrow,MidArrow,NOT,NewCenturySchoolBook,NoBox,NoFill,NoMargin,NoTicks,NoTicks3,NoZero,NoZeroFormat,None,OR,OmitFormat,OmitTick,OutTicks,Palatino,PaletteTicks,Pen,PenMargin,PenMargins,Portrait,RadialShade,Rainbow,Range,Relative,Right,RightTicks,Rotate,Round,Scale,ScaleX,ScaleY,ScaleZ,Seascape,Shift,Sin,Slant,Spline,StickIntervalMarker,Straight,Symbol,Tan,TeXify,Ticks,Ticks3,TildeIntervalMarker,TimesRoman,Top,TrueMargin,UnFill,UpsideDown,VERSION,X,XEquals,XOR,XY,XYEquals,XYZero,XYgrid,XZEquals,XZZero,XZero,XZgrid,Y,YEquals,YXgrid,YZ,YZEquals,YZZero,YZero,YZgrid,Z,ZX,ZXgrid,ZYgrid,ZapfChancery,ZapfDingbats,_cputime,_draw,_eval,_image,_labelpath,_strokepath,_texpath,aCos,aSin,aTan,abort,abs,accel,acos,acosh,acot,acsc,add,addArrow,addSaveFunction,addseg,adjust,alias,align,all,angle,animate,annotate,apply,arc,arcarrowsize,arcdir,arclength,arcpoint,arctime,array,arrow,arrow2,arrowbase,arrowbasepoints,arrowsize,asec,asin,asinh,ask,assert,asy,asycode,asydir,asyfigure,asyfilecode,asywrite,atan,atan2,atanh,atbreakpoint,atexit,attach,atupdate,autoformat,autoscale,autoscale3,axes,axes3,axialshade,axis,axiscoverage,azimuth,babel,background,bar,barmarksize,barsize,basealign,baseline,bbox,beep,beginclip,begingroup,beginpoint,bevel,bezier,bezierP,bezierPP,bezierPPP,bezulate,bibliography,bibliographystyle,binarytree,binarytreeNode,binput,bins,bispline,blend,boutput,box,breakpoint,breakpoints,brick,buildRestoreDefaults,buildRestoreThunk,buildcycle,bulletcolor,case1,case2,case3,cbrt,cd,ceil,center,change2,checkSegment,checker,checklengths,checkposition,checktriangle,circle,circlebarframe,circlemarkradius,clamped,clear,clip,close,cmyk,code,colatitude,collect,color,colorless,colors,colorspace,comma,complement,concat,conditional,cone,conj,connect,containmentTree,contains,contour,contour3,controlSpecifier,convert,copy,cos,cosh,cot,countIntersections,cputime,crop,cropcode,cross,crossframe,crosshatch,crossmarksize,csc,csv,cubicroots,curlSpecifier,currentarrow,currentexitfunction,currentmomarrow,curve,cut,cutafter,cutbefore,cyclic,cylinder,debugger,deconstruct,defaultdir,defaultformat,defaultpen,defaultspline,degrees,delete,deletepreamble,determinant,diagonal,diamond,diffdiv,dimension,dir,dirSpecifier,dirtime,display,divisors,do_overpaint,dot,dotframe,dotsize,downcase,draw,drawAll,drawDoubleLine,drawFermion,drawGhost,drawGluon,drawMomArrow,drawPhoton,drawScalar,drawVertex,drawVertexBox,drawVertexBoxO,drawVertexBoxX,drawVertexO,drawVertexOX,drawVertexTriangle,drawVertexTriangleO,drawVertexX,drawarrow,drawarrow2,drawline,drawtick,duplicate,ellipse,embed,embed3,empty,enclose,endScript,endclip,endgroup,endl,endpoint,endpoints,eof,eol,equation,equations,erase,erf,erfc,error,errorbar,errorbars,euler,eval,exit,exitXasyMode,exitfunction,exp,expi,expm1,extend,extension,fabs,fft,fhorner,figure,file,filecode,fill,filldraw,filloutside,fillrule,find,finite,firstcut,fit,fixedscaling,floor,flush,fmdefaults,fmod,font,fontcommand,fontsize,format,frac,frequency,fspline,gamma,generate_random_backtrace,generateticks,getc,getint,getpair,getreal,getstring,gluon,gouraudshade,graph,graphic,gray,grestore,grid,grid3,gsave,halfbox,hatch,hdiffdiv,hermite,histogram,history,hsv,hyperlink,hypot,identity,image,incircle,increasing,incrementposition,indexedTransform,initXasyMode,initdefaults,input,insert,inside,interactive,interior,interp,interpolate,intersect,intersection,intersectionpoint,intersectionpoints,intersections,inverse,invisible,is3D,isDuplicate,italic,item,key,kurtosis,kurtosisexcess,label,labelaxis,labelmargin,labelpath,labels,labeltick,labelx,labelx3,labely,labely3,labelz,labelz3,lastcut,latex,latitude,latticeshade,layer,layout,leastsquares,legend,legenditem,length,lift,limits,line,linear,linecap,linejoin,lineskip,linetype,linewidth,link,list,locale,locatefile,location,log,log10,logaxiscoverage,longitude,lookup,makeNode,makedraw,makepen,map,margin,markangle,markangleradius,markanglespace,marker,markinterval,marknodes,markuniform,math,max,max3,maxbound,maxcoords,maxratio,maxtimes,mean,midpoint,min,min3,minbound,minipage,minratio,mintimes,momArrowPath,momarrowsize,monotonic,nativeformat,natural,needshipout,newl,newpage,newslide,newton,newtree,nextpage,nib,none,normalvideo,notaknot,numberpage,nurb,object,offset,opacity,orientation,outline,outprefix,output,overwrite,pack,pairs,palette,partialsum,path,path3,pattern,pause,pdf,periodic,perpendicular,phantom,photon,piecewisestraight,point,polar,polargraph,polygon,postcontrol,postscript,pow10,prc,prc0,precision,precontrol,prepend,print_random_addresses,project,projection,purge,pwhermite,quadrant,quadraticroots,quantize,quarticroots,quotient,radialshade,radians,radius,rand,randompath,read1,read2,read3,readline,realmult,rectangle,rectangular,rectify,reflect,relative,relativedistance,reldir,relpoint,reltime,remainder,remark,removeDuplicates,rename,replace,plane,report,resetdefaultpen,restore,restoredefaults,reverse,reversevideo,rfind,rgb,rgba,rgbint,rmf,rms,rotate,rotation,round,roundbox,roundedpath,roundrectangle,sample,save,savedefaults,saveline,scale,scale3,scaleless,scientific,search,searchtree,sec,secondaryX,secondaryY,seconds,section,seek,seekeof,segment,sequence,setpens,sgn,shift,shiftless,shipout,shipout3,side,simpson,sin,single,sinh,size,size3,skewness,skip,slant,sleep,slope,slopefield,solve,sort,sortByInside,sourceline,sphere,split,sqrt,square,srand,startScript,stdev,step,stickframe,stickmarksize,stickmarkspace,stop,straight,straightness,string,stripdirectory,stripextension,strokepath,subdivide,subitem,subpath,substr,sum,surface,system,tab,tableau,tan,tangent,tanh,tell,tensionSpecifier,tensorshade,tex,texcolor,texify,texpath,texpreamble,texreset,texshipout,thick,thin,tick,tickMax,tickMax3,tickMin,tickMin3,ticklabelshift,ticklocate,tildeframe,tildemarksize,tile,tiling,time,times,title,titlepage,topbox,transform,transformation,transpose,triangulate,tridiagonal,trim,truepoint,tube,uncycle,unfill,uniform,unit,unitrand,unitsize,unityroot,unstraighten,upcase,updatefunction,upscale,uptodate,usepackage,usersetting,usleep,value,variance,variancebiased,vbox,vectorfield,verbatim,view,windingnumber,word,write,xaxis,xaxis3,xaxis3At,xaxisAt,xequals,xinput,xlimits,xoutput,xpart,xscale,xscale3,xtick,xtick3,xtrans,yaxis,yaxis3,yaxis3At,yaxisAt,yequals,ylimits,ypart,yscale,yscale3,ytick,ytick3,ytrans,zaxis3,zaxis3At,zero,zero3,zlimits,zpart,zscale3,ztick,ztick3,ztrans},
  keywords=[4]{AliceBlue,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,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,E,ENE,ESE,Emerald,EndPoint,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,Label,Lavender,LavenderBlush,LawnGreen,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,NoSide,OldLace,Olive,OliveDrab,OliveGreen,Orange,OrangeRed,Orchid,PaleGoldenrod,PaleGreen,PaleTurquoise,PaleVioletRed,PapayaWhip,Peach,PeachPuff,Periwinkle,Peru,PineGreen,Pink,Plum,PowderBlue,ProcessBlue,Purple,RawSienna,Red,RedOrange,RedViolet,Rhodamine,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,VERSION,Value,Vertical,Violet,VioletRed,W,WNW,WSW,Wheat,White,WhiteSmoke,WildStrawberry,XYAlign,YAlign,Yellow,YellowGreen,YellowOrange,align,allowstepping,animationdelay,appendsuffix,arcarrowangle,arcarrowfactor,arrow2sizelimit,arrowangle,arrowbarb,arrowdir,arrowfactor,arrowhookfactor,arrowlength,arrowsizelimit,arrowtexfactor,authorpen,axis,axiscoverage,axislabelfactor,background,backgroundcolor,backgroundpen,barfactor,barmarksizefactor,basealign,beveljoin,bigvertexpen,bigvertexsize,black,blue,bm,bottom,bp,brown,bullet,chartreuse,circlemarkradiusfactor,circleprecision,circlescale,cm,cmyk,codefile,codepen,codeskip,colorPen,coloredNodes,coloredSegments,conditionlength,count,cputimeformat,crossmarksizefactor,currentpatterns,currentpen,currentpicture,currentposition,currentprojection,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,defaultS,defaultbackpen,defaultfilename,defaultformat,defaultpen,diagnostics,differentlengths,dot,dotfactor,dotframe,dotted,doublelinepen,doublelinespacing,down,eps,epsilon,evenodd,extendcap,fermionpen,figureborder,figuremattpen,firstnode,firststep,foregroundcolor,fuchsia,fuzz,gapfactor,ghostpen,gluonamplitude,gluonpen,gluonratio,gray,green,grey,hatchepsilon,havepagenumber,heavyblue,heavycyan,heavygray,heavygreen,heavygrey,heavymagenta,heavyred,hwratio,identity4,ignore,inXasyMode,inch,inches,includegraphicscommand,incommensurate,inf,infinity,institutionpen,intMax,intMin,invert,invisible,itempen,itemskip,itemstep,labelmargin,landscape,lastnode,left,legendhskip,legendlinelength,legendmargin,legendmarkersize,legendmaxrelativewidth,legendvskip,lightblue,lightcyan,lightgray,lightgreen,lightgrey,lightmagenta,lightolive,lightred,lightyellow,linemargin,longdashdotted,longdashed,magenta,markangleradius,markangleradiusfactor,markanglespace,markanglespacefactor,mediumblue,mediumcyan,mediumgray,mediumgreen,mediumgrey,mediummagenta,mediumred,mediumyellow,middle,minDistDefault,minipagemargin,minipagewidth,minvertexangle,miterjoin,mm,momarrowfactor,momarrowlength,momarrowmargin,momarrowoffset,momarrowpen,monoPen,morepoints,nCircle,ncell,newbulletcolor,ngraph,nil,nmesh,nobasealign,nodeMarginDefault,nomarker,nopoint,noprimary,nullpath,nullpen,oldbulletcolor,olive,orange,overpaint,page,pageheight,pagemargin,pagenumberalign,pagenumberpen,pagenumberposition,pagewidth,paleblue,palecyan,palegray,palegreen,palegrey,palemagenta,palered,paleyellow,perpfactor,phi,photonamplitude,photonpen,photonratio,pi,pink,plain,plus,preamblenodes,pt,purple,r3,r4a,r4b,randMax,realDigits,realEpsilon,realMax,realMin,red,reverse,right,roundcap,roundjoin,royalblue,salmon,saveFunctions,scalarpen,sequencereal,settings,shipped,solid,springgreen,squarecap,squarepen,startposition,stdin,stdout,stepfraction,steppagenumberpen,stepping,stickframe,stickmarksizefactor,stickmarkspacefactor,textpen,ticksize,tildeframe,tildemarksizefactor,tinv,titlealign,titlepagepen,titlepageposition,titlepen,titleskip,top,trailingzero,treeLevelStep,treeMinNodeWidth,treeNodeStep,undefined,unitcircle,unitsquare,up,urlpen,urlskip,version,vertexpen,vertexsize,white,wye,xformStack,yellow,ylabelwidth,zerotickfuzz,zerowinding},
  % otherkeywords={!,@,\$,\%,+,-,^,=,>,<,->,
  %   --,..,**,::,\@\@,\$\$,---,...},% 运算符等，但小心会与注释冲突
  morecomment=[l]{//},% 注释
  morecomment=[s]{/*}{*/},% 注释
  morestring=[b]",% 字符串
}
% 定义别名
\lstalias{asy}{Asymptote}
\lstset{extendedchars=false,% 重要！解决中文跨页出错的问题
  language={Asymptote},
  basewidth={.5em},
  basicstyle={\ttfamily},
  keywordstyle={\color{keyword}},
  keywordstyle=[2]{\color{type}},
  keywordstyle=[3]{\color{function-name}},
  keywordstyle=[4]{\color{variable-name}},
  commentstyle={\color{comment}},
  stringstyle={\color{string}},
  xleftmargin={2em},
  xrightmargin={2em},
  tabsize=8,
  backgroundcolor={\color{shadecolor}},
  % numbers=left,
  numberstyle=\tiny,
  stepnumber=1,
  numbersep=5pt}
% 
\lstMakeShortInline\|

\usepackage{filecontents}
% \usepackage{framed}

\makeatletter
\newenvironment{asycode}[2][]
{\lstset{#1}%
  \def\asycode@name{#2}%
  \edef\asycode@curpage{\arabic{page}}%
  \@tempswafalse\filec@ntents{\asycode@name.asy}%
  \setcounter{page}{\asycode@curpage}}
{\endfilecontents
  \begin{shaded}
     %\begin{center}\includegraphics{\asycode@name.pdf}\end{center}%
    \begin{center}\Large\color{brick}\asycode@name\end{center}%
    \lstinputlisting{\asycode@name.asy}
  \end{shaded}
  % \end{framed}
}
\makeatother

\newenvironment{funclist}{\trivlist
  \parindent=0pt
  \item[]
  \def\item{\medskip\par\leftskip=0pt}
  \def\go{\par\leftskip=4em}}
  {\endtrivlist}

