editormd.js 155 KB

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