editormd.js 157 KB

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