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. });
  899. }
  900. else
  901. {
  902. toolbar.css({
  903. position : "absolute",
  904. width : "100%",
  905. left : 0
  906. });
  907. }
  908. };
  909. if (!state.fullscreen && !state.preview && settings.toolbar && settings.toolbarAutoFixed)
  910. {
  911. $(window).bind("scroll", autoFixedHandle);
  912. }
  913. return this;
  914. },
  915. /**
  916. * 配置和初始化工具栏
  917. * Set toolbar and Initialization
  918. *
  919. * @returns {editormd} 返回editormd的实例对象
  920. */
  921. setToolbar : function() {
  922. var settings = this.settings;
  923. if(settings.readOnly) {
  924. return this;
  925. }
  926. var editor = this.editor;
  927. var preview = this.preview;
  928. var classPrefix = this.classPrefix;
  929. var toolbar = this.toolbar = editor.children("." + classPrefix + "toolbar");
  930. if (settings.toolbar && toolbar.length < 1)
  931. {
  932. var toolbarHTML = "<div class=\"" + classPrefix + "toolbar\"><div class=\"" + classPrefix + "toolbar-container\"><ul class=\"" + classPrefix + "menu\"></ul></div></div>";
  933. editor.append(toolbarHTML);
  934. toolbar = this.toolbar = editor.children("." + classPrefix + "toolbar");
  935. }
  936. if (!settings.toolbar)
  937. {
  938. toolbar.hide();
  939. return this;
  940. }
  941. toolbar.show();
  942. var icons = (typeof settings.toolbarIcons === "function") ? settings.toolbarIcons()
  943. : ((typeof settings.toolbarIcons === "string") ? editormd.toolbarModes[settings.toolbarIcons] : settings.toolbarIcons);
  944. var toolbarMenu = toolbar.find("." + this.classPrefix + "menu"), menu = "";
  945. var pullRight = false;
  946. for (var i = 0, len = icons.length; i < len; i++)
  947. {
  948. var name = icons[i];
  949. if (name === "||")
  950. {
  951. pullRight = true;
  952. }
  953. else if (name === "|")
  954. {
  955. menu += "<li class=\"divider\" unselectable=\"on\">|</li>";
  956. }
  957. else
  958. {
  959. var isHeader = (/h(\d)/.test(name));
  960. var index = name;
  961. if (name === "watch" && !settings.watch) {
  962. index = "unwatch";
  963. }
  964. var title = settings.lang.toolbar[index];
  965. var iconTexts = settings.toolbarIconTexts[index];
  966. var iconClass = settings.toolbarIconsClass[index];
  967. title = (typeof title === "undefined") ? "" : title;
  968. iconTexts = (typeof iconTexts === "undefined") ? "" : iconTexts;
  969. iconClass = (typeof iconClass === "undefined") ? "" : iconClass;
  970. var menuItem = pullRight ? "<li class=\"pull-right\">" : "<li>";
  971. if (typeof settings.toolbarCustomIcons[name] !== "undefined" && typeof settings.toolbarCustomIcons[name] !== "function")
  972. {
  973. menuItem += settings.toolbarCustomIcons[name];
  974. }
  975. else
  976. {
  977. menuItem += "<a href=\"javascript:;\" title=\"" + title + "\" unselectable=\"on\">";
  978. menuItem += "<i class=\"fa " + iconClass + "\" name=\""+name+"\" unselectable=\"on\">"+((isHeader) ? name.toUpperCase() : ( (iconClass === "") ? iconTexts : "") ) + "</i>";
  979. menuItem += "</a>";
  980. }
  981. menuItem += "</li>";
  982. menu = pullRight ? menuItem + menu : menu + menuItem;
  983. }
  984. }
  985. toolbarMenu.html(menu);
  986. toolbarMenu.find("[title=\"Lowercase\"]").attr("title", settings.lang.toolbar.lowercase);
  987. toolbarMenu.find("[title=\"ucwords\"]").attr("title", settings.lang.toolbar.ucwords);
  988. this.setToolbarHandler();
  989. this.setToolbarAutoFixed();
  990. return this;
  991. },
  992. /**
  993. * 工具栏图标事件处理对象序列
  994. * Get toolbar icons event handlers
  995. *
  996. * @param {Object} cm CodeMirror的实例对象
  997. * @param {String} name 要获取的事件处理器名称
  998. * @returns {Object} 返回处理对象序列
  999. */
  1000. dialogLockScreen : function() {
  1001. $.proxy(editormd.dialogLockScreen, this)();
  1002. return this;
  1003. },
  1004. dialogShowMask : function(dialog) {
  1005. $.proxy(editormd.dialogShowMask, this)(dialog);
  1006. return this;
  1007. },
  1008. getToolbarHandles : function(name) {
  1009. var toolbarHandlers = this.toolbarHandlers = editormd.toolbarHandlers;
  1010. return (name && typeof toolbarIconHandlers[name] !== "undefined") ? toolbarHandlers[name] : toolbarHandlers;
  1011. },
  1012. /**
  1013. * 工具栏图标事件处理器
  1014. * Bind toolbar icons event handle
  1015. *
  1016. * @returns {editormd} 返回editormd的实例对象
  1017. */
  1018. setToolbarHandler : function() {
  1019. var _this = this;
  1020. var settings = this.settings;
  1021. if (!settings.toolbar || settings.readOnly) {
  1022. return this;
  1023. }
  1024. var toolbar = this.toolbar;
  1025. var cm = this.cm;
  1026. var classPrefix = this.classPrefix;
  1027. var toolbarIcons = this.toolbarIcons = toolbar.find("." + classPrefix + "menu > li > a");
  1028. var toolbarIconHandlers = this.getToolbarHandles();
  1029. toolbarIcons.bind(editormd.mouseOrTouch("click", "touchend"), function(event) {
  1030. var icon = $(this).children(".fa");
  1031. var name = icon.attr("name");
  1032. var cursor = cm.getCursor();
  1033. var selection = cm.getSelection();
  1034. if (name === "") {
  1035. return ;
  1036. }
  1037. _this.activeIcon = icon;
  1038. if (typeof toolbarIconHandlers[name] !== "undefined")
  1039. {
  1040. $.proxy(toolbarIconHandlers[name], _this)(cm);
  1041. }
  1042. else
  1043. {
  1044. if (typeof settings.toolbarHandlers[name] !== "undefined")
  1045. {
  1046. $.proxy(settings.toolbarHandlers[name], _this)(cm, icon, cursor, selection);
  1047. }
  1048. }
  1049. if (name !== "link" && name !== "reference-link" && name !== "image" && name !== "code-block" &&
  1050. name !== "preformatted-text" && name !== "watch" && name !== "preview" && name !== "search" && name !== "fullscreen" && name !== "info")
  1051. {
  1052. cm.focus();
  1053. }
  1054. return false;
  1055. });
  1056. return this;
  1057. },
  1058. /**
  1059. * 动态创建对话框
  1060. * Creating custom dialogs
  1061. *
  1062. * @param {Object} options 配置项键值对 Key/Value
  1063. * @returns {dialog} 返回创建的dialog的jQuery实例对象
  1064. */
  1065. createDialog : function(options) {
  1066. return $.proxy(editormd.createDialog, this)(options);
  1067. },
  1068. /**
  1069. * 创建关于Editor.md的对话框
  1070. * Create about Editor.md dialog
  1071. *
  1072. * @returns {editormd} 返回editormd的实例对象
  1073. */
  1074. createInfoDialog : function() {
  1075. var _this = this;
  1076. var editor = this.editor;
  1077. var classPrefix = this.classPrefix;
  1078. var infoDialogHTML = [
  1079. "<div class=\"" + classPrefix + "dialog " + classPrefix + "dialog-info\" style=\"\">",
  1080. "<div class=\"" + classPrefix + "dialog-container\">",
  1081. "<h1><i class=\"editormd-logo editormd-logo-lg editormd-logo-color\"></i> " + editormd.title + "<small>v" + editormd.version + "</small></h1>",
  1082. "<p>" + this.lang.description + "</p>",
  1083. "<p style=\"margin: 10px 0 20px 0;\"><a href=\"" + editormd.homePage + "\" target=\"_blank\">" + editormd.homePage + " <i class=\"fa fa-external-link\"></i></a></p>",
  1084. "<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>",
  1085. "</div>",
  1086. "<a href=\"javascript:;\" class=\"fa fa-close " + classPrefix + "dialog-close\"></a>",
  1087. "</div>"
  1088. ].join("\n");
  1089. editor.append(infoDialogHTML);
  1090. var infoDialog = this.infoDialog = editor.children("." + classPrefix + "dialog-info");
  1091. infoDialog.find("." + classPrefix + "dialog-close").bind(editormd.mouseOrTouch("click", "touchend"), function() {
  1092. _this.hideInfoDialog();
  1093. });
  1094. infoDialog.css("border", (editormd.isIE8) ? "1px solid #ddd" : "").css("z-index", editormd.dialogZindex).show();
  1095. this.infoDialogPosition();
  1096. return this;
  1097. },
  1098. /**
  1099. * 关于Editor.md对话居中定位
  1100. * Editor.md dialog position handle
  1101. *
  1102. * @returns {editormd} 返回editormd的实例对象
  1103. */
  1104. infoDialogPosition : function() {
  1105. var infoDialog = this.infoDialog;
  1106. var _infoDialogPosition = function() {
  1107. infoDialog.css({
  1108. top : ($(window).height() - infoDialog.height()) / 2 + "px",
  1109. left : ($(window).width() - infoDialog.width()) / 2 + "px"
  1110. });
  1111. };
  1112. _infoDialogPosition();
  1113. $(window).resize(_infoDialogPosition);
  1114. return this;
  1115. },
  1116. /**
  1117. * 显示关于Editor.md
  1118. * Display about Editor.md dialog
  1119. *
  1120. * @returns {editormd} 返回editormd的实例对象
  1121. */
  1122. showInfoDialog : function() {
  1123. $("html,body").css("overflow-x", "hidden");
  1124. var _this = this;
  1125. var editor = this.editor;
  1126. var settings = this.settings;
  1127. var infoDialog = this.infoDialog = editor.children("." + this.classPrefix + "dialog-info");
  1128. if (infoDialog.length < 1)
  1129. {
  1130. this.createInfoDialog();
  1131. }
  1132. this.lockScreen(true);
  1133. this.mask.css({
  1134. opacity : settings.dialogMaskOpacity,
  1135. backgroundColor : settings.dialogMaskBgColor
  1136. }).show();
  1137. infoDialog.css("z-index", editormd.dialogZindex).show();
  1138. this.infoDialogPosition();
  1139. return this;
  1140. },
  1141. /**
  1142. * 隐藏关于Editor.md
  1143. * Hide about Editor.md dialog
  1144. *
  1145. * @returns {editormd} 返回editormd的实例对象
  1146. */
  1147. hideInfoDialog : function() {
  1148. $("html,body").css("overflow-x", "");
  1149. this.infoDialog.hide();
  1150. this.mask.hide();
  1151. this.lockScreen(false);
  1152. return this;
  1153. },
  1154. /**
  1155. * 锁屏
  1156. * lock screen
  1157. *
  1158. * @param {Boolean} lock Boolean 布尔值,是否锁屏
  1159. * @returns {editormd} 返回editormd的实例对象
  1160. */
  1161. lockScreen : function(lock) {
  1162. editormd.lockScreen(lock);
  1163. this.resize();
  1164. return this;
  1165. },
  1166. /**
  1167. * 编辑器界面重建,用于动态语言包或模块加载等
  1168. * Recreate editor
  1169. *
  1170. * @returns {editormd} 返回editormd的实例对象
  1171. */
  1172. recreate : function() {
  1173. var _this = this;
  1174. var editor = this.editor;
  1175. var settings = this.settings;
  1176. this.codeMirror.remove();
  1177. this.setCodeMirror();
  1178. if (!settings.readOnly)
  1179. {
  1180. if (editor.find(".editormd-dialog").length > 0) {
  1181. editor.find(".editormd-dialog").remove();
  1182. }
  1183. if (settings.toolbar)
  1184. {
  1185. this.getToolbarHandles();
  1186. this.setToolbar();
  1187. }
  1188. }
  1189. this.loadedDisplay(true);
  1190. return this;
  1191. },
  1192. /**
  1193. * 高亮预览HTML的pre代码部分
  1194. * highlight of preview codes
  1195. *
  1196. * @returns {editormd} 返回editormd的实例对象
  1197. */
  1198. previewCodeHighlight : function() {
  1199. var settings = this.settings;
  1200. var previewContainer = this.previewContainer;
  1201. if (settings.previewCodeHighlight)
  1202. {
  1203. previewContainer.find("pre").addClass("prettyprint linenums");
  1204. if (typeof prettyPrint !== "undefined")
  1205. {
  1206. prettyPrint();
  1207. }
  1208. }
  1209. return this;
  1210. },
  1211. /**
  1212. * 解析TeX(KaTeX)科学公式
  1213. * TeX(KaTeX) Renderer
  1214. *
  1215. * @returns {editormd} 返回editormd的实例对象
  1216. */
  1217. katexRender : function() {
  1218. if (timer === null)
  1219. {
  1220. return this;
  1221. }
  1222. this.previewContainer.find("." + editormd.classNames.tex).each(function(){
  1223. var tex = $(this);
  1224. editormd.$katex.render(tex.text(), tex[0]);
  1225. tex.find(".katex").css("font-size", "1.6em");
  1226. });
  1227. return this;
  1228. },
  1229. /**
  1230. * 解析和渲染流程图及时序图
  1231. * FlowChart and SequenceDiagram Renderer
  1232. *
  1233. * @returns {editormd} 返回editormd的实例对象
  1234. */
  1235. flowChartAndSequenceDiagramRender : function() {
  1236. var $this = this;
  1237. var settings = this.settings;
  1238. var previewContainer = this.previewContainer;
  1239. if (editormd.isIE8) {
  1240. return this;
  1241. }
  1242. if (settings.flowChart) {
  1243. if (flowchartTimer === null) {
  1244. return this;
  1245. }
  1246. previewContainer.find(".flowchart").flowChart();
  1247. }
  1248. if (settings.sequenceDiagram) {
  1249. previewContainer.find(".sequence-diagram").sequenceDiagram({theme: "simple"});
  1250. }
  1251. var preview = $this.preview;
  1252. var codeMirror = $this.codeMirror;
  1253. var codeView = codeMirror.find(".CodeMirror-scroll");
  1254. var height = codeView.height();
  1255. var scrollTop = codeView.scrollTop();
  1256. var percent = (scrollTop / codeView[0].scrollHeight);
  1257. var tocHeight = 0;
  1258. preview.find(".markdown-toc-list").each(function(){
  1259. tocHeight += $(this).height();
  1260. });
  1261. var tocMenuHeight = preview.find(".editormd-toc-menu").height();
  1262. tocMenuHeight = (!tocMenuHeight) ? 0 : tocMenuHeight;
  1263. if (scrollTop === 0)
  1264. {
  1265. preview.scrollTop(0);
  1266. }
  1267. else if (scrollTop + height >= codeView[0].scrollHeight - 16)
  1268. {
  1269. preview.scrollTop(preview[0].scrollHeight);
  1270. }
  1271. else
  1272. {
  1273. preview.scrollTop((preview[0].scrollHeight + tocHeight + tocMenuHeight) * percent);
  1274. }
  1275. return this;
  1276. },
  1277. /**
  1278. * 注册键盘快捷键处理
  1279. * Register CodeMirror keyMaps (keyboard shortcuts).
  1280. *
  1281. * @param {Object} keyMap KeyMap key/value {"(Ctrl/Shift/Alt)-Key" : function(){}}
  1282. * @returns {editormd} return this
  1283. */
  1284. registerKeyMaps : function(keyMap) {
  1285. var _this = this;
  1286. var cm = this.cm;
  1287. var settings = this.settings;
  1288. var toolbarHandlers = editormd.toolbarHandlers;
  1289. var disabledKeyMaps = settings.disabledKeyMaps;
  1290. keyMap = keyMap || null;
  1291. if (keyMap)
  1292. {
  1293. for (var i in keyMap)
  1294. {
  1295. if ($.inArray(i, disabledKeyMaps) < 0)
  1296. {
  1297. var map = {};
  1298. map[i] = keyMap[i];
  1299. cm.addKeyMap(keyMap);
  1300. }
  1301. }
  1302. }
  1303. else
  1304. {
  1305. for (var k in editormd.keyMaps)
  1306. {
  1307. var _keyMap = editormd.keyMaps[k];
  1308. var handle = (typeof _keyMap === "string") ? $.proxy(toolbarHandlers[_keyMap], _this) : $.proxy(_keyMap, _this);
  1309. if ($.inArray(k, ["F9", "F10", "F11"]) < 0 && $.inArray(k, disabledKeyMaps) < 0)
  1310. {
  1311. var _map = {};
  1312. _map[k] = handle;
  1313. cm.addKeyMap(_map);
  1314. }
  1315. }
  1316. $(window).keydown(function(event) {
  1317. var keymaps = {
  1318. "120" : "F9",
  1319. "121" : "F10",
  1320. "122" : "F11"
  1321. };
  1322. if ( $.inArray(keymaps[event.keyCode], disabledKeyMaps) < 0 )
  1323. {
  1324. switch (event.keyCode)
  1325. {
  1326. case 120:
  1327. $.proxy(toolbarHandlers["watch"], _this)();
  1328. return false;
  1329. break;
  1330. case 121:
  1331. $.proxy(toolbarHandlers["preview"], _this)();
  1332. return false;
  1333. break;
  1334. case 122:
  1335. $.proxy(toolbarHandlers["fullscreen"], _this)();
  1336. return false;
  1337. break;
  1338. default:
  1339. break;
  1340. }
  1341. }
  1342. });
  1343. }
  1344. return this;
  1345. },
  1346. /**
  1347. * 绑定同步滚动
  1348. *
  1349. * @returns {editormd} return this
  1350. */
  1351. bindScrollEvent : function() {
  1352. var _this = this;
  1353. var preview = this.preview;
  1354. var settings = this.settings;
  1355. var codeMirror = this.codeMirror;
  1356. var mouseOrTouch = editormd.mouseOrTouch;
  1357. if (!settings.syncScrolling) {
  1358. return this;
  1359. }
  1360. var cmBindScroll = function() {
  1361. codeMirror.find(".CodeMirror-scroll").bind(mouseOrTouch("scroll", "touchmove"), function(event) {
  1362. var height = $(this).height();
  1363. var scrollTop = $(this).scrollTop();
  1364. var percent = (scrollTop / $(this)[0].scrollHeight);
  1365. var tocHeight = 0;
  1366. preview.find(".markdown-toc-list").each(function(){
  1367. tocHeight += $(this).height();
  1368. });
  1369. var tocMenuHeight = preview.find(".editormd-toc-menu").height();
  1370. tocMenuHeight = (!tocMenuHeight) ? 0 : tocMenuHeight;
  1371. if (scrollTop === 0)
  1372. {
  1373. preview.scrollTop(0);
  1374. }
  1375. else if (scrollTop + height >= $(this)[0].scrollHeight - 16)
  1376. {
  1377. preview.scrollTop(preview[0].scrollHeight);
  1378. }
  1379. else
  1380. {
  1381. preview.scrollTop((preview[0].scrollHeight + tocHeight + tocMenuHeight) * percent);
  1382. }
  1383. $.proxy(settings.onscroll, _this)(event);
  1384. });
  1385. };
  1386. var cmUnbindScroll = function() {
  1387. codeMirror.find(".CodeMirror-scroll").unbind(mouseOrTouch("scroll", "touchmove"));
  1388. };
  1389. var previewBindScroll = function() {
  1390. preview.bind(mouseOrTouch("scroll", "touchmove"), function(event) {
  1391. var height = $(this).height();
  1392. var scrollTop = $(this).scrollTop();
  1393. var percent = (scrollTop / $(this)[0].scrollHeight);
  1394. var codeView = codeMirror.find(".CodeMirror-scroll");
  1395. if(scrollTop === 0)
  1396. {
  1397. codeView.scrollTop(0);
  1398. }
  1399. else if (scrollTop + height >= $(this)[0].scrollHeight)
  1400. {
  1401. codeView.scrollTop(codeView[0].scrollHeight);
  1402. }
  1403. else
  1404. {
  1405. codeView.scrollTop(codeView[0].scrollHeight * percent);
  1406. }
  1407. $.proxy(settings.onpreviewscroll, _this)(event);
  1408. });
  1409. };
  1410. var previewUnbindScroll = function() {
  1411. preview.unbind(mouseOrTouch("scroll", "touchmove"));
  1412. };
  1413. codeMirror.bind({
  1414. mouseover : cmBindScroll,
  1415. mouseout : cmUnbindScroll,
  1416. touchstart : cmBindScroll,
  1417. touchend : cmUnbindScroll
  1418. });
  1419. if (settings.syncScrolling === "single") {
  1420. return this;
  1421. }
  1422. preview.bind({
  1423. mouseover : previewBindScroll,
  1424. mouseout : previewUnbindScroll,
  1425. touchstart : previewBindScroll,
  1426. touchend : previewUnbindScroll
  1427. });
  1428. return this;
  1429. },
  1430. bindChangeEvent : function() {
  1431. var _this = this;
  1432. var cm = this.cm;
  1433. var settings = this.settings;
  1434. if (!settings.syncScrolling) {
  1435. return this;
  1436. }
  1437. cm.on("change", function(_cm, changeObj) {
  1438. if (settings.watch)
  1439. {
  1440. _this.previewContainer.css("padding", settings.autoHeight ? "20px 20px 50px 40px" : "20px");
  1441. }
  1442. timer = setTimeout(function() {
  1443. clearTimeout(timer);
  1444. _this.save();
  1445. timer = null;
  1446. }, settings.delay);
  1447. });
  1448. return this;
  1449. },
  1450. /**
  1451. * 加载队列完成之后的显示处理
  1452. * Display handle of the module queues loaded after.
  1453. *
  1454. * @param {Boolean} recreate 是否为重建编辑器
  1455. * @returns {editormd} 返回editormd的实例对象
  1456. */
  1457. loadedDisplay : function(recreate) {
  1458. recreate = recreate || false;
  1459. var _this = this;
  1460. var editor = this.editor;
  1461. var preview = this.preview;
  1462. var settings = this.settings;
  1463. this.containerMask.hide();
  1464. this.save();
  1465. if (settings.watch) {
  1466. preview.show();
  1467. }
  1468. editor.data("oldWidth", editor.width()).data("oldHeight", editor.height()); // 为了兼容Zepto
  1469. this.resize();
  1470. this.registerKeyMaps();
  1471. $(window).resize(function(){
  1472. _this.resize();
  1473. });
  1474. this.bindScrollEvent().bindChangeEvent();
  1475. if (!recreate)
  1476. {
  1477. $.proxy(settings.onload, this)();
  1478. }
  1479. this.state.loaded = true;
  1480. return this;
  1481. },
  1482. /**
  1483. * 设置编辑器的宽度
  1484. * Set editor width
  1485. *
  1486. * @param {Number|String} width 编辑器宽度值
  1487. * @returns {editormd} 返回editormd的实例对象
  1488. */
  1489. width : function(width) {
  1490. this.editor.css("width", (typeof width === "number") ? width + "px" : width);
  1491. this.resize();
  1492. return this;
  1493. },
  1494. /**
  1495. * 设置编辑器的高度
  1496. * Set editor height
  1497. *
  1498. * @param {Number|String} height 编辑器高度值
  1499. * @returns {editormd} 返回editormd的实例对象
  1500. */
  1501. height : function(height) {
  1502. this.editor.css("height", (typeof height === "number") ? height + "px" : height);
  1503. this.resize();
  1504. return this;
  1505. },
  1506. /**
  1507. * 调整编辑器的尺寸和布局
  1508. * Resize editor layout
  1509. *
  1510. * @param {Number|String} [width=null] 编辑器宽度值
  1511. * @param {Number|String} [height=null] 编辑器高度值
  1512. * @returns {editormd} 返回editormd的实例对象
  1513. */
  1514. resize : function(width, height) {
  1515. width = width || null;
  1516. height = height || null;
  1517. var state = this.state;
  1518. var editor = this.editor;
  1519. var preview = this.preview;
  1520. var toolbar = this.toolbar;
  1521. var settings = this.settings;
  1522. var codeMirror = this.codeMirror;
  1523. if (width)
  1524. {
  1525. editor.css("width", (typeof width === "number") ? width + "px" : width);
  1526. }
  1527. if (settings.autoHeight && !state.fullscreen && !state.preview)
  1528. {
  1529. editor.css("height", "auto");
  1530. codeMirror.css("height", "auto");
  1531. }
  1532. else
  1533. {
  1534. if (height)
  1535. {
  1536. editor.css("height", (typeof height === "number") ? height + "px" : height);
  1537. }
  1538. if (state.fullscreen)
  1539. {
  1540. editor.height($(window).height());
  1541. }
  1542. if (settings.toolbar && !settings.readOnly)
  1543. {
  1544. codeMirror.css("margin-top", toolbar.height() + 1).height(editor.height() - toolbar.height());
  1545. }
  1546. else
  1547. {
  1548. codeMirror.css("margin-top", 0).height(editor.height());
  1549. }
  1550. }
  1551. if(settings.watch)
  1552. {
  1553. codeMirror.width(editor.width() / 2);
  1554. preview.width((!state.preview) ? editor.width() / 2 : editor.width());
  1555. this.previewContainer.css("padding", settings.autoHeight ? "20px 20px 50px 40px" : "20px");
  1556. if (settings.toolbar && !settings.readOnly)
  1557. {
  1558. preview.css("top", toolbar.height() + 1);
  1559. }
  1560. else
  1561. {
  1562. preview.css("top", 0);
  1563. }
  1564. if (settings.autoHeight && !state.fullscreen && !state.preview)
  1565. {
  1566. preview.height("");
  1567. }
  1568. else
  1569. {
  1570. var previewHeight = (settings.toolbar && !settings.readOnly) ? editor.height() - toolbar.height() : editor.height();
  1571. preview.height(previewHeight);
  1572. }
  1573. }
  1574. else
  1575. {
  1576. codeMirror.width(editor.width());
  1577. preview.hide();
  1578. }
  1579. if (state.loaded)
  1580. {
  1581. $.proxy(settings.onresize, this)();
  1582. }
  1583. return this;
  1584. },
  1585. /**
  1586. * 解析和保存Markdown代码
  1587. * Parse & Saving Markdown source code
  1588. *
  1589. * @returns {editormd} 返回editormd的实例对象
  1590. */
  1591. save : function() {
  1592. var _this = this;
  1593. var state = this.state;
  1594. var settings = this.settings;
  1595. if (timer === null && !(!settings.watch && state.preview))
  1596. {
  1597. return this;
  1598. }
  1599. var cm = this.cm;
  1600. var cmValue = cm.getValue();
  1601. var previewContainer = this.previewContainer;
  1602. if (settings.mode !== "gfm" && settings.mode !== "markdown")
  1603. {
  1604. this.markdownTextarea.val(cmValue);
  1605. return this;
  1606. }
  1607. var marked = editormd.$marked;
  1608. var markdownToC = this.markdownToC = [];
  1609. var rendererOptions = this.markedRendererOptions = {
  1610. toc : settings.toc,
  1611. tocm : settings.tocm,
  1612. tocStartLevel : settings.tocStartLevel,
  1613. pageBreak : settings.pageBreak,
  1614. taskList : settings.taskList,
  1615. emoji : settings.emoji,
  1616. tex : settings.tex,
  1617. atLink : settings.atLink, // for @link
  1618. emailLink : settings.emailLink, // for mail address auto link
  1619. flowChart : settings.flowChart,
  1620. sequenceDiagram : settings.sequenceDiagram,
  1621. previewCodeHighlight : settings.previewCodeHighlight,
  1622. };
  1623. var markedOptions = this.markedOptions = {
  1624. renderer : editormd.markedRenderer(markdownToC, rendererOptions),
  1625. gfm : true,
  1626. tables : true,
  1627. breaks : true,
  1628. pedantic : false,
  1629. sanitize : (settings.htmlDecode) ? false : true, // 关闭忽略HTML标签,即开启识别HTML标签,默认为false
  1630. smartLists : true,
  1631. smartypants : true
  1632. };
  1633. marked.setOptions(markedOptions);
  1634. var newMarkdownDoc = editormd.$marked(cmValue, markedOptions);
  1635. //console.info("cmValue", cmValue, newMarkdownDoc);
  1636. newMarkdownDoc = editormd.filterHTMLTags(newMarkdownDoc, settings.htmlDecode);
  1637. //console.error("cmValue", cmValue, newMarkdownDoc);
  1638. this.markdownTextarea.text(cmValue);
  1639. cm.save();
  1640. if (settings.saveHTMLToTextarea)
  1641. {
  1642. this.htmlTextarea.text(newMarkdownDoc);
  1643. }
  1644. if(settings.watch || (!settings.watch && state.preview))
  1645. {
  1646. previewContainer.html(newMarkdownDoc);
  1647. this.previewCodeHighlight();
  1648. if (settings.toc)
  1649. {
  1650. var tocContainer = (settings.tocContainer === "") ? previewContainer : $(settings.tocContainer);
  1651. var tocMenu = tocContainer.find("." + this.classPrefix + "toc-menu");
  1652. tocContainer.attr("previewContainer", (settings.tocContainer === "") ? "true" : "false");
  1653. if (settings.tocContainer !== "" && tocMenu.length > 0)
  1654. {
  1655. tocMenu.remove();
  1656. }
  1657. editormd.markdownToCRenderer(markdownToC, tocContainer, settings.tocDropdown, settings.tocStartLevel);
  1658. if (settings.tocDropdown || tocContainer.find("." + this.classPrefix + "toc-menu").length > 0)
  1659. {
  1660. editormd.tocDropdownMenu(tocContainer, (settings.tocTitle !== "") ? settings.tocTitle : this.lang.tocTitle);
  1661. }
  1662. if (settings.tocContainer !== "")
  1663. {
  1664. previewContainer.find(".markdown-toc").css("border", "none");
  1665. }
  1666. }
  1667. if (settings.tex)
  1668. {
  1669. if (!editormd.kaTeXLoaded && settings.autoLoadModules)
  1670. {
  1671. editormd.loadKaTeX(function() {
  1672. editormd.$katex = katex;
  1673. editormd.kaTeXLoaded = true;
  1674. _this.katexRender();
  1675. });
  1676. }
  1677. else
  1678. {
  1679. editormd.$katex = katex;
  1680. this.katexRender();
  1681. }
  1682. }
  1683. if (settings.flowChart || settings.sequenceDiagram)
  1684. {
  1685. flowchartTimer = setTimeout(function(){
  1686. clearTimeout(flowchartTimer);
  1687. _this.flowChartAndSequenceDiagramRender();
  1688. flowchartTimer = null;
  1689. }, 10);
  1690. }
  1691. if (state.loaded)
  1692. {
  1693. $.proxy(settings.onchange, this)();
  1694. }
  1695. }
  1696. return this;
  1697. },
  1698. /**
  1699. * 聚焦光标位置
  1700. * Focusing the cursor position
  1701. *
  1702. * @returns {editormd} 返回editormd的实例对象
  1703. */
  1704. focus : function() {
  1705. this.cm.focus();
  1706. return this;
  1707. },
  1708. /**
  1709. * 设置光标的位置
  1710. * Set cursor position
  1711. *
  1712. * @param {Object} cursor 要设置的光标位置键值对象,例:{line:1, ch:0}
  1713. * @returns {editormd} 返回editormd的实例对象
  1714. */
  1715. setCursor : function(cursor) {
  1716. this.cm.setCursor(cursor);
  1717. return this;
  1718. },
  1719. /**
  1720. * 获取当前光标的位置
  1721. * Get the current position of the cursor
  1722. *
  1723. * @returns {Cursor} 返回一个光标Cursor对象
  1724. */
  1725. getCursor : function() {
  1726. return this.cm.getCursor();
  1727. },
  1728. /**
  1729. * 设置光标选中的范围
  1730. * Set cursor selected ranges
  1731. *
  1732. * @param {Object} from 开始位置的光标键值对象,例:{line:1, ch:0}
  1733. * @param {Object} to 结束位置的光标键值对象,例:{line:1, ch:0}
  1734. * @returns {editormd} 返回editormd的实例对象
  1735. */
  1736. setSelection : function(from, to) {
  1737. this.cm.setSelection(from, to);
  1738. return this;
  1739. },
  1740. /**
  1741. * 获取光标选中的文本
  1742. * Get the texts from cursor selected
  1743. *
  1744. * @returns {String} 返回选中文本的字符串形式
  1745. */
  1746. getSelection : function() {
  1747. return this.cm.getSelection();
  1748. },
  1749. /**
  1750. * 设置光标选中的文本范围
  1751. * Set the cursor selection ranges
  1752. *
  1753. * @param {Array} ranges cursor selection ranges array
  1754. * @returns {Array} return this
  1755. */
  1756. setSelections : function(ranges) {
  1757. this.cm.setSelections(ranges);
  1758. return this;
  1759. },
  1760. /**
  1761. * 获取光标选中的文本范围
  1762. * Get the cursor selection ranges
  1763. *
  1764. * @returns {Array} return selection ranges array
  1765. */
  1766. getSelections : function() {
  1767. return this.cm.getSelections();
  1768. },
  1769. /**
  1770. * 替换当前光标选中的文本或在当前光标处插入新字符
  1771. * Replace the text at the current cursor selected or insert a new character at the current cursor position
  1772. *
  1773. * @param {String} value 要插入的字符值
  1774. * @returns {editormd} 返回editormd的实例对象
  1775. */
  1776. replaceSelection : function(value) {
  1777. this.cm.replaceSelection(value);
  1778. return this;
  1779. },
  1780. /**
  1781. * 在当前光标处插入新字符
  1782. * Insert a new character at the current cursor position
  1783. *
  1784. * 同replaceSelection()方法
  1785. * With the replaceSelection() method
  1786. *
  1787. * @param {String} value 要插入的字符值
  1788. * @returns {editormd} 返回editormd的实例对象
  1789. */
  1790. insertValue : function(value) {
  1791. this.replaceSelection(value);
  1792. return this;
  1793. },
  1794. /**
  1795. * 追加markdown
  1796. * append Markdown to editor
  1797. *
  1798. * @param {String} md 要追加的markdown源文档
  1799. * @returns {editormd} 返回editormd的实例对象
  1800. */
  1801. appendMarkdown : function(md) {
  1802. var settings = this.settings;
  1803. var cm = this.cm;
  1804. cm.setValue(cm.getValue() + md);
  1805. return this;
  1806. },
  1807. /**
  1808. * 设置和传入编辑器的markdown源文档
  1809. * Set Markdown source document
  1810. *
  1811. * @param {String} md 要传入的markdown源文档
  1812. * @returns {editormd} 返回editormd的实例对象
  1813. */
  1814. setMarkdown : function(md) {
  1815. this.cm.setValue(md || this.settings.markdown);
  1816. return this;
  1817. },
  1818. /**
  1819. * 获取编辑器的markdown源文档
  1820. * Set Editor.md markdown/CodeMirror value
  1821. *
  1822. * @returns {editormd} 返回editormd的实例对象
  1823. */
  1824. getMarkdown : function() {
  1825. return this.cm.getValue();
  1826. },
  1827. /**
  1828. * 获取编辑器的源文档
  1829. * Get CodeMirror value
  1830. *
  1831. * @returns {editormd} 返回editormd的实例对象
  1832. */
  1833. getValue : function() {
  1834. return this.cm.getValue();
  1835. },
  1836. /**
  1837. * 设置编辑器的源文档
  1838. * Set CodeMirror value
  1839. *
  1840. * @param {String} value set code/value/string/text
  1841. * @returns {editormd} 返回editormd的实例对象
  1842. */
  1843. setValue : function(value) {
  1844. this.cm.setValue(value);
  1845. return this;
  1846. },
  1847. /**
  1848. * 清空编辑器
  1849. * Empty CodeMirror editor container
  1850. *
  1851. * @returns {editormd} 返回editormd的实例对象
  1852. */
  1853. clear : function() {
  1854. this.cm.setValue("");
  1855. return this;
  1856. },
  1857. /**
  1858. * 获取解析后存放在Textarea的HTML源码
  1859. * Get parsed html code from Textarea
  1860. *
  1861. * @returns {String} 返回HTML源码
  1862. */
  1863. getHTML : function() {
  1864. if (!this.settings.saveHTMLToTextarea)
  1865. {
  1866. alert("Error: settings.saveHTMLToTextarea == false");
  1867. return false;
  1868. }
  1869. return this.htmlTextarea.val();
  1870. },
  1871. /**
  1872. * getHTML()的别名
  1873. * getHTML (alias)
  1874. *
  1875. * @returns {String} Return html code 返回HTML源码
  1876. */
  1877. getTextareaSavedHTML : function() {
  1878. return this.getHTML();
  1879. },
  1880. /**
  1881. * 获取预览窗口的HTML源码
  1882. * Get html from preview container
  1883. *
  1884. * @returns {editormd} 返回editormd的实例对象
  1885. */
  1886. getPreviewedHTML : function() {
  1887. if (!this.settings.watch)
  1888. {
  1889. alert("Error: settings.watch == false");
  1890. return false;
  1891. }
  1892. return this.previewContainer.html();
  1893. },
  1894. /**
  1895. * 开启实时预览
  1896. * Enable real-time watching
  1897. *
  1898. * @returns {editormd} 返回editormd的实例对象
  1899. */
  1900. watch : function(callback) {
  1901. var settings = this.settings;
  1902. if ($.inArray(settings.mode, ["gfm", "markdown"]) < 0)
  1903. {
  1904. return this;
  1905. }
  1906. this.state.watching = settings.watch = true;
  1907. this.preview.show();
  1908. if (this.toolbar)
  1909. {
  1910. var watchIcon = settings.toolbarIconsClass.watch;
  1911. var unWatchIcon = settings.toolbarIconsClass.unwatch;
  1912. var icon = this.toolbar.find(".fa[name=watch]");
  1913. icon.parent().attr("title", settings.lang.toolbar.watch);
  1914. icon.removeClass(unWatchIcon).addClass(watchIcon);
  1915. }
  1916. this.codeMirror.css("border-right", "1px solid #ddd").width(this.editor.width() / 2);
  1917. timer = 0;
  1918. this.save().resize();
  1919. if (!settings.onwatch)
  1920. {
  1921. settings.onwatch = callback || function() {};
  1922. }
  1923. $.proxy(settings.onwatch, this)();
  1924. return this;
  1925. },
  1926. /**
  1927. * 关闭实时预览
  1928. * Disable real-time watching
  1929. *
  1930. * @returns {editormd} 返回editormd的实例对象
  1931. */
  1932. unwatch : function(callback) {
  1933. var settings = this.settings;
  1934. this.state.watching = settings.watch = false;
  1935. this.preview.hide();
  1936. if (this.toolbar)
  1937. {
  1938. var watchIcon = settings.toolbarIconsClass.watch;
  1939. var unWatchIcon = settings.toolbarIconsClass.unwatch;
  1940. var icon = this.toolbar.find(".fa[name=watch]");
  1941. icon.parent().attr("title", settings.lang.toolbar.unwatch);
  1942. icon.removeClass(watchIcon).addClass(unWatchIcon);
  1943. }
  1944. this.codeMirror.css("border-right", "none").width(this.editor.width());
  1945. this.resize();
  1946. if (!settings.onunwatch)
  1947. {
  1948. settings.onunwatch = callback || function() {};
  1949. }
  1950. $.proxy(settings.onunwatch, this)();
  1951. return this;
  1952. },
  1953. /**
  1954. * 显示编辑器
  1955. * Show editor
  1956. *
  1957. * @param {Function} [callback=function()] 回调函数
  1958. * @returns {editormd} 返回editormd的实例对象
  1959. */
  1960. show : function(callback) {
  1961. callback = callback || function() {};
  1962. var _this = this;
  1963. this.editor.show(0, function() {
  1964. $.proxy(callback, _this)();
  1965. });
  1966. return this;
  1967. },
  1968. /**
  1969. * 隐藏编辑器
  1970. * Hide editor
  1971. *
  1972. * @param {Function} [callback=function()] 回调函数
  1973. * @returns {editormd} 返回editormd的实例对象
  1974. */
  1975. hide : function(callback) {
  1976. callback = callback || function() {};
  1977. var _this = this;
  1978. this.editor.hide(0, function() {
  1979. $.proxy(callback, _this)();
  1980. });
  1981. return this;
  1982. },
  1983. /**
  1984. * 隐藏编辑器部分,只预览HTML
  1985. * Enter preview html state
  1986. *
  1987. * @returns {editormd} 返回editormd的实例对象
  1988. */
  1989. previewing : function() {
  1990. var _this = this;
  1991. var editor = this.editor;
  1992. var preview = this.preview;
  1993. var toolbar = this.toolbar;
  1994. var settings = this.settings;
  1995. var codeMirror = this.codeMirror;
  1996. var previewContainer = this.previewContainer;
  1997. if ($.inArray(settings.mode, ["gfm", "markdown"]) < 0) {
  1998. return this;
  1999. }
  2000. if (settings.toolbar && toolbar) {
  2001. toolbar.toggle();
  2002. toolbar.find(".fa[name=preview]").toggleClass("active");
  2003. }
  2004. codeMirror.toggle();
  2005. var escHandle = function(event) {
  2006. if (event.shiftKey && event.keyCode === 27) {
  2007. _this.previewed();
  2008. }
  2009. };
  2010. if (codeMirror.css("display") === "none") // 为了兼容Zepto,而不使用codeMirror.is(":hidden")
  2011. {
  2012. this.state.preview = true;
  2013. if (this.state.fullscreen) {
  2014. preview.css("background", "#fff");
  2015. }
  2016. editor.find("." + this.classPrefix + "preview-close-btn").show().bind(editormd.mouseOrTouch("click", "touchend"), function(){
  2017. _this.previewed();
  2018. });
  2019. if (!settings.watch)
  2020. {
  2021. this.save();
  2022. }
  2023. else
  2024. {
  2025. previewContainer.css("padding", "");
  2026. }
  2027. previewContainer.addClass(this.classPrefix + "preview-active");
  2028. preview.show().css({
  2029. position : "",
  2030. top : 0,
  2031. width : editor.width(),
  2032. height : (settings.autoHeight && !this.state.fullscreen) ? "auto" : editor.height()
  2033. });
  2034. if (this.state.loaded)
  2035. {
  2036. $.proxy(settings.onpreviewing, this)();
  2037. }
  2038. $(window).bind("keyup", escHandle);
  2039. }
  2040. else
  2041. {
  2042. $(window).unbind("keyup", escHandle);
  2043. this.previewed();
  2044. }
  2045. },
  2046. /**
  2047. * 显示编辑器部分,退出只预览HTML
  2048. * Exit preview html state
  2049. *
  2050. * @returns {editormd} 返回editormd的实例对象
  2051. */
  2052. previewed : function() {
  2053. var editor = this.editor;
  2054. var preview = this.preview;
  2055. var toolbar = this.toolbar;
  2056. var settings = this.settings;
  2057. var previewContainer = this.previewContainer;
  2058. var previewCloseBtn = editor.find("." + this.classPrefix + "preview-close-btn");
  2059. this.state.preview = false;
  2060. this.codeMirror.show();
  2061. if (settings.toolbar) {
  2062. toolbar.show();
  2063. }
  2064. preview[(settings.watch) ? "show" : "hide"]();
  2065. previewCloseBtn.hide().unbind(editormd.mouseOrTouch("click", "touchend"));
  2066. previewContainer.removeClass(this.classPrefix + "preview-active");
  2067. if (settings.watch)
  2068. {
  2069. previewContainer.css("padding", "20px");
  2070. }
  2071. preview.css({
  2072. background : null,
  2073. position : "absolute",
  2074. width : editor.width() / 2,
  2075. height : (settings.autoHeight && !this.state.fullscreen) ? "auto" : editor.height() - toolbar.height(),
  2076. top : (settings.toolbar) ? toolbar.height() : 0
  2077. });
  2078. if (this.state.loaded)
  2079. {
  2080. $.proxy(settings.onpreviewed, this)();
  2081. }
  2082. return this;
  2083. },
  2084. /**
  2085. * 编辑器全屏显示
  2086. * Fullscreen show
  2087. *
  2088. * @returns {editormd} 返回editormd的实例对象
  2089. */
  2090. fullscreen : function() {
  2091. var _this = this;
  2092. var state = this.state;
  2093. var editor = this.editor;
  2094. var preview = this.preview;
  2095. var toolbar = this.toolbar;
  2096. var settings = this.settings;
  2097. var fullscreenClass = this.classPrefix + "fullscreen";
  2098. if (toolbar) {
  2099. toolbar.find(".fa[name=fullscreen]").parent().toggleClass("active");
  2100. }
  2101. var escHandle = function(event) {
  2102. if (!event.shiftKey && event.keyCode === 27)
  2103. {
  2104. if (state.fullscreen)
  2105. {
  2106. _this.fullscreenExit();
  2107. }
  2108. }
  2109. };
  2110. if (!editor.hasClass(fullscreenClass))
  2111. {
  2112. state.fullscreen = true;
  2113. $("html,body").css("overflow", "hidden");
  2114. editor.css({
  2115. width : $(window).width(),
  2116. height : $(window).height()
  2117. }).addClass(fullscreenClass);
  2118. this.resize();
  2119. $.proxy(settings.onfullscreen, this)();
  2120. $(window).bind("keyup", escHandle);
  2121. }
  2122. else
  2123. {
  2124. $(window).unbind("keyup", escHandle);
  2125. this.fullscreenExit();
  2126. }
  2127. return this;
  2128. },
  2129. /**
  2130. * 编辑器退出全屏显示
  2131. * Exit fullscreen state
  2132. *
  2133. * @returns {editormd} 返回editormd的实例对象
  2134. */
  2135. fullscreenExit : function() {
  2136. var editor = this.editor;
  2137. var settings = this.settings;
  2138. var toolbar = this.toolbar;
  2139. var fullscreenClass = this.classPrefix + "fullscreen";
  2140. this.state.fullscreen = false;
  2141. if (toolbar) {
  2142. toolbar.find(".fa[name=fullscreen]").parent().removeClass("active");
  2143. }
  2144. $("html,body").css("overflow", "");
  2145. editor.css({
  2146. width : editor.data("oldWidth"),
  2147. height : editor.data("oldHeight")
  2148. }).removeClass(fullscreenClass);
  2149. this.resize();
  2150. $.proxy(settings.onfullscreenExit, this)();
  2151. return this;
  2152. },
  2153. /**
  2154. * 加载并执行插件
  2155. * Load and execute the plugin
  2156. *
  2157. * @param {String} name plugin name / function name
  2158. * @param {String} path plugin load path
  2159. * @returns {editormd} 返回editormd的实例对象
  2160. */
  2161. executePlugin : function(name, path) {
  2162. var _this = this;
  2163. var cm = this.cm;
  2164. var settings = this.settings;
  2165. path = settings.pluginPath + path;
  2166. if (typeof define === "function")
  2167. {
  2168. if (typeof this[name] === "undefined")
  2169. {
  2170. alert("Error: " + name + " plugin is not found, you are not load this plugin.");
  2171. return this;
  2172. }
  2173. this[name](cm);
  2174. return this;
  2175. }
  2176. if ($.inArray(path, editormd.loadFiles.plugin) < 0)
  2177. {
  2178. editormd.loadPlugin(path, function() {
  2179. editormd.loadPlugins[name] = _this[name];
  2180. _this[name](cm);
  2181. });
  2182. }
  2183. else
  2184. {
  2185. $.proxy(editormd.loadPlugins[name], this)(cm);
  2186. }
  2187. return this;
  2188. },
  2189. /**
  2190. * 搜索替换
  2191. * Search & replace
  2192. *
  2193. * @param {String} command CodeMirror serach commands, "find, fintNext, fintPrev, clearSearch, replace, replaceAll"
  2194. * @returns {editormd} return this
  2195. */
  2196. search : function(command) {
  2197. var settings = this.settings;
  2198. if (!settings.searchReplace)
  2199. {
  2200. alert("Error: settings.searchReplace == false");
  2201. return this;
  2202. }
  2203. if (!settings.readOnly)
  2204. {
  2205. this.cm.execCommand(command || "find");
  2206. }
  2207. return this;
  2208. },
  2209. searchReplace : function() {
  2210. this.search("replace");
  2211. return this;
  2212. },
  2213. searchReplaceAll : function() {
  2214. this.search("replaceAll");
  2215. return this;
  2216. }
  2217. };
  2218. editormd.fn.init.prototype = editormd.fn;
  2219. /**
  2220. * 锁屏
  2221. * lock screen when dialog opening
  2222. *
  2223. * @returns {void}
  2224. */
  2225. editormd.dialogLockScreen = function() {
  2226. var settings = this.settings || {dialogLockScreen : true};
  2227. if (settings.dialogLockScreen)
  2228. {
  2229. $("html,body").css("overflow", "hidden");
  2230. this.resize();
  2231. }
  2232. };
  2233. /**
  2234. * 显示透明背景层
  2235. * Display mask layer when dialog opening
  2236. *
  2237. * @param {Object} dialog dialog jQuery object
  2238. * @returns {void}
  2239. */
  2240. editormd.dialogShowMask = function(dialog) {
  2241. var editor = this.editor;
  2242. var settings = this.settings || {dialogShowMask : true};
  2243. dialog.css({
  2244. top : ($(window).height() - dialog.height()) / 2 + "px",
  2245. left : ($(window).width() - dialog.width()) / 2 + "px"
  2246. });
  2247. if (settings.dialogShowMask) {
  2248. editor.children("." + this.classPrefix + "mask").css("z-index", parseInt(dialog.css("z-index")) - 1).show();
  2249. }
  2250. };
  2251. editormd.toolbarHandlers = {
  2252. undo : function() {
  2253. this.cm.undo();
  2254. },
  2255. redo : function() {
  2256. this.cm.redo();
  2257. },
  2258. bold : function() {
  2259. var cm = this.cm;
  2260. var cursor = cm.getCursor();
  2261. var selection = cm.getSelection();
  2262. cm.replaceSelection("**" + selection + "**");
  2263. if(selection === "") {
  2264. cm.setCursor(cursor.line, cursor.ch + 2);
  2265. }
  2266. },
  2267. del : function() {
  2268. var cm = this.cm;
  2269. var cursor = cm.getCursor();
  2270. var selection = cm.getSelection();
  2271. cm.replaceSelection("~~" + selection + "~~");
  2272. if(selection === "") {
  2273. cm.setCursor(cursor.line, cursor.ch + 2);
  2274. }
  2275. },
  2276. italic : function() {
  2277. var cm = this.cm;
  2278. var cursor = cm.getCursor();
  2279. var selection = cm.getSelection();
  2280. cm.replaceSelection("*" + selection + "*");
  2281. if(selection === "") {
  2282. cm.setCursor(cursor.line, cursor.ch + 1);
  2283. }
  2284. },
  2285. quote : function() {
  2286. var cm = this.cm;
  2287. var cursor = cm.getCursor();
  2288. var selection = cm.getSelection();
  2289. if (cursor.ch !== 0)
  2290. {
  2291. cm.setCursor(cursor.line, 0);
  2292. cm.replaceSelection("> " + selection);
  2293. cm.setCursor(cursor.line, cursor.ch + 2);
  2294. }
  2295. else
  2296. {
  2297. cm.replaceSelection("> " + selection);
  2298. }
  2299. //cm.replaceSelection("> " + selection);
  2300. //cm.setCursor(cursor.line, (selection === "") ? cursor.ch + 2 : cursor.ch + selection.length + 2);
  2301. },
  2302. ucfirst : function() {
  2303. var cm = this.cm;
  2304. var selection = cm.getSelection();
  2305. var selections = cm.listSelections();
  2306. cm.replaceSelection(editormd.firstUpperCase(selection));
  2307. cm.setSelections(selections);
  2308. },
  2309. ucwords : function() {
  2310. var cm = this.cm;
  2311. var selection = cm.getSelection();
  2312. var selections = cm.listSelections();
  2313. cm.replaceSelection(editormd.wordsFirstUpperCase(selection));
  2314. cm.setSelections(selections);
  2315. },
  2316. uppercase : function() {
  2317. var cm = this.cm;
  2318. var selection = cm.getSelection();
  2319. var selections = cm.listSelections();
  2320. cm.replaceSelection(selection.toUpperCase());
  2321. cm.setSelections(selections);
  2322. },
  2323. lowercase : function() {
  2324. var cm = this.cm;
  2325. var cursor = cm.getCursor();
  2326. var selection = cm.getSelection();
  2327. var selections = cm.listSelections();
  2328. cm.replaceSelection(selection.toLowerCase());
  2329. cm.setSelections(selections);
  2330. },
  2331. h1 : function() {
  2332. var cm = this.cm;
  2333. var cursor = cm.getCursor();
  2334. var selection = cm.getSelection();
  2335. if (cursor.ch !== 0)
  2336. {
  2337. cm.setCursor(cursor.line, 0);
  2338. cm.replaceSelection("# " + selection);
  2339. cm.setCursor(cursor.line, cursor.ch + 2);
  2340. }
  2341. else
  2342. {
  2343. cm.replaceSelection("# " + selection);
  2344. }
  2345. },
  2346. h2 : function() {
  2347. var cm = this.cm;
  2348. var cursor = cm.getCursor();
  2349. var selection = cm.getSelection();
  2350. if (cursor.ch !== 0)
  2351. {
  2352. cm.setCursor(cursor.line, 0);
  2353. cm.replaceSelection("## " + selection);
  2354. cm.setCursor(cursor.line, cursor.ch + 3);
  2355. }
  2356. else
  2357. {
  2358. cm.replaceSelection("## " + selection);
  2359. }
  2360. },
  2361. h3 : function() {
  2362. var cm = this.cm;
  2363. var cursor = cm.getCursor();
  2364. var selection = cm.getSelection();
  2365. if (cursor.ch !== 0)
  2366. {
  2367. cm.setCursor(cursor.line, 0);
  2368. cm.replaceSelection("### " + selection);
  2369. cm.setCursor(cursor.line, cursor.ch + 4);
  2370. }
  2371. else
  2372. {
  2373. cm.replaceSelection("### " + selection);
  2374. }
  2375. },
  2376. h4 : function() {
  2377. var cm = this.cm;
  2378. var cursor = cm.getCursor();
  2379. var selection = cm.getSelection();
  2380. if (cursor.ch !== 0)
  2381. {
  2382. cm.setCursor(cursor.line, 0);
  2383. cm.replaceSelection("#### " + selection);
  2384. cm.setCursor(cursor.line, cursor.ch + 5);
  2385. }
  2386. else
  2387. {
  2388. cm.replaceSelection("#### " + selection);
  2389. }
  2390. },
  2391. h5 : function() {
  2392. var cm = this.cm;
  2393. var cursor = cm.getCursor();
  2394. var selection = cm.getSelection();
  2395. if (cursor.ch !== 0)
  2396. {
  2397. cm.setCursor(cursor.line, 0);
  2398. cm.replaceSelection("##### " + selection);
  2399. cm.setCursor(cursor.line, cursor.ch + 6);
  2400. }
  2401. else
  2402. {
  2403. cm.replaceSelection("##### " + selection);
  2404. }
  2405. },
  2406. h6 : function() {
  2407. var cm = this.cm;
  2408. var cursor = cm.getCursor();
  2409. var selection = cm.getSelection();
  2410. if (cursor.ch !== 0)
  2411. {
  2412. cm.setCursor(cursor.line, 0);
  2413. cm.replaceSelection("###### " + selection);
  2414. cm.setCursor(cursor.line, cursor.ch + 7);
  2415. }
  2416. else
  2417. {
  2418. cm.replaceSelection("###### " + selection);
  2419. }
  2420. },
  2421. "list-ul" : function() {
  2422. var cm = this.cm;
  2423. var cursor = cm.getCursor();
  2424. var selection = cm.getSelection();
  2425. if (selection === "")
  2426. {
  2427. cm.replaceSelection("- " + selection);
  2428. }
  2429. else
  2430. {
  2431. var selectionText = selection.split("\n");
  2432. for (var i = 0, len = selectionText.length; i < len; i++)
  2433. {
  2434. selectionText[i] = (selectionText[i] === "") ? "" : "- " + selectionText[i];
  2435. }
  2436. cm.replaceSelection(selectionText.join("\n"));
  2437. }
  2438. },
  2439. "list-ol" : function() {
  2440. var cm = this.cm;
  2441. var cursor = cm.getCursor();
  2442. var selection = cm.getSelection();
  2443. if(selection === "")
  2444. {
  2445. cm.replaceSelection("1. " + selection);
  2446. }
  2447. else
  2448. {
  2449. var selectionText = selection.split("\n");
  2450. for (var i = 0, len = selectionText.length; i < len; i++)
  2451. {
  2452. selectionText[i] = (selectionText[i] === "") ? "" : (i+1) + ". " + selectionText[i];
  2453. }
  2454. cm.replaceSelection(selectionText.join("\n"));
  2455. }
  2456. },
  2457. hr : function() {
  2458. var cm = this.cm;
  2459. var cursor = cm.getCursor();
  2460. var selection = cm.getSelection();
  2461. cm.replaceSelection(((cursor.ch !== 0) ? "\n\n" : "\n") + "------------\n\n");
  2462. },
  2463. tex : function() {
  2464. if (!this.settings.tex)
  2465. {
  2466. alert("settings.tex === false");
  2467. return this;
  2468. }
  2469. var cm = this.cm;
  2470. var cursor = cm.getCursor();
  2471. var selection = cm.getSelection();
  2472. cm.replaceSelection("$$" + selection + "$$");
  2473. if(selection === "") {
  2474. cm.setCursor(cursor.line, cursor.ch + 2);
  2475. }
  2476. },
  2477. link : function() {
  2478. this.executePlugin("linkDialog", "link-dialog/link-dialog");
  2479. },
  2480. "reference-link" : function() {
  2481. this.executePlugin("referenceLinkDialog", "reference-link-dialog/reference-link-dialog");
  2482. },
  2483. pagebreak : function() {
  2484. if (!this.settings.pageBreak)
  2485. {
  2486. alert("settings.pageBreak === false");
  2487. return this;
  2488. }
  2489. var cm = this.cm;
  2490. var selection = cm.getSelection();
  2491. cm.replaceSelection("\r\n[========]\r\n");
  2492. },
  2493. image : function() {
  2494. this.executePlugin("imageDialog", "image-dialog/image-dialog");
  2495. },
  2496. code : function() {
  2497. var cm = this.cm;
  2498. var cursor = cm.getCursor();
  2499. var selection = cm.getSelection();
  2500. cm.replaceSelection("`" + selection + "`");
  2501. if (selection === "") {
  2502. cm.setCursor(cursor.line, cursor.ch + 1);
  2503. }
  2504. },
  2505. "code-block" : function() {
  2506. this.executePlugin("codeBlockDialog", "code-block-dialog/code-block-dialog");
  2507. },
  2508. "preformatted-text" : function() {
  2509. this.executePlugin("preformattedTextDialog", "preformatted-text-dialog/preformatted-text-dialog");
  2510. },
  2511. table : function() {
  2512. this.executePlugin("tableDialog", "table-dialog/table-dialog");
  2513. },
  2514. datetime : function() {
  2515. var cm = this.cm;
  2516. var selection = cm.getSelection();
  2517. var date = new Date();
  2518. var langName = this.settings.lang.name;
  2519. var datefmt = editormd.dateFormat() + " " + editormd.dateFormat((langName === "zh-cn" || langName === "zh-tw") ? "cn-week-day" : "week-day");
  2520. cm.replaceSelection(datefmt);
  2521. },
  2522. emoji : function() {
  2523. this.executePlugin("emojiDialog", "emoji-dialog/emoji-dialog");
  2524. },
  2525. "html-entities" : function() {
  2526. this.executePlugin("htmlEntitiesDialog", "html-entities-dialog/html-entities-dialog");
  2527. },
  2528. "goto-line" : function() {
  2529. this.executePlugin("gotoLineDialog", "goto-line-dialog/goto-line-dialog");
  2530. },
  2531. watch : function() {
  2532. this[this.settings.watch ? "unwatch" : "watch"]();
  2533. },
  2534. preview : function() {
  2535. this.previewing();
  2536. },
  2537. fullscreen : function() {
  2538. this.fullscreen();
  2539. },
  2540. clear : function() {
  2541. this.clear();
  2542. },
  2543. search : function() {
  2544. this.search();
  2545. },
  2546. help : function() {
  2547. this.executePlugin("helpDialog", "help-dialog/help-dialog");
  2548. },
  2549. info : function() {
  2550. this.showInfoDialog();
  2551. }
  2552. };
  2553. editormd.keyMaps = {
  2554. "Ctrl-1" : "h1",
  2555. "Ctrl-2" : "h2",
  2556. "Ctrl-3" : "h3",
  2557. "Ctrl-4" : "h4",
  2558. "Ctrl-5" : "h5",
  2559. "Ctrl-6" : "h6",
  2560. "Ctrl-B" : "bold", // if this is string == editormd.toolbarHandlers.xxxx
  2561. "Ctrl-D" : "datetime",
  2562. "Ctrl-E" : function() { // emoji
  2563. var cm = this.cm;
  2564. var cursor = cm.getCursor();
  2565. var selection = cm.getSelection();
  2566. if (!this.settings.emoji)
  2567. {
  2568. alert("Error: settings.emoji == false");
  2569. return ;
  2570. }
  2571. cm.replaceSelection(":" + selection + ":");
  2572. if (selection === "") {
  2573. cm.setCursor(cursor.line, cursor.ch + 1);
  2574. }
  2575. },
  2576. "Ctrl-Alt-G" : "goto-line",
  2577. "Ctrl-H" : "hr",
  2578. "Ctrl-I" : "italic",
  2579. "Ctrl-K" : "code",
  2580. "Ctrl-L" : function() {
  2581. var cm = this.cm;
  2582. var cursor = cm.getCursor();
  2583. var selection = cm.getSelection();
  2584. var title = (selection === "") ? "" : " \""+selection+"\"";
  2585. cm.replaceSelection("[" + selection + "]("+title+")");
  2586. if (selection === "") {
  2587. cm.setCursor(cursor.line, cursor.ch + 1);
  2588. }
  2589. },
  2590. "Ctrl-U" : "list-ul",
  2591. "Shift-Ctrl-A" : function() {
  2592. var cm = this.cm;
  2593. var cursor = cm.getCursor();
  2594. var selection = cm.getSelection();
  2595. if (!this.settings.atLink)
  2596. {
  2597. alert("Error: settings.atLink == false");
  2598. return ;
  2599. }
  2600. cm.replaceSelection("@" + selection);
  2601. if (selection === "") {
  2602. cm.setCursor(cursor.line, cursor.ch + 1);
  2603. }
  2604. },
  2605. "Shift-Ctrl-C" : "code",
  2606. "Shift-Ctrl-Q" : "quote",
  2607. "Shift-Ctrl-S" : "del",
  2608. "Shift-Ctrl-K" : "tex", // KaTeX
  2609. "Shift-Alt-C" : function() {
  2610. var cm = this.cm;
  2611. var cursor = cm.getCursor();
  2612. var selection = cm.getSelection();
  2613. cm.replaceSelection(["```", selection, "```"].join("\n"));
  2614. if (selection === "") {
  2615. cm.setCursor(cursor.line, cursor.ch + 3);
  2616. }
  2617. },
  2618. "Shift-Ctrl-Alt-C" : "code-block",
  2619. "Shift-Ctrl-H" : "html-entities",
  2620. "Shift-Alt-H" : "help",
  2621. "Shift-Ctrl-E" : "emoji",
  2622. "Shift-Ctrl-U" : "uppercase",
  2623. "Shift-Alt-U" : "ucwords",
  2624. "Shift-Ctrl-Alt-U" : "ucfirst",
  2625. "Shift-Alt-L" : "lowercase",
  2626. "Shift-Ctrl-I" : function() {
  2627. var cm = this.cm;
  2628. var cursor = cm.getCursor();
  2629. var selection = cm.getSelection();
  2630. var title = (selection === "") ? "" : " \""+selection+"\"";
  2631. cm.replaceSelection("![" + selection + "]("+title+")");
  2632. if (selection === "") {
  2633. cm.setCursor(cursor.line, cursor.ch + 4);
  2634. }
  2635. },
  2636. "Shift-Ctrl-Alt-I" : "image",
  2637. "Shift-Ctrl-L" : "link",
  2638. "Shift-Ctrl-O" : "list-ol",
  2639. "Shift-Ctrl-P" : "preformatted-text",
  2640. "Shift-Ctrl-T" : "table",
  2641. "Shift-Alt-P" : "pagebreak",
  2642. "F9" : "watch",
  2643. "F10" : "preview",
  2644. "F11" : "fullscreen",
  2645. };
  2646. /**
  2647. * 清除字符串两边的空格
  2648. * Clear the space of strings both sides.
  2649. *
  2650. * @param {String} str string
  2651. * @returns {String} trimed string
  2652. */
  2653. var trim = function(str) {
  2654. return (!String.prototype.trim) ? str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "") : str.trim();
  2655. };
  2656. editormd.trim = trim;
  2657. /**
  2658. * 所有单词首字母大写
  2659. * Words first to uppercase
  2660. *
  2661. * @param {String} str string
  2662. * @returns {String} string
  2663. */
  2664. var ucwords = function (str) {
  2665. return str.toLowerCase().replace(/\b(\w)|\s(\w)/g, function($1) {
  2666. return $1.toUpperCase();
  2667. });
  2668. };
  2669. editormd.ucwords = editormd.wordsFirstUpperCase = ucwords;
  2670. /**
  2671. * 字符串首字母大写
  2672. * Only string first char to uppercase
  2673. *
  2674. * @param {String} str string
  2675. * @returns {String} string
  2676. */
  2677. var firstUpperCase = function(str) {
  2678. return str.toLowerCase().replace(/\b(\w)/, function($1){
  2679. return $1.toUpperCase();
  2680. });
  2681. };
  2682. var ucfirst = firstUpperCase;
  2683. editormd.firstUpperCase = editormd.ucfirst = firstUpperCase;
  2684. editormd.urls = {
  2685. atLinkBase : "https://github.com/"
  2686. };
  2687. editormd.regexs = {
  2688. atLink : /@(\w+)/g,
  2689. email : /(\w+)@(\w+)\.(\w+)\.?(\w+)?/g,
  2690. emailLink : /(mailto:)?([\w\.\_]+)@(\w+)\.(\w+)\.?(\w+)?/g,
  2691. emoji : /:([\w\+-]+):/g,
  2692. emojiDatetime : /(\d{2}:\d{2}:\d{2})/g,
  2693. twemoji : /:(tw-([\w]+)-?(\w+)?):/g,
  2694. fontAwesome : /:(fa-([\w]+)(-(\w+)){0,}):/g,
  2695. editormdLogo : /:(editormd-logo-?(\w+)?):/g,
  2696. pageBreak : /^\[[=]{8,}\]$/
  2697. };
  2698. // Emoji graphics files url path
  2699. editormd.emoji = {
  2700. path : "http://www.emoji-cheat-sheet.com/graphics/emojis/",
  2701. ext : ".png"
  2702. };
  2703. // Twitter Emoji (Twemoji) graphics files url path
  2704. editormd.twemoji = {
  2705. path : "http://twemoji.maxcdn.com/36x36/",
  2706. ext : ".png"
  2707. };
  2708. /**
  2709. * 自定义marked的解析器
  2710. * Custom Marked renderer rules
  2711. *
  2712. * @param {Array} markdownToC 传入用于接收TOC的数组
  2713. * @returns {Renderer} markedRenderer 返回marked的Renderer自定义对象
  2714. */
  2715. editormd.markedRenderer = function(markdownToC, options) {
  2716. var defaults = {
  2717. toc : true, // Table of contents
  2718. tocm : false,
  2719. tocStartLevel : 1, // Said from H1 to create ToC
  2720. pageBreak : true,
  2721. atLink : true, // for @link
  2722. emailLink : true, // for mail address auto link
  2723. taskList : false, // Enable Github Flavored Markdown task lists
  2724. emoji : false, // :emoji: , Support Twemoji, fontAwesome, Editor.md logo emojis.
  2725. tex : false, // TeX(LaTeX), based on KaTeX
  2726. flowChart : false, // flowChart.js only support IE9+
  2727. sequenceDiagram : false, // sequenceDiagram.js only support IE9+
  2728. };
  2729. var settings = $.extend(defaults, options || {});
  2730. var marked = editormd.$marked;
  2731. var markedRenderer = new marked.Renderer();
  2732. markdownToC = markdownToC || [];
  2733. var regexs = editormd.regexs;
  2734. var atLinkReg = regexs.atLink;
  2735. var emojiReg = regexs.emoji;
  2736. var emailReg = regexs.email;
  2737. var emailLinkReg = regexs.emailLink;
  2738. var twemojiReg = regexs.twemoji;
  2739. var faIconReg = regexs.fontAwesome;
  2740. var editormdLogoReg = regexs.editormdLogo;
  2741. var pageBreakReg = regexs.pageBreak;
  2742. markedRenderer.emoji = function(text) {
  2743. text = text.replace(editormd.regexs.emojiDatetime, function($1) {
  2744. return $1.replace(/:/g, "&#58;");
  2745. });
  2746. var matchs = text.match(emojiReg);
  2747. if (!matchs || !settings.emoji) {
  2748. return text;
  2749. }
  2750. for (var i = 0, len = matchs.length; i < len; i++)
  2751. {
  2752. if (matchs[i] === ":+1:") {
  2753. matchs[i] = ":\\+1:";
  2754. }
  2755. text = text.replace(new RegExp(matchs[i]), function($1, $2){
  2756. var faMatchs = $1.match(faIconReg);
  2757. var name = $1.replace(/:/g, "");
  2758. if (faMatchs)
  2759. {
  2760. for (var fa = 0, len1 = faMatchs.length; fa < len1; fa++)
  2761. {
  2762. var faName = faMatchs[fa].replace(/:/g, "");
  2763. return "<i class=\"fa " + faName + " fa-emoji\" title=\"" + faName.replace("fa-", "") + "\"></i>";
  2764. }
  2765. }
  2766. else
  2767. {
  2768. var emdlogoMathcs = $1.match(editormdLogoReg);
  2769. var twemojiMatchs = $1.match(twemojiReg);
  2770. if (emdlogoMathcs)
  2771. {
  2772. for (var x = 0, len2 = emdlogoMathcs.length; x < len2; x++)
  2773. {
  2774. var logoName = emdlogoMathcs[x].replace(/:/g, "");
  2775. return "<i class=\"" + logoName + "\" title=\"Editor.md logo (" + logoName + ")\"></i>";
  2776. }
  2777. }
  2778. else if (twemojiMatchs)
  2779. {
  2780. for (var t = 0, len3 = twemojiMatchs.length; t < len3; t++)
  2781. {
  2782. var twe = twemojiMatchs[t].replace(/:/g, "").replace("tw-", "");
  2783. return "<img src=\"" + editormd.twemoji.path + twe + editormd.twemoji.ext + "\" title=\"twemoji-" + twe + "\" alt=\"twemoji-" + twe + "\" class=\"emoji twemoji\" />";
  2784. }
  2785. }
  2786. else
  2787. {
  2788. var src = (name === "+1") ? "plus1" : name;
  2789. src = (src === "black_large_square") ? "black_square" : src;
  2790. src = (src === "moon") ? "waxing_gibbous_moon" : src;
  2791. return "<img src=\"" + editormd.emoji.path + src + editormd.emoji.ext + "\" class=\"emoji\" title=\"&#58;" + name + "&#58;\" alt=\"&#58;" + name + "&#58;\" />";
  2792. }
  2793. }
  2794. });
  2795. }
  2796. return text;
  2797. };
  2798. markedRenderer.atLink = function(text) {
  2799. if (atLinkReg.test(text))
  2800. {
  2801. if (settings.atLink)
  2802. {
  2803. text = text.replace(emailReg, function($1, $2, $3, $4) {
  2804. return $1.replace(/@/g, "_#_&#64;_#_");
  2805. });
  2806. text = text.replace(atLinkReg, function($1, $2) {
  2807. return "<a href=\"" + editormd.urls.atLinkBase + "" + $2 + "\" title=\"&#64;" + $2 + "\" class=\"at-link\">" + $1 + "</a>";
  2808. }).replace(/_#_&#64;_#_/g, "@");
  2809. }
  2810. if (settings.emailLink)
  2811. {
  2812. text = text.replace(emailLinkReg, function($1, $2, $3, $4, $5) {
  2813. return (!$2 && $.inArray($5, "jpg|jpeg|png|gif|webp|ico|icon|pdf".split("|")) < 0) ? "<a href=\"mailto:" + $1 + "\">"+$1+"</a>" : $1;
  2814. });
  2815. }
  2816. return text;
  2817. }
  2818. return text;
  2819. };
  2820. markedRenderer.link = function (href, title, text) {
  2821. if (this.options.sanitize) {
  2822. try {
  2823. var prot = decodeURIComponent(unescape(href)).replace(/[^\w:]/g,"").toLowerCase();
  2824. } catch(e) {
  2825. return "";
  2826. }
  2827. if (prot.indexOf("javascript:") === 0) {
  2828. return "";
  2829. }
  2830. }
  2831. var out = "<a href=\"" + href + "\"";
  2832. if (atLinkReg.test(title) || atLinkReg.test(text))
  2833. {
  2834. if (title)
  2835. {
  2836. out += " title=\"" + title.replace(/@/g, "&#64;");
  2837. }
  2838. return out + "\">" + text.replace(/@/g, "&#64;") + "</a>";
  2839. }
  2840. if (title) {
  2841. out += " title=\"" + title + "\"";
  2842. }
  2843. out += ">" + text + "</a>";
  2844. return out;
  2845. };
  2846. markedRenderer.heading = function(text, level, raw) {
  2847. var linkText = text;
  2848. var hasLinkReg = /\s*\<a\s*href\=\"(.*)\"\s*([^\>]*)\>(.*)\<\/a\>\s*/;
  2849. var getLinkTextReg = /\s*\<a\s*([^\>]+)\>([^\>]*)\<\/a\>\s*/g;
  2850. if (hasLinkReg.test(text))
  2851. {
  2852. var tempText = [];
  2853. text = text.split(/\<a\s*([^\>]+)\>([^\>]*)\<\/a\>/);
  2854. for (var i = 0, len = text.length; i < len; i++)
  2855. {
  2856. tempText.push(text[i].replace(/\s*href\=\"(.*)\"\s*/g, ""));
  2857. }
  2858. text = tempText.join(" ");
  2859. }
  2860. text = trim(text);
  2861. var escapedText = text.toLowerCase().replace(/[^\w]+/g, "-");
  2862. var toc = {
  2863. text : text,
  2864. level : level,
  2865. slug : escapedText
  2866. };
  2867. var isChinese = /^[\u4e00-\u9fa5]+$/.test(text);
  2868. var id = (isChinese) ? escape(text).replace(/\%/g, "") : text.toLowerCase().replace(/[^\w]+/g, "-");
  2869. markdownToC.push(toc);
  2870. var headingHTML = "<h" + level + " id=\"h"+ level + "-" + this.options.headerPrefix + id +"\">";
  2871. headingHTML += "<a name=\"" + text + "\" class=\"reference-link\"></a>";
  2872. headingHTML += "<span class=\"header-link octicon octicon-link\"></span>";
  2873. headingHTML += (hasLinkReg) ? this.atLink(this.emoji(linkText)) : this.atLink(this.emoji(text));
  2874. headingHTML += "</h" + level + ">";
  2875. return headingHTML;
  2876. };
  2877. markedRenderer.pageBreak = function(text) {
  2878. if (pageBreakReg.test(text) && settings.pageBreak)
  2879. {
  2880. text = "<hr style=\"page-break-after:always;\" class=\"page-break editormd-page-break\" />";
  2881. }
  2882. return text;
  2883. };
  2884. markedRenderer.paragraph = function(text) {
  2885. var isTeXInline = /\$\$(.*)\$\$/g.test(text);
  2886. var isTeXLine = /^\$\$(.*)\$\$$/.test(text);
  2887. var isTeXAddClass = (isTeXLine) ? " class=\"" + editormd.classNames.tex + "\"" : "";
  2888. var isToC = (settings.tocm) ? /^(\[TOC\]|\[TOCM\])$/.test(text) : /^\[TOC\]$/.test(text);
  2889. var isToCMenu = /^\[TOCM\]$/.test(text);
  2890. if (!isTeXLine && isTeXInline)
  2891. {
  2892. text = text.replace(/(\$\$([^\$]*)\$\$)+/g, function($1, $2) {
  2893. return "<span class=\"" + editormd.classNames.tex + "\">" + $2.replace(/\$/g, "") + "</span>";
  2894. });
  2895. }
  2896. else
  2897. {
  2898. text = (isTeXLine) ? text.replace(/\$/g, "") : text;
  2899. }
  2900. var tocHTML = "<div class=\"markdown-toc editormd-markdown-toc\">" + text + "</div>";
  2901. return (isToC) ? ( (isToCMenu) ? "<div class=\"editormd-toc-menu\">" + tocHTML + "</div><br/>" : tocHTML )
  2902. : ( (pageBreakReg.test(text)) ? this.pageBreak(text) : "<p" + isTeXAddClass + ">" + this.atLink(this.emoji(text)) + "</p>\n" );
  2903. };
  2904. markedRenderer.code = function (code, lang, escaped) {
  2905. if (lang === "seq" || lang === "sequence")
  2906. {
  2907. return "<div class=\"sequence-diagram\">" + code + "</div>";
  2908. }
  2909. else if ( lang === "flow")
  2910. {
  2911. return "<div class=\"flowchart\">" + code + "</div>";
  2912. }
  2913. else if ( lang === "math" || lang === "latex" || lang === "katex")
  2914. {
  2915. return "<p class=\"" + editormd.classNames.tex + "\">" + code + "</p>";
  2916. }
  2917. else
  2918. {
  2919. return marked.Renderer.prototype.code.apply(this, arguments);
  2920. }
  2921. };
  2922. markedRenderer.tablecell = function(content, flags) {
  2923. var type = (flags.header) ? "th" : "td";
  2924. var tag = (flags.align) ? "<" + type +" style=\"text-align:" + flags.align + "\">" : "<" + type + ">";
  2925. return tag + this.atLink(this.emoji(content)) + "</" + type + ">\n";
  2926. };
  2927. markedRenderer.listitem = function(text) {
  2928. if (settings.taskList && /^\s*\[[x\s]\]\s*/.test(text))
  2929. {
  2930. text = text.replace(/^\s*\[\s\]\s*/, "<input type=\"checkbox\" class=\"task-list-item-checkbox\" /> ")
  2931. .replace(/^\s*\[x\]\s*/, "<input type=\"checkbox\" class=\"task-list-item-checkbox\" checked disabled /> ");
  2932. return "<li style=\"list-style: none;\">" + this.atLink(this.emoji(text)) + "</li>";
  2933. }
  2934. else
  2935. {
  2936. return "<li>" + this.atLink(this.emoji(text)) + "</li>";
  2937. }
  2938. };
  2939. return markedRenderer;
  2940. };
  2941. /**
  2942. *
  2943. * 生成TOC(Table of Contents)
  2944. * Creating ToC (Table of Contents)
  2945. *
  2946. * @param {Array} toc 从marked获取的TOC数组列表
  2947. * @param {Element} container 插入TOC的容器元素
  2948. * @param {Integer} startLevel Hx 起始层级
  2949. * @returns {Object} tocContainer 返回ToC列表容器层的jQuery对象元素
  2950. */
  2951. editormd.markdownToCRenderer = function(toc, container, tocDropdown, startLevel) {
  2952. var html = "";
  2953. var lastLevel = 0;
  2954. var classPrefix = this.classPrefix;
  2955. startLevel = startLevel || 1;
  2956. for (var i = 0, len = toc.length; i < len; i++)
  2957. {
  2958. var text = toc[i].text;
  2959. var level = toc[i].level;
  2960. if (level < startLevel) {
  2961. continue;
  2962. }
  2963. if (level > lastLevel)
  2964. {
  2965. html += "";
  2966. }
  2967. else if (level < lastLevel)
  2968. {
  2969. html += (new Array(lastLevel - level + 2)).join("</ul></li>");
  2970. }
  2971. else
  2972. {
  2973. html += "</ul></li>";
  2974. }
  2975. html += "<li><a class=\"toc-level-" + level + "\" href=\"#" + text + "\" level=\"" + level + "\">" + text + "</a><ul>";
  2976. lastLevel = level;
  2977. }
  2978. var tocContainer = container.find(".markdown-toc");
  2979. if ((tocContainer.length < 1 && container.attr("previewContainer") === "false"))
  2980. {
  2981. var tocHTML = "<div class=\"markdown-toc " + classPrefix + "markdown-toc\"></div>";
  2982. tocHTML = (tocDropdown) ? "<div class=\"" + classPrefix + "toc-menu\">" + tocHTML + "</div>" : tocHTML;
  2983. container.html(tocHTML);
  2984. tocContainer = container.find(".markdown-toc");
  2985. }
  2986. if (tocDropdown)
  2987. {
  2988. tocContainer.wrap("<div class=\"" + classPrefix + "toc-menu\"></div><br/>");
  2989. }
  2990. tocContainer.html("<ul class=\"markdown-toc-list\"></ul>").children(".markdown-toc-list").html(html.replace(/\r?\n?\<ul\>\<\/ul\>/g, ""));
  2991. return tocContainer;
  2992. };
  2993. /**
  2994. *
  2995. * 生成TOC下拉菜单
  2996. * Creating ToC dropdown menu
  2997. *
  2998. * @param {Object} container 插入TOC的容器jQuery对象元素
  2999. * @param {String} tocTitle ToC title
  3000. * @returns {Object} return toc-menu object
  3001. */
  3002. editormd.tocDropdownMenu = function(container, tocTitle) {
  3003. tocTitle = tocTitle || "Table of Contents";
  3004. var zindex = 400;
  3005. var tocMenus = container.find("." + this.classPrefix + "toc-menu");
  3006. tocMenus.each(function() {
  3007. var $this = $(this);
  3008. var toc = $this.children(".markdown-toc");
  3009. var icon = "<i class=\"fa fa-angle-down\"></i>";
  3010. var btn = "<a href=\"javascript:;\" class=\"toc-menu-btn\">" + icon + tocTitle + "</a>";
  3011. var menu = toc.children("ul");
  3012. var list = menu.find("li");
  3013. toc.append(btn);
  3014. list.first().before("<li><h1>" + tocTitle + " " + icon + "</h1></li>");
  3015. $this.mouseover(function(){
  3016. menu.show();
  3017. list.each(function(){
  3018. var li = $(this);
  3019. var ul = li.children("ul");
  3020. if (ul.html() === "")
  3021. {
  3022. ul.remove();
  3023. }
  3024. if (ul.length > 0 && ul.html() !== "")
  3025. {
  3026. var firstA = li.children("a").first();
  3027. if (firstA.children(".fa").length < 1)
  3028. {
  3029. firstA.append( $(icon).css({ float:"right", paddingTop:"4px" }) );
  3030. }
  3031. }
  3032. li.mouseover(function(){
  3033. ul.css("z-index", zindex).show();
  3034. zindex += 1;
  3035. }).mouseleave(function(){
  3036. ul.hide();
  3037. });
  3038. });
  3039. }).mouseleave(function(){
  3040. menu.hide();
  3041. });
  3042. });
  3043. return tocMenus;
  3044. };
  3045. /**
  3046. * 简单地过滤指定的HTML标签
  3047. * Filter custom html tags
  3048. *
  3049. * @param {String} html 要过滤HTML
  3050. * @param {String} filters 要过滤的标签
  3051. * @returns {String} html 返回过滤的HTML
  3052. */
  3053. editormd.filterHTMLTags = function(html, filters) {
  3054. if (typeof html !== "string") {
  3055. html = new String(html);
  3056. }
  3057. if (typeof filters !== "string") {
  3058. return html;
  3059. }
  3060. var expression = filters.split("|");
  3061. var filterTags = expression[0].split(",");
  3062. var attrs = expression[1];
  3063. for (var i = 0, len = filterTags.length; i < len; i++)
  3064. {
  3065. var tag = filterTags[i];
  3066. html = html.replace(new RegExp("\<\s*" + tag + "\s*([^\>]*)\>([^\>]*)\<\s*\/" + tag + "\s*\>", "igm"), "");
  3067. }
  3068. //return html;
  3069. if (typeof attrs !== "undefined")
  3070. {
  3071. var htmlTagRegex = /\<(\w+)\s*([^\>]*)\>([^\>]*)\<\/(\w+)\>/ig;
  3072. if (attrs === "*")
  3073. {
  3074. html = html.replace(htmlTagRegex, function($1, $2, $3, $4, $5) {
  3075. return "<" + $2 + ">" + $4 + "</" + $5 + ">";
  3076. });
  3077. }
  3078. else if (attrs === "on*")
  3079. {
  3080. html = html.replace(htmlTagRegex, function($1, $2, $3, $4, $5) {
  3081. var el = $("<" + $2 + ">" + $4 + "</" + $5 + ">");
  3082. var _attrs = $($1)[0].attributes;
  3083. var $attrs = {};
  3084. $.each(_attrs, function(i, e) {
  3085. if (e.nodeName !== '"') $attrs[e.nodeName] = e.nodeValue;
  3086. });
  3087. $.each($attrs, function(i) {
  3088. if (i.indexOf("on") === 0) {
  3089. delete $attrs[i];
  3090. }
  3091. });
  3092. el.attr($attrs);
  3093. var text = (typeof el[1] !== "undefined") ? $(el[1]).text() : "";
  3094. return el[0].outerHTML + text;
  3095. });
  3096. }
  3097. else
  3098. {
  3099. html = html.replace(htmlTagRegex, function($1, $2, $3, $4) {
  3100. var filterAttrs = attrs.split(",");
  3101. var el = $($1);
  3102. el.html($4);
  3103. $.each(filterAttrs, function(i) {
  3104. el.attr(filterAttrs[i], null);
  3105. });
  3106. return el[0].outerHTML;
  3107. });
  3108. }
  3109. }
  3110. return html;
  3111. };
  3112. /**
  3113. * 将Markdown文档解析为HTML用于前台显示
  3114. * Parse Markdown to HTML for Font-end preview.
  3115. *
  3116. * @param {String} id 用于显示HTML的对象ID
  3117. * @param {Object} [options={}] 配置选项,可选
  3118. * @returns {Object} div 返回jQuery对象元素
  3119. */
  3120. editormd.markdownToHTML = function(id, options) {
  3121. var defaults = {
  3122. gfm : true,
  3123. toc : true,
  3124. tocm : false,
  3125. tocStartLevel : 1,
  3126. tocTitle : "目录",
  3127. tocDropdown : false,
  3128. tocContainer : "",
  3129. markdown : "",
  3130. markdownSourceCode : false,
  3131. htmlDecode : false,
  3132. autoLoadKaTeX : true,
  3133. pageBreak : true,
  3134. atLink : true, // for @link
  3135. emailLink : true, // for mail address auto link
  3136. tex : false,
  3137. taskList : false, // Github Flavored Markdown task lists
  3138. emoji : false,
  3139. flowChart : false,
  3140. sequenceDiagram : false,
  3141. previewCodeHighlight : true
  3142. };
  3143. editormd.$marked = marked;
  3144. var div = $("#" + id);
  3145. var settings = div.settings = $.extend(true, defaults, options || {});
  3146. var saveTo = div.find("textarea");
  3147. if (saveTo.length < 1)
  3148. {
  3149. div.append("<textarea></textarea>");
  3150. saveTo = div.find("textarea");
  3151. }
  3152. var markdownDoc = (settings.markdown === "") ? saveTo.val() : settings.markdown;
  3153. var markdownToC = [];
  3154. var rendererOptions = {
  3155. toc : settings.toc,
  3156. tocm : settings.tocm,
  3157. tocStartLevel : settings.tocStartLevel,
  3158. taskList : settings.taskList,
  3159. emoji : settings.emoji,
  3160. tex : settings.tex,
  3161. pageBreak : settings.pageBreak,
  3162. atLink : settings.atLink, // for @link
  3163. emailLink : settings.emailLink, // for mail address auto link
  3164. flowChart : settings.flowChart,
  3165. sequenceDiagram : settings.sequenceDiagram,
  3166. previewCodeHighlight : settings.previewCodeHighlight,
  3167. };
  3168. var markedOptions = {
  3169. renderer : editormd.markedRenderer(markdownToC, rendererOptions),
  3170. gfm : settings.gfm,
  3171. tables : true,
  3172. breaks : true,
  3173. pedantic : false,
  3174. sanitize : (settings.htmlDecode) ? false : true, // 是否忽略HTML标签,即是否开启HTML标签解析,为了安全性,默认不开启
  3175. smartLists : true,
  3176. smartypants : true
  3177. };
  3178. markdownDoc = new String(markdownDoc);
  3179. var markdownParsed = marked(markdownDoc, markedOptions);
  3180. markdownParsed = editormd.filterHTMLTags(markdownParsed, settings.htmlDecode);
  3181. if (settings.markdownSourceCode) {
  3182. saveTo.text(markdownDoc);
  3183. } else {
  3184. saveTo.remove();
  3185. }
  3186. div.addClass("markdown-body " + this.classPrefix + "html-preview").append(markdownParsed);
  3187. var tocContainer = (settings.tocContainer !== "") ? $(settings.tocContainer) : div;
  3188. if (settings.tocContainer !== "")
  3189. {
  3190. tocContainer.attr("previewContainer", false);
  3191. }
  3192. if (settings.toc)
  3193. {
  3194. div.tocContainer = this.markdownToCRenderer(markdownToC, tocContainer, settings.tocDropdown, settings.tocStartLevel);
  3195. if (settings.tocDropdown || div.find("." + this.classPrefix + "toc-menu").length > 0)
  3196. {
  3197. this.tocDropdownMenu(div, settings.tocTitle);
  3198. }
  3199. if (settings.tocContainer !== "")
  3200. {
  3201. div.find(".editormd-toc-menu, .editormd-markdown-toc").remove();
  3202. }
  3203. }
  3204. if (settings.previewCodeHighlight)
  3205. {
  3206. div.find("pre").addClass("prettyprint linenums");
  3207. prettyPrint();
  3208. }
  3209. if (!editormd.isIE8)
  3210. {
  3211. if (settings.flowChart) {
  3212. div.find(".flowchart").flowChart();
  3213. }
  3214. if (settings.sequenceDiagram) {
  3215. div.find(".sequence-diagram").sequenceDiagram({theme: "simple"});
  3216. }
  3217. }
  3218. if (settings.tex)
  3219. {
  3220. var katexHandle = function() {
  3221. div.find("." + editormd.classNames.tex).each(function(){
  3222. var tex = $(this);
  3223. katex.render(tex.html().replace(/&lt;/g, "<").replace(/&gt;/g, ">"), tex[0]);
  3224. tex.find(".katex").css("font-size", "1.6em");
  3225. });
  3226. };
  3227. if (settings.autoLoadKaTeX && !editormd.$katex && !editormd.kaTeXLoaded)
  3228. {
  3229. this.loadKaTeX(function() {
  3230. editormd.$katex = katex;
  3231. editormd.kaTeXLoaded = true;
  3232. katexHandle();
  3233. });
  3234. }
  3235. else
  3236. {
  3237. katexHandle();
  3238. }
  3239. }
  3240. div.getMarkdown = function() {
  3241. return saveTo.val();
  3242. };
  3243. return div;
  3244. };
  3245. // Editor.md themes, change toolbar themes etc.
  3246. // added @1.5.0
  3247. editormd.themes = ["default", "dark"];
  3248. // Preview area themes
  3249. // added @1.5.0
  3250. editormd.previewThemes = ["default", "dark"];
  3251. // CodeMirror / editor area themes
  3252. // @1.5.0 rename -> editorThemes, old version -> themes
  3253. editormd.editorThemes = [
  3254. "default", "3024-day", "3024-night",
  3255. "ambiance", "ambiance-mobile",
  3256. "base16-dark", "base16-light", "blackboard",
  3257. "cobalt",
  3258. "eclipse", "elegant", "erlang-dark",
  3259. "lesser-dark",
  3260. "mbo", "mdn-like", "midnight", "monokai",
  3261. "neat", "neo", "night",
  3262. "paraiso-dark", "paraiso-light", "pastel-on-dark",
  3263. "rubyblue",
  3264. "solarized",
  3265. "the-matrix", "tomorrow-night-eighties", "twilight",
  3266. "vibrant-ink",
  3267. "xq-dark", "xq-light"
  3268. ];
  3269. editormd.loadPlugins = {};
  3270. editormd.loadFiles = {
  3271. js : [],
  3272. css : [],
  3273. plugin : []
  3274. };
  3275. /**
  3276. * 动态加载Editor.md插件,但不立即执行
  3277. * Load editor.md plugins
  3278. *
  3279. * @param {String} fileName 插件文件路径
  3280. * @param {Function} [callback=function()] 加载成功后执行的回调函数
  3281. * @param {String} [into="head"] 嵌入页面的位置
  3282. */
  3283. editormd.loadPlugin = function(fileName, callback, into) {
  3284. callback = callback || function() {};
  3285. this.loadScript(fileName, function() {
  3286. editormd.loadFiles.plugin.push(fileName);
  3287. callback();
  3288. }, into);
  3289. };
  3290. /**
  3291. * 动态加载CSS文件的方法
  3292. * Load css file method
  3293. *
  3294. * @param {String} fileName CSS文件名
  3295. * @param {Function} [callback=function()] 加载成功后执行的回调函数
  3296. * @param {String} [into="head"] 嵌入页面的位置
  3297. */
  3298. editormd.loadCSS = function(fileName, callback, into) {
  3299. into = into || "head";
  3300. callback = callback || function() {};
  3301. var css = document.createElement("link");
  3302. css.type = "text/css";
  3303. css.rel = "stylesheet";
  3304. css.onload = css.onreadystatechange = function() {
  3305. editormd.loadFiles.css.push(fileName);
  3306. callback();
  3307. };
  3308. css.href = fileName + ".css";
  3309. if(into === "head") {
  3310. document.getElementsByTagName("head")[0].appendChild(css);
  3311. } else {
  3312. document.body.appendChild(css);
  3313. }
  3314. };
  3315. editormd.isIE = (navigator.appName == "Microsoft Internet Explorer");
  3316. editormd.isIE8 = (editormd.isIE && navigator.appVersion.match(/8./i) == "8.");
  3317. /**
  3318. * 动态加载JS文件的方法
  3319. * Load javascript file method
  3320. *
  3321. * @param {String} fileName JS文件名
  3322. * @param {Function} [callback=function()] 加载成功后执行的回调函数
  3323. * @param {String} [into="head"] 嵌入页面的位置
  3324. */
  3325. editormd.loadScript = function(fileName, callback, into) {
  3326. into = into || "head";
  3327. callback = callback || function() {};
  3328. var script = null;
  3329. script = document.createElement("script");
  3330. script.id = fileName.replace(/[\./]+/g, "-");
  3331. script.type = "text/javascript";
  3332. script.src = fileName + ".js";
  3333. if (editormd.isIE8)
  3334. {
  3335. script.onreadystatechange = function() {
  3336. if(script.readyState)
  3337. {
  3338. if (script.readyState === "loaded" || script.readyState === "complete")
  3339. {
  3340. script.onreadystatechange = null;
  3341. editormd.loadFiles.js.push(fileName);
  3342. callback();
  3343. }
  3344. }
  3345. };
  3346. }
  3347. else
  3348. {
  3349. script.onload = function() {
  3350. editormd.loadFiles.js.push(fileName);
  3351. callback();
  3352. };
  3353. }
  3354. if (into === "head") {
  3355. document.getElementsByTagName("head")[0].appendChild(script);
  3356. } else {
  3357. document.body.appendChild(script);
  3358. }
  3359. };
  3360. // 使用国外的CDN,加载速度有时会很慢,或者自定义URL
  3361. // You can custom KaTeX load url.
  3362. editormd.katexURL = {
  3363. css : "//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min",
  3364. js : "//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min"
  3365. };
  3366. editormd.kaTeXLoaded = false;
  3367. /**
  3368. * 加载KaTeX文件
  3369. * load KaTeX files
  3370. *
  3371. * @param {Function} [callback=function()] 加载成功后执行的回调函数
  3372. */
  3373. editormd.loadKaTeX = function (callback) {
  3374. editormd.loadCSS(editormd.katexURL.css, function(){
  3375. editormd.loadScript(editormd.katexURL.js, callback || function(){});
  3376. });
  3377. };
  3378. /**
  3379. * 锁屏
  3380. * lock screen
  3381. *
  3382. * @param {Boolean} lock Boolean 布尔值,是否锁屏
  3383. * @returns {void}
  3384. */
  3385. editormd.lockScreen = function(lock) {
  3386. $("html,body").css("overflow", (lock) ? "hidden" : "");
  3387. };
  3388. /**
  3389. * 动态创建对话框
  3390. * Creating custom dialogs
  3391. *
  3392. * @param {Object} options 配置项键值对 Key/Value
  3393. * @returns {dialog} 返回创建的dialog的jQuery实例对象
  3394. */
  3395. editormd.createDialog = function(options) {
  3396. var defaults = {
  3397. name : "",
  3398. width : 420,
  3399. height: 240,
  3400. title : "",
  3401. drag : true,
  3402. closed : true,
  3403. content : "",
  3404. mask : true,
  3405. maskStyle : {
  3406. backgroundColor : "#fff",
  3407. opacity : 0.1
  3408. },
  3409. lockScreen : true,
  3410. footer : true,
  3411. buttons : false
  3412. };
  3413. options = $.extend(true, defaults, options);
  3414. var $this = this;
  3415. var editor = this.editor;
  3416. var classPrefix = editormd.classPrefix;
  3417. var guid = (new Date()).getTime();
  3418. var dialogName = ( (options.name === "") ? classPrefix + "dialog-" + guid : options.name);
  3419. var mouseOrTouch = editormd.mouseOrTouch;
  3420. var html = "<div class=\"" + classPrefix + "dialog " + dialogName + "\">";
  3421. if (options.title !== "")
  3422. {
  3423. html += "<div class=\"" + classPrefix + "dialog-header\"" + ( (options.drag) ? " style=\"cursor: move;\"" : "" ) + ">";
  3424. html += "<strong class=\"" + classPrefix + "dialog-title\">" + options.title + "</strong>";
  3425. html += "</div>";
  3426. }
  3427. if (options.closed)
  3428. {
  3429. html += "<a href=\"javascript:;\" class=\"fa fa-close " + classPrefix + "dialog-close\"></a>";
  3430. }
  3431. html += "<div class=\"" + classPrefix + "dialog-container\">" + options.content;
  3432. if (options.footer || typeof options.footer === "string")
  3433. {
  3434. html += "<div class=\"" + classPrefix + "dialog-footer\">" + ( (typeof options.footer === "boolean") ? "" : options.footer) + "</div>";
  3435. }
  3436. html += "</div>";
  3437. html += "<div class=\"" + classPrefix + "dialog-mask " + classPrefix + "dialog-mask-bg\"></div>";
  3438. html += "<div class=\"" + classPrefix + "dialog-mask " + classPrefix + "dialog-mask-con\"></div>";
  3439. html += "</div>";
  3440. editor.append(html);
  3441. var dialog = editor.find("." + dialogName);
  3442. dialog.lockScreen = function(lock) {
  3443. if (options.lockScreen)
  3444. {
  3445. $("html,body").css("overflow", (lock) ? "hidden" : "");
  3446. $this.resize();
  3447. }
  3448. return dialog;
  3449. };
  3450. dialog.showMask = function() {
  3451. if (options.mask)
  3452. {
  3453. editor.find("." + classPrefix + "mask").css(options.maskStyle).css("z-index", editormd.dialogZindex - 1).show();
  3454. }
  3455. return dialog;
  3456. };
  3457. dialog.hideMask = function() {
  3458. if (options.mask)
  3459. {
  3460. editor.find("." + classPrefix + "mask").hide();
  3461. }
  3462. return dialog;
  3463. };
  3464. dialog.loading = function(show) {
  3465. var loading = dialog.find("." + classPrefix + "dialog-mask");
  3466. loading[(show) ? "show" : "hide"]();
  3467. return dialog;
  3468. };
  3469. dialog.lockScreen(true).showMask();
  3470. dialog.show().css({
  3471. zIndex : editormd.dialogZindex,
  3472. border : (editormd.isIE8) ? "1px solid #ddd" : "",
  3473. width : (typeof options.width === "number") ? options.width + "px" : options.width,
  3474. height : (typeof options.height === "number") ? options.height + "px" : options.height
  3475. });
  3476. var dialogPosition = function(){
  3477. dialog.css({
  3478. top : ($(window).height() - dialog.height()) / 2 + "px",
  3479. left : ($(window).width() - dialog.width()) / 2 + "px"
  3480. });
  3481. };
  3482. dialogPosition();
  3483. $(window).resize(dialogPosition);
  3484. dialog.children("." + classPrefix + "dialog-close").bind(mouseOrTouch("click", "touchend"), function() {
  3485. dialog.hide().lockScreen(false).hideMask();
  3486. });
  3487. if (typeof options.buttons === "object")
  3488. {
  3489. var footer = dialog.footer = dialog.find("." + classPrefix + "dialog-footer");
  3490. for (var key in options.buttons)
  3491. {
  3492. var btn = options.buttons[key];
  3493. var btnClassName = classPrefix + key + "-btn";
  3494. footer.append("<button class=\"" + classPrefix + "btn " + btnClassName + "\">" + btn[0] + "</button>");
  3495. btn[1] = $.proxy(btn[1], dialog);
  3496. footer.children("." + btnClassName).bind(mouseOrTouch("click", "touchend"), btn[1]);
  3497. }
  3498. }
  3499. if (options.title !== "" && options.drag)
  3500. {
  3501. var posX, posY;
  3502. var dialogHeader = dialog.children("." + classPrefix + "dialog-header");
  3503. if (!options.mask) {
  3504. dialogHeader.bind(mouseOrTouch("click", "touchend"), function(){
  3505. editormd.dialogZindex += 2;
  3506. dialog.css("z-index", editormd.dialogZindex);
  3507. });
  3508. }
  3509. dialogHeader.mousedown(function(e) {
  3510. e = e || window.event; //IE
  3511. posX = e.clientX - parseInt(dialog[0].style.left);
  3512. posY = e.clientY - parseInt(dialog[0].style.top);
  3513. document.onmousemove = moveAction;
  3514. });
  3515. var userCanSelect = function (obj) {
  3516. obj.removeClass(classPrefix + "user-unselect").off("selectstart");
  3517. };
  3518. var userUnselect = function (obj) {
  3519. obj.addClass(classPrefix + "user-unselect").on("selectstart", function(event) { // selectstart for IE
  3520. return false;
  3521. });
  3522. };
  3523. var moveAction = function (e) {
  3524. e = e || window.event; //IE
  3525. var left, top, nowLeft = parseInt(dialog[0].style.left), nowTop = parseInt(dialog[0].style.top);
  3526. if( nowLeft >= 0 ) {
  3527. if( nowLeft + dialog.width() <= $(window).width()) {
  3528. left = e.clientX - posX;
  3529. } else {
  3530. left = $(window).width() - dialog.width();
  3531. document.onmousemove = null;
  3532. }
  3533. } else {
  3534. left = 0;
  3535. document.onmousemove = null;
  3536. }
  3537. if( nowTop >= 0 ) {
  3538. top = e.clientY - posY;
  3539. } else {
  3540. top = 0;
  3541. document.onmousemove = null;
  3542. }
  3543. document.onselectstart = function() {
  3544. return false;
  3545. };
  3546. userUnselect($("body"));
  3547. userUnselect(dialog);
  3548. dialog[0].style.left = left + "px";
  3549. dialog[0].style.top = top + "px";
  3550. };
  3551. document.onmouseup = function() {
  3552. userCanSelect($("body"));
  3553. userCanSelect(dialog);
  3554. document.onselectstart = null;
  3555. document.onmousemove = null;
  3556. };
  3557. dialogHeader.touchDraggable = function() {
  3558. var offset = null;
  3559. var start = function(e) {
  3560. var orig = e.originalEvent;
  3561. var pos = $(this).parent().position();
  3562. offset = {
  3563. x : orig.changedTouches[0].pageX - pos.left,
  3564. y : orig.changedTouches[0].pageY - pos.top
  3565. };
  3566. };
  3567. var move = function(e) {
  3568. e.preventDefault();
  3569. var orig = e.originalEvent;
  3570. $(this).parent().css({
  3571. top : orig.changedTouches[0].pageY - offset.y,
  3572. left : orig.changedTouches[0].pageX - offset.x
  3573. });
  3574. };
  3575. this.bind("touchstart", start).bind("touchmove", move);
  3576. };
  3577. dialogHeader.touchDraggable();
  3578. }
  3579. editormd.dialogZindex += 2;
  3580. return dialog;
  3581. };
  3582. /**
  3583. * 鼠标和触摸事件的判断/选择方法
  3584. * MouseEvent or TouchEvent type switch
  3585. *
  3586. * @param {String} [mouseEventType="click"] 供选择的鼠标事件
  3587. * @param {String} [touchEventType="touchend"] 供选择的触摸事件
  3588. * @returns {String} EventType 返回事件类型名称
  3589. */
  3590. editormd.mouseOrTouch = function(mouseEventType, touchEventType) {
  3591. mouseEventType = mouseEventType || "click";
  3592. touchEventType = touchEventType || "touchend";
  3593. var eventType = mouseEventType;
  3594. try {
  3595. document.createEvent("TouchEvent");
  3596. eventType = touchEventType;
  3597. } catch(e) {}
  3598. return eventType;
  3599. };
  3600. /**
  3601. * 日期时间的格式化方法
  3602. * Datetime format method
  3603. *
  3604. * @param {String} [format=""] 日期时间的格式,类似PHP的格式
  3605. * @returns {String} datefmt 返回格式化后的日期时间字符串
  3606. */
  3607. editormd.dateFormat = function(format) {
  3608. format = format || "";
  3609. var addZero = function(d) {
  3610. return (d < 10) ? "0" + d : d;
  3611. };
  3612. var date = new Date();
  3613. var year = date.getFullYear();
  3614. var year2 = year.toString().slice(2, 4);
  3615. var month = addZero(date.getMonth() + 1);
  3616. var day = addZero(date.getDate());
  3617. var weekDay = date.getDay();
  3618. var hour = addZero(date.getHours());
  3619. var min = addZero(date.getMinutes());
  3620. var second = addZero(date.getSeconds());
  3621. var ms = addZero(date.getMilliseconds());
  3622. var datefmt = "";
  3623. var ymd = year2 + "-" + month + "-" + day;
  3624. var fymd = year + "-" + month + "-" + day;
  3625. var hms = hour + ":" + min + ":" + second;
  3626. switch (format)
  3627. {
  3628. case "UNIX Time" :
  3629. datefmt = date.getTime();
  3630. break;
  3631. case "UTC" :
  3632. datefmt = date.toUTCString();
  3633. break;
  3634. case "yy" :
  3635. datefmt = year2;
  3636. break;
  3637. case "year" :
  3638. case "yyyy" :
  3639. datefmt = year;
  3640. break;
  3641. case "month" :
  3642. case "mm" :
  3643. datefmt = month;
  3644. break;
  3645. case "cn-week-day" :
  3646. case "cn-wd" :
  3647. var cnWeekDays = ["日", "一", "二", "三", "四", "五", "六"];
  3648. datefmt = "星期" + cnWeekDays[weekDay];
  3649. break;
  3650. case "week-day" :
  3651. case "wd" :
  3652. var weekDays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
  3653. datefmt = weekDays[weekDay];
  3654. break;
  3655. case "day" :
  3656. case "dd" :
  3657. datefmt = day;
  3658. break;
  3659. case "hour" :
  3660. case "hh" :
  3661. datefmt = hour;
  3662. break;
  3663. case "min" :
  3664. case "ii" :
  3665. datefmt = min;
  3666. break;
  3667. case "second" :
  3668. case "ss" :
  3669. datefmt = second;
  3670. break;
  3671. case "ms" :
  3672. datefmt = ms;
  3673. break;
  3674. case "yy-mm-dd" :
  3675. datefmt = ymd;
  3676. break;
  3677. case "yyyy-mm-dd" :
  3678. datefmt = fymd;
  3679. break;
  3680. case "yyyy-mm-dd h:i:s ms" :
  3681. case "full + ms" :
  3682. datefmt = fymd + " " + hms + " " + ms;
  3683. break;
  3684. case "full" :
  3685. case "yyyy-mm-dd h:i:s" :
  3686. default:
  3687. datefmt = fymd + " " + hms;
  3688. break;
  3689. }
  3690. return datefmt;
  3691. };
  3692. return editormd;
  3693. }));