editormd.js 155 KB

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