editormd.js 155 KB

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