editormd.amd.js 159 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692
  1. /*
  2. * Editor.md
  3. *
  4. * @file editormd.amd.js
  5. * @version v1.5.0
  6. * @description Open source online markdown editor.
  7. * @license MIT License
  8. * @author Pandao
  9. * {@link https://github.com/pandao/editor.md}
  10. * @updateTime 2015-06-09
  11. */
  12. ;(function(factory) {
  13. "use strict";
  14. // CommonJS/Node.js
  15. if (typeof require === "function" && typeof exports === "object" && typeof module === "object")
  16. {
  17. module.exports = factory;
  18. }
  19. else if (typeof define === "function") // AMD/CMD/Sea.js
  20. {
  21. if (define.amd) // for Require.js
  22. {
  23. var cmModePath = "codemirror/mode/";
  24. var cmAddonPath = "codemirror/addon/";
  25. var codeMirrorModules = [
  26. "jquery", "marked",
  27. //"prettify",
  28. "highlight/highlight",
  29. "mermaid/mermaid",
  30. "katex", "raphael", "underscore", "flowchart", "jqueryflowchart", "sequenceDiagram",
  31. "codemirror/lib/codemirror",
  32. cmModePath + "css/css",
  33. cmModePath + "sass/sass",
  34. cmModePath + "shell/shell",
  35. cmModePath + "sql/sql",
  36. cmModePath + "clike/clike",
  37. cmModePath + "php/php",
  38. cmModePath + "xml/xml",
  39. cmModePath + "markdown/markdown",
  40. cmModePath + "javascript/javascript",
  41. cmModePath + "htmlmixed/htmlmixed",
  42. cmModePath + "gfm/gfm",
  43. cmModePath + "http/http",
  44. cmModePath + "go/go",
  45. cmModePath + "dart/dart",
  46. cmModePath + "coffeescript/coffeescript",
  47. cmModePath + "nginx/nginx",
  48. cmModePath + "python/python",
  49. cmModePath + "perl/perl",
  50. cmModePath + "lua/lua",
  51. cmModePath + "r/r",
  52. cmModePath + "ruby/ruby",
  53. cmModePath + "rst/rst",
  54. cmModePath + "smartymixed/smartymixed",
  55. cmModePath + "vb/vb",
  56. cmModePath + "vbscript/vbscript",
  57. cmModePath + "velocity/velocity",
  58. cmModePath + "xquery/xquery",
  59. cmModePath + "yaml/yaml",
  60. cmModePath + "erlang/erlang",
  61. cmModePath + "jade/jade",
  62. cmAddonPath + "edit/trailingspace",
  63. cmAddonPath + "dialog/dialog",
  64. cmAddonPath + "search/searchcursor",
  65. cmAddonPath + "search/search",
  66. cmAddonPath + "scroll/annotatescrollbar",
  67. cmAddonPath + "search/matchesonscrollbar",
  68. cmAddonPath + "display/placeholder",
  69. cmAddonPath + "edit/closetag",
  70. cmAddonPath + "fold/foldcode",
  71. cmAddonPath + "fold/foldgutter",
  72. cmAddonPath + "fold/indent-fold",
  73. cmAddonPath + "fold/brace-fold",
  74. cmAddonPath + "fold/xml-fold",
  75. cmAddonPath + "fold/markdown-fold",
  76. cmAddonPath + "fold/comment-fold",
  77. cmAddonPath + "mode/overlay",
  78. cmAddonPath + "selection/active-line",
  79. cmAddonPath + "edit/closebrackets",
  80. cmAddonPath + "display/fullscreen",
  81. cmAddonPath + "search/match-highlighter"
  82. ];
  83. define(codeMirrorModules, factory);
  84. }
  85. else
  86. {
  87. define(["jquery"], factory); // for Sea.js
  88. }
  89. }
  90. else
  91. {
  92. window.editormd = factory();
  93. }
  94. }(function() {
  95. if (typeof define == "function" && define.amd) {
  96. $ = arguments[0];
  97. marked = arguments[1];
  98. prettify = arguments[2];
  99. katex = arguments[3];
  100. Raphael = arguments[4];
  101. _ = arguments[5];
  102. flowchart = arguments[6];
  103. CodeMirror = arguments[9];
  104. }
  105. "use strict";
  106. var $ = (typeof (jQuery) !== "undefined") ? jQuery : Zepto;
  107. if (typeof ($) === "undefined") {
  108. return ;
  109. }
  110. /**
  111. * editormd
  112. *
  113. * @param {String} id 编辑器的ID
  114. * @param {Object} options 配置选项 Key/Value
  115. * @returns {Object} editormd 返回editormd对象
  116. */
  117. var editormd = function (id, options) {
  118. return new editormd.fn.init(id, options);
  119. };
  120. editormd.title = editormd.$name = "Editor.md";
  121. editormd.version = "1.5.0";
  122. editormd.homePage = "https://pandao.github.io/editor.md/";
  123. editormd.classPrefix = "editormd-";
  124. editormd.toolbarModes = {
  125. full : [
  126. "undo", "redo", "|",
  127. "bold", "del", "italic", "quote", "ucwords", "uppercase", "lowercase", "|",
  128. "h1", "h2", "h3", "h4", "h5", "h6", "|",
  129. "list-ul", "list-ol", "hr", "|",
  130. "link", "reference-link", "image", "code", "preformatted-text", "code-block", "table", "datetime", "emoji", "html-entities", "pagebreak", "|",
  131. "goto-line", "watch", "preview", "fullscreen", "clear", "search", "|",
  132. "help", "info"
  133. ],
  134. simple : [
  135. "undo", "redo", "|",
  136. "bold", "del", "italic", "quote", "uppercase", "lowercase", "|",
  137. "h1", "h2", "h3", "h4", "h5", "h6", "|",
  138. "list-ul", "list-ol", "hr", "|",
  139. "watch", "preview", "fullscreen", "|",
  140. "help", "info"
  141. ],
  142. mini : [
  143. "undo", "redo", "|",
  144. "watch", "preview", "|",
  145. "help", "info"
  146. ]
  147. };
  148. editormd.defaults = {
  149. mode : "gfm", //gfm or markdown
  150. name : "", // Form element name
  151. value : "", // value for CodeMirror, if mode not gfm/markdown
  152. theme : "", // Editor.md self themes, before v1.5.0 is CodeMirror theme, default empty
  153. editorTheme : "default", // Editor area, this is CodeMirror theme at v1.5.0
  154. previewTheme : "", // Preview area theme, default empty
  155. markdown : "", // Markdown source code
  156. appendMarkdown : "", // if in init textarea value not empty, append markdown to textarea
  157. width : "100%",
  158. height : "100%",
  159. path : "./lib/", // Dependents module file directory
  160. pluginPath : "", // If this empty, default use settings.path + "../plugins/"
  161. delay : 300, // Delay parse markdown to html, Uint : ms
  162. autoLoadModules : true, // Automatic load dependent module files
  163. watch : true,
  164. placeholder : "Enjoy Markdown! coding now...",
  165. gotoLine : true,
  166. codeFold : false,
  167. autoHeight : false,
  168. autoFocus : true,
  169. autoCloseTags : true,
  170. searchReplace : true,
  171. syncScrolling : true, // true | false | "single", default true
  172. readOnly : false,
  173. tabSize : 4,
  174. indentUnit : 4,
  175. lineNumbers : true,
  176. lineWrapping : true,
  177. autoCloseBrackets : true,
  178. showTrailingSpace : true,
  179. matchBrackets : true,
  180. indentWithTabs : true,
  181. styleSelectedText : true,
  182. matchWordHighlight : true, // options: true, false, "onselected"
  183. styleActiveLine : true, // Highlight the current line
  184. dialogLockScreen : true,
  185. dialogShowMask : true,
  186. dialogDraggable : true,
  187. dialogMaskBgColor : "#fff",
  188. dialogMaskOpacity : 0.1,
  189. fontSize : "13px",
  190. saveHTMLToTextarea : false,
  191. disabledKeyMaps : [],
  192. onload : function() {},
  193. onresize : function() {},
  194. onchange : function() {},
  195. onwatch : null,
  196. onunwatch : null,
  197. onpreviewing : function() {},
  198. onpreviewed : function() {},
  199. onfullscreen : function() {},
  200. onfullscreenExit : function() {},
  201. onscroll : function() {},
  202. onpreviewscroll : function() {},
  203. imageUpload : false,
  204. imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
  205. imageUploadURL : "",
  206. crossDomainUpload : false,
  207. uploadCallbackURL : "",
  208. toc : true, // Table of contents
  209. tocm : false, // Using [TOCM], auto create ToC dropdown menu
  210. tocTitle : "", // for ToC dropdown menu btn
  211. tocDropdown : false,
  212. tocContainer : "",
  213. tocStartLevel : 1, // Said from H1 to create ToC
  214. htmlDecode : false, // Open the HTML tag identification
  215. pageBreak : true, // Enable parse page break [========]
  216. atLink : true, // for @link
  217. emailLink : true, // for email address auto link
  218. taskList : false, // Enable Github Flavored Markdown task lists
  219. emoji : false, // :emoji: , Support Github emoji, Twitter Emoji (Twemoji);
  220. // Support FontAwesome icon emoji :fa-xxx: > Using fontAwesome icon web fonts;
  221. // Support Editor.md logo icon emoji :editormd-logo: :editormd-logo-1x: > 1~8x;
  222. tex : false, // TeX(LaTeX), based on KaTeX
  223. flowChart : false, // flowChart.js only support IE9+
  224. sequenceDiagram : false, // sequenceDiagram.js only support IE9+
  225. mermaidGantt : false, //mermaid/mermaid.js
  226. mermaidSequence : false,
  227. mermaidFlowChat : false,
  228. previewCodeHighlight : true,
  229. highlightStyle : "github",
  230. toolbar : true, // show/hide toolbar
  231. toolbarAutoFixed : true, // on window scroll auto fixed position
  232. toolbarIcons : "full",
  233. toolbarTitles : {},
  234. toolbarHandlers : {
  235. ucwords : function() {
  236. return editormd.toolbarHandlers.ucwords;
  237. },
  238. lowercase : function() {
  239. return editormd.toolbarHandlers.lowercase;
  240. }
  241. },
  242. toolbarCustomIcons : { // using html tag create toolbar icon, unused default <a> tag.
  243. lowercase : "<a href=\"javascript:;\" title=\"Lowercase\" unselectable=\"on\"><i class=\"fa\" name=\"lowercase\" style=\"font-size:24px;margin-top: -10px;\">a</i></a>",
  244. "ucwords" : "<a href=\"javascript:;\" title=\"ucwords\" unselectable=\"on\"><i class=\"fa\" name=\"ucwords\" style=\"font-size:20px;margin-top: -3px;\">Aa</i></a>"
  245. },
  246. toolbarIconsClass : {
  247. undo : "fa-undo",
  248. redo : "fa-repeat",
  249. bold : "fa-bold",
  250. del : "fa-strikethrough",
  251. italic : "fa-italic",
  252. quote : "fa-quote-left",
  253. uppercase : "fa-font",
  254. h1 : editormd.classPrefix + "bold",
  255. h2 : editormd.classPrefix + "bold",
  256. h3 : editormd.classPrefix + "bold",
  257. h4 : editormd.classPrefix + "bold",
  258. h5 : editormd.classPrefix + "bold",
  259. h6 : editormd.classPrefix + "bold",
  260. "list-ul" : "fa-list-ul",
  261. "list-ol" : "fa-list-ol",
  262. hr : "fa-minus",
  263. link : "fa-link",
  264. "reference-link" : "fa-anchor",
  265. image : "fa-picture-o",
  266. code : "fa-code",
  267. "preformatted-text" : "fa-file-code-o",
  268. "code-block" : "fa-file-code-o",
  269. table : "fa-table",
  270. datetime : "fa-clock-o",
  271. emoji : "fa-smile-o",
  272. "html-entities" : "fa-copyright",
  273. pagebreak : "fa-newspaper-o",
  274. "goto-line" : "fa-terminal", // fa-crosshairs
  275. watch : "fa-eye-slash",
  276. unwatch : "fa-eye",
  277. preview : "fa-desktop",
  278. search : "fa-search",
  279. fullscreen : "fa-arrows-alt",
  280. clear : "fa-eraser",
  281. help : "fa-question-circle",
  282. info : "fa-info-circle"
  283. },
  284. toolbarIconTexts : {},
  285. lang : {
  286. name : "zh-cn",
  287. description : "开源在线Markdown编辑器<br/>Open source online Markdown editor.",
  288. tocTitle : "目录",
  289. toolbar : {
  290. undo : "撤销(Ctrl+Z)",
  291. redo : "重做(Ctrl+Y)",
  292. bold : "粗体",
  293. del : "删除线",
  294. italic : "斜体",
  295. quote : "引用",
  296. ucwords : "将每个单词首字母转成大写",
  297. uppercase : "将所选转换成大写",
  298. lowercase : "将所选转换成小写",
  299. h1 : "标题1",
  300. h2 : "标题2",
  301. h3 : "标题3",
  302. h4 : "标题4",
  303. h5 : "标题5",
  304. h6 : "标题6",
  305. "list-ul" : "无序列表",
  306. "list-ol" : "有序列表",
  307. hr : "横线",
  308. link : "链接",
  309. "reference-link" : "引用链接",
  310. image : "添加图片",
  311. code : "行内代码",
  312. "preformatted-text" : "预格式文本 / 代码块(缩进风格)",
  313. "code-block" : "代码块(多语言风格)",
  314. table : "添加表格",
  315. datetime : "日期时间",
  316. emoji : "Emoji表情",
  317. "html-entities" : "HTML实体字符",
  318. pagebreak : "插入分页符",
  319. "goto-line" : "跳转到行",
  320. watch : "关闭实时预览",
  321. unwatch : "开启实时预览",
  322. preview : "全窗口预览HTML(按 Shift + ESC还原)",
  323. fullscreen : "全屏(按ESC还原)",
  324. clear : "清空",
  325. search : "搜索",
  326. help : "使用帮助",
  327. info : "关于" + editormd.title
  328. },
  329. buttons : {
  330. enter : "确定",
  331. cancel : "取消",
  332. close : "关闭"
  333. },
  334. dialog : {
  335. link : {
  336. title : "添加链接",
  337. url : "链接地址",
  338. urlTitle : "链接标题",
  339. urlEmpty : "错误:请填写链接地址。"
  340. },
  341. referenceLink : {
  342. title : "添加引用链接",
  343. name : "引用名称",
  344. url : "链接地址",
  345. urlId : "链接ID",
  346. urlTitle : "链接标题",
  347. nameEmpty: "错误:引用链接的名称不能为空。",
  348. idEmpty : "错误:请填写引用链接的ID。",
  349. urlEmpty : "错误:请填写引用链接的URL地址。"
  350. },
  351. image : {
  352. title : "添加图片",
  353. url : "图片地址",
  354. link : "图片链接",
  355. alt : "图片描述",
  356. uploadButton : "本地上传",
  357. imageURLEmpty : "错误:图片地址不能为空。",
  358. uploadFileEmpty : "错误:上传的图片不能为空。",
  359. formatNotAllowed : "错误:只允许上传图片文件,允许上传的图片文件格式有:"
  360. },
  361. preformattedText : {
  362. title : "添加预格式文本或代码块",
  363. emptyAlert : "错误:请填写预格式文本或代码的内容。"
  364. },
  365. codeBlock : {
  366. title : "添加代码块",
  367. selectLabel : "代码语言:",
  368. selectDefaultText : "请选择代码语言",
  369. otherLanguage : "其他语言",
  370. unselectedLanguageAlert : "错误:请选择代码所属的语言类型。",
  371. codeEmptyAlert : "错误:请填写代码内容。"
  372. },
  373. htmlEntities : {
  374. title : "HTML 实体字符"
  375. },
  376. help : {
  377. title : "使用帮助"
  378. }
  379. }
  380. }
  381. };
  382. editormd.classNames = {
  383. tex : editormd.classPrefix + "tex"
  384. };
  385. editormd.dialogZindex = 99999;
  386. editormd.$katex = null;
  387. editormd.$marked = null;
  388. editormd.$CodeMirror = null;
  389. editormd.$prettyPrint = null;
  390. var timer, flowchartTimer;
  391. editormd.prototype = editormd.fn = {
  392. state : {
  393. watching : false,
  394. loaded : false,
  395. preview : false,
  396. fullscreen : false
  397. },
  398. /**
  399. * 构造函数/实例初始化
  400. * Constructor / instance initialization
  401. *
  402. * @param {String} id 编辑器的ID
  403. * @param {Object} [options={}] 配置选项 Key/Value
  404. * @returns {editormd} 返回editormd的实例对象
  405. */
  406. init : function (id, options) {
  407. options = options || {};
  408. if (typeof id === "object")
  409. {
  410. options = id;
  411. }
  412. var _this = this;
  413. var classPrefix = this.classPrefix = editormd.classPrefix;
  414. var settings = this.settings = $.extend(true, editormd.defaults, options);
  415. id = (typeof id === "object") ? settings.id : id;
  416. var editor = this.editor = $("#" + id);
  417. this.id = id;
  418. this.lang = settings.lang;
  419. var classNames = this.classNames = {
  420. textarea : {
  421. html : classPrefix + "html-textarea",
  422. markdown : classPrefix + "markdown-textarea"
  423. }
  424. };
  425. settings.pluginPath = (settings.pluginPath === "") ? settings.path + "../plugins/" : settings.pluginPath;
  426. this.state.watching = (settings.watch) ? true : false;
  427. if ( !editor.hasClass("editormd") ) {
  428. editor.addClass("editormd");
  429. }
  430. editor.css({
  431. width : (typeof settings.width === "number") ? settings.width + "px" : settings.width,
  432. height : (typeof settings.height === "number") ? settings.height + "px" : settings.height
  433. });
  434. if (settings.autoHeight)
  435. {
  436. editor.css("height", "auto");
  437. }
  438. var markdownTextarea = this.markdownTextarea = editor.children("textarea");
  439. if (markdownTextarea.length < 1)
  440. {
  441. editor.append("<textarea></textarea>");
  442. markdownTextarea = this.markdownTextarea = editor.children("textarea");
  443. }
  444. markdownTextarea.addClass(classNames.textarea.markdown).attr("placeholder", settings.placeholder);
  445. if (typeof markdownTextarea.attr("name") === "undefined" || markdownTextarea.attr("name") === "")
  446. {
  447. markdownTextarea.attr("name", (settings.name !== "") ? settings.name : id + "-markdown-doc");
  448. }
  449. var appendElements = [
  450. (!settings.readOnly) ? "<a href=\"javascript:;\" class=\"fa fa-close " + classPrefix + "preview-close-btn\"></a>" : "",
  451. ( (settings.saveHTMLToTextarea) ? "<textarea class=\"" + classNames.textarea.html + "\" name=\"" + id + "-html-code\"></textarea>" : "" ),
  452. "<div class=\"" + classPrefix + "preview\"><div class=\"markdown-body " + classPrefix + "preview-container\"></div></div>",
  453. "<div class=\"" + classPrefix + "container-mask\" style=\"display:block;\"></div>",
  454. "<div class=\"" + classPrefix + "mask\"></div>"
  455. ].join("\n");
  456. editor.append(appendElements).addClass(classPrefix + "vertical");
  457. if (settings.theme !== "")
  458. {
  459. editor.addClass(classPrefix + "theme-" + settings.theme);
  460. }
  461. this.mask = editor.children("." + classPrefix + "mask");
  462. this.containerMask = editor.children("." + classPrefix + "container-mask");
  463. if (settings.markdown !== "")
  464. {
  465. markdownTextarea.val(settings.markdown);
  466. }
  467. if (settings.appendMarkdown !== "")
  468. {
  469. markdownTextarea.val(markdownTextarea.val() + settings.appendMarkdown);
  470. }
  471. this.htmlTextarea = editor.children("." + classNames.textarea.html);
  472. this.preview = editor.children("." + classPrefix + "preview");
  473. this.previewContainer = this.preview.children("." + classPrefix + "preview-container");
  474. if (settings.previewTheme !== "")
  475. {
  476. this.preview.addClass(classPrefix + "preview-theme-" + settings.previewTheme);
  477. }
  478. if (typeof define === "function" && define.amd)
  479. {
  480. if (typeof katex !== "undefined")
  481. {
  482. editormd.$katex = katex;
  483. }
  484. if (settings.searchReplace && !settings.readOnly)
  485. {
  486. editormd.loadCSS(settings.path + "codemirror/addon/dialog/dialog");
  487. editormd.loadCSS(settings.path + "codemirror/addon/search/matchesonscrollbar");
  488. }
  489. }
  490. if ((typeof define === "function" && define.amd) || !settings.autoLoadModules)
  491. {
  492. if (typeof CodeMirror !== "undefined") {
  493. editormd.$CodeMirror = CodeMirror;
  494. }
  495. if (typeof marked !== "undefined") {
  496. editormd.$marked = marked;
  497. }
  498. this.setCodeMirror().setToolbar().loadedDisplay();
  499. }
  500. else
  501. {
  502. this.loadQueues();
  503. }
  504. return this;
  505. },
  506. /**
  507. * 所需组件加载队列
  508. * Required components loading queue
  509. *
  510. * @returns {editormd} 返回editormd的实例对象
  511. */
  512. loadQueues : function() {
  513. var _this = this;
  514. var settings = this.settings;
  515. var loadPath = settings.path;
  516. var loadFlowChartOrSequenceDiagram = function() {
  517. if (editormd.isIE8)
  518. {
  519. _this.loadedDisplay();
  520. return ;
  521. }
  522. if (settings.mermaidGantt || settings.mermaidFlowChat || settings.mermaidSequence) {
  523. console.log("aa")
  524. editormd.loadScript(loadPath + "mermaid/mermaid.min", function () {
  525. _this.loadedDisplay();
  526. });
  527. }
  528. if (settings.flowChart || settings.sequenceDiagram)
  529. {
  530. editormd.loadScript(loadPath + "raphael.min", function() {
  531. editormd.loadScript(loadPath + "underscore.min", function() {
  532. if (!settings.flowChart && settings.sequenceDiagram)
  533. {
  534. editormd.loadScript(loadPath + "sequence-diagram.min", function() {
  535. _this.loadedDisplay();
  536. });
  537. }
  538. else if (settings.flowChart && !settings.sequenceDiagram)
  539. {
  540. editormd.loadScript(loadPath + "flowchart.min", function() {
  541. editormd.loadScript(loadPath + "jquery.flowchart.min", function() {
  542. _this.loadedDisplay();
  543. });
  544. });
  545. }
  546. else if (settings.flowChart && settings.sequenceDiagram)
  547. {
  548. editormd.loadScript(loadPath + "flowchart.min", function() {
  549. editormd.loadScript(loadPath + "jquery.flowchart.min", function() {
  550. editormd.loadScript(loadPath + "sequence-diagram.min", function() {
  551. _this.loadedDisplay();
  552. });
  553. });
  554. });
  555. }
  556. });
  557. });
  558. }
  559. else
  560. {
  561. _this.loadedDisplay();
  562. }
  563. };
  564. editormd.loadCSS(loadPath + "codemirror/codemirror.min");
  565. if (settings.searchReplace && !settings.readOnly)
  566. {
  567. editormd.loadCSS(loadPath + "codemirror/addon/dialog/dialog");
  568. editormd.loadCSS(loadPath + "codemirror/addon/search/matchesonscrollbar");
  569. }
  570. if (settings.codeFold)
  571. {
  572. editormd.loadCSS(loadPath + "codemirror/addon/fold/foldgutter");
  573. }
  574. editormd.loadScript(loadPath + "codemirror/codemirror.min", function() {
  575. editormd.$CodeMirror = CodeMirror;
  576. editormd.loadScript(loadPath + "codemirror/modes.min", function() {
  577. editormd.loadScript(loadPath + "codemirror/addons.min", function() {
  578. _this.setCodeMirror();
  579. if (settings.mode !== "gfm" && settings.mode !== "markdown")
  580. {
  581. _this.loadedDisplay();
  582. return false;
  583. }
  584. _this.setToolbar();
  585. editormd.loadScript(loadPath + "marked.min", function() {
  586. editormd.$marked = marked;
  587. if (settings.previewCodeHighlight)
  588. {
  589. // editormd.loadScript(loadPath + "prettify.min", function() {
  590. // loadFlowChartOrSequenceDiagram();
  591. // });
  592. editormd.loadScript(loadPath + "highlight/highlight", function() {
  593. loadFlowChartOrSequenceDiagram();
  594. });
  595. }
  596. else
  597. {
  598. loadFlowChartOrSequenceDiagram();
  599. }
  600. });
  601. });
  602. });
  603. });
  604. return this;
  605. },
  606. /**
  607. * 设置 Editor.md 的整体主题,主要是工具栏
  608. * Setting Editor.md theme
  609. *
  610. * @returns {editormd} 返回editormd的实例对象
  611. */
  612. setTheme : function(theme) {
  613. var editor = this.editor;
  614. var oldTheme = this.settings.theme;
  615. var themePrefix = this.classPrefix + "theme-";
  616. editor.removeClass(themePrefix + oldTheme).addClass(themePrefix + theme);
  617. this.settings.theme = theme;
  618. return this;
  619. },
  620. /**
  621. * 设置 CodeMirror(编辑区)的主题
  622. * Setting CodeMirror (Editor area) theme
  623. *
  624. * @returns {editormd} 返回editormd的实例对象
  625. */
  626. setEditorTheme : function(theme) {
  627. var settings = this.settings;
  628. settings.editorTheme = theme;
  629. if (theme !== "default")
  630. {
  631. editormd.loadCSS(settings.path + "codemirror/theme/" + settings.editorTheme);
  632. }
  633. this.cm.setOption("theme", theme);
  634. return this;
  635. },
  636. /**
  637. * setEditorTheme() 的别名
  638. * setEditorTheme() alias
  639. *
  640. * @returns {editormd} 返回editormd的实例对象
  641. */
  642. setCodeMirrorTheme : function (theme) {
  643. this.setEditorTheme(theme);
  644. return this;
  645. },
  646. /**
  647. * 设置 Editor.md 的主题
  648. * Setting Editor.md theme
  649. *
  650. * @returns {editormd} 返回editormd的实例对象
  651. */
  652. setPreviewTheme : function(theme) {
  653. var preview = this.preview;
  654. var oldTheme = this.settings.previewTheme;
  655. var themePrefix = this.classPrefix + "preview-theme-";
  656. preview.removeClass(themePrefix + oldTheme).addClass(themePrefix + theme);
  657. this.settings.previewTheme = theme;
  658. return this;
  659. },
  660. /**
  661. * 配置和初始化CodeMirror组件
  662. * CodeMirror initialization
  663. *
  664. * @returns {editormd} 返回editormd的实例对象
  665. */
  666. setCodeMirror : function() {
  667. var settings = this.settings;
  668. var editor = this.editor;
  669. if (settings.editorTheme !== "default")
  670. {
  671. editormd.loadCSS(settings.path + "codemirror/theme/" + settings.editorTheme);
  672. }
  673. var codeMirrorConfig = {
  674. mode : settings.mode,
  675. theme : settings.editorTheme,
  676. tabSize : settings.tabSize,
  677. dragDrop : false,
  678. autofocus : settings.autoFocus,
  679. autoCloseTags : settings.autoCloseTags,
  680. readOnly : (settings.readOnly) ? "nocursor" : false,
  681. indentUnit : settings.indentUnit,
  682. lineNumbers : settings.lineNumbers,
  683. lineWrapping : settings.lineWrapping,
  684. extraKeys : {
  685. "Ctrl-Q": function(cm) {
  686. cm.foldCode(cm.getCursor());
  687. }
  688. },
  689. foldGutter : settings.codeFold,
  690. gutters : ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
  691. matchBrackets : settings.matchBrackets,
  692. indentWithTabs : settings.indentWithTabs,
  693. styleActiveLine : settings.styleActiveLine,
  694. styleSelectedText : settings.styleSelectedText,
  695. autoCloseBrackets : settings.autoCloseBrackets,
  696. showTrailingSpace : settings.showTrailingSpace,
  697. highlightSelectionMatches : ( (!settings.matchWordHighlight) ? false : { showToken: (settings.matchWordHighlight === "onselected") ? false : /\w/ } )
  698. };
  699. this.codeEditor = this.cm = editormd.$CodeMirror.fromTextArea(this.markdownTextarea[0], codeMirrorConfig);
  700. this.codeMirror = this.cmElement = editor.children(".CodeMirror");
  701. if (settings.value !== "")
  702. {
  703. this.cm.setValue(settings.value);
  704. }
  705. this.codeMirror.css({
  706. fontSize : settings.fontSize,
  707. width : (!settings.watch) ? "100%" : "50%"
  708. });
  709. if (settings.autoHeight)
  710. {
  711. this.codeMirror.css("height", "auto");
  712. this.cm.setOption("viewportMargin", Infinity);
  713. }
  714. if (!settings.lineNumbers)
  715. {
  716. this.codeMirror.find(".CodeMirror-gutters").css("border-right", "none");
  717. }
  718. return this;
  719. },
  720. /**
  721. * 获取CodeMirror的配置选项
  722. * Get CodeMirror setting options
  723. *
  724. * @returns {Mixed} return CodeMirror setting option value
  725. */
  726. getCodeMirrorOption : function(key) {
  727. return this.cm.getOption(key);
  728. },
  729. /**
  730. * 配置和重配置CodeMirror的选项
  731. * CodeMirror setting options / resettings
  732. *
  733. * @returns {editormd} 返回editormd的实例对象
  734. */
  735. setCodeMirrorOption : function(key, value) {
  736. this.cm.setOption(key, value);
  737. return this;
  738. },
  739. /**
  740. * 添加 CodeMirror 键盘快捷键
  741. * Add CodeMirror keyboard shortcuts key map
  742. *
  743. * @returns {editormd} 返回editormd的实例对象
  744. */
  745. addKeyMap : function(map, bottom) {
  746. this.cm.addKeyMap(map, bottom);
  747. return this;
  748. },
  749. /**
  750. * 移除 CodeMirror 键盘快捷键
  751. * Remove CodeMirror keyboard shortcuts key map
  752. *
  753. * @returns {editormd} 返回editormd的实例对象
  754. */
  755. removeKeyMap : function(map) {
  756. this.cm.removeKeyMap(map);
  757. return this;
  758. },
  759. /**
  760. * 跳转到指定的行
  761. * Goto CodeMirror line
  762. *
  763. * @param {String|Intiger} line line number or "first"|"last"
  764. * @returns {editormd} 返回editormd的实例对象
  765. */
  766. gotoLine : function (line) {
  767. var settings = this.settings;
  768. if (!settings.gotoLine)
  769. {
  770. return this;
  771. }
  772. var cm = this.cm;
  773. var editor = this.editor;
  774. var count = cm.lineCount();
  775. var preview = this.preview;
  776. if (typeof line === "string")
  777. {
  778. if(line === "last")
  779. {
  780. line = count;
  781. }
  782. if (line === "first")
  783. {
  784. line = 1;
  785. }
  786. }
  787. if (typeof line !== "number")
  788. {
  789. alert("Error: The line number must be an integer.");
  790. return this;
  791. }
  792. line = parseInt(line) - 1;
  793. if (line > count)
  794. {
  795. alert("Error: The line number range 1-" + count);
  796. return this;
  797. }
  798. cm.setCursor( {line : line, ch : 0} );
  799. var scrollInfo = cm.getScrollInfo();
  800. var clientHeight = scrollInfo.clientHeight;
  801. var coords = cm.charCoords({line : line, ch : 0}, "local");
  802. cm.scrollTo(null, (coords.top + coords.bottom - clientHeight) / 2);
  803. if (settings.watch)
  804. {
  805. var cmScroll = this.codeMirror.find(".CodeMirror-scroll")[0];
  806. var height = $(cmScroll).height();
  807. var scrollTop = cmScroll.scrollTop;
  808. var percent = (scrollTop / cmScroll.scrollHeight);
  809. if (scrollTop === 0)
  810. {
  811. preview.scrollTop(0);
  812. }
  813. else if (scrollTop + height >= cmScroll.scrollHeight - 16)
  814. {
  815. preview.scrollTop(preview[0].scrollHeight);
  816. }
  817. else
  818. {
  819. preview.scrollTop(preview[0].scrollHeight * percent);
  820. }
  821. }
  822. cm.focus();
  823. return this;
  824. },
  825. /**
  826. * 扩展当前实例对象,可同时设置多个或者只设置一个
  827. * Extend editormd instance object, can mutil setting.
  828. *
  829. * @returns {editormd} this(editormd instance object.)
  830. */
  831. extend : function() {
  832. if (typeof arguments[1] !== "undefined")
  833. {
  834. if (typeof arguments[1] === "function")
  835. {
  836. arguments[1] = $.proxy(arguments[1], this);
  837. }
  838. this[arguments[0]] = arguments[1];
  839. }
  840. if (typeof arguments[0] === "object" && typeof arguments[0].length === "undefined")
  841. {
  842. $.extend(true, this, arguments[0]);
  843. }
  844. return this;
  845. },
  846. /**
  847. * 设置或扩展当前实例对象,单个设置
  848. * Extend editormd instance object, one by one
  849. *
  850. * @param {String|Object} key option key
  851. * @param {String|Object} value option value
  852. * @returns {editormd} this(editormd instance object.)
  853. */
  854. set : function (key, value) {
  855. if (typeof value !== "undefined" && typeof value === "function")
  856. {
  857. value = $.proxy(value, this);
  858. }
  859. this[key] = value;
  860. return this;
  861. },
  862. /**
  863. * 重新配置
  864. * Resetting editor options
  865. *
  866. * @param {String|Object} key option key
  867. * @param {String|Object} value option value
  868. * @returns {editormd} this(editormd instance object.)
  869. */
  870. config : function(key, value) {
  871. var settings = this.settings;
  872. if (typeof key === "object")
  873. {
  874. settings = $.extend(true, settings, key);
  875. }
  876. if (typeof key === "string")
  877. {
  878. settings[key] = value;
  879. }
  880. this.settings = settings;
  881. this.recreate();
  882. return this;
  883. },
  884. /**
  885. * 注册事件处理方法
  886. * Bind editor event handle
  887. *
  888. * @param {String} eventType event type
  889. * @param {Function} callback 回调函数
  890. * @returns {editormd} this(editormd instance object.)
  891. */
  892. on : function(eventType, callback) {
  893. var settings = this.settings;
  894. if (typeof settings["on" + eventType] !== "undefined")
  895. {
  896. settings["on" + eventType] = $.proxy(callback, this);
  897. }
  898. return this;
  899. },
  900. /**
  901. * 解除事件处理方法
  902. * Unbind editor event handle
  903. *
  904. * @param {String} eventType event type
  905. * @returns {editormd} this(editormd instance object.)
  906. */
  907. off : function(eventType) {
  908. var settings = this.settings;
  909. if (typeof settings["on" + eventType] !== "undefined")
  910. {
  911. settings["on" + eventType] = function(){};
  912. }
  913. return this;
  914. },
  915. /**
  916. * 显示工具栏
  917. * Display toolbar
  918. *
  919. * @param {Function} [callback=function(){}] 回调函数
  920. * @returns {editormd} 返回editormd的实例对象
  921. */
  922. showToolbar : function(callback) {
  923. var settings = this.settings;
  924. if(settings.readOnly) {
  925. return this;
  926. }
  927. if (settings.toolbar && (this.toolbar.length < 1 || this.toolbar.find("." + this.classPrefix + "menu").html() === "") )
  928. {
  929. this.setToolbar();
  930. }
  931. settings.toolbar = true;
  932. this.toolbar.show();
  933. this.resize();
  934. $.proxy(callback || function(){}, this)();
  935. return this;
  936. },
  937. /**
  938. * 隐藏工具栏
  939. * Hide toolbar
  940. *
  941. * @param {Function} [callback=function(){}] 回调函数
  942. * @returns {editormd} this(editormd instance object.)
  943. */
  944. hideToolbar : function(callback) {
  945. var settings = this.settings;
  946. settings.toolbar = false;
  947. this.toolbar.hide();
  948. this.resize();
  949. $.proxy(callback || function(){}, this)();
  950. return this;
  951. },
  952. /**
  953. * 页面滚动时工具栏的固定定位
  954. * Set toolbar in window scroll auto fixed position
  955. *
  956. * @returns {editormd} 返回editormd的实例对象
  957. */
  958. setToolbarAutoFixed : function(fixed) {
  959. var state = this.state;
  960. var editor = this.editor;
  961. var toolbar = this.toolbar;
  962. var settings = this.settings;
  963. if (typeof fixed !== "undefined")
  964. {
  965. settings.toolbarAutoFixed = fixed;
  966. }
  967. var autoFixedHandle = function(){
  968. var $window = $(window);
  969. var top = $window.scrollTop();
  970. if (!settings.toolbarAutoFixed)
  971. {
  972. return false;
  973. }
  974. if (top - editor.offset().top > 10 && top < editor.height())
  975. {
  976. toolbar.css({
  977. position : "fixed",
  978. width : editor.width() + "px",
  979. left : ($window.width() - editor.width()) / 2 + "px"
  980. });
  981. }
  982. else
  983. {
  984. toolbar.css({
  985. position : "absolute",
  986. width : "100%",
  987. left : 0
  988. });
  989. }
  990. };
  991. if (!state.fullscreen && !state.preview && settings.toolbar && settings.toolbarAutoFixed)
  992. {
  993. $(window).bind("scroll", autoFixedHandle);
  994. }
  995. return this;
  996. },
  997. /**
  998. * 配置和初始化工具栏
  999. * Set toolbar and Initialization
  1000. *
  1001. * @returns {editormd} 返回editormd的实例对象
  1002. */
  1003. setToolbar : function() {
  1004. var settings = this.settings;
  1005. if(settings.readOnly) {
  1006. return this;
  1007. }
  1008. var editor = this.editor;
  1009. var preview = this.preview;
  1010. var classPrefix = this.classPrefix;
  1011. var toolbar = this.toolbar = editor.children("." + classPrefix + "toolbar");
  1012. if (settings.toolbar && toolbar.length < 1)
  1013. {
  1014. var toolbarHTML = "<div class=\"" + classPrefix + "toolbar\"><div class=\"" + classPrefix + "toolbar-container\"><ul class=\"" + classPrefix + "menu\"></ul></div></div>";
  1015. editor.append(toolbarHTML);
  1016. toolbar = this.toolbar = editor.children("." + classPrefix + "toolbar");
  1017. }
  1018. if (!settings.toolbar)
  1019. {
  1020. toolbar.hide();
  1021. return this;
  1022. }
  1023. toolbar.show();
  1024. var icons = (typeof settings.toolbarIcons === "function") ? settings.toolbarIcons()
  1025. : ((typeof settings.toolbarIcons === "string") ? editormd.toolbarModes[settings.toolbarIcons] : settings.toolbarIcons);
  1026. var toolbarMenu = toolbar.find("." + this.classPrefix + "menu"), menu = "";
  1027. var pullRight = false;
  1028. for (var i = 0, len = icons.length; i < len; i++)
  1029. {
  1030. var name = icons[i];
  1031. if (name === "||")
  1032. {
  1033. pullRight = true;
  1034. }
  1035. else if (name === "|")
  1036. {
  1037. menu += "<li class=\"divider\" unselectable=\"on\">|</li>";
  1038. }
  1039. else
  1040. {
  1041. var isHeader = (/h(\d)/.test(name));
  1042. var index = name;
  1043. if (name === "watch" && !settings.watch) {
  1044. index = "unwatch";
  1045. }
  1046. var title = settings.lang.toolbar[index];
  1047. var iconTexts = settings.toolbarIconTexts[index];
  1048. var iconClass = settings.toolbarIconsClass[index];
  1049. title = (typeof title === "undefined") ? "" : title;
  1050. iconTexts = (typeof iconTexts === "undefined") ? "" : iconTexts;
  1051. iconClass = (typeof iconClass === "undefined") ? "" : iconClass;
  1052. var menuItem = pullRight ? "<li class=\"pull-right\">" : "<li>";
  1053. if (typeof settings.toolbarCustomIcons[name] !== "undefined" && typeof settings.toolbarCustomIcons[name] !== "function")
  1054. {
  1055. menuItem += settings.toolbarCustomIcons[name];
  1056. }
  1057. else
  1058. {
  1059. menuItem += "<a href=\"javascript:;\" title=\"" + title + "\" unselectable=\"on\">";
  1060. menuItem += "<i class=\"fa " + iconClass + "\" name=\""+name+"\" unselectable=\"on\">"+((isHeader) ? name.toUpperCase() : ( (iconClass === "") ? iconTexts : "") ) + "</i>";
  1061. menuItem += "</a>";
  1062. }
  1063. menuItem += "</li>";
  1064. menu = pullRight ? menuItem + menu : menu + menuItem;
  1065. }
  1066. }
  1067. toolbarMenu.html(menu);
  1068. toolbarMenu.find("[title=\"Lowercase\"]").attr("title", settings.lang.toolbar.lowercase);
  1069. toolbarMenu.find("[title=\"ucwords\"]").attr("title", settings.lang.toolbar.ucwords);
  1070. this.setToolbarHandler();
  1071. this.setToolbarAutoFixed();
  1072. return this;
  1073. },
  1074. /**
  1075. * 工具栏图标事件处理对象序列
  1076. * Get toolbar icons event handlers
  1077. *
  1078. * @param {Object} cm CodeMirror的实例对象
  1079. * @param {String} name 要获取的事件处理器名称
  1080. * @returns {Object} 返回处理对象序列
  1081. */
  1082. dialogLockScreen : function() {
  1083. $.proxy(editormd.dialogLockScreen, this)();
  1084. return this;
  1085. },
  1086. dialogShowMask : function(dialog) {
  1087. $.proxy(editormd.dialogShowMask, this)(dialog);
  1088. return this;
  1089. },
  1090. getToolbarHandles : function(name) {
  1091. var toolbarHandlers = this.toolbarHandlers = editormd.toolbarHandlers;
  1092. return (name && typeof toolbarIconHandlers[name] !== "undefined") ? toolbarHandlers[name] : toolbarHandlers;
  1093. },
  1094. /**
  1095. * 工具栏图标事件处理器
  1096. * Bind toolbar icons event handle
  1097. *
  1098. * @returns {editormd} 返回editormd的实例对象
  1099. */
  1100. setToolbarHandler : function() {
  1101. var _this = this;
  1102. var settings = this.settings;
  1103. if (!settings.toolbar || settings.readOnly) {
  1104. return this;
  1105. }
  1106. var toolbar = this.toolbar;
  1107. var cm = this.cm;
  1108. var classPrefix = this.classPrefix;
  1109. var toolbarIcons = this.toolbarIcons = toolbar.find("." + classPrefix + "menu > li > a");
  1110. var toolbarIconHandlers = this.getToolbarHandles();
  1111. toolbarIcons.bind(editormd.mouseOrTouch("click", "touchend"), function(event) {
  1112. var icon = $(this).children(".fa");
  1113. var name = icon.attr("name");
  1114. var cursor = cm.getCursor();
  1115. var selection = cm.getSelection();
  1116. if (name === "") {
  1117. return ;
  1118. }
  1119. _this.activeIcon = icon;
  1120. if (typeof toolbarIconHandlers[name] !== "undefined")
  1121. {
  1122. $.proxy(toolbarIconHandlers[name], _this)(cm);
  1123. }
  1124. else
  1125. {
  1126. if (typeof settings.toolbarHandlers[name] !== "undefined")
  1127. {
  1128. $.proxy(settings.toolbarHandlers[name], _this)(cm, icon, cursor, selection);
  1129. }
  1130. }
  1131. if (name !== "link" && name !== "reference-link" && name !== "image" && name !== "code-block" &&
  1132. name !== "preformatted-text" && name !== "watch" && name !== "preview" && name !== "search" && name !== "fullscreen" && name !== "info")
  1133. {
  1134. cm.focus();
  1135. }
  1136. return false;
  1137. });
  1138. return this;
  1139. },
  1140. /**
  1141. * 动态创建对话框
  1142. * Creating custom dialogs
  1143. *
  1144. * @param {Object} options 配置项键值对 Key/Value
  1145. * @returns {dialog} 返回创建的dialog的jQuery实例对象
  1146. */
  1147. createDialog : function(options) {
  1148. return $.proxy(editormd.createDialog, this)(options);
  1149. },
  1150. /**
  1151. * 创建关于Editor.md的对话框
  1152. * Create about Editor.md dialog
  1153. *
  1154. * @returns {editormd} 返回editormd的实例对象
  1155. */
  1156. createInfoDialog : function() {
  1157. var _this = this;
  1158. var editor = this.editor;
  1159. var classPrefix = this.classPrefix;
  1160. var infoDialogHTML = [
  1161. "<div class=\"" + classPrefix + "dialog " + classPrefix + "dialog-info\" style=\"\">",
  1162. "<div class=\"" + classPrefix + "dialog-container\">",
  1163. "<h1><i class=\"editormd-logo editormd-logo-lg editormd-logo-color\"></i> " + editormd.title + "<small>v" + editormd.version + "</small></h1>",
  1164. "<p>" + this.lang.description + "</p>",
  1165. "<p style=\"margin: 10px 0 20px 0;\"><a href=\"" + editormd.homePage + "\" target=\"_blank\">" + editormd.homePage + " <i class=\"fa fa-external-link\"></i></a></p>",
  1166. "<p style=\"font-size: 0.85em;\">Copyright &copy; 2015 <a href=\"https://github.com/pandao\" target=\"_blank\" class=\"hover-link\">Pandao</a>, The <a href=\"https://github.com/pandao/editor.md/blob/master/LICENSE\" target=\"_blank\" class=\"hover-link\">MIT</a> License.</p>",
  1167. "</div>",
  1168. "<a href=\"javascript:;\" class=\"fa fa-close " + classPrefix + "dialog-close\"></a>",
  1169. "</div>"
  1170. ].join("\n");
  1171. editor.append(infoDialogHTML);
  1172. var infoDialog = this.infoDialog = editor.children("." + classPrefix + "dialog-info");
  1173. infoDialog.find("." + classPrefix + "dialog-close").bind(editormd.mouseOrTouch("click", "touchend"), function() {
  1174. _this.hideInfoDialog();
  1175. });
  1176. infoDialog.css("border", (editormd.isIE8) ? "1px solid #ddd" : "").css("z-index", editormd.dialogZindex).show();
  1177. this.infoDialogPosition();
  1178. return this;
  1179. },
  1180. /**
  1181. * 关于Editor.md对话居中定位
  1182. * Editor.md dialog position handle
  1183. *
  1184. * @returns {editormd} 返回editormd的实例对象
  1185. */
  1186. infoDialogPosition : function() {
  1187. var infoDialog = this.infoDialog;
  1188. var _infoDialogPosition = function() {
  1189. infoDialog.css({
  1190. top : ($(window).height() - infoDialog.height()) / 2 + "px",
  1191. left : ($(window).width() - infoDialog.width()) / 2 + "px"
  1192. });
  1193. };
  1194. _infoDialogPosition();
  1195. $(window).resize(_infoDialogPosition);
  1196. return this;
  1197. },
  1198. /**
  1199. * 显示关于Editor.md
  1200. * Display about Editor.md dialog
  1201. *
  1202. * @returns {editormd} 返回editormd的实例对象
  1203. */
  1204. showInfoDialog : function() {
  1205. $("html,body").css("overflow-x", "hidden");
  1206. var _this = this;
  1207. var editor = this.editor;
  1208. var settings = this.settings;
  1209. var infoDialog = this.infoDialog = editor.children("." + this.classPrefix + "dialog-info");
  1210. if (infoDialog.length < 1)
  1211. {
  1212. this.createInfoDialog();
  1213. }
  1214. this.lockScreen(true);
  1215. this.mask.css({
  1216. opacity : settings.dialogMaskOpacity,
  1217. backgroundColor : settings.dialogMaskBgColor
  1218. }).show();
  1219. infoDialog.css("z-index", editormd.dialogZindex).show();
  1220. this.infoDialogPosition();
  1221. return this;
  1222. },
  1223. /**
  1224. * 隐藏关于Editor.md
  1225. * Hide about Editor.md dialog
  1226. *
  1227. * @returns {editormd} 返回editormd的实例对象
  1228. */
  1229. hideInfoDialog : function() {
  1230. $("html,body").css("overflow-x", "");
  1231. this.infoDialog.hide();
  1232. this.mask.hide();
  1233. this.lockScreen(false);
  1234. return this;
  1235. },
  1236. /**
  1237. * 锁屏
  1238. * lock screen
  1239. *
  1240. * @param {Boolean} lock Boolean 布尔值,是否锁屏
  1241. * @returns {editormd} 返回editormd的实例对象
  1242. */
  1243. lockScreen : function(lock) {
  1244. editormd.lockScreen(lock);
  1245. this.resize();
  1246. return this;
  1247. },
  1248. /**
  1249. * 编辑器界面重建,用于动态语言包或模块加载等
  1250. * Recreate editor
  1251. *
  1252. * @returns {editormd} 返回editormd的实例对象
  1253. */
  1254. recreate : function() {
  1255. var _this = this;
  1256. var editor = this.editor;
  1257. var settings = this.settings;
  1258. this.codeMirror.remove();
  1259. this.setCodeMirror();
  1260. if (!settings.readOnly)
  1261. {
  1262. if (editor.find(".editormd-dialog").length > 0) {
  1263. editor.find(".editormd-dialog").remove();
  1264. }
  1265. if (settings.toolbar)
  1266. {
  1267. this.getToolbarHandles();
  1268. this.setToolbar();
  1269. }
  1270. }
  1271. this.loadedDisplay(true);
  1272. return this;
  1273. },
  1274. /**
  1275. * 高亮预览HTML的pre代码部分
  1276. * highlight of preview codes
  1277. *
  1278. * @returns {editormd} 返回editormd的实例对象
  1279. */
  1280. previewCodeHighlight : function() {
  1281. var settings = this.settings;
  1282. var previewContainer = this.previewContainer;
  1283. if (settings.previewCodeHighlight)
  1284. {
  1285. // previewContainer.find("pre").addClass("prettyprint");
  1286. //
  1287. // if (typeof prettyPrint !== "undefined")
  1288. // {
  1289. // prettyPrint();
  1290. // }
  1291. if (typeof hljs !== "undefined") {
  1292. previewContainer.find('pre').each(function (i, block) {
  1293. hljs.highlightBlock(block);
  1294. });
  1295. }
  1296. }
  1297. return this;
  1298. },
  1299. /**
  1300. * 解析TeX(KaTeX)科学公式
  1301. * TeX(KaTeX) Renderer
  1302. *
  1303. * @returns {editormd} 返回editormd的实例对象
  1304. */
  1305. katexRender : function() {
  1306. if (timer === null)
  1307. {
  1308. return this;
  1309. }
  1310. this.previewContainer.find("." + editormd.classNames.tex).each(function(){
  1311. var tex = $(this);
  1312. editormd.$katex.render(tex.text(), tex[0]);
  1313. tex.find(".katex").css("font-size", "1.6em");
  1314. });
  1315. return this;
  1316. },
  1317. /**
  1318. * 解析和渲染流程图及时序图
  1319. * FlowChart and SequenceDiagram Renderer
  1320. *
  1321. * @returns {editormd} 返回editormd的实例对象
  1322. */
  1323. flowChartAndSequenceDiagramRender : function() {
  1324. var $this = this;
  1325. var settings = this.settings;
  1326. var previewContainer = this.previewContainer;
  1327. if (editormd.isIE8) {
  1328. return this;
  1329. }
  1330. if (settings.flowChart) {
  1331. if (flowchartTimer === null) {
  1332. return this;
  1333. }
  1334. previewContainer.find(".flowchart").flowChart();
  1335. }
  1336. if (settings.sequenceDiagram) {
  1337. previewContainer.find(".sequence-diagram").sequenceDiagram({theme: "simple"});
  1338. }
  1339. var preview = $this.preview;
  1340. var codeMirror = $this.codeMirror;
  1341. var codeView = codeMirror.find(".CodeMirror-scroll");
  1342. var height = codeView.height();
  1343. var scrollTop = codeView.scrollTop();
  1344. var percent = (scrollTop / codeView[0].scrollHeight);
  1345. var tocHeight = 0;
  1346. preview.find(".markdown-toc-list").each(function(){
  1347. tocHeight += $(this).height();
  1348. });
  1349. var tocMenuHeight = preview.find(".editormd-toc-menu").height();
  1350. tocMenuHeight = (!tocMenuHeight) ? 0 : tocMenuHeight;
  1351. if (scrollTop === 0)
  1352. {
  1353. preview.scrollTop(0);
  1354. }
  1355. else if (scrollTop + height >= codeView[0].scrollHeight - 16)
  1356. {
  1357. preview.scrollTop(preview[0].scrollHeight);
  1358. }
  1359. else
  1360. {
  1361. preview.scrollTop((preview[0].scrollHeight + tocHeight + tocMenuHeight) * percent);
  1362. }
  1363. return this;
  1364. },
  1365. /**
  1366. * 注册键盘快捷键处理
  1367. * Register CodeMirror keyMaps (keyboard shortcuts).
  1368. *
  1369. * @param {Object} keyMap KeyMap key/value {"(Ctrl/Shift/Alt)-Key" : function(){}}
  1370. * @returns {editormd} return this
  1371. */
  1372. registerKeyMaps : function(keyMap) {
  1373. var _this = this;
  1374. var cm = this.cm;
  1375. var settings = this.settings;
  1376. var toolbarHandlers = editormd.toolbarHandlers;
  1377. var disabledKeyMaps = settings.disabledKeyMaps;
  1378. keyMap = keyMap || null;
  1379. if (keyMap)
  1380. {
  1381. for (var i in keyMap)
  1382. {
  1383. if ($.inArray(i, disabledKeyMaps) < 0)
  1384. {
  1385. var map = {};
  1386. map[i] = keyMap[i];
  1387. cm.addKeyMap(keyMap);
  1388. }
  1389. }
  1390. }
  1391. else
  1392. {
  1393. for (var k in editormd.keyMaps)
  1394. {
  1395. var _keyMap = editormd.keyMaps[k];
  1396. var handle = (typeof _keyMap === "string") ? $.proxy(toolbarHandlers[_keyMap], _this) : $.proxy(_keyMap, _this);
  1397. if ($.inArray(k, ["F9", "F10", "F11"]) < 0 && $.inArray(k, disabledKeyMaps) < 0)
  1398. {
  1399. var _map = {};
  1400. _map[k] = handle;
  1401. cm.addKeyMap(_map);
  1402. }
  1403. }
  1404. $(window).keydown(function(event) {
  1405. var keymaps = {
  1406. "120" : "F9",
  1407. "121" : "F10",
  1408. "122" : "F11"
  1409. };
  1410. if ( $.inArray(keymaps[event.keyCode], disabledKeyMaps) < 0 )
  1411. {
  1412. switch (event.keyCode)
  1413. {
  1414. case 120:
  1415. $.proxy(toolbarHandlers["watch"], _this)();
  1416. return false;
  1417. break;
  1418. case 121:
  1419. $.proxy(toolbarHandlers["preview"], _this)();
  1420. return false;
  1421. break;
  1422. case 122:
  1423. $.proxy(toolbarHandlers["fullscreen"], _this)();
  1424. return false;
  1425. break;
  1426. default:
  1427. break;
  1428. }
  1429. }
  1430. });
  1431. }
  1432. return this;
  1433. },
  1434. /**
  1435. * 绑定同步滚动
  1436. *
  1437. * @returns {editormd} return this
  1438. */
  1439. bindScrollEvent : function() {
  1440. var _this = this;
  1441. var preview = this.preview;
  1442. var settings = this.settings;
  1443. var codeMirror = this.codeMirror;
  1444. var mouseOrTouch = editormd.mouseOrTouch;
  1445. if (!settings.syncScrolling) {
  1446. return this;
  1447. }
  1448. var cmBindScroll = function() {
  1449. codeMirror.find(".CodeMirror-scroll").bind(mouseOrTouch("scroll", "touchmove"), function(event) {
  1450. var height = $(this).height();
  1451. var scrollTop = $(this).scrollTop();
  1452. var percent = (scrollTop / $(this)[0].scrollHeight);
  1453. var tocHeight = 0;
  1454. preview.find(".markdown-toc-list").each(function(){
  1455. tocHeight += $(this).height();
  1456. });
  1457. var tocMenuHeight = preview.find(".editormd-toc-menu").height();
  1458. tocMenuHeight = (!tocMenuHeight) ? 0 : tocMenuHeight;
  1459. if (scrollTop === 0)
  1460. {
  1461. preview.scrollTop(0);
  1462. }
  1463. else if (scrollTop + height >= $(this)[0].scrollHeight - 16)
  1464. {
  1465. preview.scrollTop(preview[0].scrollHeight);
  1466. }
  1467. else
  1468. {
  1469. preview.scrollTop((preview[0].scrollHeight + tocHeight + tocMenuHeight) * percent);
  1470. }
  1471. $.proxy(settings.onscroll, _this)(event);
  1472. });
  1473. };
  1474. var cmUnbindScroll = function() {
  1475. codeMirror.find(".CodeMirror-scroll").unbind(mouseOrTouch("scroll", "touchmove"));
  1476. };
  1477. var previewBindScroll = function() {
  1478. preview.bind(mouseOrTouch("scroll", "touchmove"), function(event) {
  1479. var height = $(this).height();
  1480. var scrollTop = $(this).scrollTop();
  1481. var percent = (scrollTop / $(this)[0].scrollHeight);
  1482. var codeView = codeMirror.find(".CodeMirror-scroll");
  1483. if(scrollTop === 0)
  1484. {
  1485. codeView.scrollTop(0);
  1486. }
  1487. else if (scrollTop + height >= $(this)[0].scrollHeight)
  1488. {
  1489. codeView.scrollTop(codeView[0].scrollHeight);
  1490. }
  1491. else
  1492. {
  1493. codeView.scrollTop(codeView[0].scrollHeight * percent);
  1494. }
  1495. $.proxy(settings.onpreviewscroll, _this)(event);
  1496. });
  1497. };
  1498. var previewUnbindScroll = function() {
  1499. preview.unbind(mouseOrTouch("scroll", "touchmove"));
  1500. };
  1501. codeMirror.bind({
  1502. mouseover : cmBindScroll,
  1503. mouseout : cmUnbindScroll,
  1504. touchstart : cmBindScroll,
  1505. touchend : cmUnbindScroll
  1506. });
  1507. if (settings.syncScrolling === "single") {
  1508. return this;
  1509. }
  1510. preview.bind({
  1511. mouseover : previewBindScroll,
  1512. mouseout : previewUnbindScroll,
  1513. touchstart : previewBindScroll,
  1514. touchend : previewUnbindScroll
  1515. });
  1516. return this;
  1517. },
  1518. bindChangeEvent : function() {
  1519. var _this = this;
  1520. var cm = this.cm;
  1521. var settings = this.settings;
  1522. if (!settings.syncScrolling) {
  1523. return this;
  1524. }
  1525. cm.on("change", function(_cm, changeObj) {
  1526. if (settings.watch)
  1527. {
  1528. _this.previewContainer.css("padding", settings.autoHeight ? "20px 20px 50px 40px" : "20px");
  1529. }
  1530. timer = setTimeout(function() {
  1531. clearTimeout(timer);
  1532. _this.save();
  1533. timer = null;
  1534. }, settings.delay);
  1535. });
  1536. return this;
  1537. },
  1538. /**
  1539. * 加载队列完成之后的显示处理
  1540. * Display handle of the module queues loaded after.
  1541. *
  1542. * @param {Boolean} recreate 是否为重建编辑器
  1543. * @returns {editormd} 返回editormd的实例对象
  1544. */
  1545. loadedDisplay : function(recreate) {
  1546. recreate = recreate || false;
  1547. var _this = this;
  1548. var editor = this.editor;
  1549. var preview = this.preview;
  1550. var settings = this.settings;
  1551. this.containerMask.hide();
  1552. this.save();
  1553. if (settings.watch) {
  1554. preview.show();
  1555. }
  1556. editor.data("oldWidth", editor.width()).data("oldHeight", editor.height()); // 为了兼容Zepto
  1557. this.resize();
  1558. this.registerKeyMaps();
  1559. $(window).resize(function(){
  1560. _this.resize();
  1561. });
  1562. this.bindScrollEvent().bindChangeEvent();
  1563. if (!recreate)
  1564. {
  1565. $.proxy(settings.onload, this)();
  1566. }
  1567. this.state.loaded = true;
  1568. return this;
  1569. },
  1570. /**
  1571. * 设置编辑器的宽度
  1572. * Set editor width
  1573. *
  1574. * @param {Number|String} width 编辑器宽度值
  1575. * @returns {editormd} 返回editormd的实例对象
  1576. */
  1577. width : function(width) {
  1578. this.editor.css("width", (typeof width === "number") ? width + "px" : width);
  1579. this.resize();
  1580. return this;
  1581. },
  1582. /**
  1583. * 设置编辑器的高度
  1584. * Set editor height
  1585. *
  1586. * @param {Number|String} height 编辑器高度值
  1587. * @returns {editormd} 返回editormd的实例对象
  1588. */
  1589. height : function(height) {
  1590. this.editor.css("height", (typeof height === "number") ? height + "px" : height);
  1591. this.resize();
  1592. return this;
  1593. },
  1594. /**
  1595. * 调整编辑器的尺寸和布局
  1596. * Resize editor layout
  1597. *
  1598. * @param {Number|String} [width=null] 编辑器宽度值
  1599. * @param {Number|String} [height=null] 编辑器高度值
  1600. * @returns {editormd} 返回editormd的实例对象
  1601. */
  1602. resize : function(width, height) {
  1603. width = width || null;
  1604. height = height || null;
  1605. var state = this.state;
  1606. var editor = this.editor;
  1607. var preview = this.preview;
  1608. var toolbar = this.toolbar;
  1609. var settings = this.settings;
  1610. var codeMirror = this.codeMirror;
  1611. if (width)
  1612. {
  1613. editor.css("width", (typeof width === "number") ? width + "px" : width);
  1614. }
  1615. if (settings.autoHeight && !state.fullscreen && !state.preview)
  1616. {
  1617. editor.css("height", "auto");
  1618. codeMirror.css("height", "auto");
  1619. }
  1620. else
  1621. {
  1622. if (height)
  1623. {
  1624. editor.css("height", (typeof height === "number") ? height + "px" : height);
  1625. }
  1626. if (state.fullscreen)
  1627. {
  1628. editor.height($(window).height());
  1629. }
  1630. if (settings.toolbar && !settings.readOnly)
  1631. {
  1632. codeMirror.css("margin-top", toolbar.height() + 1).height(editor.height() - toolbar.height());
  1633. }
  1634. else
  1635. {
  1636. codeMirror.css("margin-top", 0).height(editor.height());
  1637. }
  1638. }
  1639. if(settings.watch)
  1640. {
  1641. codeMirror.width(editor.width() / 2);
  1642. preview.width((!state.preview) ? editor.width() / 2 : editor.width());
  1643. this.previewContainer.css("padding", settings.autoHeight ? "20px 20px 50px 40px" : "20px");
  1644. if (settings.toolbar && !settings.readOnly)
  1645. {
  1646. preview.css("top", toolbar.height() + 1);
  1647. }
  1648. else
  1649. {
  1650. preview.css("top", 0);
  1651. }
  1652. if (settings.autoHeight && !state.fullscreen && !state.preview)
  1653. {
  1654. preview.height("");
  1655. }
  1656. else
  1657. {
  1658. var previewHeight = (settings.toolbar && !settings.readOnly) ? editor.height() - toolbar.height() : editor.height();
  1659. preview.height(previewHeight);
  1660. }
  1661. }
  1662. else
  1663. {
  1664. codeMirror.width(editor.width());
  1665. preview.hide();
  1666. }
  1667. if (state.loaded)
  1668. {
  1669. $.proxy(settings.onresize, this)();
  1670. }
  1671. return this;
  1672. },
  1673. /**
  1674. * 解析和保存Markdown代码
  1675. * Parse & Saving Markdown source code
  1676. *
  1677. * @returns {editormd} 返回editormd的实例对象
  1678. */
  1679. save : function() {
  1680. if (timer === null)
  1681. {
  1682. return this;
  1683. }
  1684. var _this = this;
  1685. var state = this.state;
  1686. var settings = this.settings;
  1687. var cm = this.cm;
  1688. var cmValue = cm.getValue();
  1689. var previewContainer = this.previewContainer;
  1690. if (settings.mode !== "gfm" && settings.mode !== "markdown")
  1691. {
  1692. this.markdownTextarea.val(cmValue);
  1693. return this;
  1694. }
  1695. var marked = editormd.$marked;
  1696. var markdownToC = this.markdownToC = [];
  1697. var rendererOptions = this.markedRendererOptions = {
  1698. toc : settings.toc,
  1699. tocm : settings.tocm,
  1700. tocStartLevel : settings.tocStartLevel,
  1701. pageBreak : settings.pageBreak,
  1702. taskList : settings.taskList,
  1703. emoji : settings.emoji,
  1704. tex : settings.tex,
  1705. atLink : settings.atLink, // for @link
  1706. emailLink : settings.emailLink, // for mail address auto link
  1707. flowChart : settings.flowChart,
  1708. sequenceDiagram : settings.sequenceDiagram,
  1709. previewCodeHighlight : settings.previewCodeHighlight,
  1710. };
  1711. var markedOptions = this.markedOptions = {
  1712. renderer : editormd.markedRenderer(markdownToC, rendererOptions),
  1713. gfm : true,
  1714. tables : true,
  1715. breaks : true,
  1716. pedantic : false,
  1717. sanitize : (settings.htmlDecode) ? false : true, // 关闭忽略HTML标签,即开启识别HTML标签,默认为false
  1718. smartLists : true,
  1719. smartypants : true
  1720. };
  1721. marked.setOptions(markedOptions);
  1722. var newMarkdownDoc = editormd.$marked(cmValue, markedOptions);
  1723. //console.info("cmValue", cmValue, newMarkdownDoc);
  1724. newMarkdownDoc = editormd.filterHTMLTags(newMarkdownDoc, settings.htmlDecode);
  1725. //console.error("cmValue", cmValue, newMarkdownDoc);
  1726. this.markdownTextarea.text(cmValue);
  1727. cm.save();
  1728. if (settings.saveHTMLToTextarea)
  1729. {
  1730. this.htmlTextarea.text(newMarkdownDoc);
  1731. }
  1732. if(settings.watch || (!settings.watch && state.preview))
  1733. {
  1734. previewContainer.html(newMarkdownDoc);
  1735. this.previewCodeHighlight();
  1736. if (settings.toc)
  1737. {
  1738. var tocContainer = (settings.tocContainer === "") ? previewContainer : $(settings.tocContainer);
  1739. var tocMenu = tocContainer.find("." + this.classPrefix + "toc-menu");
  1740. tocContainer.attr("previewContainer", (settings.tocContainer === "") ? "true" : "false");
  1741. if (settings.tocContainer !== "" && tocMenu.length > 0)
  1742. {
  1743. tocMenu.remove();
  1744. }
  1745. editormd.markdownToCRenderer(markdownToC, tocContainer, settings.tocDropdown, settings.tocStartLevel);
  1746. if (settings.tocDropdown || tocContainer.find("." + this.classPrefix + "toc-menu").length > 0)
  1747. {
  1748. editormd.tocDropdownMenu(tocContainer, (settings.tocTitle !== "") ? settings.tocTitle : this.lang.tocTitle);
  1749. }
  1750. if (settings.tocContainer !== "")
  1751. {
  1752. previewContainer.find(".markdown-toc").css("border", "none");
  1753. }
  1754. }
  1755. if (settings.tex)
  1756. {
  1757. if (!editormd.kaTeXLoaded && settings.autoLoadModules)
  1758. {
  1759. editormd.loadKaTeX(function() {
  1760. editormd.$katex = katex;
  1761. editormd.kaTeXLoaded = true;
  1762. _this.katexRender();
  1763. });
  1764. }
  1765. else
  1766. {
  1767. editormd.$katex = katex;
  1768. this.katexRender();
  1769. }
  1770. }
  1771. if (settings.flowChart || settings.sequenceDiagram)
  1772. {
  1773. flowchartTimer = setTimeout(function(){
  1774. clearTimeout(flowchartTimer);
  1775. _this.flowChartAndSequenceDiagramRender();
  1776. flowchartTimer = null;
  1777. }, 10);
  1778. }
  1779. if (state.loaded)
  1780. {
  1781. $.proxy(settings.onchange, this)();
  1782. }
  1783. }
  1784. return this;
  1785. },
  1786. /**
  1787. * 聚焦光标位置
  1788. * Focusing the cursor position
  1789. *
  1790. * @returns {editormd} 返回editormd的实例对象
  1791. */
  1792. focus : function() {
  1793. this.cm.focus();
  1794. return this;
  1795. },
  1796. /**
  1797. * 设置光标的位置
  1798. * Set cursor position
  1799. *
  1800. * @param {Object} cursor 要设置的光标位置键值对象,例:{line:1, ch:0}
  1801. * @returns {editormd} 返回editormd的实例对象
  1802. */
  1803. setCursor : function(cursor) {
  1804. this.cm.setCursor(cursor);
  1805. return this;
  1806. },
  1807. /**
  1808. * 获取当前光标的位置
  1809. * Get the current position of the cursor
  1810. *
  1811. * @returns {Cursor} 返回一个光标Cursor对象
  1812. */
  1813. getCursor : function() {
  1814. return this.cm.getCursor();
  1815. },
  1816. /**
  1817. * 设置光标选中的范围
  1818. * Set cursor selected ranges
  1819. *
  1820. * @param {Object} from 开始位置的光标键值对象,例:{line:1, ch:0}
  1821. * @param {Object} to 结束位置的光标键值对象,例:{line:1, ch:0}
  1822. * @returns {editormd} 返回editormd的实例对象
  1823. */
  1824. setSelection : function(from, to) {
  1825. this.cm.setSelection(from, to);
  1826. return this;
  1827. },
  1828. /**
  1829. * 获取光标选中的文本
  1830. * Get the texts from cursor selected
  1831. *
  1832. * @returns {String} 返回选中文本的字符串形式
  1833. */
  1834. getSelection : function() {
  1835. return this.cm.getSelection();
  1836. },
  1837. /**
  1838. * 设置光标选中的文本范围
  1839. * Set the cursor selection ranges
  1840. *
  1841. * @param {Array} ranges cursor selection ranges array
  1842. * @returns {Array} return this
  1843. */
  1844. setSelections : function(ranges) {
  1845. this.cm.setSelections(ranges);
  1846. return this;
  1847. },
  1848. /**
  1849. * 获取光标选中的文本范围
  1850. * Get the cursor selection ranges
  1851. *
  1852. * @returns {Array} return selection ranges array
  1853. */
  1854. getSelections : function() {
  1855. return this.cm.getSelections();
  1856. },
  1857. /**
  1858. * 替换当前光标选中的文本或在当前光标处插入新字符
  1859. * Replace the text at the current cursor selected or insert a new character at the current cursor position
  1860. *
  1861. * @param {String} value 要插入的字符值
  1862. * @returns {editormd} 返回editormd的实例对象
  1863. */
  1864. replaceSelection : function(value) {
  1865. this.cm.replaceSelection(value);
  1866. return this;
  1867. },
  1868. /**
  1869. * 在当前光标处插入新字符
  1870. * Insert a new character at the current cursor position
  1871. *
  1872. * 同replaceSelection()方法
  1873. * With the replaceSelection() method
  1874. *
  1875. * @param {String} value 要插入的字符值
  1876. * @returns {editormd} 返回editormd的实例对象
  1877. */
  1878. insertValue : function(value) {
  1879. this.replaceSelection(value);
  1880. return this;
  1881. },
  1882. /**
  1883. * 追加markdown
  1884. * append Markdown to editor
  1885. *
  1886. * @param {String} md 要追加的markdown源文档
  1887. * @returns {editormd} 返回editormd的实例对象
  1888. */
  1889. appendMarkdown : function(md) {
  1890. var settings = this.settings;
  1891. var cm = this.cm;
  1892. cm.setValue(cm.getValue() + md);
  1893. return this;
  1894. },
  1895. /**
  1896. * 设置和传入编辑器的markdown源文档
  1897. * Set Markdown source document
  1898. *
  1899. * @param {String} md 要传入的markdown源文档
  1900. * @returns {editormd} 返回editormd的实例对象
  1901. */
  1902. setMarkdown : function(md) {
  1903. this.cm.setValue(md || this.settings.markdown);
  1904. return this;
  1905. },
  1906. /**
  1907. * 获取编辑器的markdown源文档
  1908. * Set Editor.md markdown/CodeMirror value
  1909. *
  1910. * @returns {editormd} 返回editormd的实例对象
  1911. */
  1912. getMarkdown : function() {
  1913. return this.cm.getValue();
  1914. },
  1915. /**
  1916. * 获取编辑器的源文档
  1917. * Get CodeMirror value
  1918. *
  1919. * @returns {editormd} 返回editormd的实例对象
  1920. */
  1921. getValue : function() {
  1922. return this.cm.getValue();
  1923. },
  1924. /**
  1925. * 设置编辑器的源文档
  1926. * Set CodeMirror value
  1927. *
  1928. * @param {String} value set code/value/string/text
  1929. * @returns {editormd} 返回editormd的实例对象
  1930. */
  1931. setValue : function(value) {
  1932. this.cm.setValue(value);
  1933. return this;
  1934. },
  1935. /**
  1936. * 清空编辑器
  1937. * Empty CodeMirror editor container
  1938. *
  1939. * @returns {editormd} 返回editormd的实例对象
  1940. */
  1941. clear : function() {
  1942. this.cm.setValue("");
  1943. return this;
  1944. },
  1945. /**
  1946. * 获取解析后存放在Textarea的HTML源码
  1947. * Get parsed html code from Textarea
  1948. *
  1949. * @returns {String} 返回HTML源码
  1950. */
  1951. getHTML : function() {
  1952. if (!this.settings.saveHTMLToTextarea)
  1953. {
  1954. alert("Error: settings.saveHTMLToTextarea == false");
  1955. return false;
  1956. }
  1957. return this.htmlTextarea.val();
  1958. },
  1959. /**
  1960. * getHTML()的别名
  1961. * getHTML (alias)
  1962. *
  1963. * @returns {String} Return html code 返回HTML源码
  1964. */
  1965. getTextareaSavedHTML : function() {
  1966. return this.getHTML();
  1967. },
  1968. /**
  1969. * 获取预览窗口的HTML源码
  1970. * Get html from preview container
  1971. *
  1972. * @returns {editormd} 返回editormd的实例对象
  1973. */
  1974. getPreviewedHTML : function() {
  1975. if (!this.settings.watch)
  1976. {
  1977. alert("Error: settings.watch == false");
  1978. return false;
  1979. }
  1980. return this.previewContainer.html();
  1981. },
  1982. /**
  1983. * 开启实时预览
  1984. * Enable real-time watching
  1985. *
  1986. * @returns {editormd} 返回editormd的实例对象
  1987. */
  1988. watch : function(callback) {
  1989. var settings = this.settings;
  1990. if ($.inArray(settings.mode, ["gfm", "markdown"]) < 0)
  1991. {
  1992. return this;
  1993. }
  1994. this.state.watching = settings.watch = true;
  1995. this.preview.show();
  1996. if (this.toolbar)
  1997. {
  1998. var watchIcon = settings.toolbarIconsClass.watch;
  1999. var unWatchIcon = settings.toolbarIconsClass.unwatch;
  2000. var icon = this.toolbar.find(".fa[name=watch]");
  2001. icon.parent().attr("title", settings.lang.toolbar.watch);
  2002. icon.removeClass(unWatchIcon).addClass(watchIcon);
  2003. }
  2004. this.codeMirror.css("border-right", "1px solid #ddd").width(this.editor.width() / 2);
  2005. timer = 0;
  2006. this.save().resize();
  2007. if (!settings.onwatch)
  2008. {
  2009. settings.onwatch = callback || function() {};
  2010. }
  2011. $.proxy(settings.onwatch, this)();
  2012. return this;
  2013. },
  2014. /**
  2015. * 关闭实时预览
  2016. * Disable real-time watching
  2017. *
  2018. * @returns {editormd} 返回editormd的实例对象
  2019. */
  2020. unwatch : function(callback) {
  2021. var settings = this.settings;
  2022. this.state.watching = settings.watch = false;
  2023. this.preview.hide();
  2024. if (this.toolbar)
  2025. {
  2026. var watchIcon = settings.toolbarIconsClass.watch;
  2027. var unWatchIcon = settings.toolbarIconsClass.unwatch;
  2028. var icon = this.toolbar.find(".fa[name=watch]");
  2029. icon.parent().attr("title", settings.lang.toolbar.unwatch);
  2030. icon.removeClass(watchIcon).addClass(unWatchIcon);
  2031. }
  2032. this.codeMirror.css("border-right", "none").width(this.editor.width());
  2033. this.resize();
  2034. if (!settings.onunwatch)
  2035. {
  2036. settings.onunwatch = callback || function() {};
  2037. }
  2038. $.proxy(settings.onunwatch, this)();
  2039. return this;
  2040. },
  2041. /**
  2042. * 显示编辑器
  2043. * Show editor
  2044. *
  2045. * @param {Function} [callback=function()] 回调函数
  2046. * @returns {editormd} 返回editormd的实例对象
  2047. */
  2048. show : function(callback) {
  2049. callback = callback || function() {};
  2050. var _this = this;
  2051. this.editor.show(0, function() {
  2052. $.proxy(callback, _this)();
  2053. });
  2054. return this;
  2055. },
  2056. /**
  2057. * 隐藏编辑器
  2058. * Hide editor
  2059. *
  2060. * @param {Function} [callback=function()] 回调函数
  2061. * @returns {editormd} 返回editormd的实例对象
  2062. */
  2063. hide : function(callback) {
  2064. callback = callback || function() {};
  2065. var _this = this;
  2066. this.editor.hide(0, function() {
  2067. $.proxy(callback, _this)();
  2068. });
  2069. return this;
  2070. },
  2071. /**
  2072. * 隐藏编辑器部分,只预览HTML
  2073. * Enter preview html state
  2074. *
  2075. * @returns {editormd} 返回editormd的实例对象
  2076. */
  2077. previewing : function() {
  2078. var _this = this;
  2079. var editor = this.editor;
  2080. var preview = this.preview;
  2081. var toolbar = this.toolbar;
  2082. var settings = this.settings;
  2083. var codeMirror = this.codeMirror;
  2084. var previewContainer = this.previewContainer;
  2085. if ($.inArray(settings.mode, ["gfm", "markdown"]) < 0) {
  2086. return this;
  2087. }
  2088. if (settings.toolbar && toolbar) {
  2089. toolbar.toggle();
  2090. toolbar.find(".fa[name=preview]").toggleClass("active");
  2091. }
  2092. codeMirror.toggle();
  2093. var escHandle = function(event) {
  2094. if (event.shiftKey && event.keyCode === 27) {
  2095. _this.previewed();
  2096. }
  2097. };
  2098. if (codeMirror.css("display") === "none") // 为了兼容Zepto,而不使用codeMirror.is(":hidden")
  2099. {
  2100. this.state.preview = true;
  2101. if (this.state.fullscreen) {
  2102. preview.css("background", "#fff");
  2103. }
  2104. editor.find("." + this.classPrefix + "preview-close-btn").show().bind(editormd.mouseOrTouch("click", "touchend"), function(){
  2105. _this.previewed();
  2106. });
  2107. if (!settings.watch)
  2108. {
  2109. this.save();
  2110. }
  2111. else
  2112. {
  2113. previewContainer.css("padding", "");
  2114. }
  2115. previewContainer.addClass(this.classPrefix + "preview-active");
  2116. preview.show().css({
  2117. position : "",
  2118. top : 0,
  2119. width : editor.width(),
  2120. height : (settings.autoHeight && !this.state.fullscreen) ? "auto" : editor.height()
  2121. });
  2122. if (this.state.loaded)
  2123. {
  2124. $.proxy(settings.onpreviewing, this)();
  2125. }
  2126. $(window).bind("keyup", escHandle);
  2127. }
  2128. else
  2129. {
  2130. $(window).unbind("keyup", escHandle);
  2131. this.previewed();
  2132. }
  2133. },
  2134. /**
  2135. * 显示编辑器部分,退出只预览HTML
  2136. * Exit preview html state
  2137. *
  2138. * @returns {editormd} 返回editormd的实例对象
  2139. */
  2140. previewed : function() {
  2141. var editor = this.editor;
  2142. var preview = this.preview;
  2143. var toolbar = this.toolbar;
  2144. var settings = this.settings;
  2145. var previewContainer = this.previewContainer;
  2146. var previewCloseBtn = editor.find("." + this.classPrefix + "preview-close-btn");
  2147. this.state.preview = false;
  2148. this.codeMirror.show();
  2149. if (settings.toolbar) {
  2150. toolbar.show();
  2151. }
  2152. preview[(settings.watch) ? "show" : "hide"]();
  2153. previewCloseBtn.hide().unbind(editormd.mouseOrTouch("click", "touchend"));
  2154. previewContainer.removeClass(this.classPrefix + "preview-active");
  2155. if (settings.watch)
  2156. {
  2157. previewContainer.css("padding", "20px");
  2158. }
  2159. preview.css({
  2160. background : null,
  2161. position : "absolute",
  2162. width : editor.width() / 2,
  2163. height : (settings.autoHeight && !this.state.fullscreen) ? "auto" : editor.height() - toolbar.height(),
  2164. top : (settings.toolbar) ? toolbar.height() : 0
  2165. });
  2166. if (this.state.loaded)
  2167. {
  2168. $.proxy(settings.onpreviewed, this)();
  2169. }
  2170. return this;
  2171. },
  2172. /**
  2173. * 编辑器全屏显示
  2174. * Fullscreen show
  2175. *
  2176. * @returns {editormd} 返回editormd的实例对象
  2177. */
  2178. fullscreen : function() {
  2179. var _this = this;
  2180. var state = this.state;
  2181. var editor = this.editor;
  2182. var preview = this.preview;
  2183. var toolbar = this.toolbar;
  2184. var settings = this.settings;
  2185. var fullscreenClass = this.classPrefix + "fullscreen";
  2186. if (toolbar) {
  2187. toolbar.find(".fa[name=fullscreen]").parent().toggleClass("active");
  2188. }
  2189. var escHandle = function(event) {
  2190. if (!event.shiftKey && event.keyCode === 27)
  2191. {
  2192. if (state.fullscreen)
  2193. {
  2194. _this.fullscreenExit();
  2195. }
  2196. }
  2197. };
  2198. if (!editor.hasClass(fullscreenClass))
  2199. {
  2200. state.fullscreen = true;
  2201. $("html,body").css("overflow", "hidden");
  2202. editor.css({
  2203. width : $(window).width(),
  2204. height : $(window).height()
  2205. }).addClass(fullscreenClass);
  2206. this.resize();
  2207. $.proxy(settings.onfullscreen, this)();
  2208. $(window).bind("keyup", escHandle);
  2209. }
  2210. else
  2211. {
  2212. $(window).unbind("keyup", escHandle);
  2213. this.fullscreenExit();
  2214. }
  2215. return this;
  2216. },
  2217. /**
  2218. * 编辑器退出全屏显示
  2219. * Exit fullscreen state
  2220. *
  2221. * @returns {editormd} 返回editormd的实例对象
  2222. */
  2223. fullscreenExit : function() {
  2224. var editor = this.editor;
  2225. var settings = this.settings;
  2226. var toolbar = this.toolbar;
  2227. var fullscreenClass = this.classPrefix + "fullscreen";
  2228. this.state.fullscreen = false;
  2229. if (toolbar) {
  2230. toolbar.find(".fa[name=fullscreen]").parent().removeClass("active");
  2231. }
  2232. $("html,body").css("overflow", "");
  2233. editor.css({
  2234. width : editor.data("oldWidth"),
  2235. height : editor.data("oldHeight")
  2236. }).removeClass(fullscreenClass);
  2237. this.resize();
  2238. $.proxy(settings.onfullscreenExit, this)();
  2239. return this;
  2240. },
  2241. /**
  2242. * 加载并执行插件
  2243. * Load and execute the plugin
  2244. *
  2245. * @param {String} name plugin name / function name
  2246. * @param {String} path plugin load path
  2247. * @returns {editormd} 返回editormd的实例对象
  2248. */
  2249. executePlugin : function(name, path) {
  2250. var _this = this;
  2251. var cm = this.cm;
  2252. var settings = this.settings;
  2253. path = settings.pluginPath + path;
  2254. if (typeof define === "function")
  2255. {
  2256. if (typeof this[name] === "undefined")
  2257. {
  2258. alert("Error: " + name + " plugin is not found, you are not load this plugin.");
  2259. return this;
  2260. }
  2261. this[name](cm);
  2262. return this;
  2263. }
  2264. if ($.inArray(path, editormd.loadFiles.plugin) < 0)
  2265. {
  2266. editormd.loadPlugin(path, function() {
  2267. editormd.loadPlugins[name] = _this[name];
  2268. _this[name](cm);
  2269. });
  2270. }
  2271. else
  2272. {
  2273. $.proxy(editormd.loadPlugins[name], this)(cm);
  2274. }
  2275. return this;
  2276. },
  2277. /**
  2278. * 搜索替换
  2279. * Search & replace
  2280. *
  2281. * @param {String} command CodeMirror serach commands, "find, fintNext, fintPrev, clearSearch, replace, replaceAll"
  2282. * @returns {editormd} return this
  2283. */
  2284. search : function(command) {
  2285. var settings = this.settings;
  2286. if (!settings.searchReplace)
  2287. {
  2288. alert("Error: settings.searchReplace == false");
  2289. return this;
  2290. }
  2291. if (!settings.readOnly)
  2292. {
  2293. this.cm.execCommand(command || "find");
  2294. }
  2295. return this;
  2296. },
  2297. searchReplace : function() {
  2298. this.search("replace");
  2299. return this;
  2300. },
  2301. searchReplaceAll : function() {
  2302. this.search("replaceAll");
  2303. return this;
  2304. }
  2305. };
  2306. editormd.fn.init.prototype = editormd.fn;
  2307. /**
  2308. * 锁屏
  2309. * lock screen when dialog opening
  2310. *
  2311. * @returns {void}
  2312. */
  2313. editormd.dialogLockScreen = function() {
  2314. var settings = this.settings || {dialogLockScreen : true};
  2315. if (settings.dialogLockScreen)
  2316. {
  2317. $("html,body").css("overflow", "hidden");
  2318. this.resize();
  2319. }
  2320. };
  2321. /**
  2322. * 显示透明背景层
  2323. * Display mask layer when dialog opening
  2324. *
  2325. * @param {Object} dialog dialog jQuery object
  2326. * @returns {void}
  2327. */
  2328. editormd.dialogShowMask = function(dialog) {
  2329. var editor = this.editor;
  2330. var settings = this.settings || {dialogShowMask : true};
  2331. dialog.css({
  2332. top : ($(window).height() - dialog.height()) / 2 + "px",
  2333. left : ($(window).width() - dialog.width()) / 2 + "px"
  2334. });
  2335. if (settings.dialogShowMask) {
  2336. editor.children("." + this.classPrefix + "mask").css("z-index", parseInt(dialog.css("z-index")) - 1).show();
  2337. }
  2338. };
  2339. editormd.toolbarHandlers = {
  2340. undo : function() {
  2341. this.cm.undo();
  2342. },
  2343. redo : function() {
  2344. this.cm.redo();
  2345. },
  2346. bold : function() {
  2347. var cm = this.cm;
  2348. var cursor = cm.getCursor();
  2349. var selection = cm.getSelection();
  2350. cm.replaceSelection("**" + selection + "**");
  2351. if(selection === "") {
  2352. cm.setCursor(cursor.line, cursor.ch + 2);
  2353. }
  2354. },
  2355. del : function() {
  2356. var cm = this.cm;
  2357. var cursor = cm.getCursor();
  2358. var selection = cm.getSelection();
  2359. cm.replaceSelection("~~" + selection + "~~");
  2360. if(selection === "") {
  2361. cm.setCursor(cursor.line, cursor.ch + 2);
  2362. }
  2363. },
  2364. italic : function() {
  2365. var cm = this.cm;
  2366. var cursor = cm.getCursor();
  2367. var selection = cm.getSelection();
  2368. cm.replaceSelection("*" + selection + "*");
  2369. if(selection === "") {
  2370. cm.setCursor(cursor.line, cursor.ch + 1);
  2371. }
  2372. },
  2373. quote : function() {
  2374. var cm = this.cm;
  2375. var cursor = cm.getCursor();
  2376. var selection = cm.getSelection();
  2377. if (cursor.ch !== 0)
  2378. {
  2379. cm.setCursor(cursor.line, 0);
  2380. cm.replaceSelection("> " + selection);
  2381. cm.setCursor(cursor.line, cursor.ch + 2);
  2382. }
  2383. else
  2384. {
  2385. cm.replaceSelection("> " + selection);
  2386. }
  2387. //cm.replaceSelection("> " + selection);
  2388. //cm.setCursor(cursor.line, (selection === "") ? cursor.ch + 2 : cursor.ch + selection.length + 2);
  2389. },
  2390. ucfirst : function() {
  2391. var cm = this.cm;
  2392. var selection = cm.getSelection();
  2393. var selections = cm.listSelections();
  2394. cm.replaceSelection(editormd.firstUpperCase(selection));
  2395. cm.setSelections(selections);
  2396. },
  2397. ucwords : function() {
  2398. var cm = this.cm;
  2399. var selection = cm.getSelection();
  2400. var selections = cm.listSelections();
  2401. cm.replaceSelection(editormd.wordsFirstUpperCase(selection));
  2402. cm.setSelections(selections);
  2403. },
  2404. uppercase : function() {
  2405. var cm = this.cm;
  2406. var selection = cm.getSelection();
  2407. var selections = cm.listSelections();
  2408. cm.replaceSelection(selection.toUpperCase());
  2409. cm.setSelections(selections);
  2410. },
  2411. lowercase : function() {
  2412. var cm = this.cm;
  2413. var cursor = cm.getCursor();
  2414. var selection = cm.getSelection();
  2415. var selections = cm.listSelections();
  2416. cm.replaceSelection(selection.toLowerCase());
  2417. cm.setSelections(selections);
  2418. },
  2419. h1 : function() {
  2420. var cm = this.cm;
  2421. var cursor = cm.getCursor();
  2422. var selection = cm.getSelection();
  2423. if (cursor.ch !== 0)
  2424. {
  2425. cm.setCursor(cursor.line, 0);
  2426. cm.replaceSelection("# " + selection);
  2427. cm.setCursor(cursor.line, cursor.ch + 2);
  2428. }
  2429. else
  2430. {
  2431. cm.replaceSelection("# " + selection);
  2432. }
  2433. },
  2434. h2 : function() {
  2435. var cm = this.cm;
  2436. var cursor = cm.getCursor();
  2437. var selection = cm.getSelection();
  2438. if (cursor.ch !== 0)
  2439. {
  2440. cm.setCursor(cursor.line, 0);
  2441. cm.replaceSelection("## " + selection);
  2442. cm.setCursor(cursor.line, cursor.ch + 3);
  2443. }
  2444. else
  2445. {
  2446. cm.replaceSelection("## " + selection);
  2447. }
  2448. },
  2449. h3 : function() {
  2450. var cm = this.cm;
  2451. var cursor = cm.getCursor();
  2452. var selection = cm.getSelection();
  2453. if (cursor.ch !== 0)
  2454. {
  2455. cm.setCursor(cursor.line, 0);
  2456. cm.replaceSelection("### " + selection);
  2457. cm.setCursor(cursor.line, cursor.ch + 4);
  2458. }
  2459. else
  2460. {
  2461. cm.replaceSelection("### " + selection);
  2462. }
  2463. },
  2464. h4 : function() {
  2465. var cm = this.cm;
  2466. var cursor = cm.getCursor();
  2467. var selection = cm.getSelection();
  2468. if (cursor.ch !== 0)
  2469. {
  2470. cm.setCursor(cursor.line, 0);
  2471. cm.replaceSelection("#### " + selection);
  2472. cm.setCursor(cursor.line, cursor.ch + 5);
  2473. }
  2474. else
  2475. {
  2476. cm.replaceSelection("#### " + selection);
  2477. }
  2478. },
  2479. h5 : function() {
  2480. var cm = this.cm;
  2481. var cursor = cm.getCursor();
  2482. var selection = cm.getSelection();
  2483. if (cursor.ch !== 0)
  2484. {
  2485. cm.setCursor(cursor.line, 0);
  2486. cm.replaceSelection("##### " + selection);
  2487. cm.setCursor(cursor.line, cursor.ch + 6);
  2488. }
  2489. else
  2490. {
  2491. cm.replaceSelection("##### " + selection);
  2492. }
  2493. },
  2494. h6 : function() {
  2495. var cm = this.cm;
  2496. var cursor = cm.getCursor();
  2497. var selection = cm.getSelection();
  2498. if (cursor.ch !== 0)
  2499. {
  2500. cm.setCursor(cursor.line, 0);
  2501. cm.replaceSelection("###### " + selection);
  2502. cm.setCursor(cursor.line, cursor.ch + 7);
  2503. }
  2504. else
  2505. {
  2506. cm.replaceSelection("###### " + selection);
  2507. }
  2508. },
  2509. "list-ul" : function() {
  2510. var cm = this.cm;
  2511. var cursor = cm.getCursor();
  2512. var selection = cm.getSelection();
  2513. if (selection === "")
  2514. {
  2515. cm.replaceSelection("- " + selection);
  2516. }
  2517. else
  2518. {
  2519. var selectionText = selection.split("\n");
  2520. for (var i = 0, len = selectionText.length; i < len; i++)
  2521. {
  2522. selectionText[i] = (selectionText[i] === "") ? "" : "- " + selectionText[i];
  2523. }
  2524. cm.replaceSelection(selectionText.join("\n"));
  2525. }
  2526. },
  2527. "list-ol" : function() {
  2528. var cm = this.cm;
  2529. var cursor = cm.getCursor();
  2530. var selection = cm.getSelection();
  2531. if(selection === "")
  2532. {
  2533. cm.replaceSelection("1. " + selection);
  2534. }
  2535. else
  2536. {
  2537. var selectionText = selection.split("\n");
  2538. for (var i = 0, len = selectionText.length; i < len; i++)
  2539. {
  2540. selectionText[i] = (selectionText[i] === "") ? "" : (i+1) + ". " + selectionText[i];
  2541. }
  2542. cm.replaceSelection(selectionText.join("\n"));
  2543. }
  2544. },
  2545. hr : function() {
  2546. var cm = this.cm;
  2547. var cursor = cm.getCursor();
  2548. var selection = cm.getSelection();
  2549. cm.replaceSelection(((cursor.ch !== 0) ? "\n\n" : "\n") + "------------\n\n");
  2550. },
  2551. tex : function() {
  2552. if (!this.settings.tex)
  2553. {
  2554. alert("settings.tex === false");
  2555. return this;
  2556. }
  2557. var cm = this.cm;
  2558. var cursor = cm.getCursor();
  2559. var selection = cm.getSelection();
  2560. cm.replaceSelection("$$" + selection + "$$");
  2561. if(selection === "") {
  2562. cm.setCursor(cursor.line, cursor.ch + 2);
  2563. }
  2564. },
  2565. link : function() {
  2566. this.executePlugin("linkDialog", "link-dialog/link-dialog");
  2567. },
  2568. "reference-link" : function() {
  2569. this.executePlugin("referenceLinkDialog", "reference-link-dialog/reference-link-dialog");
  2570. },
  2571. pagebreak : function() {
  2572. if (!this.settings.pageBreak)
  2573. {
  2574. alert("settings.pageBreak === false");
  2575. return this;
  2576. }
  2577. var cm = this.cm;
  2578. var selection = cm.getSelection();
  2579. cm.replaceSelection("\r\n[========]\r\n");
  2580. },
  2581. image : function() {
  2582. this.executePlugin("imageDialog", "image-dialog/image-dialog");
  2583. },
  2584. code : function() {
  2585. var cm = this.cm;
  2586. var cursor = cm.getCursor();
  2587. var selection = cm.getSelection();
  2588. cm.replaceSelection("`" + selection + "`");
  2589. if (selection === "") {
  2590. cm.setCursor(cursor.line, cursor.ch + 1);
  2591. }
  2592. },
  2593. "code-block" : function() {
  2594. this.executePlugin("codeBlockDialog", "code-block-dialog/code-block-dialog");
  2595. },
  2596. "preformatted-text" : function() {
  2597. this.executePlugin("preformattedTextDialog", "preformatted-text-dialog/preformatted-text-dialog");
  2598. },
  2599. table : function() {
  2600. this.executePlugin("tableDialog", "table-dialog/table-dialog");
  2601. },
  2602. datetime : function() {
  2603. var cm = this.cm;
  2604. var selection = cm.getSelection();
  2605. var date = new Date();
  2606. var langName = this.settings.lang.name;
  2607. var datefmt = editormd.dateFormat() + " " + editormd.dateFormat((langName === "zh-cn" || langName === "zh-tw") ? "cn-week-day" : "week-day");
  2608. cm.replaceSelection(datefmt);
  2609. },
  2610. emoji : function() {
  2611. this.executePlugin("emojiDialog", "emoji-dialog/emoji-dialog");
  2612. },
  2613. "html-entities" : function() {
  2614. this.executePlugin("htmlEntitiesDialog", "html-entities-dialog/html-entities-dialog");
  2615. },
  2616. "goto-line" : function() {
  2617. this.executePlugin("gotoLineDialog", "goto-line-dialog/goto-line-dialog");
  2618. },
  2619. watch : function() {
  2620. this[this.settings.watch ? "unwatch" : "watch"]();
  2621. },
  2622. preview : function() {
  2623. this.previewing();
  2624. },
  2625. fullscreen : function() {
  2626. this.fullscreen();
  2627. },
  2628. clear : function() {
  2629. this.clear();
  2630. },
  2631. search : function() {
  2632. this.search();
  2633. },
  2634. help : function() {
  2635. this.executePlugin("helpDialog", "help-dialog/help-dialog");
  2636. },
  2637. info : function() {
  2638. this.showInfoDialog();
  2639. }
  2640. };
  2641. editormd.keyMaps = {
  2642. "Ctrl-1" : "h1",
  2643. "Ctrl-2" : "h2",
  2644. "Ctrl-3" : "h3",
  2645. "Ctrl-4" : "h4",
  2646. "Ctrl-5" : "h5",
  2647. "Ctrl-6" : "h6",
  2648. "Ctrl-B" : "bold", // if this is string == editormd.toolbarHandlers.xxxx
  2649. "Ctrl-D" : "datetime",
  2650. "Ctrl-E" : function() { // emoji
  2651. var cm = this.cm;
  2652. var cursor = cm.getCursor();
  2653. var selection = cm.getSelection();
  2654. if (!this.settings.emoji)
  2655. {
  2656. alert("Error: settings.emoji == false");
  2657. return ;
  2658. }
  2659. cm.replaceSelection(":" + selection + ":");
  2660. if (selection === "") {
  2661. cm.setCursor(cursor.line, cursor.ch + 1);
  2662. }
  2663. },
  2664. "Ctrl-Alt-G" : "goto-line",
  2665. "Ctrl-H" : "hr",
  2666. "Ctrl-I" : "italic",
  2667. "Ctrl-K" : "code",
  2668. "Ctrl-L" : function() {
  2669. var cm = this.cm;
  2670. var cursor = cm.getCursor();
  2671. var selection = cm.getSelection();
  2672. var title = (selection === "") ? "" : " \""+selection+"\"";
  2673. cm.replaceSelection("[" + selection + "]("+title+")");
  2674. if (selection === "") {
  2675. cm.setCursor(cursor.line, cursor.ch + 1);
  2676. }
  2677. },
  2678. "Ctrl-U" : "list-ul",
  2679. "Shift-Ctrl-A" : function() {
  2680. var cm = this.cm;
  2681. var cursor = cm.getCursor();
  2682. var selection = cm.getSelection();
  2683. if (!this.settings.atLink)
  2684. {
  2685. alert("Error: settings.atLink == false");
  2686. return ;
  2687. }
  2688. cm.replaceSelection("@" + selection);
  2689. if (selection === "") {
  2690. cm.setCursor(cursor.line, cursor.ch + 1);
  2691. }
  2692. },
  2693. "Shift-Ctrl-C" : "code",
  2694. "Shift-Ctrl-Q" : "quote",
  2695. "Shift-Ctrl-S" : "del",
  2696. "Shift-Ctrl-K" : "tex", // KaTeX
  2697. "Shift-Alt-C" : function() {
  2698. var cm = this.cm;
  2699. var cursor = cm.getCursor();
  2700. var selection = cm.getSelection();
  2701. cm.replaceSelection(["```", selection, "```"].join("\n"));
  2702. if (selection === "") {
  2703. cm.setCursor(cursor.line, cursor.ch + 3);
  2704. }
  2705. },
  2706. "Shift-Ctrl-Alt-C" : "code-block",
  2707. "Shift-Ctrl-H" : "html-entities",
  2708. "Shift-Alt-H" : "help",
  2709. "Shift-Ctrl-E" : "emoji",
  2710. "Shift-Ctrl-U" : "uppercase",
  2711. "Shift-Alt-U" : "ucwords",
  2712. "Shift-Ctrl-Alt-U" : "ucfirst",
  2713. "Shift-Alt-L" : "lowercase",
  2714. "Shift-Ctrl-I" : function() {
  2715. var cm = this.cm;
  2716. var cursor = cm.getCursor();
  2717. var selection = cm.getSelection();
  2718. var title = (selection === "") ? "" : " \""+selection+"\"";
  2719. cm.replaceSelection("![" + selection + "]("+title+")");
  2720. if (selection === "") {
  2721. cm.setCursor(cursor.line, cursor.ch + 4);
  2722. }
  2723. },
  2724. "Shift-Ctrl-Alt-I" : "image",
  2725. "Shift-Ctrl-L" : "link",
  2726. "Shift-Ctrl-O" : "list-ol",
  2727. "Shift-Ctrl-P" : "preformatted-text",
  2728. "Shift-Ctrl-T" : "table",
  2729. "Shift-Alt-P" : "pagebreak",
  2730. "F9" : "watch",
  2731. "F10" : "preview",
  2732. "F11" : "fullscreen",
  2733. };
  2734. /**
  2735. * 清除字符串两边的空格
  2736. * Clear the space of strings both sides.
  2737. *
  2738. * @param {String} str string
  2739. * @returns {String} trimed string
  2740. */
  2741. var trim = function(str) {
  2742. return (!String.prototype.trim) ? str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "") : str.trim();
  2743. };
  2744. editormd.trim = trim;
  2745. /**
  2746. * 所有单词首字母大写
  2747. * Words first to uppercase
  2748. *
  2749. * @param {String} str string
  2750. * @returns {String} string
  2751. */
  2752. var ucwords = function (str) {
  2753. return str.toLowerCase().replace(/\b(\w)|\s(\w)/g, function($1) {
  2754. return $1.toUpperCase();
  2755. });
  2756. };
  2757. editormd.ucwords = editormd.wordsFirstUpperCase = ucwords;
  2758. /**
  2759. * 字符串首字母大写
  2760. * Only string first char to uppercase
  2761. *
  2762. * @param {String} str string
  2763. * @returns {String} string
  2764. */
  2765. var firstUpperCase = function(str) {
  2766. return str.toLowerCase().replace(/\b(\w)/, function($1){
  2767. return $1.toUpperCase();
  2768. });
  2769. };
  2770. var ucfirst = firstUpperCase;
  2771. editormd.firstUpperCase = editormd.ucfirst = firstUpperCase;
  2772. editormd.urls = {
  2773. atLinkBase : "https://github.com/"
  2774. };
  2775. editormd.regexs = {
  2776. atLink : /@(\w+)/g,
  2777. email : /(\w+)@(\w+)\.(\w+)\.?(\w+)?/g,
  2778. emailLink : /(mailto:)?([\w\.\_]+)@(\w+)\.(\w+)\.?(\w+)?/g,
  2779. emoji : /:([\w\+-]+):/g,
  2780. emojiDatetime : /(\d{2}:\d{2}:\d{2})/g,
  2781. twemoji : /:(tw-([\w]+)-?(\w+)?):/g,
  2782. fontAwesome : /:(fa-([\w]+)(-(\w+)){0,}):/g,
  2783. editormdLogo : /:(editormd-logo-?(\w+)?):/g,
  2784. pageBreak : /^\[[=]{8,}\]$/
  2785. };
  2786. // Emoji graphics files url path
  2787. editormd.emoji = {
  2788. path : "http://www.emoji-cheat-sheet.com/graphics/emojis/",
  2789. ext : ".png"
  2790. };
  2791. // Twitter Emoji (Twemoji) graphics files url path
  2792. editormd.twemoji = {
  2793. path : "http://twemoji.maxcdn.com/36x36/",
  2794. ext : ".png"
  2795. };
  2796. /**
  2797. * 自定义marked的解析器
  2798. * Custom Marked renderer rules
  2799. *
  2800. * @param {Array} markdownToC 传入用于接收TOC的数组
  2801. * @returns {Renderer} markedRenderer 返回marked的Renderer自定义对象
  2802. */
  2803. editormd.markedRenderer = function(markdownToC, options) {
  2804. var defaults = {
  2805. toc : true, // Table of contents
  2806. tocm : false,
  2807. tocStartLevel : 1, // Said from H1 to create ToC
  2808. pageBreak : true,
  2809. atLink : true, // for @link
  2810. emailLink : true, // for mail address auto link
  2811. taskList : false, // Enable Github Flavored Markdown task lists
  2812. emoji : false, // :emoji: , Support Twemoji, fontAwesome, Editor.md logo emojis.
  2813. tex : false, // TeX(LaTeX), based on KaTeX
  2814. flowChart : false, // flowChart.js only support IE9+
  2815. sequenceDiagram : false, // sequenceDiagram.js only support IE9+
  2816. };
  2817. var settings = $.extend(defaults, options || {});
  2818. var marked = editormd.$marked;
  2819. var markedRenderer = new marked.Renderer();
  2820. markdownToC = markdownToC || [];
  2821. var regexs = editormd.regexs;
  2822. var atLinkReg = regexs.atLink;
  2823. var emojiReg = regexs.emoji;
  2824. var emailReg = regexs.email;
  2825. var emailLinkReg = regexs.emailLink;
  2826. var twemojiReg = regexs.twemoji;
  2827. var faIconReg = regexs.fontAwesome;
  2828. var editormdLogoReg = regexs.editormdLogo;
  2829. var pageBreakReg = regexs.pageBreak;
  2830. markedRenderer.emoji = function(text) {
  2831. text = text.replace(editormd.regexs.emojiDatetime, function($1) {
  2832. return $1.replace(/:/g, "&#58;");
  2833. });
  2834. var matchs = text.match(emojiReg);
  2835. if (!matchs || !settings.emoji) {
  2836. return text;
  2837. }
  2838. for (var i = 0, len = matchs.length; i < len; i++)
  2839. {
  2840. if (matchs[i] === ":+1:") {
  2841. matchs[i] = ":\\+1:";
  2842. }
  2843. text = text.replace(new RegExp(matchs[i]), function($1, $2){
  2844. var faMatchs = $1.match(faIconReg);
  2845. var name = $1.replace(/:/g, "");
  2846. if (faMatchs)
  2847. {
  2848. for (var fa = 0, len1 = faMatchs.length; fa < len1; fa++)
  2849. {
  2850. var faName = faMatchs[fa].replace(/:/g, "");
  2851. return "<i class=\"fa " + faName + " fa-emoji\" title=\"" + faName.replace("fa-", "") + "\"></i>";
  2852. }
  2853. }
  2854. else
  2855. {
  2856. var emdlogoMathcs = $1.match(editormdLogoReg);
  2857. var twemojiMatchs = $1.match(twemojiReg);
  2858. if (emdlogoMathcs)
  2859. {
  2860. for (var x = 0, len2 = emdlogoMathcs.length; x < len2; x++)
  2861. {
  2862. var logoName = emdlogoMathcs[x].replace(/:/g, "");
  2863. return "<i class=\"" + logoName + "\" title=\"Editor.md logo (" + logoName + ")\"></i>";
  2864. }
  2865. }
  2866. else if (twemojiMatchs)
  2867. {
  2868. for (var t = 0, len3 = twemojiMatchs.length; t < len3; t++)
  2869. {
  2870. var twe = twemojiMatchs[t].replace(/:/g, "").replace("tw-", "");
  2871. return "<img src=\"" + editormd.twemoji.path + twe + editormd.twemoji.ext + "\" title=\"twemoji-" + twe + "\" alt=\"twemoji-" + twe + "\" class=\"emoji twemoji\" />";
  2872. }
  2873. }
  2874. else
  2875. {
  2876. var src = (name === "+1") ? "plus1" : name;
  2877. src = (src === "black_large_square") ? "black_square" : src;
  2878. src = (src === "moon") ? "waxing_gibbous_moon" : src;
  2879. return "<img src=\"" + editormd.emoji.path + src + editormd.emoji.ext + "\" class=\"emoji\" title=\"&#58;" + name + "&#58;\" alt=\"&#58;" + name + "&#58;\" />";
  2880. }
  2881. }
  2882. });
  2883. }
  2884. return text;
  2885. };
  2886. markedRenderer.atLink = function(text) {
  2887. if (atLinkReg.test(text))
  2888. {
  2889. if (settings.atLink)
  2890. {
  2891. text = text.replace(emailReg, function($1, $2, $3, $4) {
  2892. return $1.replace(/@/g, "_#_&#64;_#_");
  2893. });
  2894. text = text.replace(atLinkReg, function($1, $2) {
  2895. return "<a href=\"" + editormd.urls.atLinkBase + "" + $2 + "\" title=\"&#64;" + $2 + "\" class=\"at-link\">" + $1 + "</a>";
  2896. }).replace(/_#_&#64;_#_/g, "@");
  2897. }
  2898. if (settings.emailLink)
  2899. {
  2900. text = text.replace(emailLinkReg, function($1, $2, $3, $4, $5) {
  2901. return (!$2 && $.inArray($5, "jpg|jpeg|png|gif|webp|ico|icon|pdf".split("|")) < 0) ? "<a href=\"mailto:" + $1 + "\">"+$1+"</a>" : $1;
  2902. });
  2903. }
  2904. return text;
  2905. }
  2906. return text;
  2907. };
  2908. markedRenderer.link = function (href, title, text) {
  2909. if (this.options.sanitize) {
  2910. try {
  2911. var prot = decodeURIComponent(unescape(href)).replace(/[^\w:]/g,"").toLowerCase();
  2912. } catch(e) {
  2913. return "";
  2914. }
  2915. if (prot.indexOf("javascript:") === 0) {
  2916. return "";
  2917. }
  2918. }
  2919. var out = "<a href=\"" + href + "\"";
  2920. if (atLinkReg.test(title) || atLinkReg.test(text))
  2921. {
  2922. if (title)
  2923. {
  2924. out += " title=\"" + title.replace(/@/g, "&#64;");
  2925. }
  2926. return out + "\">" + text.replace(/@/g, "&#64;") + "</a>";
  2927. }
  2928. if (title) {
  2929. out += " title=\"" + title + "\"";
  2930. }
  2931. out += ">" + text + "</a>";
  2932. return out;
  2933. };
  2934. markedRenderer.heading = function(text, level, raw) {
  2935. var linkText = text;
  2936. var hasLinkReg = /\s*\<a\s*href\=\"(.*)\"\s*([^\>]*)\>(.*)\<\/a\>\s*/;
  2937. var getLinkTextReg = /\s*\<a\s*([^\>]+)\>([^\>]*)\<\/a\>\s*/g;
  2938. if (hasLinkReg.test(text))
  2939. {
  2940. var tempText = [];
  2941. text = text.split(/\<a\s*([^\>]+)\>([^\>]*)\<\/a\>/);
  2942. for (var i = 0, len = text.length; i < len; i++)
  2943. {
  2944. tempText.push(text[i].replace(/\s*href\=\"(.*)\"\s*/g, ""));
  2945. }
  2946. text = tempText.join(" ");
  2947. }
  2948. text = trim(text);
  2949. var escapedText = text.toLowerCase().replace(/[^\w]+/g, "-");
  2950. var toc = {
  2951. text : text,
  2952. level : level,
  2953. slug : escapedText
  2954. };
  2955. var isChinese = /^[\u4e00-\u9fa5]+$/.test(text);
  2956. var id = (isChinese) ? escape(text).replace(/\%/g, "") : text.toLowerCase().replace(/[^\w]+/g, "-");
  2957. markdownToC.push(toc);
  2958. var headingHTML = "<h" + level + " id=\"h"+ level + "-" + this.options.headerPrefix + id +"\">";
  2959. headingHTML += "<a name=\"" + text + "\" class=\"reference-link\"></a>";
  2960. headingHTML += "<span class=\"header-link octicon octicon-link\"></span>";
  2961. headingHTML += (hasLinkReg) ? this.atLink(this.emoji(linkText)) : this.atLink(this.emoji(text));
  2962. headingHTML += "</h" + level + ">";
  2963. return headingHTML;
  2964. };
  2965. markedRenderer.pageBreak = function(text) {
  2966. if (pageBreakReg.test(text) && settings.pageBreak)
  2967. {
  2968. text = "<hr style=\"page-break-after:always;\" class=\"page-break editormd-page-break\" />";
  2969. }
  2970. return text;
  2971. };
  2972. markedRenderer.paragraph = function(text) {
  2973. var isTeXInline = /\$\$(.*)\$\$/g.test(text);
  2974. var isTeXLine = /^\$\$(.*)\$\$$/.test(text);
  2975. var isTeXAddClass = (isTeXLine) ? " class=\"" + editormd.classNames.tex + "\"" : "";
  2976. var isToC = (settings.tocm) ? /^(\[TOC\]|\[TOCM\])$/.test(text) : /^\[TOC\]$/.test(text);
  2977. var isToCMenu = /^\[TOCM\]$/.test(text);
  2978. if (!isTeXLine && isTeXInline)
  2979. {
  2980. text = text.replace(/(\$\$([^\$]*)\$\$)+/g, function($1, $2) {
  2981. return "<span class=\"" + editormd.classNames.tex + "\">" + $2.replace(/\$/g, "") + "</span>";
  2982. });
  2983. }
  2984. else
  2985. {
  2986. text = (isTeXLine) ? text.replace(/\$/g, "") : text;
  2987. }
  2988. var tocHTML = "<div class=\"markdown-toc editormd-markdown-toc\">" + text + "</div>";
  2989. return (isToC) ? ( (isToCMenu) ? "<div class=\"editormd-toc-menu\">" + tocHTML + "</div><br/>" : tocHTML )
  2990. : ( (pageBreakReg.test(text)) ? this.pageBreak(text) : "<p" + isTeXAddClass + ">" + this.atLink(this.emoji(text)) + "</p>\n" );
  2991. };
  2992. markedRenderer.code = function (code, lang, escaped) {
  2993. if (lang === "seq" || lang === "sequence")
  2994. {
  2995. return "<div class=\"sequence-diagram\">" + code + "</div>";
  2996. } else if (lang === "gantt"){
  2997. return "<div class=\"mermain-gantt\""> + code + "</div>"
  2998. }
  2999. else if ( lang === "flow")
  3000. {
  3001. return "<div class=\"flowchart\">" + code + "</div>";
  3002. }
  3003. else if ( lang === "math" || lang === "latex" || lang === "katex")
  3004. {
  3005. return "<p class=\"" + editormd.classNames.tex + "\">" + code + "</p>";
  3006. }
  3007. else
  3008. {
  3009. return marked.Renderer.prototype.code.apply(this, arguments);
  3010. }
  3011. };
  3012. markedRenderer.tablecell = function(content, flags) {
  3013. var type = (flags.header) ? "th" : "td";
  3014. var tag = (flags.align) ? "<" + type +" style=\"text-align:" + flags.align + "\">" : "<" + type + ">";
  3015. return tag + this.atLink(this.emoji(content)) + "</" + type + ">\n";
  3016. };
  3017. markedRenderer.listitem = function(text) {
  3018. if (settings.taskList && /^\s*\[[x\s]\]\s*/.test(text))
  3019. {
  3020. text = text.replace(/^\s*\[\s\]\s*/, "<input type=\"checkbox\" class=\"task-list-item-checkbox\" /> ")
  3021. .replace(/^\s*\[x\]\s*/, "<input type=\"checkbox\" class=\"task-list-item-checkbox\" checked disabled /> ");
  3022. return "<li style=\"list-style: none;\">" + this.atLink(this.emoji(text)) + "</li>";
  3023. }
  3024. else
  3025. {
  3026. return "<li>" + this.atLink(this.emoji(text)) + "</li>";
  3027. }
  3028. };
  3029. return markedRenderer;
  3030. };
  3031. /**
  3032. *
  3033. * 生成TOC(Table of Contents)
  3034. * Creating ToC (Table of Contents)
  3035. *
  3036. * @param {Array} toc 从marked获取的TOC数组列表
  3037. * @param {Element} container 插入TOC的容器元素
  3038. * @param {Integer} startLevel Hx 起始层级
  3039. * @returns {Object} tocContainer 返回ToC列表容器层的jQuery对象元素
  3040. */
  3041. editormd.markdownToCRenderer = function(toc, container, tocDropdown, startLevel) {
  3042. var html = "";
  3043. var lastLevel = 0;
  3044. var classPrefix = this.classPrefix;
  3045. startLevel = startLevel || 1;
  3046. for (var i = 0, len = toc.length; i < len; i++)
  3047. {
  3048. var text = toc[i].text;
  3049. var level = toc[i].level;
  3050. if (level < startLevel) {
  3051. continue;
  3052. }
  3053. if (level > lastLevel)
  3054. {
  3055. html += "";
  3056. }
  3057. else if (level < lastLevel)
  3058. {
  3059. html += (new Array(lastLevel - level + 2)).join("</ul></li>");
  3060. }
  3061. else
  3062. {
  3063. html += "</ul></li>";
  3064. }
  3065. html += "<li><a class=\"toc-level-" + level + "\" href=\"#" + text + "\" level=\"" + level + "\">" + text + "</a><ul>";
  3066. lastLevel = level;
  3067. }
  3068. var tocContainer = container.find(".markdown-toc");
  3069. if ((tocContainer.length < 1 && container.attr("previewContainer") === "false"))
  3070. {
  3071. var tocHTML = "<div class=\"markdown-toc " + classPrefix + "markdown-toc\"></div>";
  3072. tocHTML = (tocDropdown) ? "<div class=\"" + classPrefix + "toc-menu\">" + tocHTML + "</div>" : tocHTML;
  3073. container.html(tocHTML);
  3074. tocContainer = container.find(".markdown-toc");
  3075. }
  3076. if (tocDropdown)
  3077. {
  3078. tocContainer.wrap("<div class=\"" + classPrefix + "toc-menu\"></div><br/>");
  3079. }
  3080. tocContainer.html("<ul class=\"markdown-toc-list\"></ul>").children(".markdown-toc-list").html(html.replace(/\r?\n?\<ul\>\<\/ul\>/g, ""));
  3081. return tocContainer;
  3082. };
  3083. /**
  3084. *
  3085. * 生成TOC下拉菜单
  3086. * Creating ToC dropdown menu
  3087. *
  3088. * @param {Object} container 插入TOC的容器jQuery对象元素
  3089. * @param {String} tocTitle ToC title
  3090. * @returns {Object} return toc-menu object
  3091. */
  3092. editormd.tocDropdownMenu = function(container, tocTitle) {
  3093. tocTitle = tocTitle || "Table of Contents";
  3094. var zindex = 400;
  3095. var tocMenus = container.find("." + this.classPrefix + "toc-menu");
  3096. tocMenus.each(function() {
  3097. var $this = $(this);
  3098. var toc = $this.children(".markdown-toc");
  3099. var icon = "<i class=\"fa fa-angle-down\"></i>";
  3100. var btn = "<a href=\"javascript:;\" class=\"toc-menu-btn\">" + icon + tocTitle + "</a>";
  3101. var menu = toc.children("ul");
  3102. var list = menu.find("li");
  3103. toc.append(btn);
  3104. list.first().before("<li><h1>" + tocTitle + " " + icon + "</h1></li>");
  3105. $this.mouseover(function(){
  3106. menu.show();
  3107. list.each(function(){
  3108. var li = $(this);
  3109. var ul = li.children("ul");
  3110. if (ul.html() === "")
  3111. {
  3112. ul.remove();
  3113. }
  3114. if (ul.length > 0 && ul.html() !== "")
  3115. {
  3116. var firstA = li.children("a").first();
  3117. if (firstA.children(".fa").length < 1)
  3118. {
  3119. firstA.append( $(icon).css({ float:"right", paddingTop:"4px" }) );
  3120. }
  3121. }
  3122. li.mouseover(function(){
  3123. ul.css("z-index", zindex).show();
  3124. zindex += 1;
  3125. }).mouseleave(function(){
  3126. ul.hide();
  3127. });
  3128. });
  3129. }).mouseleave(function(){
  3130. menu.hide();
  3131. });
  3132. });
  3133. return tocMenus;
  3134. };
  3135. /**
  3136. * 简单地过滤指定的HTML标签
  3137. * Filter custom html tags
  3138. *
  3139. * @param {String} html 要过滤HTML
  3140. * @param {String} filters 要过滤的标签
  3141. * @returns {String} html 返回过滤的HTML
  3142. */
  3143. editormd.filterHTMLTags = function(html, filters) {
  3144. if (typeof html !== "string") {
  3145. html = new String(html);
  3146. }
  3147. if (typeof filters !== "string") {
  3148. return html;
  3149. }
  3150. var expression = filters.split("|");
  3151. var filterTags = expression[0].split(",");
  3152. var attrs = expression[1];
  3153. for (var i = 0, len = filterTags.length; i < len; i++)
  3154. {
  3155. var tag = filterTags[i];
  3156. html = html.replace(new RegExp("\<\s*" + tag + "\s*([^\>]*)\>([^\>]*)\<\s*\/" + tag + "\s*\>", "igm"), "");
  3157. }
  3158. //return html;
  3159. if (typeof attrs !== "undefined")
  3160. {
  3161. var htmlTagRegex = /\<(\w+)\s*([^\>]*)\>([^\>]*)\<\/(\w+)\>/ig;
  3162. if (attrs === "*")
  3163. {
  3164. html = html.replace(htmlTagRegex, function($1, $2, $3, $4, $5) {
  3165. return "<" + $2 + ">" + $4 + "</" + $5 + ">";
  3166. });
  3167. }
  3168. else if (attrs === "on*")
  3169. {
  3170. html = html.replace(htmlTagRegex, function($1, $2, $3, $4, $5) {
  3171. var el = $("<" + $2 + ">" + $4 + "</" + $5 + ">");
  3172. var _attrs = $($1)[0].attributes;
  3173. var $attrs = {};
  3174. $.each(_attrs, function(i, e) {
  3175. if (e.nodeName !== '"') $attrs[e.nodeName] = e.nodeValue;
  3176. });
  3177. $.each($attrs, function(i) {
  3178. if (i.indexOf("on") === 0) {
  3179. delete $attrs[i];
  3180. }
  3181. });
  3182. el.attr($attrs);
  3183. var text = (typeof el[1] !== "undefined") ? $(el[1]).text() : "";
  3184. return el[0].outerHTML + text;
  3185. });
  3186. }
  3187. else
  3188. {
  3189. html = html.replace(htmlTagRegex, function($1, $2, $3, $4) {
  3190. var filterAttrs = attrs.split(",");
  3191. var el = $($1);
  3192. el.html($4);
  3193. $.each(filterAttrs, function(i) {
  3194. el.attr(filterAttrs[i], null);
  3195. });
  3196. return el[0].outerHTML;
  3197. });
  3198. }
  3199. }
  3200. return html;
  3201. };
  3202. /**
  3203. * 将Markdown文档解析为HTML用于前台显示
  3204. * Parse Markdown to HTML for Font-end preview.
  3205. *
  3206. * @param {String} id 用于显示HTML的对象ID
  3207. * @param {Object} [options={}] 配置选项,可选
  3208. * @returns {Object} div 返回jQuery对象元素
  3209. */
  3210. editormd.markdownToHTML = function(id, options) {
  3211. var defaults = {
  3212. gfm : true,
  3213. toc : true,
  3214. tocm : false,
  3215. tocStartLevel : 1,
  3216. tocTitle : "目录",
  3217. tocDropdown : false,
  3218. tocContainer : "",
  3219. markdown : "",
  3220. markdownSourceCode : false,
  3221. htmlDecode : false,
  3222. autoLoadKaTeX : true,
  3223. pageBreak : true,
  3224. atLink : true, // for @link
  3225. emailLink : true, // for mail address auto link
  3226. tex : false,
  3227. taskList : false, // Github Flavored Markdown task lists
  3228. emoji : false,
  3229. flowChart : false,
  3230. sequenceDiagram : false,
  3231. previewCodeHighlight : true
  3232. };
  3233. editormd.$marked = marked;
  3234. var div = $("#" + id);
  3235. var settings = div.settings = $.extend(true, defaults, options || {});
  3236. var saveTo = div.find("textarea");
  3237. if (saveTo.length < 1)
  3238. {
  3239. div.append("<textarea></textarea>");
  3240. saveTo = div.find("textarea");
  3241. }
  3242. var markdownDoc = (settings.markdown === "") ? saveTo.val() : settings.markdown;
  3243. var markdownToC = [];
  3244. var rendererOptions = {
  3245. toc : settings.toc,
  3246. tocm : settings.tocm,
  3247. tocStartLevel : settings.tocStartLevel,
  3248. taskList : settings.taskList,
  3249. emoji : settings.emoji,
  3250. tex : settings.tex,
  3251. pageBreak : settings.pageBreak,
  3252. atLink : settings.atLink, // for @link
  3253. emailLink : settings.emailLink, // for mail address auto link
  3254. flowChart : settings.flowChart,
  3255. sequenceDiagram : settings.sequenceDiagram,
  3256. previewCodeHighlight : settings.previewCodeHighlight,
  3257. };
  3258. var markedOptions = {
  3259. renderer : editormd.markedRenderer(markdownToC, rendererOptions),
  3260. gfm : settings.gfm,
  3261. tables : true,
  3262. breaks : true,
  3263. pedantic : false,
  3264. sanitize : (settings.htmlDecode) ? false : true, // 是否忽略HTML标签,即是否开启HTML标签解析,为了安全性,默认不开启
  3265. smartLists : true,
  3266. smartypants : true
  3267. };
  3268. markdownDoc = new String(markdownDoc);
  3269. var markdownParsed = marked(markdownDoc, markedOptions);
  3270. markdownParsed = editormd.filterHTMLTags(markdownParsed, settings.htmlDecode);
  3271. if (settings.markdownSourceCode) {
  3272. saveTo.text(markdownDoc);
  3273. } else {
  3274. saveTo.remove();
  3275. }
  3276. div.addClass("markdown-body " + this.classPrefix + "html-preview").append(markdownParsed);
  3277. var tocContainer = (settings.tocContainer !== "") ? $(settings.tocContainer) : div;
  3278. if (settings.tocContainer !== "")
  3279. {
  3280. tocContainer.attr("previewContainer", false);
  3281. }
  3282. if (settings.toc)
  3283. {
  3284. div.tocContainer = this.markdownToCRenderer(markdownToC, tocContainer, settings.tocDropdown, settings.tocStartLevel);
  3285. if (settings.tocDropdown || div.find("." + this.classPrefix + "toc-menu").length > 0)
  3286. {
  3287. this.tocDropdownMenu(div, settings.tocTitle);
  3288. }
  3289. if (settings.tocContainer !== "")
  3290. {
  3291. div.find(".editormd-toc-menu, .editormd-markdown-toc").remove();
  3292. }
  3293. }
  3294. if (settings.previewCodeHighlight)
  3295. {
  3296. //div.find("pre").addClass("prettyprint");
  3297. //prettyPrint();
  3298. div.find("pre").each(function (i, block) {
  3299. hljs.highlightBlock(block);
  3300. });
  3301. }
  3302. if (!editormd.isIE8)
  3303. {
  3304. if (settings.flowChart) {
  3305. div.find(".flowchart").flowChart();
  3306. }
  3307. if (settings.sequenceDiagram) {
  3308. div.find(".sequence-diagram").sequenceDiagram({theme: "simple"});
  3309. }
  3310. }
  3311. if (settings.tex)
  3312. {
  3313. var katexHandle = function() {
  3314. div.find("." + editormd.classNames.tex).each(function(){
  3315. var tex = $(this);
  3316. katex.render(tex.html().replace(/&lt;/g, "<").replace(/&gt;/g, ">"), tex[0]);
  3317. tex.find(".katex").css("font-size", "1.6em");
  3318. });
  3319. };
  3320. if (settings.autoLoadKaTeX && !editormd.$katex && !editormd.kaTeXLoaded)
  3321. {
  3322. this.loadKaTeX(function() {
  3323. editormd.$katex = katex;
  3324. editormd.kaTeXLoaded = true;
  3325. katexHandle();
  3326. });
  3327. }
  3328. else
  3329. {
  3330. katexHandle();
  3331. }
  3332. }
  3333. div.getMarkdown = function() {
  3334. return saveTo.val();
  3335. };
  3336. return div;
  3337. };
  3338. // Editor.md themes, change toolbar themes etc.
  3339. // added @1.5.0
  3340. editormd.themes = ["default", "dark"];
  3341. // Preview area themes
  3342. // added @1.5.0
  3343. editormd.previewThemes = ["default", "dark"];
  3344. // CodeMirror / editor area themes
  3345. // @1.5.0 rename -> editorThemes, old version -> themes
  3346. editormd.editorThemes = [
  3347. "default", "3024-day", "3024-night",
  3348. "ambiance", "ambiance-mobile",
  3349. "base16-dark", "base16-light", "blackboard",
  3350. "cobalt",
  3351. "eclipse", "elegant", "erlang-dark",
  3352. "lesser-dark",
  3353. "mbo", "mdn-like", "midnight", "monokai",
  3354. "neat", "neo", "night",
  3355. "paraiso-dark", "paraiso-light", "pastel-on-dark",
  3356. "rubyblue",
  3357. "solarized",
  3358. "the-matrix", "tomorrow-night-eighties", "twilight",
  3359. "vibrant-ink",
  3360. "xq-dark", "xq-light"
  3361. ];
  3362. editormd.loadPlugins = {};
  3363. editormd.loadFiles = {
  3364. js : [],
  3365. css : [],
  3366. plugin : []
  3367. };
  3368. /**
  3369. * 动态加载Editor.md插件,但不立即执行
  3370. * Load editor.md plugins
  3371. *
  3372. * @param {String} fileName 插件文件路径
  3373. * @param {Function} [callback=function()] 加载成功后执行的回调函数
  3374. * @param {String} [into="head"] 嵌入页面的位置
  3375. */
  3376. editormd.loadPlugin = function(fileName, callback, into) {
  3377. callback = callback || function() {};
  3378. this.loadScript(fileName, function() {
  3379. editormd.loadFiles.plugin.push(fileName);
  3380. callback();
  3381. }, into);
  3382. };
  3383. /**
  3384. * 动态加载CSS文件的方法
  3385. * Load css file method
  3386. *
  3387. * @param {String} fileName CSS文件名
  3388. * @param {Function} [callback=function()] 加载成功后执行的回调函数
  3389. * @param {String} [into="head"] 嵌入页面的位置
  3390. */
  3391. editormd.loadCSS = function(fileName, callback, into) {
  3392. into = into || "head";
  3393. callback = callback || function() {};
  3394. var css = document.createElement("link");
  3395. css.type = "text/css";
  3396. css.rel = "stylesheet";
  3397. css.onload = css.onreadystatechange = function() {
  3398. editormd.loadFiles.css.push(fileName);
  3399. callback();
  3400. };
  3401. css.href = fileName + ".css";
  3402. if(into === "head") {
  3403. document.getElementsByTagName("head")[0].appendChild(css);
  3404. } else {
  3405. document.body.appendChild(css);
  3406. }
  3407. };
  3408. editormd.isIE = (navigator.appName == "Microsoft Internet Explorer");
  3409. editormd.isIE8 = (editormd.isIE && navigator.appVersion.match(/8./i) == "8.");
  3410. /**
  3411. * 动态加载JS文件的方法
  3412. * Load javascript file method
  3413. *
  3414. * @param {String} fileName JS文件名
  3415. * @param {Function} [callback=function()] 加载成功后执行的回调函数
  3416. * @param {String} [into="head"] 嵌入页面的位置
  3417. */
  3418. editormd.loadScript = function(fileName, callback, into) {
  3419. into = into || "head";
  3420. callback = callback || function() {};
  3421. var script = null;
  3422. script = document.createElement("script");
  3423. script.id = fileName.replace(/[\./]+/g, "-");
  3424. script.type = "text/javascript";
  3425. script.src = fileName + ".js";
  3426. if (editormd.isIE8)
  3427. {
  3428. script.onreadystatechange = function() {
  3429. if(script.readyState)
  3430. {
  3431. if (script.readyState === "loaded" || script.readyState === "complete")
  3432. {
  3433. script.onreadystatechange = null;
  3434. editormd.loadFiles.js.push(fileName);
  3435. callback();
  3436. }
  3437. }
  3438. };
  3439. }
  3440. else
  3441. {
  3442. script.onload = function() {
  3443. editormd.loadFiles.js.push(fileName);
  3444. callback();
  3445. };
  3446. }
  3447. if (into === "head") {
  3448. document.getElementsByTagName("head")[0].appendChild(script);
  3449. } else {
  3450. document.body.appendChild(script);
  3451. }
  3452. };
  3453. // 使用国外的CDN,加载速度有时会很慢,或者自定义URL
  3454. // You can custom KaTeX load url.
  3455. editormd.katexURL = {
  3456. css : "//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min",
  3457. js : "//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min"
  3458. };
  3459. editormd.kaTeXLoaded = false;
  3460. /**
  3461. * 加载KaTeX文件
  3462. * load KaTeX files
  3463. *
  3464. * @param {Function} [callback=function()] 加载成功后执行的回调函数
  3465. */
  3466. editormd.loadKaTeX = function (callback) {
  3467. editormd.loadCSS(editormd.katexURL.css, function(){
  3468. editormd.loadScript(editormd.katexURL.js, callback || function(){});
  3469. });
  3470. };
  3471. /**
  3472. * 锁屏
  3473. * lock screen
  3474. *
  3475. * @param {Boolean} lock Boolean 布尔值,是否锁屏
  3476. * @returns {void}
  3477. */
  3478. editormd.lockScreen = function(lock) {
  3479. $("html,body").css("overflow", (lock) ? "hidden" : "");
  3480. };
  3481. /**
  3482. * 动态创建对话框
  3483. * Creating custom dialogs
  3484. *
  3485. * @param {Object} options 配置项键值对 Key/Value
  3486. * @returns {dialog} 返回创建的dialog的jQuery实例对象
  3487. */
  3488. editormd.createDialog = function(options) {
  3489. var defaults = {
  3490. name : "",
  3491. width : 420,
  3492. height: 240,
  3493. title : "",
  3494. drag : true,
  3495. closed : true,
  3496. content : "",
  3497. mask : true,
  3498. maskStyle : {
  3499. backgroundColor : "#fff",
  3500. opacity : 0.1
  3501. },
  3502. lockScreen : true,
  3503. footer : true,
  3504. buttons : false
  3505. };
  3506. options = $.extend(true, defaults, options);
  3507. var $this = this;
  3508. var editor = this.editor;
  3509. var classPrefix = editormd.classPrefix;
  3510. var guid = (new Date()).getTime();
  3511. var dialogName = ( (options.name === "") ? classPrefix + "dialog-" + guid : options.name);
  3512. var mouseOrTouch = editormd.mouseOrTouch;
  3513. var html = "<div class=\"" + classPrefix + "dialog " + dialogName + "\">";
  3514. if (options.title !== "")
  3515. {
  3516. html += "<div class=\"" + classPrefix + "dialog-header\"" + ( (options.drag) ? " style=\"cursor: move;\"" : "" ) + ">";
  3517. html += "<strong class=\"" + classPrefix + "dialog-title\">" + options.title + "</strong>";
  3518. html += "</div>";
  3519. }
  3520. if (options.closed)
  3521. {
  3522. html += "<a href=\"javascript:;\" class=\"fa fa-close " + classPrefix + "dialog-close\"></a>";
  3523. }
  3524. html += "<div class=\"" + classPrefix + "dialog-container\">" + options.content;
  3525. if (options.footer || typeof options.footer === "string")
  3526. {
  3527. html += "<div class=\"" + classPrefix + "dialog-footer\">" + ( (typeof options.footer === "boolean") ? "" : options.footer) + "</div>";
  3528. }
  3529. html += "</div>";
  3530. html += "<div class=\"" + classPrefix + "dialog-mask " + classPrefix + "dialog-mask-bg\"></div>";
  3531. html += "<div class=\"" + classPrefix + "dialog-mask " + classPrefix + "dialog-mask-con\"></div>";
  3532. html += "</div>";
  3533. editor.append(html);
  3534. var dialog = editor.find("." + dialogName);
  3535. dialog.lockScreen = function(lock) {
  3536. if (options.lockScreen)
  3537. {
  3538. $("html,body").css("overflow", (lock) ? "hidden" : "");
  3539. $this.resize();
  3540. }
  3541. return dialog;
  3542. };
  3543. dialog.showMask = function() {
  3544. if (options.mask)
  3545. {
  3546. editor.find("." + classPrefix + "mask").css(options.maskStyle).css("z-index", editormd.dialogZindex - 1).show();
  3547. }
  3548. return dialog;
  3549. };
  3550. dialog.hideMask = function() {
  3551. if (options.mask)
  3552. {
  3553. editor.find("." + classPrefix + "mask").hide();
  3554. }
  3555. return dialog;
  3556. };
  3557. dialog.loading = function(show) {
  3558. var loading = dialog.find("." + classPrefix + "dialog-mask");
  3559. loading[(show) ? "show" : "hide"]();
  3560. return dialog;
  3561. };
  3562. dialog.lockScreen(true).showMask();
  3563. dialog.show().css({
  3564. zIndex : editormd.dialogZindex,
  3565. border : (editormd.isIE8) ? "1px solid #ddd" : "",
  3566. width : (typeof options.width === "number") ? options.width + "px" : options.width,
  3567. height : (typeof options.height === "number") ? options.height + "px" : options.height
  3568. });
  3569. var dialogPosition = function(){
  3570. dialog.css({
  3571. top : ($(window).height() - dialog.height()) / 2 + "px",
  3572. left : ($(window).width() - dialog.width()) / 2 + "px"
  3573. });
  3574. };
  3575. dialogPosition();
  3576. $(window).resize(dialogPosition);
  3577. dialog.children("." + classPrefix + "dialog-close").bind(mouseOrTouch("click", "touchend"), function() {
  3578. dialog.hide().lockScreen(false).hideMask();
  3579. });
  3580. if (typeof options.buttons === "object")
  3581. {
  3582. var footer = dialog.footer = dialog.find("." + classPrefix + "dialog-footer");
  3583. for (var key in options.buttons)
  3584. {
  3585. var btn = options.buttons[key];
  3586. var btnClassName = classPrefix + key + "-btn";
  3587. footer.append("<button class=\"" + classPrefix + "btn " + btnClassName + "\">" + btn[0] + "</button>");
  3588. btn[1] = $.proxy(btn[1], dialog);
  3589. footer.children("." + btnClassName).bind(mouseOrTouch("click", "touchend"), btn[1]);
  3590. }
  3591. }
  3592. if (options.title !== "" && options.drag)
  3593. {
  3594. var posX, posY;
  3595. var dialogHeader = dialog.children("." + classPrefix + "dialog-header");
  3596. if (!options.mask) {
  3597. dialogHeader.bind(mouseOrTouch("click", "touchend"), function(){
  3598. editormd.dialogZindex += 2;
  3599. dialog.css("z-index", editormd.dialogZindex);
  3600. });
  3601. }
  3602. dialogHeader.mousedown(function(e) {
  3603. e = e || window.event; //IE
  3604. posX = e.clientX - parseInt(dialog[0].style.left);
  3605. posY = e.clientY - parseInt(dialog[0].style.top);
  3606. document.onmousemove = moveAction;
  3607. });
  3608. var userCanSelect = function (obj) {
  3609. obj.removeClass(classPrefix + "user-unselect").off("selectstart");
  3610. };
  3611. var userUnselect = function (obj) {
  3612. obj.addClass(classPrefix + "user-unselect").on("selectstart", function(event) { // selectstart for IE
  3613. return false;
  3614. });
  3615. };
  3616. var moveAction = function (e) {
  3617. e = e || window.event; //IE
  3618. var left, top, nowLeft = parseInt(dialog[0].style.left), nowTop = parseInt(dialog[0].style.top);
  3619. if( nowLeft >= 0 ) {
  3620. if( nowLeft + dialog.width() <= $(window).width()) {
  3621. left = e.clientX - posX;
  3622. } else {
  3623. left = $(window).width() - dialog.width();
  3624. document.onmousemove = null;
  3625. }
  3626. } else {
  3627. left = 0;
  3628. document.onmousemove = null;
  3629. }
  3630. if( nowTop >= 0 ) {
  3631. top = e.clientY - posY;
  3632. } else {
  3633. top = 0;
  3634. document.onmousemove = null;
  3635. }
  3636. document.onselectstart = function() {
  3637. return false;
  3638. };
  3639. userUnselect($("body"));
  3640. userUnselect(dialog);
  3641. dialog[0].style.left = left + "px";
  3642. dialog[0].style.top = top + "px";
  3643. };
  3644. document.onmouseup = function() {
  3645. userCanSelect($("body"));
  3646. userCanSelect(dialog);
  3647. document.onselectstart = null;
  3648. document.onmousemove = null;
  3649. };
  3650. dialogHeader.touchDraggable = function() {
  3651. var offset = null;
  3652. var start = function(e) {
  3653. var orig = e.originalEvent;
  3654. var pos = $(this).parent().position();
  3655. offset = {
  3656. x : orig.changedTouches[0].pageX - pos.left,
  3657. y : orig.changedTouches[0].pageY - pos.top
  3658. };
  3659. };
  3660. var move = function(e) {
  3661. e.preventDefault();
  3662. var orig = e.originalEvent;
  3663. $(this).parent().css({
  3664. top : orig.changedTouches[0].pageY - offset.y,
  3665. left : orig.changedTouches[0].pageX - offset.x
  3666. });
  3667. };
  3668. this.bind("touchstart", start).bind("touchmove", move);
  3669. };
  3670. dialogHeader.touchDraggable();
  3671. }
  3672. editormd.dialogZindex += 2;
  3673. return dialog;
  3674. };
  3675. /**
  3676. * 鼠标和触摸事件的判断/选择方法
  3677. * MouseEvent or TouchEvent type switch
  3678. *
  3679. * @param {String} [mouseEventType="click"] 供选择的鼠标事件
  3680. * @param {String} [touchEventType="touchend"] 供选择的触摸事件
  3681. * @returns {String} EventType 返回事件类型名称
  3682. */
  3683. editormd.mouseOrTouch = function(mouseEventType, touchEventType) {
  3684. mouseEventType = mouseEventType || "click";
  3685. touchEventType = touchEventType || "touchend";
  3686. var eventType = mouseEventType;
  3687. try {
  3688. document.createEvent("TouchEvent");
  3689. eventType = touchEventType;
  3690. } catch(e) {}
  3691. return eventType;
  3692. };
  3693. /**
  3694. * 日期时间的格式化方法
  3695. * Datetime format method
  3696. *
  3697. * @param {String} [format=""] 日期时间的格式,类似PHP的格式
  3698. * @returns {String} datefmt 返回格式化后的日期时间字符串
  3699. */
  3700. editormd.dateFormat = function(format) {
  3701. format = format || "";
  3702. var addZero = function(d) {
  3703. return (d < 10) ? "0" + d : d;
  3704. };
  3705. var date = new Date();
  3706. var year = date.getFullYear();
  3707. var year2 = year.toString().slice(2, 4);
  3708. var month = addZero(date.getMonth() + 1);
  3709. var day = addZero(date.getDate());
  3710. var weekDay = date.getDay();
  3711. var hour = addZero(date.getHours());
  3712. var min = addZero(date.getMinutes());
  3713. var second = addZero(date.getSeconds());
  3714. var ms = addZero(date.getMilliseconds());
  3715. var datefmt = "";
  3716. var ymd = year2 + "-" + month + "-" + day;
  3717. var fymd = year + "-" + month + "-" + day;
  3718. var hms = hour + ":" + min + ":" + second;
  3719. switch (format)
  3720. {
  3721. case "UNIX Time" :
  3722. datefmt = date.getTime();
  3723. break;
  3724. case "UTC" :
  3725. datefmt = date.toUTCString();
  3726. break;
  3727. case "yy" :
  3728. datefmt = year2;
  3729. break;
  3730. case "year" :
  3731. case "yyyy" :
  3732. datefmt = year;
  3733. break;
  3734. case "month" :
  3735. case "mm" :
  3736. datefmt = month;
  3737. break;
  3738. case "cn-week-day" :
  3739. case "cn-wd" :
  3740. var cnWeekDays = ["日", "一", "二", "三", "四", "五", "六"];
  3741. datefmt = "星期" + cnWeekDays[weekDay];
  3742. break;
  3743. case "week-day" :
  3744. case "wd" :
  3745. var weekDays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
  3746. datefmt = weekDays[weekDay];
  3747. break;
  3748. case "day" :
  3749. case "dd" :
  3750. datefmt = day;
  3751. break;
  3752. case "hour" :
  3753. case "hh" :
  3754. datefmt = hour;
  3755. break;
  3756. case "min" :
  3757. case "ii" :
  3758. datefmt = min;
  3759. break;
  3760. case "second" :
  3761. case "ss" :
  3762. datefmt = second;
  3763. break;
  3764. case "ms" :
  3765. datefmt = ms;
  3766. break;
  3767. case "yy-mm-dd" :
  3768. datefmt = ymd;
  3769. break;
  3770. case "yyyy-mm-dd" :
  3771. datefmt = fymd;
  3772. break;
  3773. case "yyyy-mm-dd h:i:s ms" :
  3774. case "full + ms" :
  3775. datefmt = fymd + " " + hms + " " + ms;
  3776. break;
  3777. case "full" :
  3778. case "yyyy-mm-dd h:i:s" :
  3779. default:
  3780. datefmt = fymd + " " + hms;
  3781. break;
  3782. }
  3783. return datefmt;
  3784. };
  3785. return editormd;
  3786. }));