editormd.amd.js 158 KB

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