editormd.js 154 KB

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