org.el 950 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2016 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: http://orgmode.org
  9. ;;
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  22. ;;
  23. ;;; Commentary:
  24. ;;
  25. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  26. ;; project planning with a fast and effective plain-text system.
  27. ;;
  28. ;; Org mode develops organizational tasks around NOTES files that
  29. ;; contain information about projects as plain text. Org mode is
  30. ;; implemented on top of outline-mode, which makes it possible to keep
  31. ;; the content of large files well structured. Visibility cycling and
  32. ;; structure editing help to work with the tree. Tables are easily
  33. ;; created with a built-in table editor. Org mode supports ToDo
  34. ;; items, deadlines, time stamps, and scheduling. It dynamically
  35. ;; compiles entries into an agenda that utilizes and smoothly
  36. ;; integrates much of the Emacs calendar and diary. Plain text
  37. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  38. ;; entries, and any files related to the projects. For printing and
  39. ;; sharing of notes, an Org file can be exported as a structured ASCII
  40. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  41. ;; file. It can also serve as a publishing tool for a set of linked
  42. ;; webpages.
  43. ;;
  44. ;; Installation and Activation
  45. ;; ---------------------------
  46. ;; See the corresponding sections in the manual at
  47. ;;
  48. ;; http://orgmode.org/org.html#Installation
  49. ;;
  50. ;; Documentation
  51. ;; -------------
  52. ;; The documentation of Org mode can be found in the TeXInfo file. The
  53. ;; distribution also contains a PDF version of it. At the homepage of
  54. ;; Org mode, you can read the same text online as HTML. There is also an
  55. ;; excellent reference card made by Philip Rooke. This card can be found
  56. ;; in the doc/ directory.
  57. ;;
  58. ;; A list of recent changes can be found at
  59. ;; http://orgmode.org/Changes.html
  60. ;;
  61. ;;; Code:
  62. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  63. (defvar-local org-table-formula-constants-local nil
  64. "Local version of `org-table-formula-constants'.")
  65. ;;;; Require other packages
  66. (require 'cl-lib)
  67. (eval-when-compile (require 'gnus-sum))
  68. (require 'calendar)
  69. (require 'find-func)
  70. (require 'format-spec)
  71. (or (eq this-command 'eval-buffer)
  72. (condition-case nil
  73. (load (concat (file-name-directory load-file-name)
  74. "org-loaddefs.el")
  75. nil t t t)
  76. (error
  77. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  78. (sit-for 3)
  79. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  80. (sit-for 3))))
  81. (require 'org-macs)
  82. (require 'org-compat)
  83. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  84. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  85. ;;
  86. ;; In Org buffers, the value of `outline-regexp' is that of
  87. ;; `org-outline-regexp'. The only function still directly relying on
  88. ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
  89. ;; job when `orgstruct-mode' is active.
  90. (defvar org-outline-regexp "\\*+ "
  91. "Regexp to match Org headlines.")
  92. (defvar org-outline-regexp-bol "^\\*+ "
  93. "Regexp to match Org headlines.
  94. This is similar to `org-outline-regexp' but additionally makes
  95. sure that we are at the beginning of the line.")
  96. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  97. "Matches a headline, putting stars and text into groups.
  98. Stars are put in group 1 and the trimmed body in group 2.")
  99. (declare-function calendar-check-holidays "holidays" (date))
  100. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  101. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  102. (declare-function org-add-archive-files "org-archive" (files))
  103. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  104. (declare-function org-agenda-list "org-agenda"
  105. (&optional arg start-day span with-hour))
  106. (declare-function org-agenda-redo "org-agenda" (&optional all))
  107. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  108. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  109. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  110. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  111. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  112. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  113. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  114. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  115. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  116. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  117. (declare-function org-clock-update-time-maybe "org-clock" ())
  118. (declare-function org-clocktable-shift "org-clock" (dir n))
  119. (declare-function org-element-at-point "org-element" ())
  120. (declare-function org-element-cache-refresh "org-element" (pos))
  121. (declare-function org-element-cache-reset "org-element" (&optional all))
  122. (declare-function org-element-contents "org-element" (element))
  123. (declare-function org-element-context "org-element" (&optional element))
  124. (declare-function org-element-copy "org-element" (datum))
  125. (declare-function org-element-interpret-data "org-element" (data))
  126. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  127. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  128. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  129. (declare-function org-element-property "org-element" (property element))
  130. (declare-function org-element-put-property "org-element" (element property value))
  131. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  132. (declare-function org-element-type "org-element" (element))
  133. (declare-function org-element-update-syntax "org-element" ())
  134. (declare-function org-id-find-id-file "org-id" (id))
  135. (declare-function org-id-get-create "org-id" (&optional force))
  136. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  137. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  138. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  139. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  140. (declare-function org-table-align "org-table" ())
  141. (declare-function org-table-begin "org-table" (&optional table-type))
  142. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  143. (declare-function org-table-blank-field "org-table" ())
  144. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  145. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  146. (declare-function org-table-cut-region "org-table" (beg end))
  147. (declare-function org-table-edit-field "org-table" (arg))
  148. (declare-function org-table-end "org-table" (&optional table-type))
  149. (declare-function org-table-end-of-field "org-table" (&optional n))
  150. (declare-function org-table-insert-row "org-table" (&optional arg))
  151. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  152. (declare-function org-table-maybe-eval-formula "org-table" ())
  153. (declare-function org-table-maybe-recalculate-line "org-table" ())
  154. (declare-function org-table-next-row "org-table" ())
  155. (declare-function org-table-paste-rectangle "org-table" ())
  156. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  157. (declare-function org-table-wrap-region "org-table" (arg))
  158. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  159. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  160. (declare-function orgtbl-mode "org-table" (&optional arg))
  161. (defsubst org-uniquify (list)
  162. "Non-destructively remove duplicate elements from LIST."
  163. (let ((res (copy-sequence list))) (delete-dups res)))
  164. (defsubst org-get-at-bol (property)
  165. "Get text property PROPERTY at the beginning of line."
  166. (get-text-property (point-at-bol) property))
  167. (defsubst org-trim (s &optional keep-lead)
  168. "Remove whitespace at the beginning and the end of string S.
  169. When optional argument KEEP-LEAD is non-nil, removing blank lines
  170. at the beginning of the string does not affect leading indentation."
  171. (replace-regexp-in-string
  172. (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
  173. (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
  174. ;; load languages based on value of `org-babel-load-languages'
  175. (defvar org-babel-load-languages)
  176. ;;;###autoload
  177. (defun org-babel-do-load-languages (sym value)
  178. "Load the languages defined in `org-babel-load-languages'."
  179. (set-default sym value)
  180. (dolist (pair org-babel-load-languages)
  181. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  182. (if active
  183. (require (intern (concat "ob-" lang)))
  184. (funcall 'fmakunbound
  185. (intern (concat "org-babel-execute:" lang)))
  186. (funcall 'fmakunbound
  187. (intern (concat "org-babel-expand-body:" lang)))))))
  188. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  189. ;;;###autoload
  190. (defun org-babel-load-file (file &optional compile)
  191. "Load Emacs Lisp source code blocks in the Org FILE.
  192. This function exports the source code using `org-babel-tangle'
  193. and then loads the resulting file using `load-file'. With prefix
  194. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  195. file to byte-code before it is loaded."
  196. (interactive "fFile to load: \nP")
  197. (let* ((age (lambda (file)
  198. (float-time
  199. (time-subtract (current-time)
  200. (nth 5 (or (file-attributes (file-truename file))
  201. (file-attributes file)))))))
  202. (base-name (file-name-sans-extension file))
  203. (exported-file (concat base-name ".el")))
  204. ;; tangle if the Org file is newer than the elisp file
  205. (unless (and (file-exists-p exported-file)
  206. (> (funcall age file) (funcall age exported-file)))
  207. ;; Tangle-file traversal returns reversed list of tangled files
  208. ;; and we want to evaluate the first target.
  209. (setq exported-file
  210. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  211. (message "%s %s"
  212. (if compile
  213. (progn (byte-compile-file exported-file 'load)
  214. "Compiled and loaded")
  215. (progn (load-file exported-file) "Loaded"))
  216. exported-file)))
  217. (defcustom org-babel-load-languages '((emacs-lisp . t))
  218. "Languages which can be evaluated in Org buffers.
  219. This list can be used to load support for any of the languages
  220. below, note that each language will depend on a different set of
  221. system executables and/or Emacs modes. When a language is
  222. \"loaded\", then code blocks in that language can be evaluated
  223. with `org-babel-execute-src-block' bound by default to C-c
  224. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  225. be set to remove code block evaluation from the C-c C-c
  226. keybinding. By default only Emacs Lisp (which has no
  227. requirements) is loaded."
  228. :group 'org-babel
  229. :set 'org-babel-do-load-languages
  230. :version "24.1"
  231. :type '(alist :tag "Babel Languages"
  232. :key-type
  233. (choice
  234. (const :tag "Awk" awk)
  235. (const :tag "C" C)
  236. (const :tag "R" R)
  237. (const :tag "Asymptote" asymptote)
  238. (const :tag "Calc" calc)
  239. (const :tag "Clojure" clojure)
  240. (const :tag "CSS" css)
  241. (const :tag "Ditaa" ditaa)
  242. (const :tag "Dot" dot)
  243. (const :tag "Emacs Lisp" emacs-lisp)
  244. (const :tag "Forth" forth)
  245. (const :tag "Fortran" fortran)
  246. (const :tag "Gnuplot" gnuplot)
  247. (const :tag "Haskell" haskell)
  248. (const :tag "IO" io)
  249. (const :tag "J" J)
  250. (const :tag "Java" java)
  251. (const :tag "Javascript" js)
  252. (const :tag "LaTeX" latex)
  253. (const :tag "Ledger" ledger)
  254. (const :tag "Lilypond" lilypond)
  255. (const :tag "Lisp" lisp)
  256. (const :tag "Makefile" makefile)
  257. (const :tag "Maxima" maxima)
  258. (const :tag "Matlab" matlab)
  259. (const :tag "Mscgen" mscgen)
  260. (const :tag "Ocaml" ocaml)
  261. (const :tag "Octave" octave)
  262. (const :tag "Org" org)
  263. (const :tag "Perl" perl)
  264. (const :tag "Pico Lisp" picolisp)
  265. (const :tag "PlantUML" plantuml)
  266. (const :tag "Python" python)
  267. (const :tag "Ruby" ruby)
  268. (const :tag "Sass" sass)
  269. (const :tag "Scala" scala)
  270. (const :tag "Scheme" scheme)
  271. (const :tag "Screen" screen)
  272. (const :tag "Shell Script" shell)
  273. (const :tag "Shen" shen)
  274. (const :tag "Sql" sql)
  275. (const :tag "Sqlite" sqlite)
  276. (const :tag "Stan" stan)
  277. (const :tag "ebnf2ps" ebnf2ps))
  278. :value-type (boolean :tag "Activate" :value t)))
  279. ;;;; Customization variables
  280. (defcustom org-clone-delete-id nil
  281. "Remove ID property of clones of a subtree.
  282. When non-nil, clones of a subtree don't inherit the ID property.
  283. Otherwise they inherit the ID property with a new unique
  284. identifier."
  285. :type 'boolean
  286. :version "24.1"
  287. :group 'org-id)
  288. ;;; Version
  289. (org-check-version)
  290. ;;;###autoload
  291. (defun org-version (&optional here full message)
  292. "Show the Org version.
  293. Interactively, or when MESSAGE is non-nil, show it in echo area.
  294. With prefix argument, or when HERE is non-nil, insert it at point.
  295. In non-interactive uses, a reduced version string is output unless
  296. FULL is given."
  297. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  298. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  299. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  300. (load-suffixes (list ".el"))
  301. (org-install-dir
  302. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  303. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  304. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  305. (let* ((load-suffixes save-load-suffixes)
  306. (release (org-release))
  307. (git-version (org-git-version))
  308. (version (format "Org mode version %s (%s @ %s)"
  309. release
  310. git-version
  311. (if org-install-dir
  312. (if (string= org-dir org-install-dir)
  313. org-install-dir
  314. (concat "mixed installation! "
  315. org-install-dir
  316. " and "
  317. org-dir))
  318. "org-loaddefs.el can not be found!")))
  319. (version1 (if full version release)))
  320. (when here (insert version1))
  321. (when message (message "%s" version1))
  322. version1)))
  323. (defconst org-version (org-version))
  324. ;;; Syntax Constants
  325. ;;;; Block
  326. (defconst org-block-regexp
  327. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  328. "Regular expression for hiding blocks.")
  329. (defconst org-dblock-start-re
  330. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  331. "Matches the start line of a dynamic block, with parameters.")
  332. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  333. "Matches the end of a dynamic block.")
  334. ;;;; Clock and Planning
  335. (defconst org-clock-string "CLOCK:"
  336. "String used as prefix for timestamps clocking work hours on an item.")
  337. (defvar org-closed-string "CLOSED:"
  338. "String used as the prefix for timestamps logging closing a TODO entry.")
  339. (defvar org-deadline-string "DEADLINE:"
  340. "String to mark deadline entries.
  341. \\<org-mode-map>
  342. A deadline is this string, followed by a time stamp. It must be
  343. a word, terminated by a colon. You can insert a schedule keyword
  344. and a timestamp with `\\[org-deadline]'.")
  345. (defvar org-scheduled-string "SCHEDULED:"
  346. "String to mark scheduled TODO entries.
  347. \\<org-mode-map>
  348. A schedule is this string, followed by a time stamp. It must be
  349. a word, terminated by a colon. You can insert a schedule keyword
  350. and a timestamp with `\\[org-schedule]'.")
  351. (defconst org-ds-keyword-length
  352. (+ 2
  353. (apply #'max
  354. (mapcar #'length
  355. (list org-deadline-string org-scheduled-string
  356. org-clock-string org-closed-string))))
  357. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  358. (defconst org-planning-line-re
  359. (concat "^[ \t]*"
  360. (regexp-opt
  361. (list org-closed-string org-deadline-string org-scheduled-string)
  362. t))
  363. "Matches a line with planning info.
  364. Matched keyword is in group 1.")
  365. (defconst org-clock-line-re
  366. (concat "^[ \t]*" org-clock-string)
  367. "Matches a line with clock info.")
  368. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  369. "Matches the DEADLINE keyword.")
  370. (defconst org-deadline-time-regexp
  371. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  372. "Matches the DEADLINE keyword together with a time stamp.")
  373. (defconst org-deadline-time-hour-regexp
  374. (concat "\\<" org-deadline-string
  375. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  376. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  377. (defconst org-deadline-line-regexp
  378. (concat "\\<\\(" org-deadline-string "\\).*")
  379. "Matches the DEADLINE keyword and the rest of the line.")
  380. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  381. "Matches the SCHEDULED keyword.")
  382. (defconst org-scheduled-time-regexp
  383. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  384. "Matches the SCHEDULED keyword together with a time stamp.")
  385. (defconst org-scheduled-time-hour-regexp
  386. (concat "\\<" org-scheduled-string
  387. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  388. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  389. (defconst org-closed-time-regexp
  390. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  391. "Matches the CLOSED keyword together with a time stamp.")
  392. (defconst org-keyword-time-regexp
  393. (concat "\\<"
  394. (regexp-opt
  395. (list org-scheduled-string org-deadline-string org-closed-string
  396. org-clock-string)
  397. t)
  398. " *[[<]\\([^]>]+\\)[]>]")
  399. "Matches any of the 4 keywords, together with the time stamp.")
  400. (defconst org-keyword-time-not-clock-regexp
  401. (concat
  402. "\\<"
  403. (regexp-opt
  404. (list org-scheduled-string org-deadline-string org-closed-string) t)
  405. " *[[<]\\([^]>]+\\)[]>]")
  406. "Matches any of the 3 keywords, together with the time stamp.")
  407. (defconst org-maybe-keyword-time-regexp
  408. (concat "\\(\\<"
  409. (regexp-opt
  410. (list org-scheduled-string org-deadline-string org-closed-string
  411. org-clock-string)
  412. t)
  413. "\\)?"
  414. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  415. "\\|"
  416. "<%%([^\r\n>]*>\\)")
  417. "Matches a timestamp, possibly preceded by a keyword.")
  418. (defconst org-all-time-keywords
  419. (mapcar (lambda (w) (substring w 0 -1))
  420. (list org-scheduled-string org-deadline-string
  421. org-clock-string org-closed-string))
  422. "List of time keywords.")
  423. ;;;; Drawer
  424. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  425. "Matches first or last line of a hidden block.
  426. Group 1 contains drawer's name or \"END\".")
  427. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  428. "Regular expression matching the first line of a property drawer.")
  429. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  430. "Regular expression matching the last line of a property drawer.")
  431. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  432. "Regular expression matching the first line of a clock drawer.")
  433. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  434. "Regular expression matching the last line of a clock drawer.")
  435. (defconst org-property-drawer-re
  436. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  437. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  438. "[ \t]*:END:[ \t]*$")
  439. "Matches an entire property drawer.")
  440. (defconst org-clock-drawer-re
  441. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  442. org-clock-drawer-end-re "\\)\n?")
  443. "Matches an entire clock drawer.")
  444. ;;;; Headline
  445. (defconst org-heading-keyword-regexp-format
  446. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  447. "Printf format for a regexp matching a headline with some keyword.
  448. This regexp will match the headline of any node which has the
  449. exact keyword that is put into the format. The keyword isn't in
  450. any group by default, but the stars and the body are.")
  451. (defconst org-heading-keyword-maybe-regexp-format
  452. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  453. "Printf format for a regexp matching a headline, possibly with some keyword.
  454. This regexp can match any headline with the specified keyword, or
  455. without a keyword. The keyword isn't in any group by default,
  456. but the stars and the body are.")
  457. (defconst org-archive-tag "ARCHIVE"
  458. "The tag that marks a subtree as archived.
  459. An archived subtree does not open during visibility cycling, and does
  460. not contribute to the agenda listings.")
  461. (defconst org-comment-string "COMMENT"
  462. "Entries starting with this keyword will never be exported.
  463. \\<org-mode-map>
  464. An entry can be toggled between COMMENT and normal with
  465. `\\[org-toggle-comment]'.")
  466. ;;;; LaTeX Environments and Fragments
  467. (defconst org-latex-regexps
  468. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  469. ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
  470. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  471. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
  472. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
  473. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  474. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  475. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  476. "Regular expressions for matching embedded LaTeX.")
  477. ;;;; Node Property
  478. (defconst org-effort-property "Effort"
  479. "The property that is being used to keep track of effort estimates.
  480. Effort estimates given in this property need to have the format H:MM.")
  481. ;;;; Table
  482. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  483. "Detect an org-type or table-type table.")
  484. (defconst org-table-line-regexp "^[ \t]*|"
  485. "Detect an org-type table line.")
  486. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  487. "Detect an org-type table line.")
  488. (defconst org-table-hline-regexp "^[ \t]*|-"
  489. "Detect an org-type table hline.")
  490. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  491. "Detect a table-type table hline.")
  492. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  493. "Detect the first line outside a table when searching from within it.
  494. This works for both table types.")
  495. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  496. "Detect a #+TBLFM line.")
  497. ;;;; Timestamp
  498. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  499. "Regular expression for fast time stamp matching.")
  500. (defconst org-ts-regexp-inactive
  501. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  502. "Regular expression for fast inactive time stamp matching.")
  503. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  504. "Regular expression for fast time stamp matching.")
  505. (defconst org-ts-regexp0
  506. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  507. "Regular expression matching time strings for analysis.
  508. This one does not require the space after the date, so it can be used
  509. on a string that terminates immediately after the date.")
  510. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  511. "Regular expression matching time strings for analysis.")
  512. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  513. "Regular expression matching time stamps, with groups.")
  514. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  515. "Regular expression matching time stamps (also [..]), with groups.")
  516. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  517. "Regular expression matching a time stamp range.")
  518. (defconst org-tr-regexp-both
  519. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  520. "Regular expression matching a time stamp range.")
  521. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  522. org-ts-regexp "\\)?")
  523. "Regular expression matching a time stamp or time stamp range.")
  524. (defconst org-tsr-regexp-both
  525. (concat org-ts-regexp-both "\\(--?-?"
  526. org-ts-regexp-both "\\)?")
  527. "Regular expression matching a time stamp or time stamp range.
  528. The time stamps may be either active or inactive.")
  529. (defconst org-repeat-re
  530. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  531. "Regular expression for specifying repeated events.
  532. After a match, group 1 contains the repeat expression.")
  533. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  534. "Formats for `format-time-string' which are used for time stamps.")
  535. ;;; The custom variables
  536. (defgroup org nil
  537. "Outline-based notes management and organizer."
  538. :tag "Org"
  539. :group 'outlines
  540. :group 'calendar)
  541. (defcustom org-mode-hook nil
  542. "Mode hook for Org mode, run after the mode was turned on."
  543. :group 'org
  544. :type 'hook)
  545. (defcustom org-load-hook nil
  546. "Hook that is run after org.el has been loaded."
  547. :group 'org
  548. :type 'hook)
  549. (defcustom org-log-buffer-setup-hook nil
  550. "Hook that is run after an Org log buffer is created."
  551. :group 'org
  552. :version "24.1"
  553. :type 'hook)
  554. (defvar org-modules) ; defined below
  555. (defvar org-modules-loaded nil
  556. "Have the modules been loaded already?")
  557. (defun org-load-modules-maybe (&optional force)
  558. "Load all extensions listed in `org-modules'."
  559. (when (or force (not org-modules-loaded))
  560. (dolist (ext org-modules)
  561. (condition-case nil (require ext)
  562. (error (message "Problems while trying to load feature `%s'" ext))))
  563. (setq org-modules-loaded t)))
  564. (defun org-set-modules (var value)
  565. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  566. (set var value)
  567. (when (featurep 'org)
  568. (org-load-modules-maybe 'force)
  569. (org-element-cache-reset 'all)))
  570. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  571. "Modules that should always be loaded together with org.el.
  572. If a description starts with <C>, the file is not part of Emacs
  573. and loading it will require that you have downloaded and properly
  574. installed the Org mode distribution.
  575. You can also use this system to load external packages (i.e. neither Org
  576. core modules, nor modules from the CONTRIB directory). Just add symbols
  577. to the end of the list. If the package is called org-xyz.el, then you need
  578. to add the symbol `xyz', and the package must have a call to:
  579. (provide \\='org-xyz)
  580. For export specific modules, see also `org-export-backends'."
  581. :group 'org
  582. :set 'org-set-modules
  583. :version "24.4"
  584. :package-version '(Org . "8.0")
  585. :type
  586. '(set :greedy t
  587. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  588. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  589. (const :tag " crypt: Encryption of subtrees" org-crypt)
  590. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  591. (const :tag " docview: Links to doc-view buffers" org-docview)
  592. (const :tag " eww: Store link to url of eww" org-eww)
  593. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  594. (const :tag " habit: Track your consistency with habits" org-habit)
  595. (const :tag " id: Global IDs for identifying entries" org-id)
  596. (const :tag " info: Links to Info nodes" org-info)
  597. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  598. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  599. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  600. (const :tag " mouse: Additional mouse support" org-mouse)
  601. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  602. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  603. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  604. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  605. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  606. (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
  607. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  608. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  609. (const :tag "C collector: Collect properties into tables" org-collector)
  610. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  611. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  612. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  613. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  614. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  615. (const :tag "C eval: Include command output as text" org-eval)
  616. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  617. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  618. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  619. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  620. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  621. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  622. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  623. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  624. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  625. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  626. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  627. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  628. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  629. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  630. (const :tag "C registry: A registry for Org links" org-registry)
  631. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  632. (const :tag "C secretary: Team management with org-mode" org-secretary)
  633. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  634. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  635. (const :tag "C track: Keep up with Org mode development" org-track)
  636. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  637. (const :tag "C vm: Links to VM folders/messages" org-vm)
  638. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  639. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  640. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  641. (defvar org-export-registered-backends) ; From ox.el.
  642. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  643. (declare-function org-export-backend-name "ox" (backend) t)
  644. (defcustom org-export-backends '(ascii html icalendar latex odt)
  645. "List of export back-ends that should be always available.
  646. If a description starts with <C>, the file is not part of Emacs
  647. and loading it will require that you have downloaded and properly
  648. installed the Org mode distribution.
  649. Unlike to `org-modules', libraries in this list will not be
  650. loaded along with Org, but only once the export framework is
  651. needed.
  652. This variable needs to be set before org.el is loaded. If you
  653. need to make a change while Emacs is running, use the customize
  654. interface or run the following code, where VAL stands for the new
  655. value of the variable, after updating it:
  656. (progn
  657. (setq org-export-registered-backends
  658. (cl-remove-if-not
  659. (lambda (backend)
  660. (let ((name (org-export-backend-name backend)))
  661. (or (memq name val)
  662. (catch \\='parentp
  663. (dolist (b val)
  664. (and (org-export-derived-backend-p b name)
  665. (throw \\='parentp t)))))))
  666. org-export-registered-backends))
  667. (let ((new-list (mapcar #\\='org-export-backend-name
  668. org-export-registered-backends)))
  669. (dolist (backend val)
  670. (cond
  671. ((not (load (format \"ox-%s\" backend) t t))
  672. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  673. backend))
  674. ((not (memq backend new-list)) (push backend new-list))))
  675. (set-default \\='org-export-backends new-list)))
  676. Adding a back-end to this list will also pull the back-end it
  677. depends on, if any."
  678. :group 'org
  679. :group 'org-export
  680. :version "25.2"
  681. :package-version '(Org . "9.0")
  682. :initialize 'custom-initialize-set
  683. :set (lambda (var val)
  684. (if (not (featurep 'ox)) (set-default var val)
  685. ;; Any back-end not required anymore (not present in VAL and not
  686. ;; a parent of any back-end in the new value) is removed from the
  687. ;; list of registered back-ends.
  688. (setq org-export-registered-backends
  689. (cl-remove-if-not
  690. (lambda (backend)
  691. (let ((name (org-export-backend-name backend)))
  692. (or (memq name val)
  693. (catch 'parentp
  694. (dolist (b val)
  695. (and (org-export-derived-backend-p b name)
  696. (throw 'parentp t)))))))
  697. org-export-registered-backends))
  698. ;; Now build NEW-LIST of both new back-ends and required
  699. ;; parents.
  700. (let ((new-list (mapcar #'org-export-backend-name
  701. org-export-registered-backends)))
  702. (dolist (backend val)
  703. (cond
  704. ((not (load (format "ox-%s" backend) t t))
  705. (message "Problems while trying to load export back-end `%s'"
  706. backend))
  707. ((not (memq backend new-list)) (push backend new-list))))
  708. ;; Set VAR to that list with fixed dependencies.
  709. (set-default var new-list))))
  710. :type '(set :greedy t
  711. (const :tag " ascii Export buffer to ASCII format" ascii)
  712. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  713. (const :tag " html Export buffer to HTML format" html)
  714. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  715. (const :tag " latex Export buffer to LaTeX format" latex)
  716. (const :tag " man Export buffer to MAN format" man)
  717. (const :tag " md Export buffer to Markdown format" md)
  718. (const :tag " odt Export buffer to ODT format" odt)
  719. (const :tag " org Export buffer to Org format" org)
  720. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  721. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  722. (const :tag "C deck Export buffer to deck.js presentations" deck)
  723. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  724. (const :tag "C groff Export buffer to Groff format" groff)
  725. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  726. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  727. (const :tag "C s5 Export buffer to s5 presentations" s5)
  728. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  729. (eval-after-load 'ox
  730. '(dolist (backend org-export-backends)
  731. (condition-case nil (require (intern (format "ox-%s" backend)))
  732. (error (message "Problems while trying to load export back-end `%s'"
  733. backend)))))
  734. (defcustom org-support-shift-select nil
  735. "Non-nil means make shift-cursor commands select text when possible.
  736. \\<org-mode-map>\
  737. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  738. start selecting a region, or enlarge regions started in this way.
  739. In Org mode, in special contexts, these same keys are used for
  740. other purposes, important enough to compete with shift selection.
  741. Org tries to balance these needs by supporting `shift-select-mode'
  742. outside these special contexts, under control of this variable.
  743. The default of this variable is nil, to avoid confusing behavior. Shifted
  744. cursor keys will then execute Org commands in the following contexts:
  745. - on a headline, changing TODO state (left/right) and priority (up/down)
  746. - on a time stamp, changing the time
  747. - in a plain list item, changing the bullet type
  748. - in a property definition line, switching between allowed values
  749. - in the BEGIN line of a clock table (changing the time block).
  750. Outside these contexts, the commands will throw an error.
  751. When this variable is t and the cursor is not in a special
  752. context, Org mode will support shift-selection for making and
  753. enlarging regions. To make this more effective, the bullet
  754. cycling will no longer happen anywhere in an item line, but only
  755. if the cursor is exactly on the bullet.
  756. If you set this variable to the symbol `always', then the keys
  757. will not be special in headlines, property lines, and item lines,
  758. to make shift selection work there as well. If this is what you
  759. want, you can use the following alternative commands:
  760. `\\[org-todo]' and `\\[org-priority]' \
  761. to change TODO state and priority,
  762. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  763. can be used to switch TODO sets,
  764. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  765. and properties can be edited by hand or in column view.
  766. However, when the cursor is on a timestamp, shift-cursor commands
  767. will still edit the time stamp - this is just too good to give up."
  768. :group 'org
  769. :type '(choice
  770. (const :tag "Never" nil)
  771. (const :tag "When outside special context" t)
  772. (const :tag "Everywhere except timestamps" always)))
  773. (defcustom org-loop-over-headlines-in-active-region nil
  774. "Shall some commands act upon headlines in the active region?
  775. When set to t, some commands will be performed in all headlines
  776. within the active region.
  777. When set to `start-level', some commands will be performed in all
  778. headlines within the active region, provided that these headlines
  779. are of the same level than the first one.
  780. When set to a string, those commands will be performed on the
  781. matching headlines within the active region. Such string must be
  782. a tags/property/todo match as it is used in the agenda tags view.
  783. The list of commands is: `org-schedule', `org-deadline',
  784. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  785. `org-archive-to-archive-sibling'. The archiving commands skip
  786. already archived entries."
  787. :type '(choice (const :tag "Don't loop" nil)
  788. (const :tag "All headlines in active region" t)
  789. (const :tag "In active region, headlines at the same level than the first one" start-level)
  790. (string :tag "Tags/Property/Todo matcher"))
  791. :version "24.1"
  792. :group 'org-todo
  793. :group 'org-archive)
  794. (defgroup org-startup nil
  795. "Options concerning startup of Org mode."
  796. :tag "Org Startup"
  797. :group 'org)
  798. (defcustom org-startup-folded t
  799. "Non-nil means entering Org mode will switch to OVERVIEW.
  800. This can also be configured on a per-file basis by adding one of
  801. the following lines anywhere in the buffer:
  802. #+STARTUP: fold (or `overview', this is equivalent)
  803. #+STARTUP: nofold (or `showall', this is equivalent)
  804. #+STARTUP: content
  805. #+STARTUP: showeverything
  806. By default, this option is ignored when Org opens agenda files
  807. for the first time. If you want the agenda to honor the startup
  808. option, set `org-agenda-inhibit-startup' to nil."
  809. :group 'org-startup
  810. :type '(choice
  811. (const :tag "nofold: show all" nil)
  812. (const :tag "fold: overview" t)
  813. (const :tag "content: all headlines" content)
  814. (const :tag "show everything, even drawers" showeverything)))
  815. (defcustom org-startup-truncated t
  816. "Non-nil means entering Org mode will set `truncate-lines'.
  817. This is useful since some lines containing links can be very long and
  818. uninteresting. Also tables look terrible when wrapped.
  819. The variable `org-startup-truncated' allows to configure
  820. truncation for Org mode different to the other modes that use the
  821. variable `truncate-lines' and as a shortcut instead of putting
  822. the variable `truncate-lines' into the `org-mode-hook'. If one
  823. wants to configure truncation for Org mode not statically but
  824. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  825. the variable `truncate-lines' has to be used because in such a
  826. case it is too late to set the variable `org-startup-truncated'."
  827. :group 'org-startup
  828. :type 'boolean)
  829. (defcustom org-startup-indented nil
  830. "Non-nil means turn on `org-indent-mode' on startup.
  831. This can also be configured on a per-file basis by adding one of
  832. the following lines anywhere in the buffer:
  833. #+STARTUP: indent
  834. #+STARTUP: noindent"
  835. :group 'org-structure
  836. :type '(choice
  837. (const :tag "Not" nil)
  838. (const :tag "Globally (slow on startup in large files)" t)))
  839. (defcustom org-use-sub-superscripts t
  840. "Non-nil means interpret \"_\" and \"^\" for display.
  841. If you want to control how Org exports those characters, see
  842. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  843. used to be an alias for `org-export-with-sub-superscripts' in
  844. Org <8.0, it is not anymore.
  845. When this option is turned on, you can use TeX-like syntax for
  846. sub- and superscripts within the buffer. Several characters after
  847. \"_\" or \"^\" will be considered as a single item - so grouping
  848. with {} is normally not needed. For example, the following things
  849. will be parsed as single sub- or superscripts:
  850. 10^24 or 10^tau several digits will be considered 1 item.
  851. 10^-12 or 10^-tau a leading sign with digits or a word
  852. x^2-y^3 will be read as x^2 - y^3, because items are
  853. terminated by almost any nonword/nondigit char.
  854. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  855. Still, ambiguity is possible. So when in doubt, use {} to enclose
  856. the sub/superscript. If you set this variable to the symbol `{}',
  857. the braces are *required* in order to trigger interpretations as
  858. sub/superscript. This can be helpful in documents that need \"_\"
  859. frequently in plain text."
  860. :group 'org-startup
  861. :version "24.4"
  862. :package-version '(Org . "8.0")
  863. :type '(choice
  864. (const :tag "Always interpret" t)
  865. (const :tag "Only with braces" {})
  866. (const :tag "Never interpret" nil)))
  867. (defcustom org-startup-with-beamer-mode nil
  868. "Non-nil means turn on `org-beamer-mode' on startup.
  869. This can also be configured on a per-file basis by adding one of
  870. the following lines anywhere in the buffer:
  871. #+STARTUP: beamer"
  872. :group 'org-startup
  873. :version "24.1"
  874. :type 'boolean)
  875. (defcustom org-startup-align-all-tables nil
  876. "Non-nil means align all tables when visiting a file.
  877. This is useful when the column width in tables is forced with <N> cookies
  878. in table fields. Such tables will look correct only after the first re-align.
  879. This can also be configured on a per-file basis by adding one of
  880. the following lines anywhere in the buffer:
  881. #+STARTUP: align
  882. #+STARTUP: noalign"
  883. :group 'org-startup
  884. :type 'boolean)
  885. (defcustom org-startup-with-inline-images nil
  886. "Non-nil means show inline images when loading a new Org file.
  887. This can also be configured on a per-file basis by adding one of
  888. the following lines anywhere in the buffer:
  889. #+STARTUP: inlineimages
  890. #+STARTUP: noinlineimages"
  891. :group 'org-startup
  892. :version "24.1"
  893. :type 'boolean)
  894. (defcustom org-startup-with-latex-preview nil
  895. "Non-nil means preview LaTeX fragments when loading a new Org file.
  896. This can also be configured on a per-file basis by adding one of
  897. the following lines anywhere in the buffer:
  898. #+STARTUP: latexpreview
  899. #+STARTUP: nolatexpreview"
  900. :group 'org-startup
  901. :version "24.4"
  902. :package-version '(Org . "8.0")
  903. :type 'boolean)
  904. (defcustom org-insert-mode-line-in-empty-file nil
  905. "Non-nil means insert the first line setting Org mode in empty files.
  906. When the function `org-mode' is called interactively in an empty file, this
  907. normally means that the file name does not automatically trigger Org mode.
  908. To ensure that the file will always be in Org mode in the future, a
  909. line enforcing Org mode will be inserted into the buffer, if this option
  910. has been set."
  911. :group 'org-startup
  912. :type 'boolean)
  913. (defcustom org-replace-disputed-keys nil
  914. "Non-nil means use alternative key bindings for some keys.
  915. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  916. These keys are also used by other packages like shift-selection-mode'
  917. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  918. If you want to use Org mode together with one of these other modes,
  919. or more generally if you would like to move some Org mode commands to
  920. other keys, set this variable and configure the keys with the variable
  921. `org-disputed-keys'.
  922. This option is only relevant at load-time of Org mode, and must be set
  923. *before* org.el is loaded. Changing it requires a restart of Emacs to
  924. become effective."
  925. :group 'org-startup
  926. :type 'boolean)
  927. (defcustom org-use-extra-keys nil
  928. "Non-nil means use extra key sequence definitions for certain commands.
  929. This happens automatically if `window-system' is nil. This
  930. variable lets you do the same manually. You must set it before
  931. loading Org."
  932. :group 'org-startup
  933. :type 'boolean)
  934. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  935. (defcustom org-disputed-keys
  936. '(([(shift up)] . [(meta p)])
  937. ([(shift down)] . [(meta n)])
  938. ([(shift left)] . [(meta -)])
  939. ([(shift right)] . [(meta +)])
  940. ([(control shift right)] . [(meta shift +)])
  941. ([(control shift left)] . [(meta shift -)]))
  942. "Keys for which Org mode and other modes compete.
  943. This is an alist, cars are the default keys, second element specifies
  944. the alternative to use when `org-replace-disputed-keys' is t.
  945. Keys can be specified in any syntax supported by `define-key'.
  946. The value of this option takes effect only at Org mode startup,
  947. therefore you'll have to restart Emacs to apply it after changing."
  948. :group 'org-startup
  949. :type 'alist)
  950. (defun org-key (key)
  951. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  952. Or return the original if not disputed."
  953. (when org-replace-disputed-keys
  954. (let* ((nkey (key-description key))
  955. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  956. org-disputed-keys)))
  957. (setq key (if x (cdr x) key))))
  958. key)
  959. (defun org-defkey (keymap key def)
  960. "Define a key, possibly translated, as returned by `org-key'."
  961. (define-key keymap (org-key key) def))
  962. (defcustom org-ellipsis nil
  963. "The ellipsis to use in the Org mode outline.
  964. When nil, just use the standard three dots.
  965. When a string, use that string instead.
  966. The change affects only Org mode (which will then use its own display table).
  967. Changing this requires executing `\\[org-mode]' in a buffer to become
  968. effective."
  969. :group 'org-startup
  970. :type '(choice (const :tag "Default" nil)
  971. (string :tag "String" :value "...#"))
  972. :safe #'string-or-null-p)
  973. (defvar org-display-table nil
  974. "The display table for org-mode, in case `org-ellipsis' is non-nil.")
  975. (defgroup org-keywords nil
  976. "Keywords in Org mode."
  977. :tag "Org Keywords"
  978. :group 'org)
  979. (defcustom org-closed-keep-when-no-todo nil
  980. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  981. :group 'org-todo
  982. :group 'org-keywords
  983. :version "24.4"
  984. :package-version '(Org . "8.0")
  985. :type 'boolean)
  986. (defgroup org-structure nil
  987. "Options concerning the general structure of Org files."
  988. :tag "Org Structure"
  989. :group 'org)
  990. (defgroup org-reveal-location nil
  991. "Options about how to make context of a location visible."
  992. :tag "Org Reveal Location"
  993. :group 'org-structure)
  994. (defcustom org-show-context-detail '((agenda . local)
  995. (bookmark-jump . lineage)
  996. (isearch . lineage)
  997. (default . ancestors))
  998. "Alist between context and visibility span when revealing a location.
  999. \\<org-mode-map>Some actions may move point into invisible
  1000. locations. As a consequence, Org always expose a neighborhood
  1001. around point. How much is shown depends on the initial action,
  1002. or context. Valid contexts are
  1003. agenda when exposing an entry from the agenda
  1004. org-goto when using the command `org-goto' (`\\[org-goto]')
  1005. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1006. tags-tree when constructing a sparse tree based on tags matches
  1007. link-search when exposing search matches associated with a link
  1008. mark-goto when exposing the jump goal of a mark
  1009. bookmark-jump when exposing a bookmark location
  1010. isearch when exiting from an incremental search
  1011. default default for all contexts not set explicitly
  1012. Allowed visibility spans are
  1013. minimal show current headline; if point is not on headline,
  1014. also show entry
  1015. local show current headline, entry and next headline
  1016. ancestors show current headline and its direct ancestors; if
  1017. point is not on headline, also show entry
  1018. lineage show current headline, its direct ancestors and all
  1019. their children; if point is not on headline, also show
  1020. entry and first child
  1021. tree show current headline, its direct ancestors and all
  1022. their children; if point is not on headline, also show
  1023. entry and all children
  1024. canonical show current headline, its direct ancestors along with
  1025. their entries and children; if point is not located on
  1026. the headline, also show current entry and all children
  1027. As special cases, a nil or t value means show all contexts in
  1028. `minimal' or `canonical' view, respectively.
  1029. Some views can make displayed information very compact, but also
  1030. make it harder to edit the location of the match. In such
  1031. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1032. more context."
  1033. :group 'org-reveal-location
  1034. :version "25.2"
  1035. :package-version '(Org . "9.0")
  1036. :type '(choice
  1037. (const :tag "Canonical" t)
  1038. (const :tag "Minimal" nil)
  1039. (repeat :greedy t :tag "Individual contexts"
  1040. (cons
  1041. (choice :tag "Context"
  1042. (const agenda)
  1043. (const org-goto)
  1044. (const occur-tree)
  1045. (const tags-tree)
  1046. (const link-search)
  1047. (const mark-goto)
  1048. (const bookmark-jump)
  1049. (const isearch)
  1050. (const default))
  1051. (choice :tag "Detail level"
  1052. (const minimal)
  1053. (const local)
  1054. (const ancestors)
  1055. (const lineage)
  1056. (const tree)
  1057. (const canonical))))))
  1058. (defcustom org-indirect-buffer-display 'other-window
  1059. "How should indirect tree buffers be displayed?
  1060. This applies to indirect buffers created with the commands
  1061. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1062. Valid values are:
  1063. current-window Display in the current window
  1064. other-window Just display in another window.
  1065. dedicated-frame Create one new frame, and re-use it each time.
  1066. new-frame Make a new frame each time. Note that in this case
  1067. previously-made indirect buffers are kept, and you need to
  1068. kill these buffers yourself."
  1069. :group 'org-structure
  1070. :group 'org-agenda-windows
  1071. :type '(choice
  1072. (const :tag "In current window" current-window)
  1073. (const :tag "In current frame, other window" other-window)
  1074. (const :tag "Each time a new frame" new-frame)
  1075. (const :tag "One dedicated frame" dedicated-frame)))
  1076. (defcustom org-use-speed-commands nil
  1077. "Non-nil means activate single letter commands at beginning of a headline.
  1078. This may also be a function to test for appropriate locations where speed
  1079. commands should be active.
  1080. For example, to activate speed commands when the point is on any
  1081. star at the beginning of the headline, you can do this:
  1082. (setq org-use-speed-commands
  1083. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1084. :group 'org-structure
  1085. :type '(choice
  1086. (const :tag "Never" nil)
  1087. (const :tag "At beginning of headline stars" t)
  1088. (function)))
  1089. (defcustom org-speed-commands-user nil
  1090. "Alist of additional speed commands.
  1091. This list will be checked before `org-speed-commands-default'
  1092. when the variable `org-use-speed-commands' is non-nil
  1093. and when the cursor is at the beginning of a headline.
  1094. The car if each entry is a string with a single letter, which must
  1095. be assigned to `self-insert-command' in the global map.
  1096. The cdr is either a command to be called interactively, a function
  1097. to be called, or a form to be evaluated.
  1098. An entry that is just a list with a single string will be interpreted
  1099. as a descriptive headline that will be added when listing the speed
  1100. commands in the Help buffer using the `?' speed command."
  1101. :group 'org-structure
  1102. :type '(repeat :value ("k" . ignore)
  1103. (choice :value ("k" . ignore)
  1104. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1105. (cons :tag "Letter and Command"
  1106. (string :tag "Command letter")
  1107. (choice
  1108. (function)
  1109. (sexp))))))
  1110. (defcustom org-bookmark-names-plist
  1111. '(:last-capture "org-capture-last-stored"
  1112. :last-refile "org-refile-last-stored"
  1113. :last-capture-marker "org-capture-last-stored-marker")
  1114. "Names for bookmarks automatically set by some Org commands.
  1115. This can provide strings as names for a number of bookmarks Org sets
  1116. automatically. The following keys are currently implemented:
  1117. :last-capture
  1118. :last-capture-marker
  1119. :last-refile
  1120. When a key does not show up in the property list, the corresponding bookmark
  1121. is not set."
  1122. :group 'org-structure
  1123. :type 'plist)
  1124. (defgroup org-cycle nil
  1125. "Options concerning visibility cycling in Org mode."
  1126. :tag "Org Cycle"
  1127. :group 'org-structure)
  1128. (defcustom org-cycle-skip-children-state-if-no-children t
  1129. "Non-nil means skip CHILDREN state in entries that don't have any."
  1130. :group 'org-cycle
  1131. :type 'boolean)
  1132. (defcustom org-cycle-max-level nil
  1133. "Maximum level which should still be subject to visibility cycling.
  1134. Levels higher than this will, for cycling, be treated as text, not a headline.
  1135. When `org-odd-levels-only' is set, a value of N in this variable actually
  1136. means 2N-1 stars as the limiting headline.
  1137. When nil, cycle all levels.
  1138. Note that the limiting level of cycling is also influenced by
  1139. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1140. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1141. than its value."
  1142. :group 'org-cycle
  1143. :type '(choice
  1144. (const :tag "No limit" nil)
  1145. (integer :tag "Maximum level")))
  1146. (defcustom org-hide-block-startup nil
  1147. "Non-nil means entering Org mode will fold all blocks.
  1148. This can also be set in on a per-file basis with
  1149. #+STARTUP: hideblocks
  1150. #+STARTUP: showblocks"
  1151. :group 'org-startup
  1152. :group 'org-cycle
  1153. :type 'boolean)
  1154. (defcustom org-cycle-global-at-bob nil
  1155. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1156. This makes it possible to do global cycling without having to use `S-TAB'
  1157. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1158. line of the buffer
  1159. must not be a headline -- it may be empty or some other text.
  1160. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1161. sure the cursor stays at the beginning of the buffer.
  1162. When this option is nil, don't do anything special at the beginning of
  1163. the buffer."
  1164. :group 'org-cycle
  1165. :type 'boolean)
  1166. (defcustom org-cycle-level-after-item/entry-creation t
  1167. "Non-nil means cycle entry level or item indentation in new empty entries.
  1168. When the cursor is at the end of an empty headline, i.e., with only stars
  1169. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1170. and then all possible ancestor states, before returning to the original state.
  1171. This makes data entry extremely fast: M-RET to create a new headline,
  1172. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1173. When the cursor is at the end of an empty plain list item, one TAB will
  1174. make it a subitem, two or more tabs will back up to make this an item
  1175. higher up in the item hierarchy."
  1176. :group 'org-cycle
  1177. :type 'boolean)
  1178. (defcustom org-cycle-emulate-tab t
  1179. "Where should `org-cycle' emulate TAB.
  1180. nil Never
  1181. white Only in completely white lines
  1182. whitestart Only at the beginning of lines, before the first non-white char
  1183. t Everywhere except in headlines
  1184. exc-hl-bol Everywhere except at the start of a headline
  1185. If TAB is used in a place where it does not emulate TAB, the current subtree
  1186. visibility is cycled."
  1187. :group 'org-cycle
  1188. :type '(choice (const :tag "Never" nil)
  1189. (const :tag "Only in completely white lines" white)
  1190. (const :tag "Before first char in a line" whitestart)
  1191. (const :tag "Everywhere except in headlines" t)
  1192. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1193. (defcustom org-cycle-separator-lines 2
  1194. "Number of empty lines needed to keep an empty line between collapsed trees.
  1195. If you leave an empty line between the end of a subtree and the following
  1196. headline, this empty line is hidden when the subtree is folded.
  1197. Org mode will leave (exactly) one empty line visible if the number of
  1198. empty lines is equal or larger to the number given in this variable.
  1199. So the default 2 means at least 2 empty lines after the end of a subtree
  1200. are needed to produce free space between a collapsed subtree and the
  1201. following headline.
  1202. If the number is negative, and the number of empty lines is at least -N,
  1203. all empty lines are shown.
  1204. Special case: when 0, never leave empty lines in collapsed view."
  1205. :group 'org-cycle
  1206. :type 'integer)
  1207. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1208. (defcustom org-pre-cycle-hook nil
  1209. "Hook that is run before visibility cycling is happening.
  1210. The function(s) in this hook must accept a single argument which indicates
  1211. the new state that will be set right after running this hook. The
  1212. argument is a symbol. Before a global state change, it can have the values
  1213. `overview', `content', or `all'. Before a local state change, it can have
  1214. the values `folded', `children', or `subtree'."
  1215. :group 'org-cycle
  1216. :type 'hook)
  1217. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1218. org-cycle-hide-drawers
  1219. org-cycle-show-empty-lines
  1220. org-optimize-window-after-visibility-change)
  1221. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1222. The function(s) in this hook must accept a single argument which indicates
  1223. the new state that was set by the most recent `org-cycle' command. The
  1224. argument is a symbol. After a global state change, it can have the values
  1225. `overview', `contents', or `all'. After a local state change, it can have
  1226. the values `folded', `children', or `subtree'."
  1227. :group 'org-cycle
  1228. :type 'hook
  1229. :version "25.2"
  1230. :package-version '(Org . "8.3"))
  1231. (defgroup org-edit-structure nil
  1232. "Options concerning structure editing in Org mode."
  1233. :tag "Org Edit Structure"
  1234. :group 'org-structure)
  1235. (defcustom org-odd-levels-only nil
  1236. "Non-nil means skip even levels and only use odd levels for the outline.
  1237. This has the effect that two stars are being added/taken away in
  1238. promotion/demotion commands. It also influences how levels are
  1239. handled by the exporters.
  1240. Changing it requires restart of `font-lock-mode' to become effective
  1241. for fontification also in regions already fontified.
  1242. You may also set this on a per-file basis by adding one of the following
  1243. lines to the buffer:
  1244. #+STARTUP: odd
  1245. #+STARTUP: oddeven"
  1246. :group 'org-edit-structure
  1247. :group 'org-appearance
  1248. :type 'boolean)
  1249. (defcustom org-adapt-indentation t
  1250. "Non-nil means adapt indentation to outline node level.
  1251. When this variable is set, Org assumes that you write outlines by
  1252. indenting text in each node to align with the headline (after the
  1253. stars). The following issues are influenced by this variable:
  1254. - The indentation is increased by one space in a demotion
  1255. command, and decreased by one in a promotion command. However,
  1256. in the latter case, if shifting some line in the entry body
  1257. would alter document structure (e.g., insert a new headline),
  1258. indentation is not changed at all.
  1259. - Property drawers and planning information is inserted indented
  1260. when this variable is set. When nil, they will not be indented.
  1261. - TAB indents a line relative to current level. The lines below
  1262. a headline will be indented when this variable is set.
  1263. Note that this is all about true indentation, by adding and
  1264. removing space characters. See also `org-indent.el' which does
  1265. level-dependent indentation in a virtual way, i.e. at display
  1266. time in Emacs."
  1267. :group 'org-edit-structure
  1268. :type 'boolean)
  1269. (defcustom org-special-ctrl-a/e nil
  1270. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1271. When t, `C-a' will bring back the cursor to the beginning of the
  1272. headline text, i.e. after the stars and after a possible TODO
  1273. keyword. In an item, this will be the position after bullet and
  1274. check-box, if any. When the cursor is already at that position,
  1275. another `C-a' will bring it to the beginning of the line.
  1276. `C-e' will jump to the end of the headline, ignoring the presence
  1277. of tags in the headline. A second `C-e' will then jump to the
  1278. true end of the line, after any tags. This also means that, when
  1279. this variable is non-nil, `C-e' also will never jump beyond the
  1280. end of the heading of a folded section, i.e. not after the
  1281. ellipses.
  1282. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1283. normally, going to the true line boundary first. Only a directly
  1284. following, identical keypress will bring the cursor to the
  1285. special positions.
  1286. This may also be a cons cell where the behavior for `C-a' and
  1287. `C-e' is set separately."
  1288. :group 'org-edit-structure
  1289. :type '(choice
  1290. (const :tag "off" nil)
  1291. (const :tag "on: after stars/bullet and before tags first" t)
  1292. (const :tag "reversed: true line boundary first" reversed)
  1293. (cons :tag "Set C-a and C-e separately"
  1294. (choice :tag "Special C-a"
  1295. (const :tag "off" nil)
  1296. (const :tag "on: after stars/bullet first" t)
  1297. (const :tag "reversed: before stars/bullet first" reversed))
  1298. (choice :tag "Special C-e"
  1299. (const :tag "off" nil)
  1300. (const :tag "on: before tags first" t)
  1301. (const :tag "reversed: after tags first" reversed)))))
  1302. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1303. (defcustom org-special-ctrl-k nil
  1304. "Non-nil means `C-k' will behave specially in headlines.
  1305. When nil, `C-k' will call the default `kill-line' command.
  1306. When t, the following will happen while the cursor is in the headline:
  1307. - When the cursor is at the beginning of a headline, kill the entire
  1308. line and possible the folded subtree below the line.
  1309. - When in the middle of the headline text, kill the headline up to the tags.
  1310. - When after the headline text, kill the tags."
  1311. :group 'org-edit-structure
  1312. :type 'boolean)
  1313. (defcustom org-ctrl-k-protect-subtree nil
  1314. "Non-nil means, do not delete a hidden subtree with C-k.
  1315. When set to the symbol `error', simply throw an error when C-k is
  1316. used to kill (part-of) a headline that has hidden text behind it.
  1317. Any other non-nil value will result in a query to the user, if it is
  1318. OK to kill that hidden subtree. When nil, kill without remorse."
  1319. :group 'org-edit-structure
  1320. :version "24.1"
  1321. :type '(choice
  1322. (const :tag "Do not protect hidden subtrees" nil)
  1323. (const :tag "Protect hidden subtrees with a security query" t)
  1324. (const :tag "Never kill a hidden subtree with C-k" error)))
  1325. (defcustom org-special-ctrl-o t
  1326. "Non-nil means, make `C-o' insert a row in tables."
  1327. :group 'org-edit-structure
  1328. :type 'boolean)
  1329. (defcustom org-catch-invisible-edits nil
  1330. "Check if in invisible region before inserting or deleting a character.
  1331. Valid values are:
  1332. nil Do not check, so just do invisible edits.
  1333. error Throw an error and do nothing.
  1334. show Make point visible, and do the requested edit.
  1335. show-and-error Make point visible, then throw an error and abort the edit.
  1336. smart Make point visible, and do insertion/deletion if it is
  1337. adjacent to visible text and the change feels predictable.
  1338. Never delete a previously invisible character or add in the
  1339. middle or right after an invisible region. Basically, this
  1340. allows insertion and backward-delete right before ellipses.
  1341. FIXME: maybe in this case we should not even show?"
  1342. :group 'org-edit-structure
  1343. :version "24.1"
  1344. :type '(choice
  1345. (const :tag "Do not check" nil)
  1346. (const :tag "Throw error when trying to edit" error)
  1347. (const :tag "Unhide, but do not do the edit" show-and-error)
  1348. (const :tag "Show invisible part and do the edit" show)
  1349. (const :tag "Be smart and do the right thing" smart)))
  1350. (defcustom org-yank-folded-subtrees t
  1351. "Non-nil means when yanking subtrees, fold them.
  1352. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1353. it starts with a heading and all other headings in it are either children
  1354. or siblings, then fold all the subtrees. However, do this only if no
  1355. text after the yank would be swallowed into a folded tree by this action."
  1356. :group 'org-edit-structure
  1357. :type 'boolean)
  1358. (defcustom org-yank-adjusted-subtrees nil
  1359. "Non-nil means when yanking subtrees, adjust the level.
  1360. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1361. this function for details."
  1362. :group 'org-edit-structure
  1363. :type 'boolean)
  1364. (defcustom org-M-RET-may-split-line '((default . t))
  1365. "Non-nil means M-RET will split the line at the cursor position.
  1366. When nil, it will go to the end of the line before making a
  1367. new line.
  1368. You may also set this option in a different way for different
  1369. contexts. Valid contexts are:
  1370. headline when creating a new headline
  1371. item when creating a new item
  1372. table in a table field
  1373. default the value to be used for all contexts not explicitly
  1374. customized"
  1375. :group 'org-structure
  1376. :group 'org-table
  1377. :type '(choice
  1378. (const :tag "Always" t)
  1379. (const :tag "Never" nil)
  1380. (repeat :greedy t :tag "Individual contexts"
  1381. (cons
  1382. (choice :tag "Context"
  1383. (const headline)
  1384. (const item)
  1385. (const table)
  1386. (const default))
  1387. (boolean)))))
  1388. (defcustom org-insert-heading-respect-content nil
  1389. "Non-nil means insert new headings after the current subtree.
  1390. \\<org-mode-map>
  1391. When nil, the new heading is created directly after the current line.
  1392. The commands `\\[org-insert-heading-respect-content]' and \
  1393. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1394. for the duration of the command."
  1395. :group 'org-structure
  1396. :type 'boolean)
  1397. (defcustom org-blank-before-new-entry '((heading . auto)
  1398. (plain-list-item . auto))
  1399. "Should `org-insert-heading' leave a blank line before new heading/item?
  1400. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1401. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1402. which case Org will look at the surrounding headings/items and try to
  1403. make an intelligent decision whether to insert a blank line or not."
  1404. :group 'org-edit-structure
  1405. :type '(list
  1406. (cons (const heading)
  1407. (choice (const :tag "Never" nil)
  1408. (const :tag "Always" t)
  1409. (const :tag "Auto" auto)))
  1410. (cons (const plain-list-item)
  1411. (choice (const :tag "Never" nil)
  1412. (const :tag "Always" t)
  1413. (const :tag "Auto" auto)))))
  1414. (defcustom org-insert-heading-hook nil
  1415. "Hook being run after inserting a new heading."
  1416. :group 'org-edit-structure
  1417. :type 'hook)
  1418. (defcustom org-enable-fixed-width-editor t
  1419. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1420. This currently only means they are never auto-wrapped.
  1421. When nil, such lines will be treated like ordinary lines."
  1422. :group 'org-edit-structure
  1423. :type 'boolean)
  1424. (defcustom org-goto-auto-isearch t
  1425. "Non-nil means typing characters in `org-goto' starts incremental search.
  1426. When nil, you can use these keybindings to navigate the buffer:
  1427. q Quit the org-goto interface
  1428. n Go to the next visible heading
  1429. p Go to the previous visible heading
  1430. f Go one heading forward on same level
  1431. b Go one heading backward on same level
  1432. u Go one heading up"
  1433. :group 'org-edit-structure
  1434. :type 'boolean)
  1435. (defgroup org-sparse-trees nil
  1436. "Options concerning sparse trees in Org mode."
  1437. :tag "Org Sparse Trees"
  1438. :group 'org-structure)
  1439. (defcustom org-highlight-sparse-tree-matches t
  1440. "Non-nil means highlight all matches that define a sparse tree.
  1441. The highlights will automatically disappear the next time the buffer is
  1442. changed by an edit command."
  1443. :group 'org-sparse-trees
  1444. :type 'boolean)
  1445. (defcustom org-remove-highlights-with-change t
  1446. "Non-nil means any change to the buffer will remove temporary highlights.
  1447. \\<org-mode-map>\
  1448. Such highlights are created by `org-occur' and `org-clock-display'.
  1449. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1450. to get rid of the highlights.
  1451. The highlights created by `org-toggle-latex-fragment' always need
  1452. `\\[org-toggle-latex-fragment]' to be removed."
  1453. :group 'org-sparse-trees
  1454. :group 'org-time
  1455. :type 'boolean)
  1456. (defcustom org-occur-case-fold-search t
  1457. "Non-nil means `org-occur' should be case-insensitive.
  1458. If set to `smart' the search will be case-insensitive only if it
  1459. doesn't specify any upper case character."
  1460. :group 'org-sparse-trees
  1461. :version "25.2"
  1462. :type '(choice
  1463. (const :tag "Case-sensitive" nil)
  1464. (const :tag "Case-insensitive" t)
  1465. (const :tag "Case-insensitive for lower case searches only" 'smart)))
  1466. (defcustom org-occur-hook '(org-first-headline-recenter)
  1467. "Hook that is run after `org-occur' has constructed a sparse tree.
  1468. This can be used to recenter the window to show as much of the structure
  1469. as possible."
  1470. :group 'org-sparse-trees
  1471. :type 'hook)
  1472. (defgroup org-imenu-and-speedbar nil
  1473. "Options concerning imenu and speedbar in Org mode."
  1474. :tag "Org Imenu and Speedbar"
  1475. :group 'org-structure)
  1476. (defcustom org-imenu-depth 2
  1477. "The maximum level for Imenu access to Org headlines.
  1478. This also applied for speedbar access."
  1479. :group 'org-imenu-and-speedbar
  1480. :type 'integer)
  1481. (defgroup org-table nil
  1482. "Options concerning tables in Org mode."
  1483. :tag "Org Table"
  1484. :group 'org)
  1485. (defcustom org-enable-table-editor 'optimized
  1486. "Non-nil means lines starting with \"|\" are handled by the table editor.
  1487. When nil, such lines will be treated like ordinary lines.
  1488. When equal to the symbol `optimized', the table editor will be optimized to
  1489. do the following:
  1490. - Automatic overwrite mode in front of whitespace in table fields.
  1491. This makes the structure of the table stay in tact as long as the edited
  1492. field does not exceed the column width.
  1493. - Minimize the number of realigns. Normally, the table is aligned each time
  1494. TAB or RET are pressed to move to another field. With optimization this
  1495. happens only if changes to a field might have changed the column width.
  1496. Optimization requires replacing the functions `self-insert-command',
  1497. `delete-char', and `backward-delete-char' in Org buffers, with a
  1498. slight (in fact: unnoticeable) speed impact for normal typing. Org is very
  1499. good at guessing when a re-align will be necessary, but you can always
  1500. force one with `\\[org-ctrl-c-ctrl-c]'.
  1501. If you would like to use the optimized version in Org mode, but the
  1502. un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
  1503. This variable can be used to turn on and off the table editor during a session,
  1504. but in order to toggle optimization, a restart is required.
  1505. See also the variable `org-table-auto-blank-field'."
  1506. :group 'org-table
  1507. :type '(choice
  1508. (const :tag "off" nil)
  1509. (const :tag "on" t)
  1510. (const :tag "on, optimized" optimized)))
  1511. (defcustom org-self-insert-cluster-for-undo nil
  1512. "Non-nil means cluster self-insert commands for undo when possible.
  1513. If this is set, then, like in the Emacs command loop, 20 consecutive
  1514. characters will be undone together.
  1515. This is configurable, because there is some impact on typing performance."
  1516. :group 'org-table
  1517. :type 'boolean)
  1518. (defcustom org-table-tab-recognizes-table.el t
  1519. "Non-nil means TAB will automatically notice a table.el table.
  1520. When it sees such a table, it moves point into it and - if necessary -
  1521. calls `table-recognize-table'."
  1522. :group 'org-table-editing
  1523. :type 'boolean)
  1524. (defgroup org-link nil
  1525. "Options concerning links in Org mode."
  1526. :tag "Org Link"
  1527. :group 'org)
  1528. (defvar-local org-link-abbrev-alist-local nil
  1529. "Buffer-local version of `org-link-abbrev-alist', which see.
  1530. The value of this is taken from the #+LINK lines.")
  1531. (defcustom org-link-parameters
  1532. '(("doi" :follow org--open-doi-link)
  1533. ("elisp" :follow org--open-elisp-link)
  1534. ("file" :complete org-file-complete-link)
  1535. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1536. ("help" :follow org--open-help-link)
  1537. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1538. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1539. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1540. ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
  1541. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1542. ("shell" :follow org--open-shell-link))
  1543. "An alist of properties that defines all the links in Org mode.
  1544. The key in each association is a string of the link type.
  1545. Subsequent optional elements make up a p-list of link properties.
  1546. :follow - A function that takes the link path as an argument.
  1547. :export - A function that takes the link path, description and
  1548. export-backend as arguments.
  1549. :store - A function responsible for storing the link. See the
  1550. function `org-store-link-functions'.
  1551. :complete - A function that inserts a link with completion. The
  1552. function takes one optional prefix arg.
  1553. :face - A face for the link, or a function that returns a face.
  1554. The function takes one argument which is the link path. The
  1555. default face is `org-link'.
  1556. :mouse-face - The mouse-face. The default is `highlight'.
  1557. :display - `full' will not fold the link in descriptive
  1558. display. Default is `org-link'.
  1559. :help-echo - A string or function that takes (window object position)
  1560. as arguments and returns a string.
  1561. :keymap - A keymap that is active on the link. The default is
  1562. `org-mouse-map'.
  1563. :htmlize-link - A function for the htmlize-link. Defaults
  1564. to (list :uri \"type:path\")
  1565. :activate-func - A function to run at the end of font-lock
  1566. activation. The function must accept (link-start link-end path bracketp)
  1567. as arguments."
  1568. :group 'org-link
  1569. :type '(alist :tag "Link display parameters"
  1570. :value-type plist))
  1571. (defun org-link-get-parameter (type key)
  1572. "Get TYPE link property for KEY.
  1573. TYPE is a string and KEY is a plist keyword."
  1574. (plist-get
  1575. (cdr (assoc type org-link-parameters))
  1576. key))
  1577. (defun org-link-set-parameters (type &rest parameters)
  1578. "Set link TYPE properties to PARAMETERS.
  1579. PARAMETERS should be :key val pairs."
  1580. (let ((data (assoc type org-link-parameters)))
  1581. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1582. (push (cons type parameters) org-link-parameters)
  1583. (org-make-link-regexps)
  1584. (org-element-update-syntax))))
  1585. (defun org-link-types ()
  1586. "Return a list of known link types."
  1587. (mapcar #'car org-link-parameters))
  1588. (defcustom org-link-abbrev-alist nil
  1589. "Alist of link abbreviations.
  1590. The car of each element is a string, to be replaced at the start of a link.
  1591. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1592. links in Org buffers can have an optional tag after a double colon, e.g.,
  1593. [[linkkey:tag][description]]
  1594. The `linkkey' must be a single word, starting with a letter, followed
  1595. by letters, numbers, `-' or `_'.
  1596. If REPLACE is a string, the tag will simply be appended to create the link.
  1597. If the string contains \"%s\", the tag will be inserted there. If the string
  1598. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1599. at that point (see the function `url-hexify-string'). If the string contains
  1600. the specifier \"%(my-function)\", then the custom function `my-function' will
  1601. be invoked: this function takes the tag as its only argument and must return
  1602. a string.
  1603. REPLACE may also be a function that will be called with the tag as the
  1604. only argument to create the link, which should be returned as a string.
  1605. See the manual for examples."
  1606. :group 'org-link
  1607. :type '(repeat
  1608. (cons
  1609. (string :tag "Protocol")
  1610. (choice
  1611. (string :tag "Format")
  1612. (function)))))
  1613. (defcustom org-descriptive-links t
  1614. "Non-nil means Org will display descriptive links.
  1615. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1616. \"Org Website\", hiding the link itself and just displaying its
  1617. description. When set to nil, Org will display the full links
  1618. literally.
  1619. You can interactively set the value of this variable by calling
  1620. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1621. :group 'org-link
  1622. :type 'boolean)
  1623. (defcustom org-link-file-path-type 'adaptive
  1624. "How the path name in file links should be stored.
  1625. Valid values are:
  1626. relative Relative to the current directory, i.e. the directory of the file
  1627. into which the link is being inserted.
  1628. absolute Absolute path, if possible with ~ for home directory.
  1629. noabbrev Absolute path, no abbreviation of home directory.
  1630. adaptive Use relative path for files in the current directory and sub-
  1631. directories of it. For other files, use an absolute path."
  1632. :group 'org-link
  1633. :type '(choice
  1634. (const relative)
  1635. (const absolute)
  1636. (const noabbrev)
  1637. (const adaptive)))
  1638. (defvaralias 'org-activate-links 'org-highlight-links)
  1639. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1640. "Types of links that should be highlighted in Org files.
  1641. This is a list of symbols, each one of them leading to the
  1642. highlighting of a certain link type.
  1643. You can still open links that are not highlighted.
  1644. In principle, it does not hurt to turn on highlighting for all
  1645. link types. There may be a small gain when turning off unused
  1646. link types. The types are:
  1647. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1648. angle Links in angular brackets that may contain whitespace like
  1649. <bbdb:Carsten Dominik>.
  1650. plain Plain links in normal text, no whitespace, like http://google.com.
  1651. radio Text that is matched by a radio target, see manual for details.
  1652. tag Tag settings in a headline (link to tag search).
  1653. date Time stamps (link to calendar).
  1654. footnote Footnote labels.
  1655. If you set this variable during an Emacs session, use `org-mode-restart'
  1656. in the Org buffer so that the change takes effect."
  1657. :group 'org-link
  1658. :group 'org-appearance
  1659. :type '(set :greedy t
  1660. (const :tag "Double bracket links" bracket)
  1661. (const :tag "Angular bracket links" angle)
  1662. (const :tag "Plain text links" plain)
  1663. (const :tag "Radio target matches" radio)
  1664. (const :tag "Tags" tag)
  1665. (const :tag "Timestamps" date)
  1666. (const :tag "Footnotes" footnote)))
  1667. (defcustom org-make-link-description-function nil
  1668. "Function to use for generating link descriptions from links.
  1669. When nil, the link location will be used. This function must take
  1670. two parameters: the first one is the link, the second one is the
  1671. description generated by `org-insert-link'. The function should
  1672. return the description to use."
  1673. :group 'org-link
  1674. :type '(choice (const nil) (function)))
  1675. (defgroup org-link-store nil
  1676. "Options concerning storing links in Org mode."
  1677. :tag "Org Store Link"
  1678. :group 'org-link)
  1679. (defcustom org-url-hexify-p t
  1680. "When non-nil, hexify URL when creating a link."
  1681. :type 'boolean
  1682. :version "24.3"
  1683. :group 'org-link-store)
  1684. (defcustom org-email-link-description-format "Email %c: %.30s"
  1685. "Format of the description part of a link to an email or usenet message.
  1686. The following %-escapes will be replaced by corresponding information:
  1687. %F full \"From\" field
  1688. %f name, taken from \"From\" field, address if no name
  1689. %T full \"To\" field
  1690. %t first name in \"To\" field, address if no name
  1691. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1692. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1693. %s subject
  1694. %d date
  1695. %m message-id.
  1696. You may use normal field width specification between the % and the letter.
  1697. This is for example useful to limit the length of the subject.
  1698. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1699. :group 'org-link-store
  1700. :type 'string)
  1701. (defcustom org-from-is-user-regexp
  1702. (let (r1 r2)
  1703. (when (and user-mail-address (not (string= user-mail-address "")))
  1704. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1705. (when (and user-full-name (not (string= user-full-name "")))
  1706. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1707. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1708. "Regexp matched against the \"From:\" header of an email or usenet message.
  1709. It should match if the message is from the user him/herself."
  1710. :group 'org-link-store
  1711. :type 'regexp)
  1712. (defcustom org-context-in-file-links t
  1713. "Non-nil means file links from `org-store-link' contain context.
  1714. \\<org-mode-map>
  1715. A search string will be added to the file name with :: as separator
  1716. and used to find the context when the link is activated by the command
  1717. `org-open-at-point'. When this option is t, the entire active region
  1718. will be placed in the search string of the file link. If set to a
  1719. positive integer, only the first n lines of context will be stored.
  1720. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1721. \\[org-store-link]')
  1722. negates this setting for the duration of the command."
  1723. :group 'org-link-store
  1724. :type '(choice boolean integer))
  1725. (defcustom org-keep-stored-link-after-insertion nil
  1726. "Non-nil means keep link in list for entire session.
  1727. \\<org-mode-map>
  1728. The command `org-store-link' adds a link pointing to the current
  1729. location to an internal list. These links accumulate during a session.
  1730. The command `org-insert-link' can be used to insert links into any
  1731. Org file (offering completion for all stored links).
  1732. When this option is nil, every link which has been inserted once using
  1733. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1734. unused
  1735. links more efficient."
  1736. :group 'org-link-store
  1737. :type 'boolean)
  1738. (defgroup org-link-follow nil
  1739. "Options concerning following links in Org mode."
  1740. :tag "Org Follow Link"
  1741. :group 'org-link)
  1742. (defcustom org-link-translation-function nil
  1743. "Function to translate links with different syntax to Org syntax.
  1744. This can be used to translate links created for example by the Planner
  1745. or emacs-wiki packages to Org syntax.
  1746. The function must accept two parameters, a TYPE containing the link
  1747. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1748. which is everything after the link protocol. It should return a cons
  1749. with possibly modified values of type and path.
  1750. Org contains a function for this, so if you set this variable to
  1751. `org-translate-link-from-planner', you should be able follow many
  1752. links created by planner."
  1753. :group 'org-link-follow
  1754. :type '(choice (const nil) (function)))
  1755. (defcustom org-follow-link-hook nil
  1756. "Hook that is run after a link has been followed."
  1757. :group 'org-link-follow
  1758. :type 'hook)
  1759. (defcustom org-tab-follows-link nil
  1760. "Non-nil means on links TAB will follow the link.
  1761. Needs to be set before org.el is loaded.
  1762. This really should not be used, it does not make sense, and the
  1763. implementation is bad."
  1764. :group 'org-link-follow
  1765. :type 'boolean)
  1766. (defcustom org-return-follows-link nil
  1767. "Non-nil means on links RET will follow the link.
  1768. In tables, the special behavior of RET has precedence."
  1769. :group 'org-link-follow
  1770. :type 'boolean)
  1771. (defcustom org-mouse-1-follows-link
  1772. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1773. "Non-nil means mouse-1 on a link will follow the link.
  1774. A longer mouse click will still set point. Needs to be set
  1775. before org.el is loaded."
  1776. :group 'org-link-follow
  1777. :version "24.4"
  1778. :package-version '(Org . "8.3")
  1779. :type '(choice
  1780. (const :tag "A double click follows the link" double)
  1781. (const :tag "Unconditionally follow the link with mouse-1" t)
  1782. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1783. (defcustom org-mark-ring-length 4
  1784. "Number of different positions to be recorded in the ring.
  1785. Changing this requires a restart of Emacs to work correctly."
  1786. :group 'org-link-follow
  1787. :type 'integer)
  1788. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1789. "Non-nil means internal links in Org files must exactly match a headline.
  1790. When nil, the link search tries to match a phrase with all words
  1791. in the search text."
  1792. :group 'org-link-follow
  1793. :version "24.1"
  1794. :type '(choice
  1795. (const :tag "Use fuzzy text search" nil)
  1796. (const :tag "Match only exact headline" t)
  1797. (const :tag "Match exact headline or query to create it"
  1798. query-to-create)))
  1799. (defcustom org-link-frame-setup
  1800. '((vm . vm-visit-folder-other-frame)
  1801. (vm-imap . vm-visit-imap-folder-other-frame)
  1802. (gnus . org-gnus-no-new-news)
  1803. (file . find-file-other-window)
  1804. (wl . wl-other-frame))
  1805. "Setup the frame configuration for following links.
  1806. When following a link with Emacs, it may often be useful to display
  1807. this link in another window or frame. This variable can be used to
  1808. set this up for the different types of links.
  1809. For VM, use any of
  1810. `vm-visit-folder'
  1811. `vm-visit-folder-other-window'
  1812. `vm-visit-folder-other-frame'
  1813. For Gnus, use any of
  1814. `gnus'
  1815. `gnus-other-frame'
  1816. `org-gnus-no-new-news'
  1817. For FILE, use any of
  1818. `find-file'
  1819. `find-file-other-window'
  1820. `find-file-other-frame'
  1821. For Wanderlust use any of
  1822. `wl'
  1823. `wl-other-frame'
  1824. For the calendar, use the variable `calendar-setup'.
  1825. For BBDB, it is currently only possible to display the matches in
  1826. another window."
  1827. :group 'org-link-follow
  1828. :type '(list
  1829. (cons (const vm)
  1830. (choice
  1831. (const vm-visit-folder)
  1832. (const vm-visit-folder-other-window)
  1833. (const vm-visit-folder-other-frame)))
  1834. (cons (const vm-imap)
  1835. (choice
  1836. (const vm-visit-imap-folder)
  1837. (const vm-visit-imap-folder-other-window)
  1838. (const vm-visit-imap-folder-other-frame)))
  1839. (cons (const gnus)
  1840. (choice
  1841. (const gnus)
  1842. (const gnus-other-frame)
  1843. (const org-gnus-no-new-news)))
  1844. (cons (const file)
  1845. (choice
  1846. (const find-file)
  1847. (const find-file-other-window)
  1848. (const find-file-other-frame)))
  1849. (cons (const wl)
  1850. (choice
  1851. (const wl)
  1852. (const wl-other-frame)))))
  1853. (defcustom org-display-internal-link-with-indirect-buffer nil
  1854. "Non-nil means use indirect buffer to display infile links.
  1855. Activating internal links (from one location in a file to another location
  1856. in the same file) normally just jumps to the location. When the link is
  1857. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1858. is displayed in
  1859. another window. When this option is set, the other window actually displays
  1860. an indirect buffer clone of the current buffer, to avoid any visibility
  1861. changes to the current buffer."
  1862. :group 'org-link-follow
  1863. :type 'boolean)
  1864. (defcustom org-open-non-existing-files nil
  1865. "Non-nil means `org-open-file' will open non-existing files.
  1866. When nil, an error will be generated.
  1867. This variable applies only to external applications because they
  1868. might choke on non-existing files. If the link is to a file that
  1869. will be opened in Emacs, the variable is ignored."
  1870. :group 'org-link-follow
  1871. :type 'boolean)
  1872. (defcustom org-open-directory-means-index-dot-org nil
  1873. "Non-nil means a link to a directory really means to index.org.
  1874. When nil, following a directory link will run dired or open a finder/explorer
  1875. window on that directory."
  1876. :group 'org-link-follow
  1877. :type 'boolean)
  1878. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1879. "Non-nil means ask for confirmation before executing shell links.
  1880. Shell links can be dangerous: just think about a link
  1881. [[shell:rm -rf ~/*][Google Search]]
  1882. This link would show up in your Org document as \"Google Search\",
  1883. but really it would remove your entire home directory.
  1884. Therefore we advise against setting this variable to nil.
  1885. Just change it to `y-or-n-p' if you want to confirm with a
  1886. single keystroke rather than having to type \"yes\"."
  1887. :group 'org-link-follow
  1888. :type '(choice
  1889. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1890. (const :tag "with y-or-n (faster)" y-or-n-p)
  1891. (const :tag "no confirmation (dangerous)" nil)))
  1892. (put 'org-confirm-shell-link-function
  1893. 'safe-local-variable
  1894. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1895. (defcustom org-confirm-shell-link-not-regexp ""
  1896. "A regexp to skip confirmation for shell links."
  1897. :group 'org-link-follow
  1898. :version "24.1"
  1899. :type 'regexp)
  1900. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1901. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1902. Elisp links can be dangerous: just think about a link
  1903. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1904. This link would show up in your Org document as \"Google Search\",
  1905. but really it would remove your entire home directory.
  1906. Therefore we advise against setting this variable to nil.
  1907. Just change it to `y-or-n-p' if you want to confirm with a
  1908. single keystroke rather than having to type \"yes\"."
  1909. :group 'org-link-follow
  1910. :type '(choice
  1911. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1912. (const :tag "with y-or-n (faster)" y-or-n-p)
  1913. (const :tag "no confirmation (dangerous)" nil)))
  1914. (put 'org-confirm-shell-link-function
  1915. 'safe-local-variable
  1916. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1917. (defcustom org-confirm-elisp-link-not-regexp ""
  1918. "A regexp to skip confirmation for Elisp links."
  1919. :group 'org-link-follow
  1920. :version "24.1"
  1921. :type 'regexp)
  1922. (defconst org-file-apps-defaults-gnu
  1923. '((remote . emacs)
  1924. (system . mailcap)
  1925. (t . mailcap))
  1926. "Default file applications on a UNIX or GNU/Linux system.
  1927. See `org-file-apps'.")
  1928. (defconst org-file-apps-defaults-macosx
  1929. '((remote . emacs)
  1930. (system . "open %s")
  1931. ("ps.gz" . "gv %s")
  1932. ("eps.gz" . "gv %s")
  1933. ("dvi" . "xdvi %s")
  1934. ("fig" . "xfig %s")
  1935. (t . "open %s"))
  1936. "Default file applications on a MacOS X system.
  1937. The system \"open\" is known as a default, but we use X11 applications
  1938. for some files for which the OS does not have a good default.
  1939. See `org-file-apps'.")
  1940. (defconst org-file-apps-defaults-windowsnt
  1941. (list '(remote . emacs)
  1942. (cons 'system (lambda (file _path)
  1943. (with-no-warnings (w32-shell-execute "open" file))))
  1944. (cons t (lambda (file _path)
  1945. (with-no-warnings (w32-shell-execute "open" file)))))
  1946. "Default file applications on a Windows NT system.
  1947. The system \"open\" is used for most files.
  1948. See `org-file-apps'.")
  1949. (defcustom org-file-apps
  1950. '((auto-mode . emacs)
  1951. ("\\.mm\\'" . default)
  1952. ("\\.x?html?\\'" . default)
  1953. ("\\.pdf\\'" . default))
  1954. "External applications for opening `file:path' items in a document.
  1955. \\<org-mode-map>\
  1956. Org mode uses system defaults for different file types, but
  1957. you can use this variable to set the application for a given file
  1958. extension. The entries in this list are cons cells where the car identifies
  1959. files and the cdr the corresponding command.
  1960. Possible values for the file identifier are:
  1961. \"string\" A string as a file identifier can be interpreted in different
  1962. ways, depending on its contents:
  1963. - Alphanumeric characters only:
  1964. Match links with this file extension.
  1965. Example: (\"pdf\" . \"evince %s\")
  1966. to open PDFs with evince.
  1967. - Regular expression: Match links where the
  1968. filename matches the regexp. If you want to
  1969. use groups here, use shy groups.
  1970. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1971. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1972. to open *.html and *.xhtml with firefox.
  1973. - Regular expression which contains (non-shy) groups:
  1974. Match links where the whole link, including \"::\", and
  1975. anything after that, matches the regexp.
  1976. In a custom command string, %1, %2, etc. are replaced with
  1977. the parts of the link that were matched by the groups.
  1978. For backwards compatibility, if a command string is given
  1979. that does not use any of the group matches, this case is
  1980. handled identically to the second one (i.e. match against
  1981. file name only).
  1982. In a custom function, you can access the group matches with
  1983. \(match-string n link).
  1984. Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
  1985. \"evince -p %1 %s\")
  1986. to open [[file:document.pdf::5]] with evince at page 5.
  1987. `directory' Matches a directory
  1988. `remote' Matches a remote file, accessible through tramp or efs.
  1989. Remote files most likely should be visited through Emacs
  1990. because external applications cannot handle such paths.
  1991. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1992. so all files Emacs knows how to handle. Using this with
  1993. command `emacs' will open most files in Emacs. Beware that this
  1994. will also open html files inside Emacs, unless you add
  1995. \(\"html\" . default) to the list as well.
  1996. `system' The system command to open files, like `open' on Windows
  1997. and Mac OS X, and mailcap under GNU/Linux. This is the command
  1998. that will be selected if you call `org-open-at-point' with a
  1999. double prefix argument (`\\[universal-argument] \
  2000. \\[universal-argument] \\[org-open-at-point]').
  2001. t Default for files not matched by any of the other options.
  2002. Possible values for the command are:
  2003. `emacs' The file will be visited by the current Emacs process.
  2004. `default' Use the default application for this file type, which is the
  2005. association for t in the list, most likely in the system-specific
  2006. part. This can be used to overrule an unwanted setting in the
  2007. system-specific variable.
  2008. `system' Use the system command for opening files, like \"open\".
  2009. This command is specified by the entry whose car is `system'.
  2010. Most likely, the system-specific version of this variable
  2011. does define this command, but you can overrule/replace it
  2012. here.
  2013. `mailcap' Use command specified in the mailcaps.
  2014. string A command to be executed by a shell; %s will be replaced
  2015. by the path to the file.
  2016. function A Lisp function, which will be called with two arguments:
  2017. the file path and the original link string, without the
  2018. \"file:\" prefix.
  2019. For more examples, see the system specific constants
  2020. `org-file-apps-defaults-macosx'
  2021. `org-file-apps-defaults-windowsnt'
  2022. `org-file-apps-defaults-gnu'."
  2023. :group 'org-link-follow
  2024. :type '(repeat
  2025. (cons (choice :value ""
  2026. (string :tag "Extension")
  2027. (const :tag "System command to open files" system)
  2028. (const :tag "Default for unrecognized files" t)
  2029. (const :tag "Remote file" remote)
  2030. (const :tag "Links to a directory" directory)
  2031. (const :tag "Any files that have Emacs modes"
  2032. auto-mode))
  2033. (choice :value ""
  2034. (const :tag "Visit with Emacs" emacs)
  2035. (const :tag "Use default" default)
  2036. (const :tag "Use the system command" system)
  2037. (string :tag "Command")
  2038. (function :tag "Function")))))
  2039. (defcustom org-doi-server-url "http://dx.doi.org/"
  2040. "The URL of the DOI server."
  2041. :type 'string
  2042. :version "24.3"
  2043. :group 'org-link-follow)
  2044. (defgroup org-refile nil
  2045. "Options concerning refiling entries in Org mode."
  2046. :tag "Org Refile"
  2047. :group 'org)
  2048. (defcustom org-directory "~/org"
  2049. "Directory with Org files.
  2050. This is just a default location to look for Org files. There is no need
  2051. at all to put your files into this directory. It is used in the
  2052. following situations:
  2053. 1. When a capture template specifies a target file that is not an
  2054. absolute path. The path will then be interpreted relative to
  2055. `org-directory'
  2056. 2. When the value of variable `org-agenda-files' is a single file, any
  2057. relative paths in this file will be taken as relative to
  2058. `org-directory'."
  2059. :group 'org-refile
  2060. :group 'org-capture
  2061. :type 'directory)
  2062. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2063. "Default target for storing notes.
  2064. Used as a fall back file for org-capture.el, for templates that
  2065. do not specify a target file."
  2066. :group 'org-refile
  2067. :group 'org-capture
  2068. :type 'file)
  2069. (defcustom org-goto-interface 'outline
  2070. "The default interface to be used for `org-goto'.
  2071. Allowed values are:
  2072. outline The interface shows an outline of the relevant file
  2073. and the correct heading is found by moving through
  2074. the outline or by searching with incremental search.
  2075. outline-path-completion Headlines in the current buffer are offered via
  2076. completion. This is the interface also used by
  2077. the refile command."
  2078. :group 'org-refile
  2079. :type '(choice
  2080. (const :tag "Outline" outline)
  2081. (const :tag "Outline-path-completion" outline-path-completion)))
  2082. (defcustom org-goto-max-level 5
  2083. "Maximum target level when running `org-goto' with refile interface."
  2084. :group 'org-refile
  2085. :type 'integer)
  2086. (defcustom org-reverse-note-order nil
  2087. "Non-nil means store new notes at the beginning of a file or entry.
  2088. When nil, new notes will be filed to the end of a file or entry.
  2089. This can also be a list with cons cells of regular expressions that
  2090. are matched against file names, and values."
  2091. :group 'org-capture
  2092. :group 'org-refile
  2093. :type '(choice
  2094. (const :tag "Reverse always" t)
  2095. (const :tag "Reverse never" nil)
  2096. (repeat :tag "By file name regexp"
  2097. (cons regexp boolean))))
  2098. (defcustom org-log-refile nil
  2099. "Information to record when a task is refiled.
  2100. Possible values are:
  2101. nil Don't add anything
  2102. time Add a time stamp to the task
  2103. note Prompt for a note and add it with template `org-log-note-headings'
  2104. This option can also be set with on a per-file-basis with
  2105. #+STARTUP: nologrefile
  2106. #+STARTUP: logrefile
  2107. #+STARTUP: lognoterefile
  2108. You can have local logging settings for a subtree by setting the LOGGING
  2109. property to one or more of these keywords.
  2110. When bulk-refiling from the agenda, the value `note' is forbidden and
  2111. will temporarily be changed to `time'."
  2112. :group 'org-refile
  2113. :group 'org-progress
  2114. :version "24.1"
  2115. :type '(choice
  2116. (const :tag "No logging" nil)
  2117. (const :tag "Record timestamp" time)
  2118. (const :tag "Record timestamp with note." note)))
  2119. (defcustom org-refile-targets nil
  2120. "Targets for refiling entries with `\\[org-refile]'.
  2121. This is a list of cons cells. Each cell contains:
  2122. - a specification of the files to be considered, either a list of files,
  2123. or a symbol whose function or variable value will be used to retrieve
  2124. a file name or a list of file names. If you use `org-agenda-files' for
  2125. that, all agenda files will be scanned for targets. Nil means consider
  2126. headings in the current buffer.
  2127. - A specification of how to find candidate refile targets. This may be
  2128. any of:
  2129. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2130. This tag has to be present in all target headlines, inheritance will
  2131. not be considered.
  2132. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2133. todo keyword.
  2134. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2135. headlines that are refiling targets.
  2136. - a cons cell (:level . N). Any headline of level N is considered a target.
  2137. Note that, when `org-odd-levels-only' is set, level corresponds to
  2138. order in hierarchy, not to the number of stars.
  2139. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2140. Note that, when `org-odd-levels-only' is set, level corresponds to
  2141. order in hierarchy, not to the number of stars.
  2142. Each element of this list generates a set of possible targets.
  2143. The union of these sets is presented (with completion) to
  2144. the user by `org-refile'.
  2145. You can set the variable `org-refile-target-verify-function' to a function
  2146. to verify each headline found by the simple criteria above.
  2147. When this variable is nil, all top-level headlines in the current buffer
  2148. are used, equivalent to the value `((nil . (:level . 1))'."
  2149. :group 'org-refile
  2150. :type '(repeat
  2151. (cons
  2152. (choice :value org-agenda-files
  2153. (const :tag "All agenda files" org-agenda-files)
  2154. (const :tag "Current buffer" nil)
  2155. (function) (variable) (file))
  2156. (choice :tag "Identify target headline by"
  2157. (cons :tag "Specific tag" (const :value :tag) (string))
  2158. (cons :tag "TODO keyword" (const :value :todo) (string))
  2159. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2160. (cons :tag "Level number" (const :value :level) (integer))
  2161. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2162. (defcustom org-refile-target-verify-function nil
  2163. "Function to verify if the headline at point should be a refile target.
  2164. The function will be called without arguments, with point at the
  2165. beginning of the headline. It should return t and leave point
  2166. where it is if the headline is a valid target for refiling.
  2167. If the target should not be selected, the function must return nil.
  2168. In addition to this, it may move point to a place from where the search
  2169. should be continued. For example, the function may decide that the entire
  2170. subtree of the current entry should be excluded and move point to the end
  2171. of the subtree."
  2172. :group 'org-refile
  2173. :type '(choice
  2174. (const nil)
  2175. (function)))
  2176. (defcustom org-refile-use-cache nil
  2177. "Non-nil means cache refile targets to speed up the process.
  2178. \\<org-mode-map>\
  2179. The cache for a particular file will be updated automatically when
  2180. the buffer has been killed, or when any of the marker used for flagging
  2181. refile targets no longer points at a live buffer.
  2182. If you have added new entries to a buffer that might themselves be targets,
  2183. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2184. if you find that easier, \
  2185. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2186. \\[org-refile]'."
  2187. :group 'org-refile
  2188. :version "24.1"
  2189. :type 'boolean)
  2190. (defcustom org-refile-use-outline-path nil
  2191. "Non-nil means provide refile targets as paths.
  2192. So a level 3 headline will be available as level1/level2/level3.
  2193. When the value is `file', also include the file name (without directory)
  2194. into the path. In this case, you can also stop the completion after
  2195. the file name, to get entries inserted as top level in the file.
  2196. When `full-file-path', include the full file path."
  2197. :group 'org-refile
  2198. :type '(choice
  2199. (const :tag "Not" nil)
  2200. (const :tag "Yes" t)
  2201. (const :tag "Start with file name" file)
  2202. (const :tag "Start with full file path" full-file-path)))
  2203. (defcustom org-outline-path-complete-in-steps t
  2204. "Non-nil means complete the outline path in hierarchical steps.
  2205. When Org uses the refile interface to select an outline path (see
  2206. `org-refile-use-outline-path'), the completion of the path can be
  2207. done in a single go, or it can be done in steps down the headline
  2208. hierarchy. Going in steps is probably the best if you do not use
  2209. a special completion package like `ido' or `icicles'. However,
  2210. when using these packages, going in one step can be very fast,
  2211. while still showing the whole path to the entry."
  2212. :group 'org-refile
  2213. :type 'boolean)
  2214. (defcustom org-refile-allow-creating-parent-nodes nil
  2215. "Non-nil means allow the creation of new nodes as refile targets.
  2216. New nodes are then created by adding \"/new node name\" to the completion
  2217. of an existing node. When the value of this variable is `confirm',
  2218. new node creation must be confirmed by the user (recommended).
  2219. When nil, the completion must match an existing entry.
  2220. Note that, if the new heading is not seen by the criteria
  2221. listed in `org-refile-targets', multiple instances of the same
  2222. heading would be created by trying again to file under the new
  2223. heading."
  2224. :group 'org-refile
  2225. :type '(choice
  2226. (const :tag "Never" nil)
  2227. (const :tag "Always" t)
  2228. (const :tag "Prompt for confirmation" confirm)))
  2229. (defcustom org-refile-active-region-within-subtree nil
  2230. "Non-nil means also refile active region within a subtree.
  2231. By default `org-refile' doesn't allow refiling regions if they
  2232. don't contain a set of subtrees, but it might be convenient to
  2233. do so sometimes: in that case, the first line of the region is
  2234. converted to a headline before refiling."
  2235. :group 'org-refile
  2236. :version "24.1"
  2237. :type 'boolean)
  2238. (defgroup org-todo nil
  2239. "Options concerning TODO items in Org mode."
  2240. :tag "Org TODO"
  2241. :group 'org)
  2242. (defgroup org-progress nil
  2243. "Options concerning Progress logging in Org mode."
  2244. :tag "Org Progress"
  2245. :group 'org-time)
  2246. (defvar org-todo-interpretation-widgets
  2247. '((:tag "Sequence (cycling hits every state)" sequence)
  2248. (:tag "Type (cycling directly to DONE)" type))
  2249. "The available interpretation symbols for customizing `org-todo-keywords'.
  2250. Interested libraries should add to this list.")
  2251. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2252. "List of TODO entry keyword sequences and their interpretation.
  2253. \\<org-mode-map>This is a list of sequences.
  2254. Each sequence starts with a symbol, either `sequence' or `type',
  2255. indicating if the keywords should be interpreted as a sequence of
  2256. action steps, or as different types of TODO items. The first
  2257. keywords are states requiring action - these states will select a headline
  2258. for inclusion into the global TODO list Org produces. If one of the
  2259. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2260. signify that no further action is necessary. If \"|\" is not found,
  2261. the last keyword is treated as the only DONE state of the sequence.
  2262. The command `\\[org-todo]' cycles an entry through these states, and one
  2263. additional state where no keyword is present. For details about this
  2264. cycling, see the manual.
  2265. TODO keywords and interpretation can also be set on a per-file basis with
  2266. the special #+SEQ_TODO and #+TYP_TODO lines.
  2267. Each keyword can optionally specify a character for fast state selection
  2268. \(in combination with the variable `org-use-fast-todo-selection')
  2269. and specifiers for state change logging, using the same syntax that
  2270. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2271. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2272. indicates to record a time stamp each time this state is selected.
  2273. Each keyword may also specify if a timestamp or a note should be
  2274. recorded when entering or leaving the state, by adding additional
  2275. characters in the parenthesis after the keyword. This looks like this:
  2276. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2277. record only the time of the state change. With X and Y being either
  2278. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2279. Y when leaving the state if and only if the *target* state does not
  2280. define X. You may omit any of the fast-selection key or X or /Y,
  2281. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2282. For backward compatibility, this variable may also be just a list
  2283. of keywords. In this case the interpretation (sequence or type) will be
  2284. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2285. :group 'org-todo
  2286. :group 'org-keywords
  2287. :type '(choice
  2288. (repeat :tag "Old syntax, just keywords"
  2289. (string :tag "Keyword"))
  2290. (repeat :tag "New syntax"
  2291. (cons
  2292. (choice
  2293. :tag "Interpretation"
  2294. ;;Quick and dirty way to see
  2295. ;;`org-todo-interpretations'. This takes the
  2296. ;;place of item arguments
  2297. :convert-widget
  2298. (lambda (widget)
  2299. (widget-put widget
  2300. :args (mapcar
  2301. (lambda (x)
  2302. (widget-convert
  2303. (cons 'const x)))
  2304. org-todo-interpretation-widgets))
  2305. widget))
  2306. (repeat
  2307. (string :tag "Keyword"))))))
  2308. (defvar-local org-todo-keywords-1 nil
  2309. "All TODO and DONE keywords active in a buffer.")
  2310. (defvar org-todo-keywords-for-agenda nil)
  2311. (defvar org-done-keywords-for-agenda nil)
  2312. (defvar org-todo-keyword-alist-for-agenda nil)
  2313. (defvar org-tag-alist-for-agenda nil
  2314. "Alist of all tags from all agenda files.")
  2315. (defvar org-tag-groups-alist-for-agenda nil
  2316. "Alist of all groups tags from all current agenda files.")
  2317. (defvar-local org-tag-groups-alist nil)
  2318. (defvar org-agenda-contributing-files nil)
  2319. (defvar-local org-current-tag-alist nil
  2320. "Alist of all tag groups in current buffer.
  2321. This variable takes into consideration `org-tag-alist',
  2322. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2323. (defvar-local org-not-done-keywords nil)
  2324. (defvar-local org-done-keywords nil)
  2325. (defvar-local org-todo-heads nil)
  2326. (defvar-local org-todo-sets nil)
  2327. (defvar-local org-todo-log-states nil)
  2328. (defvar-local org-todo-kwd-alist nil)
  2329. (defvar-local org-todo-key-alist nil)
  2330. (defvar-local org-todo-key-trigger nil)
  2331. (defcustom org-todo-interpretation 'sequence
  2332. "Controls how TODO keywords are interpreted.
  2333. This variable is in principle obsolete and is only used for
  2334. backward compatibility, if the interpretation of todo keywords is
  2335. not given already in `org-todo-keywords'. See that variable for
  2336. more information."
  2337. :group 'org-todo
  2338. :group 'org-keywords
  2339. :type '(choice (const sequence)
  2340. (const type)))
  2341. (defcustom org-use-fast-todo-selection t
  2342. "\\<org-mode-map>\
  2343. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2344. This variable describes if and under what circumstances the cycling
  2345. mechanism for TODO keywords will be replaced by a single-key, direct
  2346. selection scheme.
  2347. When nil, fast selection is never used.
  2348. When the symbol `prefix', it will be used when `org-todo' is called
  2349. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2350. in an Org buffer, and
  2351. `\\[universal-argument] t' in an agenda buffer.
  2352. When t, fast selection is used by default. In this case, the prefix
  2353. argument forces cycling instead.
  2354. In all cases, the special interface is only used if access keys have
  2355. actually been assigned by the user, i.e. if keywords in the configuration
  2356. are followed by a letter in parenthesis, like TODO(t)."
  2357. :group 'org-todo
  2358. :type '(choice
  2359. (const :tag "Never" nil)
  2360. (const :tag "By default" t)
  2361. (const :tag "Only with C-u C-c C-t" prefix)))
  2362. (defcustom org-provide-todo-statistics t
  2363. "Non-nil means update todo statistics after insert and toggle.
  2364. ALL-HEADLINES means update todo statistics by including headlines
  2365. with no TODO keyword as well, counting them as not done.
  2366. A list of TODO keywords means the same, but skip keywords that are
  2367. not in this list.
  2368. When set to a list of two lists, the first list contains keywords
  2369. to consider as TODO keywords, the second list contains keywords
  2370. to consider as DONE keywords.
  2371. When this is set, todo statistics is updated in the parent of the
  2372. current entry each time a todo state is changed."
  2373. :group 'org-todo
  2374. :type '(choice
  2375. (const :tag "Yes, only for TODO entries" t)
  2376. (const :tag "Yes, including all entries" all-headlines)
  2377. (repeat :tag "Yes, for TODOs in this list"
  2378. (string :tag "TODO keyword"))
  2379. (list :tag "Yes, for TODOs and DONEs in these lists"
  2380. (repeat (string :tag "TODO keyword"))
  2381. (repeat (string :tag "DONE keyword")))
  2382. (other :tag "No TODO statistics" nil)))
  2383. (defcustom org-hierarchical-todo-statistics t
  2384. "Non-nil means TODO statistics covers just direct children.
  2385. When nil, all entries in the subtree are considered.
  2386. This has only an effect if `org-provide-todo-statistics' is set.
  2387. To set this to nil for only a single subtree, use a COOKIE_DATA
  2388. property and include the word \"recursive\" into the value."
  2389. :group 'org-todo
  2390. :type 'boolean)
  2391. (defcustom org-after-todo-state-change-hook nil
  2392. "Hook which is run after the state of a TODO item was changed.
  2393. The new state (a string with a TODO keyword, or nil) is available in the
  2394. Lisp variable `org-state'."
  2395. :group 'org-todo
  2396. :type 'hook)
  2397. (defvar org-blocker-hook nil
  2398. "Hook for functions that are allowed to block a state change.
  2399. Functions in this hook should not modify the buffer.
  2400. Each function gets as its single argument a property list,
  2401. see `org-trigger-hook' for more information about this list.
  2402. If any of the functions in this hook returns nil, the state change
  2403. is blocked.")
  2404. (defvar org-trigger-hook nil
  2405. "Hook for functions that are triggered by a state change.
  2406. Each function gets as its single argument a property list with at
  2407. least the following elements:
  2408. (:type type-of-change :position pos-at-entry-start
  2409. :from old-state :to new-state)
  2410. Depending on the type, more properties may be present.
  2411. This mechanism is currently implemented for:
  2412. TODO state changes
  2413. ------------------
  2414. :type todo-state-change
  2415. :from previous state (keyword as a string), or nil, or a symbol
  2416. `todo' or `done', to indicate the general type of state.
  2417. :to new state, like in :from")
  2418. (defcustom org-enforce-todo-dependencies nil
  2419. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2420. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2421. be blocked if any prior sibling is not yet done.
  2422. Finally, if the parent is blocked because of ordered siblings of its own,
  2423. the child will also be blocked."
  2424. :set (lambda (var val)
  2425. (set var val)
  2426. (if val
  2427. (add-hook 'org-blocker-hook
  2428. 'org-block-todo-from-children-or-siblings-or-parent)
  2429. (remove-hook 'org-blocker-hook
  2430. 'org-block-todo-from-children-or-siblings-or-parent)))
  2431. :group 'org-todo
  2432. :type 'boolean)
  2433. (defcustom org-enforce-todo-checkbox-dependencies nil
  2434. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2435. When this is nil, checkboxes have no influence on switching TODO states.
  2436. When non-nil, you first need to check off all check boxes before the TODO
  2437. entry can be switched to DONE.
  2438. This variable needs to be set before org.el is loaded, and you need to
  2439. restart Emacs after a change to make the change effective. The only way
  2440. to change is while Emacs is running is through the customize interface."
  2441. :set (lambda (var val)
  2442. (set var val)
  2443. (if val
  2444. (add-hook 'org-blocker-hook
  2445. 'org-block-todo-from-checkboxes)
  2446. (remove-hook 'org-blocker-hook
  2447. 'org-block-todo-from-checkboxes)))
  2448. :group 'org-todo
  2449. :type 'boolean)
  2450. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2451. "Non-nil means inserting a TODO heading is treated as state change.
  2452. So when the command `\\[org-insert-todo-heading]' is used, state change
  2453. logging will apply if appropriate. When nil, the new TODO item will
  2454. be inserted directly, and no logging will take place."
  2455. :group 'org-todo
  2456. :type 'boolean)
  2457. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2458. "Non-nil means switching TODO states with S-cursor counts as state change.
  2459. This is the default behavior. However, setting this to nil allows a
  2460. convenient way to select a TODO state and bypass any logging associated
  2461. with that."
  2462. :group 'org-todo
  2463. :type 'boolean)
  2464. (defcustom org-todo-state-tags-triggers nil
  2465. "Tag changes that should be triggered by TODO state changes.
  2466. This is a list. Each entry is
  2467. (state-change (tag . flag) .......)
  2468. State-change can be a string with a state, and empty string to indicate the
  2469. state that has no TODO keyword, or it can be one of the symbols `todo'
  2470. or `done', meaning any not-done or done state, respectively."
  2471. :group 'org-todo
  2472. :group 'org-tags
  2473. :type '(repeat
  2474. (cons (choice :tag "When changing to"
  2475. (const :tag "Not-done state" todo)
  2476. (const :tag "Done state" done)
  2477. (string :tag "State"))
  2478. (repeat
  2479. (cons :tag "Tag action"
  2480. (string :tag "Tag")
  2481. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2482. (defcustom org-log-done nil
  2483. "Information to record when a task moves to the DONE state.
  2484. Possible values are:
  2485. nil Don't add anything, just change the keyword
  2486. time Add a time stamp to the task
  2487. note Prompt for a note and add it with template `org-log-note-headings'
  2488. This option can also be set with on a per-file-basis with
  2489. #+STARTUP: nologdone
  2490. #+STARTUP: logdone
  2491. #+STARTUP: lognotedone
  2492. You can have local logging settings for a subtree by setting the LOGGING
  2493. property to one or more of these keywords."
  2494. :group 'org-todo
  2495. :group 'org-progress
  2496. :type '(choice
  2497. (const :tag "No logging" nil)
  2498. (const :tag "Record CLOSED timestamp" time)
  2499. (const :tag "Record CLOSED timestamp with note." note)))
  2500. ;; Normalize old uses of org-log-done.
  2501. (cond
  2502. ((eq org-log-done t) (setq org-log-done 'time))
  2503. ((and (listp org-log-done) (memq 'done org-log-done))
  2504. (setq org-log-done 'note)))
  2505. (defcustom org-log-reschedule nil
  2506. "Information to record when the scheduling date of a tasks is modified.
  2507. Possible values are:
  2508. nil Don't add anything, just change the date
  2509. time Add a time stamp to the task
  2510. note Prompt for a note and add it with template `org-log-note-headings'
  2511. This option can also be set with on a per-file-basis with
  2512. #+STARTUP: nologreschedule
  2513. #+STARTUP: logreschedule
  2514. #+STARTUP: lognotereschedule"
  2515. :group 'org-todo
  2516. :group 'org-progress
  2517. :type '(choice
  2518. (const :tag "No logging" nil)
  2519. (const :tag "Record timestamp" time)
  2520. (const :tag "Record timestamp with note." note)))
  2521. (defcustom org-log-redeadline nil
  2522. "Information to record when the deadline date of a tasks is modified.
  2523. Possible values are:
  2524. nil Don't add anything, just change the date
  2525. time Add a time stamp to the task
  2526. note Prompt for a note and add it with template `org-log-note-headings'
  2527. This option can also be set with on a per-file-basis with
  2528. #+STARTUP: nologredeadline
  2529. #+STARTUP: logredeadline
  2530. #+STARTUP: lognoteredeadline
  2531. You can have local logging settings for a subtree by setting the LOGGING
  2532. property to one or more of these keywords."
  2533. :group 'org-todo
  2534. :group 'org-progress
  2535. :type '(choice
  2536. (const :tag "No logging" nil)
  2537. (const :tag "Record timestamp" time)
  2538. (const :tag "Record timestamp with note." note)))
  2539. (defcustom org-log-note-clock-out nil
  2540. "Non-nil means record a note when clocking out of an item.
  2541. This can also be configured on a per-file basis by adding one of
  2542. the following lines anywhere in the buffer:
  2543. #+STARTUP: lognoteclock-out
  2544. #+STARTUP: nolognoteclock-out"
  2545. :group 'org-todo
  2546. :group 'org-progress
  2547. :type 'boolean)
  2548. (defcustom org-log-done-with-time t
  2549. "Non-nil means the CLOSED time stamp will contain date and time.
  2550. When nil, only the date will be recorded."
  2551. :group 'org-progress
  2552. :type 'boolean)
  2553. (defcustom org-log-note-headings
  2554. '((done . "CLOSING NOTE %t")
  2555. (state . "State %-12s from %-12S %t")
  2556. (note . "Note taken on %t")
  2557. (reschedule . "Rescheduled from %S on %t")
  2558. (delschedule . "Not scheduled, was %S on %t")
  2559. (redeadline . "New deadline from %S on %t")
  2560. (deldeadline . "Removed deadline, was %S on %t")
  2561. (refile . "Refiled on %t")
  2562. (clock-out . ""))
  2563. "Headings for notes added to entries.
  2564. The value is an alist, with the car being a symbol indicating the
  2565. note context, and the cdr is the heading to be used. The heading
  2566. may also be the empty string. The following placeholders can be
  2567. used:
  2568. %t a time stamp.
  2569. %T an active time stamp instead the default inactive one
  2570. %d a short-format time stamp.
  2571. %D an active short-format time stamp.
  2572. %s the new TODO state or time stamp (inactive), in double quotes.
  2573. %S the old TODO state or time stamp (inactive), in double quotes.
  2574. %u the user name.
  2575. %U full user name.
  2576. In fact, it is not a good idea to change the `state' entry,
  2577. because Agenda Log mode depends on the format of these entries."
  2578. :group 'org-todo
  2579. :group 'org-progress
  2580. :type '(list :greedy t
  2581. (cons (const :tag "Heading when closing an item" done) string)
  2582. (cons (const :tag
  2583. "Heading when changing todo state (todo sequence only)"
  2584. state) string)
  2585. (cons (const :tag "Heading when just taking a note" note) string)
  2586. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2587. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2588. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2589. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2590. (cons (const :tag "Heading when refiling" refile) string)
  2591. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2592. (unless (assq 'note org-log-note-headings)
  2593. (push '(note . "%t") org-log-note-headings))
  2594. (defcustom org-log-into-drawer nil
  2595. "Non-nil means insert state change notes and time stamps into a drawer.
  2596. When nil, state changes notes will be inserted after the headline and
  2597. any scheduling and clock lines, but not inside a drawer.
  2598. The value of this variable should be the name of the drawer to use.
  2599. LOGBOOK is proposed as the default drawer for this purpose, you can
  2600. also set this to a string to define the drawer of your choice.
  2601. A value of t is also allowed, representing \"LOGBOOK\".
  2602. A value of t or nil can also be set with on a per-file-basis with
  2603. #+STARTUP: logdrawer
  2604. #+STARTUP: nologdrawer
  2605. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2606. will be ignored.
  2607. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2608. a subtree.
  2609. Do not check directly this variable in a Lisp program. Call
  2610. function `org-log-into-drawer' instead."
  2611. :group 'org-todo
  2612. :group 'org-progress
  2613. :type '(choice
  2614. (const :tag "Not into a drawer" nil)
  2615. (const :tag "LOGBOOK" t)
  2616. (string :tag "Other")))
  2617. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2618. (defun org-log-into-drawer ()
  2619. "Name of the log drawer, as a string, or nil.
  2620. This is the value of `org-log-into-drawer'. However, if the
  2621. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2622. be used instead of the default value."
  2623. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2624. (cond ((equal p "nil") nil)
  2625. ((equal p "t") "LOGBOOK")
  2626. ((stringp p) p)
  2627. (p "LOGBOOK")
  2628. ((stringp org-log-into-drawer) org-log-into-drawer)
  2629. (org-log-into-drawer "LOGBOOK"))))
  2630. (defcustom org-log-state-notes-insert-after-drawers nil
  2631. "Non-nil means insert state change notes after any drawers in entry.
  2632. Only the drawers that *immediately* follow the headline and the
  2633. deadline/scheduled line are skipped.
  2634. When nil, insert notes right after the heading and perhaps the line
  2635. with deadline/scheduling if present.
  2636. This variable will have no effect if `org-log-into-drawer' is
  2637. set."
  2638. :group 'org-todo
  2639. :group 'org-progress
  2640. :type 'boolean)
  2641. (defcustom org-log-states-order-reversed t
  2642. "Non-nil means the latest state note will be directly after heading.
  2643. When nil, the state change notes will be ordered according to time.
  2644. This option can also be set with on a per-file-basis with
  2645. #+STARTUP: logstatesreversed
  2646. #+STARTUP: nologstatesreversed"
  2647. :group 'org-todo
  2648. :group 'org-progress
  2649. :type 'boolean)
  2650. (defcustom org-todo-repeat-to-state nil
  2651. "The TODO state to which a repeater should return the repeating task.
  2652. By default this is the first task in a TODO sequence, or the previous state
  2653. in a TODO_TYP set. But you can specify another task here.
  2654. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2655. :group 'org-todo
  2656. :version "24.1"
  2657. :type '(choice (const :tag "Head of sequence" nil)
  2658. (string :tag "Specific state")))
  2659. (defcustom org-log-repeat 'time
  2660. "Non-nil means record moving through the DONE state when triggering repeat.
  2661. An auto-repeating task is immediately switched back to TODO when
  2662. marked DONE. If you are not logging state changes (by adding \"@\"
  2663. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2664. record a closing note, there will be no record of the task moving
  2665. through DONE. This variable forces taking a note anyway.
  2666. nil Don't force a record
  2667. time Record a time stamp
  2668. note Prompt for a note and add it with template `org-log-note-headings'
  2669. This option can also be set with on a per-file-basis with
  2670. #+STARTUP: nologrepeat
  2671. #+STARTUP: logrepeat
  2672. #+STARTUP: lognoterepeat
  2673. You can have local logging settings for a subtree by setting the LOGGING
  2674. property to one or more of these keywords."
  2675. :group 'org-todo
  2676. :group 'org-progress
  2677. :type '(choice
  2678. (const :tag "Don't force a record" nil)
  2679. (const :tag "Force recording the DONE state" time)
  2680. (const :tag "Force recording a note with the DONE state" note)))
  2681. (defgroup org-priorities nil
  2682. "Priorities in Org mode."
  2683. :tag "Org Priorities"
  2684. :group 'org-todo)
  2685. (defcustom org-enable-priority-commands t
  2686. "Non-nil means priority commands are active.
  2687. When nil, these commands will be disabled, so that you never accidentally
  2688. set a priority."
  2689. :group 'org-priorities
  2690. :type 'boolean)
  2691. (defcustom org-highest-priority ?A
  2692. "The highest priority of TODO items. A character like ?A, ?B etc.
  2693. Must have a smaller ASCII number than `org-lowest-priority'."
  2694. :group 'org-priorities
  2695. :type 'character)
  2696. (defcustom org-lowest-priority ?C
  2697. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2698. Must have a larger ASCII number than `org-highest-priority'."
  2699. :group 'org-priorities
  2700. :type 'character)
  2701. (defcustom org-default-priority ?B
  2702. "The default priority of TODO items.
  2703. This is the priority an item gets if no explicit priority is given.
  2704. When starting to cycle on an empty priority the first step in the cycle
  2705. depends on `org-priority-start-cycle-with-default'. The resulting first
  2706. step priority must not exceed the range from `org-highest-priority' to
  2707. `org-lowest-priority' which means that `org-default-priority' has to be
  2708. in this range exclusive or inclusive the range boundaries. Else the
  2709. first step refuses to set the default and the second will fall back
  2710. to (depending on the command used) the highest or lowest priority."
  2711. :group 'org-priorities
  2712. :type 'character)
  2713. (defcustom org-priority-start-cycle-with-default t
  2714. "Non-nil means start with default priority when starting to cycle.
  2715. When this is nil, the first step in the cycle will be (depending on the
  2716. command used) one higher or lower than the default priority.
  2717. See also `org-default-priority'."
  2718. :group 'org-priorities
  2719. :type 'boolean)
  2720. (defcustom org-get-priority-function nil
  2721. "Function to extract the priority from a string.
  2722. The string is normally the headline. If this is nil Org computes the
  2723. priority from the priority cookie like [#A] in the headline. It returns
  2724. an integer, increasing by 1000 for each priority level.
  2725. The user can set a different function here, which should take a string
  2726. as an argument and return the numeric priority."
  2727. :group 'org-priorities
  2728. :version "24.1"
  2729. :type '(choice
  2730. (const nil)
  2731. (function)))
  2732. (defgroup org-time nil
  2733. "Options concerning time stamps and deadlines in Org mode."
  2734. :tag "Org Time"
  2735. :group 'org)
  2736. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2737. "Number of minutes to round time stamps to.
  2738. \\<org-mode-map>\
  2739. These are two values, the first applies when first creating a time stamp.
  2740. The second applies when changing it with the commands `S-up' and `S-down'.
  2741. When changing the time stamp, this means that it will change in steps
  2742. of N minutes, as given by the second value.
  2743. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2744. numbers should be factors of 60, so for example 5, 10, 15.
  2745. When this is larger than 1, you can still force an exact time stamp by using
  2746. a double prefix argument to a time stamp command like \
  2747. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2748. and by using a prefix arg to `S-up/down' to specify the exact number
  2749. of minutes to shift."
  2750. :group 'org-time
  2751. :get (lambda (var) ; Make sure both elements are there
  2752. (if (integerp (default-value var))
  2753. (list (default-value var) 5)
  2754. (default-value var)))
  2755. :type '(list
  2756. (integer :tag "when inserting times")
  2757. (integer :tag "when modifying times")))
  2758. ;; Normalize old customizations of this variable.
  2759. (when (integerp org-time-stamp-rounding-minutes)
  2760. (setq org-time-stamp-rounding-minutes
  2761. (list org-time-stamp-rounding-minutes
  2762. org-time-stamp-rounding-minutes)))
  2763. (defcustom org-display-custom-times nil
  2764. "Non-nil means overlay custom formats over all time stamps.
  2765. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2766. To turn this on on a per-file basis, insert anywhere in the file:
  2767. #+STARTUP: customtime"
  2768. :group 'org-time
  2769. :set 'set-default
  2770. :type 'sexp)
  2771. (make-variable-buffer-local 'org-display-custom-times)
  2772. (defcustom org-time-stamp-custom-formats
  2773. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2774. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2775. These are overlaid over the default ISO format if the variable
  2776. `org-display-custom-times' is set. Time like %H:%M should be at the
  2777. end of the second format. The custom formats are also honored by export
  2778. commands, if custom time display is turned on at the time of export."
  2779. :group 'org-time
  2780. :type 'sexp)
  2781. (defun org-time-stamp-format (&optional long inactive)
  2782. "Get the right format for a time string."
  2783. (let ((f (if long (cdr org-time-stamp-formats)
  2784. (car org-time-stamp-formats))))
  2785. (if inactive
  2786. (concat "[" (substring f 1 -1) "]")
  2787. f)))
  2788. (defcustom org-time-clocksum-format
  2789. '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
  2790. "The format string used when creating CLOCKSUM lines.
  2791. This is also used when Org mode generates a time duration.
  2792. The value can be a single format string containing two
  2793. %-sequences, which will be filled with the number of hours and
  2794. minutes in that order.
  2795. Alternatively, the value can be a plist associating any of the
  2796. keys :years, :months, :weeks, :days, :hours or :minutes with
  2797. format strings. The time duration is formatted using only the
  2798. time components that are needed and concatenating the results.
  2799. If a time unit in absent, it falls back to the next smallest
  2800. unit.
  2801. The keys :require-years, :require-months, :require-days,
  2802. :require-weeks, :require-hours, :require-minutes are also
  2803. meaningful. A non-nil value for these keys indicates that the
  2804. corresponding time component should always be included, even if
  2805. its value is 0.
  2806. For example,
  2807. (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
  2808. :require-minutes t)
  2809. means durations longer than a day will be expressed in days,
  2810. hours and minutes, and durations less than a day will always be
  2811. expressed in hours and minutes (even for durations less than an
  2812. hour).
  2813. The value
  2814. (:days \"%dd\" :minutes \"%dm\")
  2815. means durations longer than a day will be expressed in days and
  2816. minutes, and durations less than a day will be expressed entirely
  2817. in minutes (even for durations longer than an hour)."
  2818. :group 'org-time
  2819. :group 'org-clock
  2820. :version "24.4"
  2821. :package-version '(Org . "8.0")
  2822. :type '(choice (string :tag "Format string")
  2823. (set :tag "Plist"
  2824. (group :inline t (const :tag "Years" :years)
  2825. (string :tag "Format string"))
  2826. (group :inline t
  2827. (const :tag "Always show years" :require-years)
  2828. (const t))
  2829. (group :inline t (const :tag "Months" :months)
  2830. (string :tag "Format string"))
  2831. (group :inline t
  2832. (const :tag "Always show months" :require-months)
  2833. (const t))
  2834. (group :inline t (const :tag "Weeks" :weeks)
  2835. (string :tag "Format string"))
  2836. (group :inline t
  2837. (const :tag "Always show weeks" :require-weeks)
  2838. (const t))
  2839. (group :inline t (const :tag "Days" :days)
  2840. (string :tag "Format string"))
  2841. (group :inline t
  2842. (const :tag "Always show days" :require-days)
  2843. (const t))
  2844. (group :inline t (const :tag "Hours" :hours)
  2845. (string :tag "Format string"))
  2846. (group :inline t
  2847. (const :tag "Always show hours" :require-hours)
  2848. (const t))
  2849. (group :inline t (const :tag "Minutes" :minutes)
  2850. (string :tag "Format string"))
  2851. (group :inline t
  2852. (const :tag "Always show minutes" :require-minutes)
  2853. (const t)))))
  2854. (defcustom org-time-clocksum-use-fractional nil
  2855. "When non-nil, `\\[org-clock-display]' uses fractional times.
  2856. See `org-time-clocksum-format' for more on time clock formats."
  2857. :group 'org-time
  2858. :group 'org-clock
  2859. :version "24.3"
  2860. :type 'boolean)
  2861. (defcustom org-time-clocksum-use-effort-durations nil
  2862. "When non-nil, `\\[org-clock-display]' uses effort durations.
  2863. E.g. by default, one day is considered to be a 8 hours effort,
  2864. so a task that has been clocked for 16 hours will be displayed
  2865. as during 2 days in the clock display or in the clocktable.
  2866. See `org-effort-durations' on how to set effort durations
  2867. and `org-time-clocksum-format' for more on time clock formats."
  2868. :group 'org-time
  2869. :group 'org-clock
  2870. :version "24.4"
  2871. :package-version '(Org . "8.0")
  2872. :type 'boolean)
  2873. (defcustom org-time-clocksum-fractional-format "%.2f"
  2874. "The format string used when creating CLOCKSUM lines,
  2875. or when Org mode generates a time duration, if
  2876. `org-time-clocksum-use-fractional' is enabled.
  2877. The value can be a single format string containing one
  2878. %-sequence, which will be filled with the number of hours as
  2879. a float.
  2880. Alternatively, the value can be a plist associating any of the
  2881. keys :years, :months, :weeks, :days, :hours or :minutes with
  2882. a format string. The time duration is formatted using the
  2883. largest time unit which gives a non-zero integer part. If all
  2884. specified formats have zero integer part, the smallest time unit
  2885. is used."
  2886. :group 'org-time
  2887. :type '(choice (string :tag "Format string")
  2888. (set (group :inline t (const :tag "Years" :years)
  2889. (string :tag "Format string"))
  2890. (group :inline t (const :tag "Months" :months)
  2891. (string :tag "Format string"))
  2892. (group :inline t (const :tag "Weeks" :weeks)
  2893. (string :tag "Format string"))
  2894. (group :inline t (const :tag "Days" :days)
  2895. (string :tag "Format string"))
  2896. (group :inline t (const :tag "Hours" :hours)
  2897. (string :tag "Format string"))
  2898. (group :inline t (const :tag "Minutes" :minutes)
  2899. (string :tag "Format string")))))
  2900. (defcustom org-deadline-warning-days 14
  2901. "Number of days before expiration during which a deadline becomes active.
  2902. This variable governs the display in sparse trees and in the agenda.
  2903. When 0 or negative, it means use this number (the absolute value of it)
  2904. even if a deadline has a different individual lead time specified.
  2905. Custom commands can set this variable in the options section."
  2906. :group 'org-time
  2907. :group 'org-agenda-daily/weekly
  2908. :type 'integer)
  2909. (defcustom org-scheduled-delay-days 0
  2910. "Number of days before a scheduled item becomes active.
  2911. This variable governs the display in sparse trees and in the agenda.
  2912. The default value (i.e. 0) means: don't delay scheduled item.
  2913. When negative, it means use this number (the absolute value of it)
  2914. even if a scheduled item has a different individual delay time
  2915. specified.
  2916. Custom commands can set this variable in the options section."
  2917. :group 'org-time
  2918. :group 'org-agenda-daily/weekly
  2919. :version "24.4"
  2920. :package-version '(Org . "8.0")
  2921. :type 'integer)
  2922. (defcustom org-read-date-prefer-future t
  2923. "Non-nil means assume future for incomplete date input from user.
  2924. This affects the following situations:
  2925. 1. The user gives a month but not a year.
  2926. For example, if it is April and you enter \"feb 2\", this will be read
  2927. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2928. 2. The user gives a day, but no month.
  2929. For example, if today is the 15th, and you enter \"3\", Org will read
  2930. this as the third of *next* month. However, if you enter \"17\",
  2931. it will be considered as *this* month.
  2932. If you set this variable to the symbol `time', then also the following
  2933. will work:
  2934. 3. If the user gives a time.
  2935. If the time is before now, it will be interpreted as tomorrow.
  2936. Currently none of this works for ISO week specifications.
  2937. When this option is nil, the current day, month and year will always be
  2938. used as defaults.
  2939. See also `org-agenda-jump-prefer-future'."
  2940. :group 'org-time
  2941. :type '(choice
  2942. (const :tag "Never" nil)
  2943. (const :tag "Check month and day" t)
  2944. (const :tag "Check month, day, and time" time)))
  2945. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2946. "Should the agenda jump command prefer the future for incomplete dates?
  2947. The default is to do the same as configured in `org-read-date-prefer-future'.
  2948. But you can also set a deviating value here.
  2949. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2950. :group 'org-agenda
  2951. :group 'org-time
  2952. :version "24.1"
  2953. :type '(choice
  2954. (const :tag "Use org-read-date-prefer-future"
  2955. org-read-date-prefer-future)
  2956. (const :tag "Never" nil)
  2957. (const :tag "Always" t)))
  2958. (defcustom org-read-date-force-compatible-dates t
  2959. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2960. Depending on the system Emacs is running on, certain dates cannot
  2961. be represented with the type used internally to represent time.
  2962. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2963. correctly. Some systems allow for earlier dates, some for later,
  2964. some for both. One way to find out it to insert any date into an
  2965. Org buffer, putting the cursor on the year and hitting S-up and
  2966. S-down to test the range.
  2967. When this variable is set to t, the date/time prompt will not let
  2968. you specify dates outside the 1970-2037 range, so it is certain that
  2969. these dates will work in whatever version of Emacs you are
  2970. running, and also that you can move a file from one Emacs implementation
  2971. to another. WHenever Org is forcing the year for you, it will display
  2972. a message and beep.
  2973. When this variable is nil, Org will check if the date is
  2974. representable in the specific Emacs implementation you are using.
  2975. If not, it will force a year, usually the current year, and beep
  2976. to remind you. Currently this setting is not recommended because
  2977. the likelihood that you will open your Org files in an Emacs that
  2978. has limited date range is not negligible.
  2979. A workaround for this problem is to use diary sexp dates for time
  2980. stamps outside of this range."
  2981. :group 'org-time
  2982. :version "24.1"
  2983. :type 'boolean)
  2984. (defcustom org-read-date-display-live t
  2985. "Non-nil means display current interpretation of date prompt live.
  2986. This display will be in an overlay, in the minibuffer."
  2987. :group 'org-time
  2988. :type 'boolean)
  2989. (defcustom org-read-date-popup-calendar t
  2990. "Non-nil means pop up a calendar when prompting for a date.
  2991. In the calendar, the date can be selected with mouse-1. However, the
  2992. minibuffer will also be active, and you can simply enter the date as well.
  2993. When nil, only the minibuffer will be available."
  2994. :group 'org-time
  2995. :type 'boolean)
  2996. (defvaralias 'org-popup-calendar-for-date-prompt
  2997. 'org-read-date-popup-calendar)
  2998. (defcustom org-extend-today-until 0
  2999. "The hour when your day really ends. Must be an integer.
  3000. This has influence for the following applications:
  3001. - When switching the agenda to \"today\". It it is still earlier than
  3002. the time given here, the day recognized as TODAY is actually yesterday.
  3003. - When a date is read from the user and it is still before the time given
  3004. here, the current date and time will be assumed to be yesterday, 23:59.
  3005. Also, timestamps inserted in capture templates follow this rule.
  3006. IMPORTANT: This is a feature whose implementation is and likely will
  3007. remain incomplete. Really, it is only here because past midnight seems to
  3008. be the favorite working time of John Wiegley :-)"
  3009. :group 'org-time
  3010. :type 'integer)
  3011. (defcustom org-use-effective-time nil
  3012. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  3013. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  3014. \"effective time\" of any timestamps between midnight and 8am will be
  3015. 23:59 of the previous day."
  3016. :group 'org-time
  3017. :version "24.1"
  3018. :type 'boolean)
  3019. (defcustom org-use-last-clock-out-time-as-effective-time nil
  3020. "When non-nil, use the last clock out time for `org-todo'.
  3021. Note that this option has precedence over the combined use of
  3022. `org-use-effective-time' and `org-extend-today-until'."
  3023. :group 'org-time
  3024. :version "24.4"
  3025. :package-version '(Org . "8.0")
  3026. :type 'boolean)
  3027. (defcustom org-edit-timestamp-down-means-later nil
  3028. "Non-nil means S-down will increase the time in a time stamp.
  3029. When nil, S-up will increase."
  3030. :group 'org-time
  3031. :type 'boolean)
  3032. (defcustom org-calendar-follow-timestamp-change t
  3033. "Non-nil means make the calendar window follow timestamp changes.
  3034. When a timestamp is modified and the calendar window is visible, it will be
  3035. moved to the new date."
  3036. :group 'org-time
  3037. :type 'boolean)
  3038. (defgroup org-tags nil
  3039. "Options concerning tags in Org mode."
  3040. :tag "Org Tags"
  3041. :group 'org)
  3042. (defcustom org-tag-alist nil
  3043. "Default tags available in Org files.
  3044. The value of this variable is an alist. Associations either:
  3045. (TAG)
  3046. (TAG . SELECT)
  3047. (SPECIAL)
  3048. where TAG is a tag as a string, SELECT is a character, used to
  3049. select that tag through the fast tag selection interface, and
  3050. SPECIAL is one of the following keywords: `:startgroup',
  3051. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  3052. `:newline'. These keywords are used to define a hierarchy of
  3053. tags. See manual for details.
  3054. When this variable is nil, Org mode bases tag input on what is
  3055. already in the buffer. The value can be overridden locally by
  3056. using a TAGS keyword, e.g.,
  3057. #+TAGS: tag1 tag2
  3058. See also `org-tag-persistent-alist' to sidestep this behavior."
  3059. :group 'org-tags
  3060. :type '(repeat
  3061. (choice
  3062. (cons (string :tag "Tag name")
  3063. (character :tag "Access char"))
  3064. (const :tag "Start radio group" (:startgroup))
  3065. (const :tag "Start tag group, non distinct" (:startgrouptag))
  3066. (const :tag "Group tags delimiter" (:grouptags))
  3067. (const :tag "End radio group" (:endgroup))
  3068. (const :tag "End tag group, non distinct" (:endgrouptag))
  3069. (const :tag "New line" (:newline)))))
  3070. (defcustom org-tag-persistent-alist nil
  3071. "Tags always available in Org files.
  3072. The value of this variable is an alist. Associations either:
  3073. (TAG)
  3074. (TAG . SELECT)
  3075. (SPECIAL)
  3076. where TAG is a tag as a string, SELECT is a character, used to
  3077. select that tag through the fast tag selection interface, and
  3078. SPECIAL is one of the following keywords: `:startgroup',
  3079. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  3080. `:newline'. These keywords are used to define a hierarchy of
  3081. tags. See manual for details.
  3082. Unlike to `org-tag-alist', tags defined in this variable do not
  3083. depend on a local TAGS keyword. Instead, to disable these tags
  3084. on a per-file basis, insert anywhere in the file:
  3085. #+STARTUP: noptag"
  3086. :group 'org-tags
  3087. :type '(repeat
  3088. (choice
  3089. (cons (string :tag "Tag name")
  3090. (character :tag "Access char"))
  3091. (const :tag "Start radio group" (:startgroup))
  3092. (const :tag "Start tag group, non distinct" (:startgrouptag))
  3093. (const :tag "Group tags delimiter" (:grouptags))
  3094. (const :tag "End radio group" (:endgroup))
  3095. (const :tag "End tag group, non distinct" (:endgrouptag))
  3096. (const :tag "New line" (:newline)))))
  3097. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  3098. "If non-nil, always offer completion for all tags of all agenda files.
  3099. Instead of customizing this variable directly, you might want to
  3100. set it locally for capture buffers, because there no list of
  3101. tags in that file can be created dynamically (there are none).
  3102. (add-hook \\='org-capture-mode-hook
  3103. (lambda ()
  3104. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  3105. :group 'org-tags
  3106. :version "24.1"
  3107. :type 'boolean)
  3108. (defvar org-file-tags nil
  3109. "List of tags that can be inherited by all entries in the file.
  3110. The tags will be inherited if the variable `org-use-tag-inheritance'
  3111. says they should be.
  3112. This variable is populated from #+FILETAGS lines.")
  3113. (defcustom org-use-fast-tag-selection 'auto
  3114. "Non-nil means use fast tag selection scheme.
  3115. This is a special interface to select and deselect tags with single keys.
  3116. When nil, fast selection is never used.
  3117. When the symbol `auto', fast selection is used if and only if selection
  3118. characters for tags have been configured, either through the variable
  3119. `org-tag-alist' or through a #+TAGS line in the buffer.
  3120. When t, fast selection is always used and selection keys are assigned
  3121. automatically if necessary."
  3122. :group 'org-tags
  3123. :type '(choice
  3124. (const :tag "Always" t)
  3125. (const :tag "Never" nil)
  3126. (const :tag "When selection characters are configured" auto)))
  3127. (defcustom org-fast-tag-selection-single-key nil
  3128. "Non-nil means fast tag selection exits after first change.
  3129. When nil, you have to press RET to exit it.
  3130. During fast tag selection, you can toggle this flag with `C-c'.
  3131. This variable can also have the value `expert'. In this case, the window
  3132. displaying the tags menu is not even shown, until you press C-c again."
  3133. :group 'org-tags
  3134. :type '(choice
  3135. (const :tag "No" nil)
  3136. (const :tag "Yes" t)
  3137. (const :tag "Expert" expert)))
  3138. (defvar org-fast-tag-selection-include-todo nil
  3139. "Non-nil means fast tags selection interface will also offer TODO states.
  3140. This is an undocumented feature, you should not rely on it.")
  3141. (defcustom org-tags-column -77
  3142. "The column to which tags should be indented in a headline.
  3143. If this number is positive, it specifies the column. If it is negative,
  3144. it means that the tags should be flushright to that column. For example,
  3145. -80 works well for a normal 80 character screen.
  3146. When 0, place tags directly after headline text, with only one space in
  3147. between."
  3148. :group 'org-tags
  3149. :type 'integer)
  3150. (defcustom org-auto-align-tags t
  3151. "Non-nil keeps tags aligned when modifying headlines.
  3152. Some operations (i.e. demoting) change the length of a headline and
  3153. therefore shift the tags around. With this option turned on, after
  3154. each such operation the tags are again aligned to `org-tags-column'."
  3155. :group 'org-tags
  3156. :type 'boolean)
  3157. (defcustom org-use-tag-inheritance t
  3158. "Non-nil means tags in levels apply also for sublevels.
  3159. When nil, only the tags directly given in a specific line apply there.
  3160. This may also be a list of tags that should be inherited, or a regexp that
  3161. matches tags that should be inherited. Additional control is possible
  3162. with the variable `org-tags-exclude-from-inheritance' which gives an
  3163. explicit list of tags to be excluded from inheritance, even if the value of
  3164. `org-use-tag-inheritance' would select it for inheritance.
  3165. If this option is t, a match early-on in a tree can lead to a large
  3166. number of matches in the subtree when constructing the agenda or creating
  3167. a sparse tree. If you only want to see the first match in a tree during
  3168. a search, check out the variable `org-tags-match-list-sublevels'."
  3169. :group 'org-tags
  3170. :type '(choice
  3171. (const :tag "Not" nil)
  3172. (const :tag "Always" t)
  3173. (repeat :tag "Specific tags" (string :tag "Tag"))
  3174. (regexp :tag "Tags matched by regexp")))
  3175. (defcustom org-tags-exclude-from-inheritance nil
  3176. "List of tags that should never be inherited.
  3177. This is a way to exclude a few tags from inheritance. For way to do
  3178. the opposite, to actively allow inheritance for selected tags,
  3179. see the variable `org-use-tag-inheritance'."
  3180. :group 'org-tags
  3181. :type '(repeat (string :tag "Tag")))
  3182. (defun org-tag-inherit-p (tag)
  3183. "Check if TAG is one that should be inherited."
  3184. (cond
  3185. ((member tag org-tags-exclude-from-inheritance) nil)
  3186. ((eq org-use-tag-inheritance t) t)
  3187. ((not org-use-tag-inheritance) nil)
  3188. ((stringp org-use-tag-inheritance)
  3189. (string-match org-use-tag-inheritance tag))
  3190. ((listp org-use-tag-inheritance)
  3191. (member tag org-use-tag-inheritance))
  3192. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3193. (defcustom org-tags-match-list-sublevels t
  3194. "Non-nil means list also sublevels of headlines matching a search.
  3195. This variable applies to tags/property searches, and also to stuck
  3196. projects because this search is based on a tags match as well.
  3197. When set to the symbol `indented', sublevels are indented with
  3198. leading dots.
  3199. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3200. the sublevels of a headline matching a tag search often also match
  3201. the same search. Listing all of them can create very long lists.
  3202. Setting this variable to nil causes subtrees of a match to be skipped.
  3203. This variable is semi-obsolete and probably should always be true. It
  3204. is better to limit inheritance to certain tags using the variables
  3205. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3206. :group 'org-tags
  3207. :type '(choice
  3208. (const :tag "No, don't list them" nil)
  3209. (const :tag "Yes, do list them" t)
  3210. (const :tag "List them, indented with leading dots" indented)))
  3211. (defcustom org-tags-sort-function nil
  3212. "When set, tags are sorted using this function as a comparator."
  3213. :group 'org-tags
  3214. :type '(choice
  3215. (const :tag "No sorting" nil)
  3216. (const :tag "Alphabetical" string<)
  3217. (const :tag "Reverse alphabetical" string>)
  3218. (function :tag "Custom function" nil)))
  3219. (defvar org-tags-history nil
  3220. "History of minibuffer reads for tags.")
  3221. (defvar org-last-tags-completion-table nil
  3222. "The last used completion table for tags.")
  3223. (defvar org-after-tags-change-hook nil
  3224. "Hook that is run after the tags in a line have changed.")
  3225. (defgroup org-properties nil
  3226. "Options concerning properties in Org mode."
  3227. :tag "Org Properties"
  3228. :group 'org)
  3229. (defcustom org-property-format "%-10s %s"
  3230. "How property key/value pairs should be formatted by `indent-line'.
  3231. When `indent-line' hits a property definition, it will format the line
  3232. according to this format, mainly to make sure that the values are
  3233. lined-up with respect to each other."
  3234. :group 'org-properties
  3235. :type 'string)
  3236. (defcustom org-properties-postprocess-alist nil
  3237. "Alist of properties and functions to adjust inserted values.
  3238. Elements of this alist must be of the form
  3239. ([string] [function])
  3240. where [string] must be a property name and [function] must be a
  3241. lambda expression: this lambda expression must take one argument,
  3242. the value to adjust, and return the new value as a string.
  3243. For example, this element will allow the property \"Remaining\"
  3244. to be updated wrt the relation between the \"Effort\" property
  3245. and the clock summary:
  3246. ((\"Remaining\" (lambda(value)
  3247. (let ((clocksum (org-clock-sum-current-item))
  3248. (effort (org-duration-string-to-minutes
  3249. (org-entry-get (point) \"Effort\"))))
  3250. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3251. :group 'org-properties
  3252. :version "24.1"
  3253. :type '(alist :key-type (string :tag "Property")
  3254. :value-type (function :tag "Function")))
  3255. (defcustom org-use-property-inheritance nil
  3256. "Non-nil means properties apply also for sublevels.
  3257. This setting is chiefly used during property searches. Turning it on can
  3258. cause significant overhead when doing a search, which is why it is not
  3259. on by default.
  3260. When nil, only the properties directly given in the current entry count.
  3261. When t, every property is inherited. The value may also be a list of
  3262. properties that should have inheritance, or a regular expression matching
  3263. properties that should be inherited.
  3264. However, note that some special properties use inheritance under special
  3265. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3266. and the properties ending in \"_ALL\" when they are used as descriptor
  3267. for valid values of a property.
  3268. Note for programmers:
  3269. When querying an entry with `org-entry-get', you can control if inheritance
  3270. should be used. By default, `org-entry-get' looks only at the local
  3271. properties. You can request inheritance by setting the inherit argument
  3272. to t (to force inheritance) or to `selective' (to respect the setting
  3273. in this variable)."
  3274. :group 'org-properties
  3275. :type '(choice
  3276. (const :tag "Not" nil)
  3277. (const :tag "Always" t)
  3278. (repeat :tag "Specific properties" (string :tag "Property"))
  3279. (regexp :tag "Properties matched by regexp")))
  3280. (defun org-property-inherit-p (property)
  3281. "Check if PROPERTY is one that should be inherited."
  3282. (cond
  3283. ((eq org-use-property-inheritance t) t)
  3284. ((not org-use-property-inheritance) nil)
  3285. ((stringp org-use-property-inheritance)
  3286. (string-match org-use-property-inheritance property))
  3287. ((listp org-use-property-inheritance)
  3288. (member property org-use-property-inheritance))
  3289. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3290. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3291. "The default column format, if no other format has been defined.
  3292. This variable can be set on the per-file basis by inserting a line
  3293. #+COLUMNS: %25ITEM ....."
  3294. :group 'org-properties
  3295. :type 'string)
  3296. (defcustom org-columns-ellipses ".."
  3297. "The ellipses to be used when a field in column view is truncated.
  3298. When this is the empty string, as many characters as possible are shown,
  3299. but then there will be no visual indication that the field has been truncated.
  3300. When this is a string of length N, the last N characters of a truncated
  3301. field are replaced by this string. If the column is narrower than the
  3302. ellipses string, only part of the ellipses string will be shown."
  3303. :group 'org-properties
  3304. :type 'string)
  3305. (defconst org-global-properties-fixed
  3306. '(("VISIBILITY_ALL" . "folded children content all")
  3307. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3308. "List of property/value pairs that can be inherited by any entry.
  3309. These are fixed values, for the preset properties. The user variable
  3310. that can be used to add to this list is `org-global-properties'.
  3311. The entries in this list are cons cells where the car is a property
  3312. name and cdr is a string with the value. If the value represents
  3313. multiple items like an \"_ALL\" property, separate the items by
  3314. spaces.")
  3315. (defcustom org-global-properties nil
  3316. "List of property/value pairs that can be inherited by any entry.
  3317. This list will be combined with the constant `org-global-properties-fixed'.
  3318. The entries in this list are cons cells where the car is a property
  3319. name and cdr is a string with the value.
  3320. You can set buffer-local values for the same purpose in the variable
  3321. `org-file-properties' this by adding lines like
  3322. #+PROPERTY: NAME VALUE"
  3323. :group 'org-properties
  3324. :type '(repeat
  3325. (cons (string :tag "Property")
  3326. (string :tag "Value"))))
  3327. (defvar-local org-file-properties nil
  3328. "List of property/value pairs that can be inherited by any entry.
  3329. Valid for the current buffer.
  3330. This variable is populated from #+PROPERTY lines.")
  3331. (defgroup org-agenda nil
  3332. "Options concerning agenda views in Org mode."
  3333. :tag "Org Agenda"
  3334. :group 'org)
  3335. (defvar-local org-category nil
  3336. "Variable used by org files to set a category for agenda display.
  3337. Such files should use a file variable to set it, for example
  3338. # -*- mode: org; org-category: \"ELisp\"
  3339. or contain a special line
  3340. #+CATEGORY: ELisp
  3341. If the file does not specify a category, then file's base name
  3342. is used instead.")
  3343. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3344. (defcustom org-agenda-files nil
  3345. "The files to be used for agenda display.
  3346. If an entry is a directory, all files in that directory that are matched
  3347. by `org-agenda-file-regexp' will be part of the file list.
  3348. If the value of the variable is not a list but a single file name, then
  3349. the list of agenda files is actually stored and maintained in that file,
  3350. one agenda file per line. In this file paths can be given relative to
  3351. `org-directory'. Tilde expansion and environment variable substitution
  3352. are also made.
  3353. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3354. and removed with `\\[org-remove-file]'."
  3355. :group 'org-agenda
  3356. :type '(choice
  3357. (repeat :tag "List of files and directories" file)
  3358. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3359. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3360. "Regular expression to match files for `org-agenda-files'.
  3361. If any element in the list in that variable contains a directory instead
  3362. of a normal file, all files in that directory that are matched by this
  3363. regular expression will be included."
  3364. :group 'org-agenda
  3365. :type 'regexp)
  3366. (defcustom org-agenda-text-search-extra-files nil
  3367. "List of extra files to be searched by text search commands.
  3368. These files will be searched in addition to the agenda files by the
  3369. commands `org-search-view' (`\\[org-agenda] s') \
  3370. and `org-occur-in-agenda-files'.
  3371. Note that these files will only be searched for text search commands,
  3372. not for the other agenda views like todo lists, tag searches or the weekly
  3373. agenda. This variable is intended to list notes and possibly archive files
  3374. that should also be searched by these two commands.
  3375. In fact, if the first element in the list is the symbol `agenda-archives',
  3376. then all archive files of all agenda files will be added to the search
  3377. scope."
  3378. :group 'org-agenda
  3379. :type '(set :greedy t
  3380. (const :tag "Agenda Archives" agenda-archives)
  3381. (repeat :inline t (file))))
  3382. (defvaralias 'org-agenda-multi-occur-extra-files
  3383. 'org-agenda-text-search-extra-files)
  3384. (defcustom org-agenda-skip-unavailable-files nil
  3385. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3386. A nil value means to remove them, after a query, from the list."
  3387. :group 'org-agenda
  3388. :type 'boolean)
  3389. (defcustom org-calendar-to-agenda-key [?c]
  3390. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3391. The command `org-calendar-goto-agenda' will be bound to this key. The
  3392. default is the character `c' because then `c' can be used to switch back and
  3393. forth between agenda and calendar."
  3394. :group 'org-agenda
  3395. :type 'sexp)
  3396. (defcustom org-calendar-insert-diary-entry-key [?i]
  3397. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3398. This option is irrelevant until `org-agenda-diary-file' has been configured
  3399. to point to an Org file. When that is the case, the command
  3400. `org-agenda-diary-entry' will be bound to the key given here, by default
  3401. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3402. if you want to continue doing this, you need to change this to a different
  3403. key."
  3404. :group 'org-agenda
  3405. :type 'sexp)
  3406. (defcustom org-agenda-diary-file 'diary-file
  3407. "File to which to add new entries with the `i' key in agenda and calendar.
  3408. When this is the symbol `diary-file', the functionality in the Emacs
  3409. calendar will be used to add entries to the `diary-file'. But when this
  3410. points to a file, `org-agenda-diary-entry' will be used instead."
  3411. :group 'org-agenda
  3412. :type '(choice
  3413. (const :tag "The standard Emacs diary file" diary-file)
  3414. (file :tag "Special Org file diary entries")))
  3415. (eval-after-load "calendar"
  3416. '(progn
  3417. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3418. 'org-calendar-goto-agenda)
  3419. (add-hook 'calendar-mode-hook
  3420. (lambda ()
  3421. (unless (eq org-agenda-diary-file 'diary-file)
  3422. (define-key calendar-mode-map
  3423. org-calendar-insert-diary-entry-key
  3424. 'org-agenda-diary-entry))))))
  3425. (defgroup org-latex nil
  3426. "Options for embedding LaTeX code into Org mode."
  3427. :tag "Org LaTeX"
  3428. :group 'org)
  3429. (defcustom org-format-latex-options
  3430. '(:foreground default :background default :scale 1.0
  3431. :html-foreground "Black" :html-background "Transparent"
  3432. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3433. "Options for creating images from LaTeX fragments.
  3434. This is a property list with the following properties:
  3435. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3436. `default' means use the foreground of the default face.
  3437. `auto' means use the foreground from the text face.
  3438. :background the background color, or \"Transparent\".
  3439. `default' means use the background of the default face.
  3440. `auto' means use the background from the text face.
  3441. :scale a scaling factor for the size of the images, to get more pixels
  3442. :html-foreground, :html-background, :html-scale
  3443. the same numbers for HTML export.
  3444. :matchers a list indicating which matchers should be used to
  3445. find LaTeX fragments. Valid members of this list are:
  3446. \"begin\" find environments
  3447. \"$1\" find single characters surrounded by $.$
  3448. \"$\" find math expressions surrounded by $...$
  3449. \"$$\" find math expressions surrounded by $$....$$
  3450. \"\\(\" find math expressions surrounded by \\(...\\)
  3451. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3452. :group 'org-latex
  3453. :type 'plist)
  3454. (defcustom org-format-latex-signal-error t
  3455. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3456. When nil, just push out a message."
  3457. :group 'org-latex
  3458. :version "24.1"
  3459. :type 'boolean)
  3460. (defcustom org-latex-to-mathml-jar-file nil
  3461. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3462. Use this to specify additional executable file say a jar file.
  3463. When using MathToWeb as the converter, specify the full-path to
  3464. your mathtoweb.jar file."
  3465. :group 'org-latex
  3466. :version "24.1"
  3467. :type '(choice
  3468. (const :tag "None" nil)
  3469. (file :tag "JAR file" :must-match t)))
  3470. (defcustom org-latex-to-mathml-convert-command nil
  3471. "Command to convert LaTeX fragments to MathML.
  3472. Replace format-specifiers in the command as noted below and use
  3473. `shell-command' to convert LaTeX to MathML.
  3474. %j: Executable file in fully expanded form as specified by
  3475. `org-latex-to-mathml-jar-file'.
  3476. %I: Input LaTeX file in fully expanded form.
  3477. %i: The latex fragment to be converted.
  3478. %o: Output MathML file.
  3479. This command is used by `org-create-math-formula'.
  3480. When using MathToWeb as the converter, set this option to
  3481. \"java -jar %j -unicode -force -df %o %I\".
  3482. When using LaTeXML set this option to
  3483. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3484. :group 'org-latex
  3485. :version "24.1"
  3486. :type '(choice
  3487. (const :tag "None" nil)
  3488. (string :tag "\nShell command")))
  3489. (defcustom org-preview-latex-default-process 'dvipng
  3490. "The default process to convert LaTeX fragments to image files.
  3491. All available processes and theirs documents can be found in
  3492. `org-preview-latex-process-alist', which see."
  3493. :group 'org-latex
  3494. :version "25.2"
  3495. :package-version '(Org . "9.0")
  3496. :type 'symbol)
  3497. (defcustom org-preview-latex-process-alist
  3498. '((dvipng
  3499. :programs ("latex" "dvipng" "gs")
  3500. :description "dvi > png"
  3501. :message "you need to install the programs: latex, dvipng and ghostscript."
  3502. :image-input-type "dvi"
  3503. :image-output-type "png"
  3504. :image-size-adjust (1.0 . 1.0)
  3505. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3506. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %b.png %f"))
  3507. (dvisvgm
  3508. :programs ("latex" "dvisvgm" "gs")
  3509. :description "dvi > svg"
  3510. :message "you need to install the programs: latex, dvisvgm and ghostscript."
  3511. :use-xcolor t
  3512. :image-input-type "dvi"
  3513. :image-output-type "svg"
  3514. :image-size-adjust (1.7 . 1.5)
  3515. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3516. :image-converter ("dvisvgm %f -n -b min -c %S -o %b.svg"))
  3517. (imagemagick
  3518. :programs ("latex" "convert" "gs")
  3519. :description "pdf > png"
  3520. :message
  3521. "you need to install the programs: latex, imagemagick and ghostscript."
  3522. :use-xcolor t
  3523. :image-input-type "pdf"
  3524. :image-output-type "png"
  3525. :image-size-adjust (1.0 . 1.0)
  3526. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3527. :image-converter
  3528. ("convert -density %D -trim -antialias %f -quality 100 %b.png")))
  3529. "Definitions of external processes for LaTeX previewing.
  3530. Org mode can use some external commands to generate TeX snippet's images for
  3531. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3532. `org-create-formula-image' how to call them.
  3533. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3534. PROPERTIES accepts the following attributes:
  3535. :programs list of strings, required programs.
  3536. :description string, describe the process.
  3537. :message string, message it when required programs cannot be found.
  3538. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3539. :image-output-type string, output file type of image converter (e.g., \"png\").
  3540. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3541. deal with background and foreground color of image.
  3542. Otherwise, dvipng style background and foregroud color
  3543. format are generated. You may then refer to them in
  3544. command options with \"%F\" and \"%B\".
  3545. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3546. image size showed in buffer and the cdr element is for
  3547. HTML file. This option is only useful for process
  3548. developers, users should use variable
  3549. `org-format-latex-options' instead.
  3550. :post-clean list of strings, files matched are to be cleaned up once
  3551. the image is generated. When nil, the files with \".dvi\",
  3552. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3553. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3554. be cleaned up.
  3555. :latex-header list of strings, the LaTeX header of the snippet file.
  3556. When nil, the fallback value is used instead, which is
  3557. controlled by `org-format-latex-header',
  3558. `org-latex-default-packages-alist' and
  3559. `org-latex-packages-alist', which see.
  3560. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3561. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3562. replaced with values defined below.
  3563. :image-converter list of image converter commands strings. Each of them is
  3564. given to the shell and supports any of the following
  3565. place-holders defined below.
  3566. Place-holders used by `:image-converter' and `:latex-compiler':
  3567. %f input file name.
  3568. %b base name of input file.
  3569. %o base directory of input file.
  3570. Place-holders only used by `:image-converter':
  3571. %F foreground of image
  3572. %B background of image
  3573. %D dpi, which is used to adjust image size by some processing commands.
  3574. %S the image size scale ratio, which is used to adjust image size by some
  3575. processing commands."
  3576. :group 'org-latex
  3577. :version "25.2"
  3578. :package-version '(Org . "9.0")
  3579. :type '(alist :tag "LaTeX to image backends"
  3580. :value-type (plist)))
  3581. (defcustom org-preview-latex-image-directory "ltximg/"
  3582. "Path to store latex preview images.
  3583. A relative path here creates many directories relative to the
  3584. processed org files paths. An absolute path puts all preview
  3585. images at the same place."
  3586. :group 'org-latex
  3587. :version "25.2"
  3588. :package-version '(Org . "9.0")
  3589. :type 'string)
  3590. (defun org-format-latex-mathml-available-p ()
  3591. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3592. (save-match-data
  3593. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3594. org-latex-to-mathml-convert-command)
  3595. (let ((executable (car (split-string
  3596. org-latex-to-mathml-convert-command))))
  3597. (when (executable-find executable)
  3598. (if (string-match
  3599. "%j" org-latex-to-mathml-convert-command)
  3600. (file-readable-p org-latex-to-mathml-jar-file)
  3601. t))))))
  3602. (defcustom org-format-latex-header "\\documentclass{article}
  3603. \\usepackage[usenames]{color}
  3604. \[PACKAGES]
  3605. \[DEFAULT-PACKAGES]
  3606. \\pagestyle{empty} % do not remove
  3607. % The settings below are copied from fullpage.sty
  3608. \\setlength{\\textwidth}{\\paperwidth}
  3609. \\addtolength{\\textwidth}{-3cm}
  3610. \\setlength{\\oddsidemargin}{1.5cm}
  3611. \\addtolength{\\oddsidemargin}{-2.54cm}
  3612. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3613. \\setlength{\\textheight}{\\paperheight}
  3614. \\addtolength{\\textheight}{-\\headheight}
  3615. \\addtolength{\\textheight}{-\\headsep}
  3616. \\addtolength{\\textheight}{-\\footskip}
  3617. \\addtolength{\\textheight}{-3cm}
  3618. \\setlength{\\topmargin}{1.5cm}
  3619. \\addtolength{\\topmargin}{-2.54cm}"
  3620. "The document header used for processing LaTeX fragments.
  3621. It is imperative that this header make sure that no page number
  3622. appears on the page. The package defined in the variables
  3623. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3624. will either replace the placeholder \"[PACKAGES]\" in this
  3625. header, or they will be appended."
  3626. :group 'org-latex
  3627. :type 'string)
  3628. (defun org-set-packages-alist (var val)
  3629. "Set the packages alist and make sure it has 3 elements per entry."
  3630. (set var (mapcar (lambda (x)
  3631. (if (and (consp x) (= (length x) 2))
  3632. (list (car x) (nth 1 x) t)
  3633. x))
  3634. val)))
  3635. (defun org-get-packages-alist (var)
  3636. "Get the packages alist and make sure it has 3 elements per entry."
  3637. (mapcar (lambda (x)
  3638. (if (and (consp x) (= (length x) 2))
  3639. (list (car x) (nth 1 x) t)
  3640. x))
  3641. (default-value var)))
  3642. (defcustom org-latex-default-packages-alist
  3643. '(("AUTO" "inputenc" t ("pdflatex"))
  3644. ("T1" "fontenc" t ("pdflatex"))
  3645. ("" "graphicx" t)
  3646. ("" "grffile" t)
  3647. ("" "longtable" nil)
  3648. ("" "wrapfig" nil)
  3649. ("" "rotating" nil)
  3650. ("normalem" "ulem" t)
  3651. ("" "amsmath" t)
  3652. ("" "textcomp" t)
  3653. ("" "amssymb" t)
  3654. ("" "capt-of" nil)
  3655. ("" "hyperref" nil))
  3656. "Alist of default packages to be inserted in the header.
  3657. Change this only if one of the packages here causes an
  3658. incompatibility with another package you are using.
  3659. The packages in this list are needed by one part or another of
  3660. Org mode to function properly:
  3661. - inputenc, fontenc: for basic font and character selection
  3662. - graphicx: for including images
  3663. - grffile: allow periods and spaces in graphics file names
  3664. - longtable: For multipage tables
  3665. - wrapfig: for figure placement
  3666. - rotating: for sideways figures and tables
  3667. - ulem: for underline and strike-through
  3668. - amsmath: for subscript and superscript and math environments
  3669. - textcomp, amssymb: for various symbols used
  3670. for interpreting the entities in `org-entities'. You can skip
  3671. some of these packages if you don't use any of their symbols.
  3672. - capt-of: for captions outside of floats
  3673. - hyperref: for cross references
  3674. Therefore you should not modify this variable unless you know
  3675. what you are doing. The one reason to change it anyway is that
  3676. you might be loading some other package that conflicts with one
  3677. of the default packages. Each element is either a cell or
  3678. a string.
  3679. A cell is of the format
  3680. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3681. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3682. when compiling LaTeX snippets into images for inclusion into
  3683. non-LaTeX output. COMPILERS is a list of compilers that should
  3684. include the package, see `org-latex-compiler'. If the document
  3685. compiler is not in the list, and the list is non-nil, the package
  3686. will not be inserted in the final document.
  3687. A string will be inserted as-is in the header of the document."
  3688. :group 'org-latex
  3689. :group 'org-export-latex
  3690. :set 'org-set-packages-alist
  3691. :get 'org-get-packages-alist
  3692. :version "25.2"
  3693. :package-version '(Org . "8.3")
  3694. :type '(repeat
  3695. (choice
  3696. (list :tag "options/package pair"
  3697. (string :tag "options")
  3698. (string :tag "package")
  3699. (boolean :tag "Snippet"))
  3700. (string :tag "A line of LaTeX"))))
  3701. (defcustom org-latex-packages-alist nil
  3702. "Alist of packages to be inserted in every LaTeX header.
  3703. These will be inserted after `org-latex-default-packages-alist'.
  3704. Each element is either a cell or a string.
  3705. A cell is of the format:
  3706. (\"options\" \"package\" SNIPPET-FLAG)
  3707. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3708. needed when turning LaTeX snippets into images for inclusion into
  3709. non-LaTeX output.
  3710. A string will be inserted as-is in the header of the document.
  3711. Make sure that you only list packages here which:
  3712. - you want in every file;
  3713. - do not conflict with the setup in `org-format-latex-header';
  3714. - do not conflict with the default packages in
  3715. `org-latex-default-packages-alist'."
  3716. :group 'org-latex
  3717. :group 'org-export-latex
  3718. :set 'org-set-packages-alist
  3719. :get 'org-get-packages-alist
  3720. :type '(repeat
  3721. (choice
  3722. (list :tag "options/package pair"
  3723. (string :tag "options")
  3724. (string :tag "package")
  3725. (boolean :tag "Snippet"))
  3726. (string :tag "A line of LaTeX"))))
  3727. (defgroup org-appearance nil
  3728. "Settings for Org mode appearance."
  3729. :tag "Org Appearance"
  3730. :group 'org)
  3731. (defcustom org-level-color-stars-only nil
  3732. "Non-nil means fontify only the stars in each headline.
  3733. When nil, the entire headline is fontified.
  3734. Changing it requires restart of `font-lock-mode' to become effective
  3735. also in regions already fontified."
  3736. :group 'org-appearance
  3737. :type 'boolean)
  3738. (defcustom org-hide-leading-stars nil
  3739. "Non-nil means hide the first N-1 stars in a headline.
  3740. This works by using the face `org-hide' for these stars. This
  3741. face is white for a light background, and black for a dark
  3742. background. You may have to customize the face `org-hide' to
  3743. make this work.
  3744. Changing it requires restart of `font-lock-mode' to become effective
  3745. also in regions already fontified.
  3746. You may also set this on a per-file basis by adding one of the following
  3747. lines to the buffer:
  3748. #+STARTUP: hidestars
  3749. #+STARTUP: showstars"
  3750. :group 'org-appearance
  3751. :type 'boolean)
  3752. (defcustom org-hidden-keywords nil
  3753. "List of symbols corresponding to keywords to be hidden the org buffer.
  3754. For example, a value \\='(title) for this list will make the document's title
  3755. appear in the buffer without the initial #+TITLE: keyword."
  3756. :group 'org-appearance
  3757. :version "24.1"
  3758. :type '(set (const :tag "#+AUTHOR" author)
  3759. (const :tag "#+DATE" date)
  3760. (const :tag "#+EMAIL" email)
  3761. (const :tag "#+TITLE" title)))
  3762. (defcustom org-custom-properties nil
  3763. "List of properties (as strings) with a special meaning.
  3764. The default use of these custom properties is to let the user
  3765. hide them with `org-toggle-custom-properties-visibility'."
  3766. :group 'org-properties
  3767. :group 'org-appearance
  3768. :version "24.3"
  3769. :type '(repeat (string :tag "Property Name")))
  3770. (defcustom org-fontify-done-headline nil
  3771. "Non-nil means change the face of a headline if it is marked DONE.
  3772. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3773. When this is non-nil, the headline after the keyword is set to the
  3774. `org-headline-done' as an additional indication."
  3775. :group 'org-appearance
  3776. :type 'boolean)
  3777. (defcustom org-fontify-emphasized-text t
  3778. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3779. Changing this variable requires a restart of Emacs to take effect."
  3780. :group 'org-appearance
  3781. :type 'boolean)
  3782. (defcustom org-fontify-whole-heading-line nil
  3783. "Non-nil means fontify the whole line for headings.
  3784. This is useful when setting a background color for the
  3785. org-level-* faces."
  3786. :group 'org-appearance
  3787. :type 'boolean)
  3788. (defcustom org-highlight-latex-and-related nil
  3789. "Non-nil means highlight LaTeX related syntax in the buffer.
  3790. When non nil, the value should be a list containing any of the
  3791. following symbols:
  3792. `latex' Highlight LaTeX snippets and environments.
  3793. `script' Highlight subscript and superscript.
  3794. `entities' Highlight entities."
  3795. :group 'org-appearance
  3796. :version "24.4"
  3797. :package-version '(Org . "8.0")
  3798. :type '(choice
  3799. (const :tag "No highlighting" nil)
  3800. (set :greedy t :tag "Highlight"
  3801. (const :tag "LaTeX snippets and environments" latex)
  3802. (const :tag "Subscript and superscript" script)
  3803. (const :tag "Entities" entities))))
  3804. (defcustom org-hide-emphasis-markers nil
  3805. "Non-nil mean font-lock should hide the emphasis marker characters."
  3806. :group 'org-appearance
  3807. :type 'boolean)
  3808. (defcustom org-hide-macro-markers nil
  3809. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3810. :group 'org-appearance
  3811. :type 'boolean)
  3812. (defcustom org-pretty-entities nil
  3813. "Non-nil means show entities as UTF8 characters.
  3814. When nil, the \\name form remains in the buffer."
  3815. :group 'org-appearance
  3816. :version "24.1"
  3817. :type 'boolean)
  3818. (defcustom org-pretty-entities-include-sub-superscripts t
  3819. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3820. :group 'org-appearance
  3821. :version "24.1"
  3822. :type 'boolean)
  3823. (defvar org-emph-re nil
  3824. "Regular expression for matching emphasis.
  3825. After a match, the match groups contain these elements:
  3826. 0 The match of the full regular expression, including the characters
  3827. before and after the proper match
  3828. 1 The character before the proper match, or empty at beginning of line
  3829. 2 The proper match, including the leading and trailing markers
  3830. 3 The leading marker like * or /, indicating the type of highlighting
  3831. 4 The text between the emphasis markers, not including the markers
  3832. 5 The character after the match, empty at the end of a line")
  3833. (defvar org-verbatim-re nil
  3834. "Regular expression for matching verbatim text.")
  3835. (defvar org-emphasis-regexp-components) ; defined just below
  3836. (defvar org-emphasis-alist) ; defined just below
  3837. (defun org-set-emph-re (var val)
  3838. "Set variable and compute the emphasis regular expression."
  3839. (set var val)
  3840. (when (and (boundp 'org-emphasis-alist)
  3841. (boundp 'org-emphasis-regexp-components)
  3842. org-emphasis-alist org-emphasis-regexp-components)
  3843. (let* ((e org-emphasis-regexp-components)
  3844. (pre (car e))
  3845. (post (nth 1 e))
  3846. (border (nth 2 e))
  3847. (body (nth 3 e))
  3848. (nl (nth 4 e))
  3849. (body1 (concat body "*?"))
  3850. (markers (mapconcat 'car org-emphasis-alist ""))
  3851. (vmarkers (mapconcat
  3852. (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
  3853. org-emphasis-alist "")))
  3854. ;; make sure special characters appear at the right position in the class
  3855. (if (string-match "\\^" markers)
  3856. (setq markers (concat (replace-match "" t t markers) "^")))
  3857. (if (string-match "-" markers)
  3858. (setq markers (concat (replace-match "" t t markers) "-")))
  3859. (if (string-match "\\^" vmarkers)
  3860. (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
  3861. (if (string-match "-" vmarkers)
  3862. (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
  3863. (if (> nl 0)
  3864. (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
  3865. (int-to-string nl) "\\}")))
  3866. ;; Make the regexp
  3867. (setq org-emph-re
  3868. (concat "\\([" pre "]\\|^\\)"
  3869. "\\("
  3870. "\\([" markers "]\\)"
  3871. "\\("
  3872. "[^" border "]\\|"
  3873. "[^" border "]"
  3874. body1
  3875. "[^" border "]"
  3876. "\\)"
  3877. "\\3\\)"
  3878. "\\([" post "]\\|$\\)"))
  3879. (setq org-verbatim-re
  3880. (concat "\\([" pre "]\\|^\\)"
  3881. "\\("
  3882. "\\([" vmarkers "]\\)"
  3883. "\\("
  3884. "[^" border "]\\|"
  3885. "[^" border "]"
  3886. body1
  3887. "[^" border "]"
  3888. "\\)"
  3889. "\\3\\)"
  3890. "\\([" post "]\\|$\\)")))))
  3891. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3892. ;; set this option proved cumbersome. See this message/thread:
  3893. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3894. (defvar org-emphasis-regexp-components
  3895. '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
  3896. "Components used to build the regular expression for emphasis.
  3897. This is a list with five entries. Terminology: In an emphasis string
  3898. like \" *strong word* \", we call the initial space PREMATCH, the final
  3899. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3900. and \"trong wor\" is the body. The different components in this variable
  3901. specify what is allowed/forbidden in each part:
  3902. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3903. post Chars allowed as postmatch. End of line will be allowed too.
  3904. border The chars *forbidden* as border characters.
  3905. body-regexp A regexp like \".\" to match a body character. Don't use
  3906. non-shy groups here, and don't allow newline here.
  3907. newline The maximum number of newlines allowed in an emphasis exp.
  3908. You need to reload Org or to restart Emacs after customizing this.")
  3909. (defcustom org-emphasis-alist
  3910. '(("*" bold)
  3911. ("/" italic)
  3912. ("_" underline)
  3913. ("=" org-verbatim verbatim)
  3914. ("~" org-code verbatim)
  3915. ("+" (:strike-through t)))
  3916. "Alist of characters and faces to emphasize text.
  3917. Text starting and ending with a special character will be emphasized,
  3918. for example *bold*, _underlined_ and /italic/. This variable sets the
  3919. marker characters and the face to be used by font-lock for highlighting
  3920. in Org buffers.
  3921. You need to reload Org or to restart Emacs after customizing this."
  3922. :group 'org-appearance
  3923. :set 'org-set-emph-re
  3924. :version "24.4"
  3925. :package-version '(Org . "8.0")
  3926. :type '(repeat
  3927. (list
  3928. (string :tag "Marker character")
  3929. (choice
  3930. (face :tag "Font-lock-face")
  3931. (plist :tag "Face property list"))
  3932. (option (const verbatim)))))
  3933. (defvar org-protecting-blocks '("src" "example" "export")
  3934. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3935. This is needed for font-lock setup.")
  3936. ;;; Functions and variables from their packages
  3937. ;; Declared here to avoid compiler warnings
  3938. (defvar mark-active)
  3939. ;; Various packages
  3940. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3941. (declare-function calendar-forward-day "cal-move" (arg))
  3942. (declare-function calendar-goto-date "cal-move" (date))
  3943. (declare-function calendar-goto-today "cal-move" ())
  3944. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3945. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3946. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3947. (declare-function cdlatex-tab "ext:cdlatex" ())
  3948. (declare-function dired-get-filename
  3949. "dired"
  3950. (&optional localp no-error-if-not-filep))
  3951. (declare-function iswitchb-read-buffer
  3952. "iswitchb"
  3953. (prompt &optional
  3954. default require-match _predicate start matches-set))
  3955. (declare-function org-agenda-change-all-lines
  3956. "org-agenda"
  3957. (newhead hdmarker &optional fixface just-this))
  3958. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3959. "org-agenda"
  3960. (&optional end))
  3961. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3962. (declare-function org-agenda-format-item
  3963. "org-agenda"
  3964. (extra txt &optional level category tags dotime
  3965. remove-re habitp))
  3966. (declare-function org-agenda-maybe-redo "org-agenda" ())
  3967. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3968. (declare-function org-agenda-save-markers-for-cut-and-paste
  3969. "org-agenda"
  3970. (beg end))
  3971. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3972. (declare-function org-agenda-skip "org-agenda" ())
  3973. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3974. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3975. (declare-function org-indent-mode "org-indent" (&optional arg))
  3976. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3977. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3978. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3979. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3980. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3981. (declare-function parse-time-string "parse-time" (string))
  3982. (declare-function speedbar-line-directory "speedbar" (&optional depth))
  3983. (defvar align-mode-rules-list)
  3984. (defvar calc-embedded-close-formula)
  3985. (defvar calc-embedded-open-formula)
  3986. (defvar calc-embedded-open-mode)
  3987. (defvar font-lock-unfontify-region-function)
  3988. (defvar iswitchb-temp-buflist)
  3989. (defvar org-agenda-tags-todo-honor-ignore-options)
  3990. (defvar remember-data-file)
  3991. (defvar texmathp-why)
  3992. ;;;###autoload
  3993. (defun turn-on-orgtbl ()
  3994. "Unconditionally turn on `orgtbl-mode'."
  3995. (require 'org-table)
  3996. (orgtbl-mode 1))
  3997. (defun org-at-table-p (&optional table-type)
  3998. "Non-nil if the cursor is inside an Org table.
  3999. If TABLE-TYPE is non-nil, also check for table.el-type tables.
  4000. If `org-enable-table-editor' is nil, return nil unconditionally."
  4001. (and
  4002. org-enable-table-editor
  4003. (save-excursion
  4004. (beginning-of-line)
  4005. (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
  4006. (or (not (derived-mode-p 'org-mode))
  4007. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  4008. (and e (or table-type (eq (org-element-property :type e) 'org)))))))
  4009. (defun org-at-table.el-p ()
  4010. "Non-nil when point is at a table.el table."
  4011. (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
  4012. (let ((element (org-element-at-point)))
  4013. (and (eq (org-element-type element) 'table)
  4014. (eq (org-element-property :type element) 'table.el)))))
  4015. (defun org-at-table-hline-p ()
  4016. "Non-nil when point is inside a hline in a table.
  4017. Assume point is already in a table. If `org-enable-table-editor'
  4018. is nil, return nil unconditionally."
  4019. (and org-enable-table-editor
  4020. (save-excursion
  4021. (beginning-of-line)
  4022. (looking-at org-table-hline-regexp))))
  4023. (defun org-table-map-tables (function &optional quietly)
  4024. "Apply FUNCTION to the start of all tables in the buffer."
  4025. (org-with-wide-buffer
  4026. (goto-char (point-min))
  4027. (while (re-search-forward org-table-any-line-regexp nil t)
  4028. (unless quietly
  4029. (message "Mapping tables: %d%%"
  4030. (floor (* 100.0 (point)) (buffer-size))))
  4031. (beginning-of-line 1)
  4032. (when (and (looking-at org-table-line-regexp)
  4033. ;; Exclude tables in src/example/verbatim/clocktable blocks
  4034. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  4035. (save-excursion (funcall function))
  4036. (or (looking-at org-table-line-regexp)
  4037. (forward-char 1)))
  4038. (re-search-forward org-table-any-border-regexp nil 1)))
  4039. (unless quietly (message "Mapping tables: done")))
  4040. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  4041. (declare-function org-clock-update-mode-line "org-clock" ())
  4042. (declare-function org-resolve-clocks "org-clock"
  4043. (&optional also-non-dangling-p prompt last-valid))
  4044. (defun org-at-TBLFM-p (&optional pos)
  4045. "Non-nil when point (or POS) is in #+TBLFM line."
  4046. (save-excursion
  4047. (goto-char (or pos (point)))
  4048. (beginning-of-line)
  4049. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  4050. (eq (org-element-type (org-element-at-point)) 'table))))
  4051. (defvar org-clock-start-time)
  4052. (defvar org-clock-marker (make-marker)
  4053. "Marker recording the last clock-in.")
  4054. (defvar org-clock-hd-marker (make-marker)
  4055. "Marker recording the last clock-in, but the headline position.")
  4056. (defvar org-clock-heading ""
  4057. "The heading of the current clock entry.")
  4058. (defun org-clock-is-active ()
  4059. "Return the buffer where the clock is currently running.
  4060. Return nil if no clock is running."
  4061. (marker-buffer org-clock-marker))
  4062. (defun org-check-running-clock ()
  4063. "Check if the current buffer contains the running clock.
  4064. If yes, offer to stop it and to save the buffer with the changes."
  4065. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  4066. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  4067. (buffer-name))))
  4068. (org-clock-out)
  4069. (when (y-or-n-p "Save changed buffer?")
  4070. (save-buffer))))
  4071. (defun org-clocktable-try-shift (dir n)
  4072. "Check if this line starts a clock table, if yes, shift the time block."
  4073. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  4074. (org-clocktable-shift dir n)))
  4075. ;;;###autoload
  4076. (defun org-clock-persistence-insinuate ()
  4077. "Set up hooks for clock persistence."
  4078. (require 'org-clock)
  4079. (add-hook 'org-mode-hook 'org-clock-load)
  4080. (add-hook 'kill-emacs-hook 'org-clock-save))
  4081. (defgroup org-archive nil
  4082. "Options concerning archiving in Org mode."
  4083. :tag "Org Archive"
  4084. :group 'org-structure)
  4085. (defcustom org-archive-location "%s_archive::"
  4086. "The location where subtrees should be archived.
  4087. The value of this variable is a string, consisting of two parts,
  4088. separated by a double-colon. The first part is a filename and
  4089. the second part is a headline.
  4090. When the filename is omitted, archiving happens in the same file.
  4091. %s in the filename will be replaced by the current file
  4092. name (without the directory part). Archiving to a different file
  4093. is useful to keep archived entries from contributing to the
  4094. Org Agenda.
  4095. The archived entries will be filed as subtrees of the specified
  4096. headline. When the headline is omitted, the subtrees are simply
  4097. filed away at the end of the file, as top-level entries. Also in
  4098. the heading you can use %s to represent the file name, this can be
  4099. useful when using the same archive for a number of different files.
  4100. Here are a few examples:
  4101. \"%s_archive::\"
  4102. If the current file is Projects.org, archive in file
  4103. Projects.org_archive, as top-level trees. This is the default.
  4104. \"::* Archived Tasks\"
  4105. Archive in the current file, under the top-level headline
  4106. \"* Archived Tasks\".
  4107. \"~/org/archive.org::\"
  4108. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  4109. \"~/org/archive.org::* From %s\"
  4110. Archive in file ~/org/archive.org (absolute path), under headlines
  4111. \"From FILENAME\" where file name is the current file name.
  4112. \"~/org/datetree.org::datetree/* Finished Tasks\"
  4113. The \"datetree/\" string is special, signifying to archive
  4114. items to the datetree. Items are placed in either the CLOSED
  4115. date of the item, or the current date if there is no CLOSED date.
  4116. The heading will be a subentry to the current date. There doesn't
  4117. need to be a heading, but there always needs to be a slash after
  4118. datetree. For example, to store archived items directly in the
  4119. datetree, use \"~/org/datetree.org::datetree/\".
  4120. \"basement::** Finished Tasks\"
  4121. Archive in file ./basement (relative path), as level 3 trees
  4122. below the level 2 heading \"** Finished Tasks\".
  4123. You may set this option on a per-file basis by adding to the buffer a
  4124. line like
  4125. #+ARCHIVE: basement::** Finished Tasks
  4126. You may also define it locally for a subtree by setting an ARCHIVE property
  4127. in the entry. If such a property is found in an entry, or anywhere up
  4128. the hierarchy, it will be used."
  4129. :group 'org-archive
  4130. :type 'string)
  4131. (defcustom org-agenda-skip-archived-trees t
  4132. "Non-nil means the agenda will skip any items located in archived trees.
  4133. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  4134. variable is no longer recommended, you should leave it at the value t.
  4135. Instead, use the key `v' to cycle the archives-mode in the agenda."
  4136. :group 'org-archive
  4137. :group 'org-agenda-skip
  4138. :type 'boolean)
  4139. (defcustom org-columns-skip-archived-trees t
  4140. "Non-nil means ignore archived trees when creating column view."
  4141. :group 'org-archive
  4142. :group 'org-properties
  4143. :type 'boolean)
  4144. (defcustom org-cycle-open-archived-trees nil
  4145. "Non-nil means `org-cycle' will open archived trees.
  4146. An archived tree is a tree marked with the tag ARCHIVE.
  4147. When nil, archived trees will stay folded. You can still open them with
  4148. normal outline commands like `show-all', but not with the cycling commands."
  4149. :group 'org-archive
  4150. :group 'org-cycle
  4151. :type 'boolean)
  4152. (defcustom org-sparse-tree-open-archived-trees nil
  4153. "Non-nil means sparse tree construction shows matches in archived trees.
  4154. When nil, matches in these trees are highlighted, but the trees are kept in
  4155. collapsed state."
  4156. :group 'org-archive
  4157. :group 'org-sparse-trees
  4158. :type 'boolean)
  4159. (defcustom org-sparse-tree-default-date-type nil
  4160. "The default date type when building a sparse tree.
  4161. When this is nil, a date is a scheduled or a deadline timestamp.
  4162. Otherwise, these types are allowed:
  4163. all: all timestamps
  4164. active: only active timestamps (<...>)
  4165. inactive: only inactive timestamps ([...])
  4166. scheduled: only scheduled timestamps
  4167. deadline: only deadline timestamps"
  4168. :type '(choice (const :tag "Scheduled or deadline" nil)
  4169. (const :tag "All timestamps" all)
  4170. (const :tag "Only active timestamps" active)
  4171. (const :tag "Only inactive timestamps" inactive)
  4172. (const :tag "Only scheduled timestamps" scheduled)
  4173. (const :tag "Only deadline timestamps" deadline)
  4174. (const :tag "Only closed timestamps" closed))
  4175. :version "25.2"
  4176. :package-version '(Org . "8.3")
  4177. :group 'org-sparse-trees)
  4178. (defun org-cycle-hide-archived-subtrees (state)
  4179. "Re-hide all archived subtrees after a visibility state change."
  4180. (when (and (not org-cycle-open-archived-trees)
  4181. (not (memq state '(overview folded))))
  4182. (save-excursion
  4183. (let* ((globalp (memq state '(contents all)))
  4184. (beg (if globalp (point-min) (point)))
  4185. (end (if globalp (point-max) (org-end-of-subtree t))))
  4186. (org-hide-archived-subtrees beg end)
  4187. (goto-char beg)
  4188. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4189. (message "%s" (substitute-command-keys
  4190. "Subtree is archived and stays closed. Use \
  4191. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  4192. (defun org-force-cycle-archived ()
  4193. "Cycle subtree even if it is archived."
  4194. (interactive)
  4195. (setq this-command 'org-cycle)
  4196. (let ((org-cycle-open-archived-trees t))
  4197. (call-interactively 'org-cycle)))
  4198. (defun org-hide-archived-subtrees (beg end)
  4199. "Re-hide all archived subtrees after a visibility state change."
  4200. (org-with-wide-buffer
  4201. (let ((case-fold-search nil)
  4202. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4203. (goto-char beg)
  4204. ;; Include headline point is currently on.
  4205. (beginning-of-line)
  4206. (while (and (< (point) end) (re-search-forward re end t))
  4207. (when (member org-archive-tag (org-get-tags))
  4208. (org-flag-subtree t)
  4209. (org-end-of-subtree t))))))
  4210. (declare-function outline-end-of-heading "outline" ())
  4211. (declare-function outline-flag-region "outline" (from to flag))
  4212. (defun org-flag-subtree (flag)
  4213. (save-excursion
  4214. (org-back-to-heading t)
  4215. (outline-end-of-heading)
  4216. (outline-flag-region (point)
  4217. (progn (org-end-of-subtree t) (point))
  4218. flag)))
  4219. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4220. ;; Declare Column View Code
  4221. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4222. (declare-function org-columns-compute "org-colview" (property))
  4223. ;; Declare ID code
  4224. (declare-function org-id-store-link "org-id")
  4225. (declare-function org-id-locations-load "org-id")
  4226. (declare-function org-id-locations-save "org-id")
  4227. (defvar org-id-track-globally)
  4228. ;;; Variables for pre-computed regular expressions, all buffer local
  4229. (defvar-local org-todo-regexp nil
  4230. "Matches any of the TODO state keywords.")
  4231. (defvar-local org-not-done-regexp nil
  4232. "Matches any of the TODO state keywords except the last one.")
  4233. (defvar-local org-not-done-heading-regexp nil
  4234. "Matches a TODO headline that is not done.")
  4235. (defvar-local org-todo-line-regexp nil
  4236. "Matches a headline and puts TODO state into group 2 if present.")
  4237. (defvar-local org-complex-heading-regexp nil
  4238. "Matches a headline and puts everything into groups:
  4239. group 1: the stars
  4240. group 2: The todo keyword, maybe
  4241. group 3: Priority cookie
  4242. group 4: True headline
  4243. group 5: Tags")
  4244. (defvar-local org-complex-heading-regexp-format nil
  4245. "Printf format to make regexp to match an exact headline.
  4246. This regexp will match the headline of any node which has the
  4247. exact headline text that is put into the format, but may have any
  4248. TODO state, priority and tags.")
  4249. (defvar-local org-todo-line-tags-regexp nil
  4250. "Matches a headline and puts TODO state into group 2 if present.
  4251. Also put tags into group 4 if tags are present.")
  4252. (defconst org-plain-time-of-day-regexp
  4253. (concat
  4254. "\\(\\<[012]?[0-9]"
  4255. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4256. "\\(--?"
  4257. "\\(\\<[012]?[0-9]"
  4258. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4259. "\\)?")
  4260. "Regular expression to match a plain time or time range.
  4261. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4262. groups carry important information:
  4263. 0 the full match
  4264. 1 the first time, range or not
  4265. 8 the second time, if it is a range.")
  4266. (defconst org-plain-time-extension-regexp
  4267. (concat
  4268. "\\(\\<[012]?[0-9]"
  4269. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4270. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4271. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4272. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4273. groups carry important information:
  4274. 0 the full match
  4275. 7 hours of duration
  4276. 9 minutes of duration")
  4277. (defconst org-stamp-time-of-day-regexp
  4278. (concat
  4279. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4280. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4281. "\\(--?"
  4282. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4283. "Regular expression to match a timestamp time or time range.
  4284. After a match, the following groups carry important information:
  4285. 0 the full match
  4286. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4287. 2 the first time, range or not
  4288. 4 the second time, if it is a range.")
  4289. (defconst org-startup-options
  4290. '(("fold" org-startup-folded t)
  4291. ("overview" org-startup-folded t)
  4292. ("nofold" org-startup-folded nil)
  4293. ("showall" org-startup-folded nil)
  4294. ("showeverything" org-startup-folded showeverything)
  4295. ("content" org-startup-folded content)
  4296. ("indent" org-startup-indented t)
  4297. ("noindent" org-startup-indented nil)
  4298. ("hidestars" org-hide-leading-stars t)
  4299. ("showstars" org-hide-leading-stars nil)
  4300. ("odd" org-odd-levels-only t)
  4301. ("oddeven" org-odd-levels-only nil)
  4302. ("align" org-startup-align-all-tables t)
  4303. ("noalign" org-startup-align-all-tables nil)
  4304. ("inlineimages" org-startup-with-inline-images t)
  4305. ("noinlineimages" org-startup-with-inline-images nil)
  4306. ("latexpreview" org-startup-with-latex-preview t)
  4307. ("nolatexpreview" org-startup-with-latex-preview nil)
  4308. ("customtime" org-display-custom-times t)
  4309. ("logdone" org-log-done time)
  4310. ("lognotedone" org-log-done note)
  4311. ("nologdone" org-log-done nil)
  4312. ("lognoteclock-out" org-log-note-clock-out t)
  4313. ("nolognoteclock-out" org-log-note-clock-out nil)
  4314. ("logrepeat" org-log-repeat state)
  4315. ("lognoterepeat" org-log-repeat note)
  4316. ("logdrawer" org-log-into-drawer t)
  4317. ("nologdrawer" org-log-into-drawer nil)
  4318. ("logstatesreversed" org-log-states-order-reversed t)
  4319. ("nologstatesreversed" org-log-states-order-reversed nil)
  4320. ("nologrepeat" org-log-repeat nil)
  4321. ("logreschedule" org-log-reschedule time)
  4322. ("lognotereschedule" org-log-reschedule note)
  4323. ("nologreschedule" org-log-reschedule nil)
  4324. ("logredeadline" org-log-redeadline time)
  4325. ("lognoteredeadline" org-log-redeadline note)
  4326. ("nologredeadline" org-log-redeadline nil)
  4327. ("logrefile" org-log-refile time)
  4328. ("lognoterefile" org-log-refile note)
  4329. ("nologrefile" org-log-refile nil)
  4330. ("fninline" org-footnote-define-inline t)
  4331. ("nofninline" org-footnote-define-inline nil)
  4332. ("fnlocal" org-footnote-section nil)
  4333. ("fnauto" org-footnote-auto-label t)
  4334. ("fnprompt" org-footnote-auto-label nil)
  4335. ("fnconfirm" org-footnote-auto-label confirm)
  4336. ("fnplain" org-footnote-auto-label plain)
  4337. ("fnadjust" org-footnote-auto-adjust t)
  4338. ("nofnadjust" org-footnote-auto-adjust nil)
  4339. ("constcgs" constants-unit-system cgs)
  4340. ("constSI" constants-unit-system SI)
  4341. ("noptag" org-tag-persistent-alist nil)
  4342. ("hideblocks" org-hide-block-startup t)
  4343. ("nohideblocks" org-hide-block-startup nil)
  4344. ("beamer" org-startup-with-beamer-mode t)
  4345. ("entitiespretty" org-pretty-entities t)
  4346. ("entitiesplain" org-pretty-entities nil))
  4347. "Variable associated with STARTUP options for org-mode.
  4348. Each element is a list of three items: the startup options (as written
  4349. in the #+STARTUP line), the corresponding variable, and the value to set
  4350. this variable to if the option is found. An optional forth element PUSH
  4351. means to push this value onto the list in the variable.")
  4352. (defcustom org-group-tags t
  4353. "When non-nil (the default), use group tags.
  4354. This can be turned on/off through `org-toggle-tags-groups'."
  4355. :group 'org-tags
  4356. :group 'org-startup
  4357. :type 'boolean)
  4358. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4359. (defun org-toggle-tags-groups ()
  4360. "Toggle support for group tags.
  4361. Support for group tags is controlled by the option
  4362. `org-group-tags', which is non-nil by default."
  4363. (interactive)
  4364. (setq org-group-tags (not org-group-tags))
  4365. (cond ((and (derived-mode-p 'org-agenda-mode)
  4366. org-group-tags)
  4367. (org-agenda-redo))
  4368. ((derived-mode-p 'org-mode)
  4369. (let ((org-inhibit-startup t)) (org-mode))))
  4370. (message "Groups tags support has been turned %s"
  4371. (if org-group-tags "on" "off")))
  4372. (defun org-set-regexps-and-options (&optional tags-only)
  4373. "Precompute regular expressions used in the current buffer.
  4374. When optional argument TAGS-ONLY is non-nil, only compute tags
  4375. related expressions."
  4376. (when (derived-mode-p 'org-mode)
  4377. (let ((alist (org--setup-collect-keywords
  4378. (org-make-options-regexp
  4379. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4380. (and (not tags-only)
  4381. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4382. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4383. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4384. ;; Startup options. Get this early since it does change
  4385. ;; behavior for other options (e.g., tags).
  4386. (let ((startup (cdr (assq 'startup alist))))
  4387. (dolist (option startup)
  4388. (let ((entry (assoc-string option org-startup-options t)))
  4389. (when entry
  4390. (let ((var (nth 1 entry))
  4391. (val (nth 2 entry)))
  4392. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4393. (unless (listp (symbol-value var))
  4394. (set (make-local-variable var) nil))
  4395. (add-to-list var val)))))))
  4396. (setq-local org-file-tags
  4397. (mapcar #'org-add-prop-inherited
  4398. (cdr (assq 'filetags alist))))
  4399. (setq org-current-tag-alist
  4400. (append org-tag-persistent-alist
  4401. (let ((tags (cdr (assq 'tags alist))))
  4402. (if tags (org-tag-string-to-alist tags)
  4403. org-tag-alist))))
  4404. (setq org-tag-groups-alist
  4405. (org-tag-alist-to-groups org-current-tag-alist))
  4406. (unless tags-only
  4407. ;; File properties.
  4408. (setq-local org-file-properties (cdr (assq 'property alist)))
  4409. ;; Archive location.
  4410. (let ((archive (cdr (assq 'archive alist))))
  4411. (when archive (setq-local org-archive-location archive)))
  4412. ;; Category.
  4413. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4414. (when cat
  4415. (setq-local org-category (intern cat))
  4416. (setq-local org-file-properties
  4417. (org--update-property-plist
  4418. "CATEGORY" cat org-file-properties))))
  4419. ;; Columns.
  4420. (let ((column (cdr (assq 'columns alist))))
  4421. (when column (setq-local org-columns-default-format column)))
  4422. ;; Constants.
  4423. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4424. ;; Link abbreviations.
  4425. (let ((links (cdr (assq 'link alist))))
  4426. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4427. ;; Priorities.
  4428. (let ((priorities (cdr (assq 'priorities alist))))
  4429. (when priorities
  4430. (setq-local org-highest-priority (nth 0 priorities))
  4431. (setq-local org-lowest-priority (nth 1 priorities))
  4432. (setq-local org-default-priority (nth 2 priorities))))
  4433. ;; Scripts.
  4434. (let ((scripts (assq 'scripts alist)))
  4435. (when scripts
  4436. (setq-local org-use-sub-superscripts (cdr scripts))))
  4437. ;; TODO keywords.
  4438. (setq-local org-todo-kwd-alist nil)
  4439. (setq-local org-todo-key-alist nil)
  4440. (setq-local org-todo-key-trigger nil)
  4441. (setq-local org-todo-keywords-1 nil)
  4442. (setq-local org-done-keywords nil)
  4443. (setq-local org-todo-heads nil)
  4444. (setq-local org-todo-sets nil)
  4445. (setq-local org-todo-log-states nil)
  4446. (let ((todo-sequences
  4447. (or (nreverse (cdr (assq 'todo alist)))
  4448. (let ((d (default-value 'org-todo-keywords)))
  4449. (if (not (stringp (car d))) d
  4450. ;; XXX: Backward compatibility code.
  4451. (list (cons org-todo-interpretation d)))))))
  4452. (dolist (sequence todo-sequences)
  4453. (let* ((sequence (or (run-hook-with-args-until-success
  4454. 'org-todo-setup-filter-hook sequence)
  4455. sequence))
  4456. (sequence-type (car sequence))
  4457. (keywords (cdr sequence))
  4458. (sep (member "|" keywords))
  4459. names alist)
  4460. (dolist (k (remove "|" keywords))
  4461. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4462. k)
  4463. (error "Invalid TODO keyword %s" k))
  4464. (let ((name (match-string 1 k))
  4465. (key (match-string 2 k))
  4466. (log (org-extract-log-state-settings k)))
  4467. (push name names)
  4468. (push (cons name (and key (string-to-char key))) alist)
  4469. (when log (push log org-todo-log-states))))
  4470. (let* ((names (nreverse names))
  4471. (done (if sep (org-remove-keyword-keys (cdr sep))
  4472. (last names)))
  4473. (head (car names))
  4474. (tail (list sequence-type head (car done) (org-last done))))
  4475. (add-to-list 'org-todo-heads head 'append)
  4476. (push names org-todo-sets)
  4477. (setq org-done-keywords (append org-done-keywords done nil))
  4478. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4479. (setq org-todo-key-alist
  4480. (append org-todo-key-alist
  4481. (and alist
  4482. (append '((:startgroup))
  4483. (nreverse alist)
  4484. '((:endgroup))))))
  4485. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4486. (setq org-todo-sets (nreverse org-todo-sets)
  4487. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4488. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4489. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4490. ;; Compute the regular expressions and other local variables.
  4491. ;; Using `org-outline-regexp-bol' would complicate them much,
  4492. ;; because of the fixed white space at the end of that string.
  4493. (unless org-done-keywords
  4494. (setq org-done-keywords
  4495. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4496. (setq org-not-done-keywords
  4497. (org-delete-all org-done-keywords
  4498. (copy-sequence org-todo-keywords-1))
  4499. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4500. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4501. org-not-done-heading-regexp
  4502. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4503. org-todo-line-regexp
  4504. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4505. org-complex-heading-regexp
  4506. (concat "^\\(\\*+\\)"
  4507. "\\(?: +" org-todo-regexp "\\)?"
  4508. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4509. "\\(?: +\\(.*?\\)\\)??"
  4510. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4511. "[ \t]*$")
  4512. org-complex-heading-regexp-format
  4513. (concat "^\\(\\*+\\)"
  4514. "\\(?: +" org-todo-regexp "\\)?"
  4515. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4516. "\\(?: +"
  4517. ;; Stats cookies can be stuck to body.
  4518. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4519. "\\(%s\\)"
  4520. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4521. "\\)"
  4522. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4523. "[ \t]*$")
  4524. org-todo-line-tags-regexp
  4525. (concat "^\\(\\*+\\)"
  4526. "\\(?: +" org-todo-regexp "\\)?"
  4527. "\\(?: +\\(.*?\\)\\)??"
  4528. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4529. "[ \t]*$"))
  4530. (org-compute-latex-and-related-regexp)))))
  4531. (defun org--setup-collect-keywords (regexp &optional files alist)
  4532. "Return setup keywords values as an alist.
  4533. REGEXP matches a subset of setup keywords. FILES is a list of
  4534. file names already visited. It is used to avoid circular setup
  4535. files. ALIST, when non-nil, is the alist computed so far.
  4536. Return value contains the following keys: `archive', `category',
  4537. `columns', `constants', `filetags', `link', `priorities',
  4538. `property', `scripts', `startup', `tags' and `todo'."
  4539. (org-with-wide-buffer
  4540. (goto-char (point-min))
  4541. (let ((case-fold-search t))
  4542. (while (re-search-forward regexp nil t)
  4543. (let ((element (org-element-at-point)))
  4544. (when (eq (org-element-type element) 'keyword)
  4545. (let ((key (org-element-property :key element))
  4546. (value (org-element-property :value element)))
  4547. (cond
  4548. ((equal key "ARCHIVE")
  4549. (when (org-string-nw-p value)
  4550. (push (cons 'archive value) alist)))
  4551. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4552. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4553. ((equal key "CONSTANTS")
  4554. (let* ((constants (assq 'constants alist))
  4555. (store (cdr constants)))
  4556. (dolist (pair (org-split-string value))
  4557. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4558. pair)
  4559. (let* ((name (match-string 1 pair))
  4560. (value (match-string 2 pair))
  4561. (old (assoc name store)))
  4562. (if old (setcdr old value)
  4563. (push (cons name value) store)))))
  4564. (if constants (setcdr constants store)
  4565. (push (cons 'constants store) alist))))
  4566. ((equal key "FILETAGS")
  4567. (when (org-string-nw-p value)
  4568. (let ((old (assq 'filetags alist))
  4569. (new (apply #'nconc
  4570. (mapcar (lambda (x) (org-split-string x ":"))
  4571. (org-split-string value)))))
  4572. (if old (setcdr old (append new (cdr old)))
  4573. (push (cons 'filetags new) alist)))))
  4574. ((equal key "LINK")
  4575. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4576. (let ((links (assq 'link alist))
  4577. (pair (cons (match-string-no-properties 1 value)
  4578. (match-string-no-properties 2 value))))
  4579. (if links (push pair (cdr links))
  4580. (push (list 'link pair) alist)))))
  4581. ((equal key "OPTIONS")
  4582. (when (and (org-string-nw-p value)
  4583. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4584. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4585. ((equal key "PRIORITIES")
  4586. (push (cons 'priorities
  4587. (let ((prio (org-split-string value)))
  4588. (if (< (length prio) 3) '(?A ?C ?B)
  4589. (mapcar #'string-to-char prio))))
  4590. alist))
  4591. ((equal key "PROPERTY")
  4592. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4593. (let* ((property (assq 'property alist))
  4594. (value (org--update-property-plist
  4595. (match-string-no-properties 1 value)
  4596. (match-string-no-properties 2 value)
  4597. (cdr property))))
  4598. (if property (setcdr property value)
  4599. (push (cons 'property value) alist)))))
  4600. ((equal key "STARTUP")
  4601. (let ((startup (assq 'startup alist)))
  4602. (if startup
  4603. (setcdr startup
  4604. (append (cdr startup) (org-split-string value)))
  4605. (push (cons 'startup (org-split-string value)) alist))))
  4606. ((equal key "TAGS")
  4607. (let ((tag-cell (assq 'tags alist)))
  4608. (if tag-cell
  4609. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4610. (push (cons 'tags value) alist))))
  4611. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4612. (let ((todo (assq 'todo alist))
  4613. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4614. (org-split-string value))))
  4615. (if todo (push value (cdr todo))
  4616. (push (list 'todo value) alist))))
  4617. ((equal key "SETUPFILE")
  4618. (unless buffer-read-only ; Do not check in Gnus messages.
  4619. (let ((f (and (org-string-nw-p value)
  4620. (expand-file-name
  4621. (org-unbracket-string "\"" "\"" value)))))
  4622. (when (and f (file-readable-p f) (not (member f files)))
  4623. (with-temp-buffer
  4624. (setq default-directory (file-name-directory f))
  4625. (insert-file-contents f)
  4626. (setq alist
  4627. ;; Fake Org mode to benefit from cache
  4628. ;; without recurring needlessly.
  4629. (let ((major-mode 'org-mode))
  4630. (org--setup-collect-keywords
  4631. regexp (cons f files) alist)))))))))))))))
  4632. alist)
  4633. (defun org-tag-string-to-alist (s)
  4634. "Return tag alist associated to string S.
  4635. S is a value for TAGS keyword or produced with
  4636. `org-tag-alist-to-string'. Return value is an alist suitable for
  4637. `org-tag-alist' or `org-tag-persistent-alist'."
  4638. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4639. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4640. "\\|{.+?}\\)" ; regular expression
  4641. "\\(?:(\\(.\\))\\)?\\'"))
  4642. alist group-flag)
  4643. (dolist (tokens lines (cdr (nreverse alist)))
  4644. (push '(:newline) alist)
  4645. (while tokens
  4646. (let ((token (pop tokens)))
  4647. (pcase token
  4648. ("{"
  4649. (push '(:startgroup) alist)
  4650. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4651. ("}"
  4652. (push '(:endgroup) alist)
  4653. (setq group-flag nil))
  4654. ("["
  4655. (push '(:startgrouptag) alist)
  4656. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4657. ("]"
  4658. (push '(:endgrouptag) alist)
  4659. (setq group-flag nil))
  4660. (":"
  4661. (push '(:grouptags) alist))
  4662. ((guard (string-match tag-re token))
  4663. (let ((tag (match-string 1 token))
  4664. (key (and (match-beginning 2)
  4665. (string-to-char (match-string 2 token)))))
  4666. ;; Push all tags in groups, no matter if they already
  4667. ;; appear somewhere else in the list.
  4668. (when (or group-flag (not (assoc tag alist)))
  4669. (push (cons tag key) alist))))))))))
  4670. (defun org-tag-alist-to-string (alist &optional skip-key)
  4671. "Return tag string associated to ALIST.
  4672. ALIST is an alist, as defined in `org-tag-alist' or
  4673. `org-tag-persistent-alist', or produced with
  4674. `org-tag-string-to-alist'.
  4675. Return value is a string suitable as a value for \"TAGS\"
  4676. keyword.
  4677. When optional argument SKIP-KEY is non-nil, skip selection keys
  4678. next to tags."
  4679. (mapconcat (lambda (token)
  4680. (pcase token
  4681. (`(:startgroup) "{")
  4682. (`(:endgroup) "}")
  4683. (`(:startgrouptag) "[")
  4684. (`(:endgrouptag) "]")
  4685. (`(:grouptags) ":")
  4686. (`(:newline) "\\n")
  4687. ((and
  4688. (guard (not skip-key))
  4689. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4690. (format "%s(%c)" tag key))
  4691. (`(,(and tag (pred stringp)) . ,_) tag)
  4692. (_ (user-error "Invalid tag token: %S" token))))
  4693. alist
  4694. " "))
  4695. (defun org-tag-alist-to-groups (alist)
  4696. "Return group alist from tag ALIST.
  4697. ALIST is an alist, as defined in `org-tag-alist' or
  4698. `org-tag-persistent-alist', or produced with
  4699. `org-tag-string-to-alist'. Return value is an alist following
  4700. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4701. a string, summarizing TAGS, as a list of strings."
  4702. (let (groups group-status current-group)
  4703. (dolist (token alist (nreverse groups))
  4704. (pcase token
  4705. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4706. (`(,(or :endgroup :endgrouptag))
  4707. (when (eq group-status 'append)
  4708. (push (nreverse current-group) groups))
  4709. (setq group-status nil))
  4710. (`(:grouptags) (setq group-status 'append))
  4711. ((and `(,tag . ,_) (guard group-status))
  4712. (if (eq group-status 'append) (push tag current-group)
  4713. (setq current-group (list tag))))
  4714. (_ nil)))))
  4715. (defun org-file-contents (file &optional noerror)
  4716. "Return the contents of FILE, as a string."
  4717. (if (and file (file-readable-p file))
  4718. (with-temp-buffer
  4719. (insert-file-contents file)
  4720. (buffer-string))
  4721. (funcall (if noerror 'message 'error)
  4722. "Cannot read file \"%s\"%s"
  4723. file
  4724. (let ((from (buffer-file-name (buffer-base-buffer))))
  4725. (if from (concat " (referenced in file \"" from "\")") "")))))
  4726. (defun org-extract-log-state-settings (x)
  4727. "Extract the log state setting from a TODO keyword string.
  4728. This will extract info from a string like \"WAIT(w@/!)\"."
  4729. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4730. (let ((kw (match-string 1 x))
  4731. (log1 (and (match-end 3) (match-string 3 x)))
  4732. (log2 (and (match-end 4) (match-string 4 x))))
  4733. (and (or log1 log2)
  4734. (list kw
  4735. (and log1 (if (equal log1 "!") 'time 'note))
  4736. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4737. (defun org-remove-keyword-keys (list)
  4738. "Remove a pair of parenthesis at the end of each string in LIST."
  4739. (mapcar (lambda (x)
  4740. (if (string-match "(.*)$" x)
  4741. (substring x 0 (match-beginning 0))
  4742. x))
  4743. list))
  4744. (defun org-assign-fast-keys (alist)
  4745. "Assign fast keys to a keyword-key alist.
  4746. Respect keys that are already there."
  4747. (let (new e (alt ?0))
  4748. (while (setq e (pop alist))
  4749. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4750. (cdr e)) ;; Key already assigned.
  4751. (push e new)
  4752. (let ((clist (string-to-list (downcase (car e))))
  4753. (used (append new alist)))
  4754. (when (= (car clist) ?@)
  4755. (pop clist))
  4756. (while (and clist (rassoc (car clist) used))
  4757. (pop clist))
  4758. (unless clist
  4759. (while (rassoc alt used)
  4760. (cl-incf alt)))
  4761. (push (cons (car e) (or (car clist) alt)) new))))
  4762. (nreverse new)))
  4763. ;;; Some variables used in various places
  4764. (defvar org-window-configuration nil
  4765. "Used in various places to store a window configuration.")
  4766. (defvar org-selected-window nil
  4767. "Used in various places to store a window configuration.")
  4768. (defvar org-finish-function nil
  4769. "Function to be called when `C-c C-c' is used.
  4770. This is for getting out of special buffers like capture.")
  4771. (defvar org-last-state)
  4772. ;; Defined somewhere in this file, but used before definition.
  4773. (defvar org-entities) ;; defined in org-entities.el
  4774. (defvar org-struct-menu)
  4775. (defvar org-org-menu)
  4776. (defvar org-tbl-menu)
  4777. ;;;; Define the Org mode
  4778. ;; We use a before-change function to check if a table might need
  4779. ;; an update.
  4780. (defvar org-table-may-need-update t
  4781. "Indicates that a table might need an update.
  4782. This variable is set by `org-before-change-function'.
  4783. `org-table-align' sets it back to nil.")
  4784. (defun org-before-change-function (_beg _end)
  4785. "Every change indicates that a table might need an update."
  4786. (setq org-table-may-need-update t))
  4787. (defvar org-mode-map)
  4788. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4789. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4790. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4791. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4792. (defvar org-table-buffer-is-an nil)
  4793. (defvar bidi-paragraph-direction)
  4794. (defvar buffer-face-mode-face)
  4795. (require 'outline)
  4796. ;; Other stuff we need.
  4797. (require 'time-date)
  4798. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4799. (require 'easymenu)
  4800. (autoload 'easy-menu-add "easymenu")
  4801. (require 'overlay)
  4802. ;; (require 'org-macs) moved higher up in the file before it is first used
  4803. (require 'org-entities)
  4804. ;; (require 'org-compat) moved higher up in the file before it is first used
  4805. (require 'org-faces)
  4806. (require 'org-list)
  4807. (require 'org-pcomplete)
  4808. (require 'org-src)
  4809. (require 'org-footnote)
  4810. (require 'org-macro)
  4811. ;; babel
  4812. (require 'ob)
  4813. ;;;###autoload
  4814. (define-derived-mode org-mode outline-mode "Org"
  4815. "Outline-based notes management and organizer, alias
  4816. \"Carsten's outline-mode for keeping track of everything.\"
  4817. Org mode develops organizational tasks around a NOTES file which
  4818. contains information about projects as plain text. Org mode is
  4819. implemented on top of Outline mode, which is ideal to keep the content
  4820. of large files well structured. It supports ToDo items, deadlines and
  4821. time stamps, which magically appear in the diary listing of the Emacs
  4822. calendar. Tables are easily created with a built-in table editor.
  4823. Plain text URL-like links connect to websites, emails (VM), Usenet
  4824. messages (Gnus), BBDB entries, and any files related to the project.
  4825. For printing and sharing of notes, an Org file (or a part of it)
  4826. can be exported as a structured ASCII or HTML file.
  4827. The following commands are available:
  4828. \\{org-mode-map}"
  4829. ;; Get rid of Outline menus, they are not needed
  4830. ;; Need to do this here because define-derived-mode sets up
  4831. ;; the keymap so late. Still, it is a waste to call this each time
  4832. ;; we switch another buffer into Org mode.
  4833. (define-key org-mode-map [menu-bar headings] 'undefined)
  4834. (define-key org-mode-map [menu-bar hide] 'undefined)
  4835. (define-key org-mode-map [menu-bar show] 'undefined)
  4836. (org-load-modules-maybe)
  4837. (org-install-agenda-files-menu)
  4838. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4839. (add-to-invisibility-spec '(org-cwidth))
  4840. (add-to-invisibility-spec '(org-hide-block . t))
  4841. (setq-local outline-regexp org-outline-regexp)
  4842. (setq-local outline-level 'org-outline-level)
  4843. (setq bidi-paragraph-direction 'left-to-right)
  4844. (when (and org-ellipsis
  4845. (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
  4846. (fboundp 'make-glyph-code))
  4847. (unless org-display-table
  4848. (setq org-display-table (make-display-table)))
  4849. (set-display-table-slot
  4850. org-display-table 4
  4851. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4852. (if (stringp org-ellipsis) org-ellipsis "..."))))
  4853. (setq buffer-display-table org-display-table))
  4854. (org-set-regexps-and-options)
  4855. (org-set-font-lock-defaults)
  4856. (when (and org-tag-faces (not org-tags-special-faces-re))
  4857. ;; tag faces set outside customize.... force initialization.
  4858. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4859. ;; Calc embedded
  4860. (setq-local calc-embedded-open-mode "# ")
  4861. ;; Modify a few syntax entries
  4862. (modify-syntax-entry ?@ "w")
  4863. (modify-syntax-entry ?\" "\"")
  4864. (modify-syntax-entry ?\\ "_")
  4865. (modify-syntax-entry ?~ "_")
  4866. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4867. ;; Activate before-change-function
  4868. (setq-local org-table-may-need-update t)
  4869. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4870. ;; Check for running clock before killing a buffer
  4871. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4872. ;; Initialize macros templates.
  4873. (org-macro-initialize-templates)
  4874. ;; Initialize radio targets.
  4875. (org-update-radio-target-regexp)
  4876. ;; Indentation.
  4877. (setq-local indent-line-function 'org-indent-line)
  4878. (setq-local indent-region-function 'org-indent-region)
  4879. ;; Filling and auto-filling.
  4880. (org-setup-filling)
  4881. ;; Comments.
  4882. (org-setup-comments-handling)
  4883. ;; Initialize cache.
  4884. (org-element-cache-reset)
  4885. ;; Beginning/end of defun
  4886. (setq-local beginning-of-defun-function 'org-backward-element)
  4887. (setq-local end-of-defun-function
  4888. (lambda ()
  4889. (if (not (org-at-heading-p))
  4890. (org-forward-element)
  4891. (org-forward-element)
  4892. (forward-char -1))))
  4893. ;; Next error for sparse trees
  4894. (setq-local next-error-function 'org-occur-next-match)
  4895. ;; Make sure dependence stuff works reliably, even for users who set it
  4896. ;; too late :-(
  4897. (if org-enforce-todo-dependencies
  4898. (add-hook 'org-blocker-hook
  4899. 'org-block-todo-from-children-or-siblings-or-parent)
  4900. (remove-hook 'org-blocker-hook
  4901. 'org-block-todo-from-children-or-siblings-or-parent))
  4902. (if org-enforce-todo-checkbox-dependencies
  4903. (add-hook 'org-blocker-hook
  4904. 'org-block-todo-from-checkboxes)
  4905. (remove-hook 'org-blocker-hook
  4906. 'org-block-todo-from-checkboxes))
  4907. ;; Align options lines
  4908. (setq-local
  4909. align-mode-rules-list
  4910. '((org-in-buffer-settings
  4911. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4912. (modes . '(org-mode)))))
  4913. ;; Imenu
  4914. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4915. ;; Make isearch reveal context
  4916. (setq-local outline-isearch-open-invisible-function
  4917. (lambda (&rest _) (org-show-context 'isearch)))
  4918. ;; Setup the pcomplete hooks
  4919. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4920. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4921. (setq-local pcomplete-default-completion-function 'ignore)
  4922. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4923. (setq-local pcomplete-termination-string "")
  4924. (setq-local buffer-face-mode-face 'org-default)
  4925. ;; If empty file that did not turn on Org mode automatically, make
  4926. ;; it to.
  4927. (when (and org-insert-mode-line-in-empty-file
  4928. (called-interactively-p 'any)
  4929. (= (point-min) (point-max)))
  4930. (insert "# -*- mode: org -*-\n\n"))
  4931. (unless org-inhibit-startup
  4932. (org-unmodified
  4933. (when org-startup-with-beamer-mode (org-beamer-mode))
  4934. (when org-startup-align-all-tables
  4935. (org-table-map-tables #'org-table-align t))
  4936. (when org-startup-with-inline-images (org-display-inline-images))
  4937. (when org-startup-with-latex-preview (org-toggle-latex-fragment))
  4938. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4939. (when org-startup-truncated (setq truncate-lines t))
  4940. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4941. (org-refresh-effort-properties)))
  4942. ;; Try to set `org-hide' face correctly.
  4943. (let ((foreground (org-find-invisible-foreground)))
  4944. (when foreground
  4945. (set-face-foreground 'org-hide foreground))))
  4946. ;; Update `customize-package-emacs-version-alist'
  4947. (add-to-list 'customize-package-emacs-version-alist
  4948. '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
  4949. ("7.8.11" . "24.1") ("7.9.4" . "24.3")
  4950. ("8.2.6" . "24.4") ("8.2.10" . "24.5")
  4951. ("9.0" . "25.2")))
  4952. (defvar org-mode-transpose-word-syntax-table
  4953. (let ((st (make-syntax-table text-mode-syntax-table)))
  4954. (dolist (c org-emphasis-alist st)
  4955. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4956. (when (fboundp 'abbrev-table-put)
  4957. (abbrev-table-put org-mode-abbrev-table
  4958. :parents (list text-mode-abbrev-table)))
  4959. (defun org-find-invisible-foreground ()
  4960. (let ((candidates (remove
  4961. "unspecified-bg"
  4962. (nconc
  4963. (list (face-background 'default)
  4964. (face-background 'org-default))
  4965. (mapcar
  4966. (lambda (alist)
  4967. (when (boundp alist)
  4968. (cdr (assq 'background-color (symbol-value alist)))))
  4969. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4970. (list (face-foreground 'org-hide))))))
  4971. (car (remove nil candidates))))
  4972. (defun org-current-time (&optional rounding-minutes past)
  4973. "Current time, possibly rounded to ROUNDING-MINUTES.
  4974. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4975. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4976. the rounding returns a past time."
  4977. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4978. (car org-time-stamp-rounding-minutes)))
  4979. (time (decode-time)) res)
  4980. (if (< r 1)
  4981. (current-time)
  4982. (setq res
  4983. (apply 'encode-time
  4984. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  4985. (nthcdr 2 time))))
  4986. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  4987. (seconds-to-time (- (float-time res) (* r 60)))
  4988. res))))
  4989. (defun org-today ()
  4990. "Return today date, considering `org-extend-today-until'."
  4991. (time-to-days
  4992. (time-subtract (current-time)
  4993. (list 0 (* 3600 org-extend-today-until) 0))))
  4994. ;;;; Font-Lock stuff, including the activators
  4995. (defvar org-mouse-map (make-sparse-keymap))
  4996. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  4997. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  4998. (when org-mouse-1-follows-link
  4999. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  5000. (when org-tab-follows-link
  5001. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  5002. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  5003. (require 'font-lock)
  5004. (defconst org-non-link-chars "]\t\n\r<>")
  5005. (defvar org-link-types-re nil
  5006. "Matches a link that has a url-like prefix like \"http:\"")
  5007. (defvar org-link-re-with-space nil
  5008. "Matches a link with spaces, optional angular brackets around it.")
  5009. (defvar org-link-re-with-space2 nil
  5010. "Matches a link with spaces, optional angular brackets around it.")
  5011. (defvar org-link-re-with-space3 nil
  5012. "Matches a link with spaces, only for internal part in bracket links.")
  5013. (defvar org-angle-link-re nil
  5014. "Matches link with angular brackets, spaces are allowed.")
  5015. (defvar org-plain-link-re nil
  5016. "Matches plain link, without spaces.")
  5017. (defvar org-bracket-link-regexp nil
  5018. "Matches a link in double brackets.")
  5019. (defvar org-bracket-link-analytic-regexp nil
  5020. "Regular expression used to analyze links.
  5021. Here is what the match groups contain after a match:
  5022. 1: http:
  5023. 2: http
  5024. 3: path
  5025. 4: [desc]
  5026. 5: desc")
  5027. (defvar org-bracket-link-analytic-regexp++ nil
  5028. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  5029. (defvar org-any-link-re nil
  5030. "Regular expression matching any link.")
  5031. (defconst org-match-sexp-depth 3
  5032. "Number of stacked braces for sub/superscript matching.")
  5033. (defun org-create-multibrace-regexp (left right n)
  5034. "Create a regular expression which will match a balanced sexp.
  5035. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  5036. as single character strings.
  5037. The regexp returned will match the entire expression including the
  5038. delimiters. It will also define a single group which contains the
  5039. match except for the outermost delimiters. The maximum depth of
  5040. stacked delimiters is N. Escaping delimiters is not possible."
  5041. (let* ((nothing (concat "[^" left right "]*?"))
  5042. (or "\\|")
  5043. (re nothing)
  5044. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  5045. (while (> n 1)
  5046. (setq n (1- n)
  5047. re (concat re or next)
  5048. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  5049. (concat left "\\(" re "\\)" right)))
  5050. (defconst org-match-substring-regexp
  5051. (concat
  5052. "\\(\\S-\\)\\([_^]\\)\\("
  5053. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  5054. "\\|"
  5055. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  5056. "\\|"
  5057. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  5058. "The regular expression matching a sub- or superscript.")
  5059. (defconst org-match-substring-with-braces-regexp
  5060. (concat
  5061. "\\(\\S-\\)\\([_^]\\)"
  5062. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  5063. "The regular expression matching a sub- or superscript, forcing braces.")
  5064. (defun org-make-link-regexps ()
  5065. "Update the link regular expressions.
  5066. This should be called after the variable `org-link-parameters' has changed."
  5067. (let ((types-re (regexp-opt (org-link-types) t)))
  5068. (setq org-link-types-re
  5069. (concat "\\`" types-re ":")
  5070. org-link-re-with-space
  5071. (concat "<?" types-re ":"
  5072. "\\([^" org-non-link-chars " ]"
  5073. "[^" org-non-link-chars "]*"
  5074. "[^" org-non-link-chars " ]\\)>?")
  5075. org-link-re-with-space2
  5076. (concat "<?" types-re ":"
  5077. "\\([^" org-non-link-chars " ]"
  5078. "[^\t\n\r]*"
  5079. "[^" org-non-link-chars " ]\\)>?")
  5080. org-link-re-with-space3
  5081. (concat "<?" types-re ":"
  5082. "\\([^" org-non-link-chars " ]"
  5083. "[^\t\n\r]*\\)")
  5084. org-angle-link-re
  5085. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  5086. types-re)
  5087. org-plain-link-re
  5088. (concat
  5089. "\\<" types-re ":"
  5090. "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  5091. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  5092. org-bracket-link-regexp
  5093. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  5094. org-bracket-link-analytic-regexp
  5095. (concat
  5096. "\\[\\["
  5097. "\\(" types-re ":\\)?"
  5098. "\\([^]]+\\)"
  5099. "\\]"
  5100. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5101. "\\]")
  5102. org-bracket-link-analytic-regexp++
  5103. (concat
  5104. "\\[\\["
  5105. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  5106. "\\([^]]+\\)"
  5107. "\\]"
  5108. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5109. "\\]")
  5110. org-any-link-re
  5111. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  5112. org-angle-link-re "\\)\\|\\("
  5113. org-plain-link-re "\\)"))))
  5114. (org-make-link-regexps)
  5115. (defvar org-emph-face nil)
  5116. (defun org-do-emphasis-faces (limit)
  5117. "Run through the buffer and emphasize strings."
  5118. (let (rtn a)
  5119. (while (and (not rtn) (re-search-forward org-emph-re limit t))
  5120. (let* ((border (char-after (match-beginning 3)))
  5121. (bre (regexp-quote (char-to-string border))))
  5122. (when (and (not (= border (char-after (match-beginning 4))))
  5123. (not (string-match-p (concat bre ".*" bre)
  5124. (replace-regexp-in-string
  5125. "\n" " "
  5126. (substring (match-string 2) 1 -1)))))
  5127. (setq rtn t)
  5128. (setq a (assoc (match-string 3) org-emphasis-alist))
  5129. (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
  5130. 'face
  5131. (nth 1 a))
  5132. (and (nth 2 a)
  5133. (org-remove-flyspell-overlays-in
  5134. (match-beginning 0) (match-end 0)))
  5135. (add-text-properties (match-beginning 2) (match-end 2)
  5136. '(font-lock-multiline t org-emphasis t))
  5137. (when org-hide-emphasis-markers
  5138. (add-text-properties (match-end 4) (match-beginning 5)
  5139. '(invisible org-link))
  5140. (add-text-properties (match-beginning 3) (match-end 3)
  5141. '(invisible org-link)))))
  5142. (goto-char (1+ (match-beginning 0))))
  5143. rtn))
  5144. (defun org-emphasize (&optional char)
  5145. "Insert or change an emphasis, i.e. a font like bold or italic.
  5146. If there is an active region, change that region to a new emphasis.
  5147. If there is no region, just insert the marker characters and position
  5148. the cursor between them.
  5149. CHAR should be the marker character. If it is a space, it means to
  5150. remove the emphasis of the selected region.
  5151. If CHAR is not given (for example in an interactive call) it will be
  5152. prompted for."
  5153. (interactive)
  5154. (let ((erc org-emphasis-regexp-components)
  5155. (string "") beg end move s)
  5156. (if (org-region-active-p)
  5157. (setq beg (region-beginning)
  5158. end (region-end)
  5159. string (buffer-substring beg end))
  5160. (setq move t))
  5161. (unless char
  5162. (message "Emphasis marker or tag: [%s]"
  5163. (mapconcat #'car org-emphasis-alist ""))
  5164. (setq char (read-char-exclusive)))
  5165. (if (equal char ?\s)
  5166. (setq s ""
  5167. move nil)
  5168. (unless (assoc (char-to-string char) org-emphasis-alist)
  5169. (user-error "No such emphasis marker: \"%c\"" char))
  5170. (setq s (char-to-string char)))
  5171. (while (and (> (length string) 1)
  5172. (equal (substring string 0 1) (substring string -1))
  5173. (assoc (substring string 0 1) org-emphasis-alist))
  5174. (setq string (substring string 1 -1)))
  5175. (setq string (concat s string s))
  5176. (when beg (delete-region beg end))
  5177. (unless (or (bolp)
  5178. (string-match (concat "[" (nth 0 erc) "\n]")
  5179. (char-to-string (char-before (point)))))
  5180. (insert " "))
  5181. (unless (or (eobp)
  5182. (string-match (concat "[" (nth 1 erc) "\n]")
  5183. (char-to-string (char-after (point)))))
  5184. (insert " ") (backward-char 1))
  5185. (insert string)
  5186. (and move (backward-char 1))))
  5187. (defconst org-nonsticky-props
  5188. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5189. (defsubst org-rear-nonsticky-at (pos)
  5190. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5191. (defun org-activate-plain-links (limit)
  5192. "Add link properties for plain links."
  5193. (when (and (re-search-forward org-plain-link-re limit t)
  5194. (not (org-in-src-block-p)))
  5195. (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
  5196. 'face))
  5197. (link (match-string-no-properties 0))
  5198. (type (match-string-no-properties 1))
  5199. (path (match-string-no-properties 2))
  5200. (link-start (match-beginning 0))
  5201. (link-end (match-end 0))
  5202. (link-face (org-link-get-parameter type :face))
  5203. (help-echo (org-link-get-parameter type :help-echo))
  5204. (htmlize-link (org-link-get-parameter type :htmlize-link))
  5205. (activate-func (org-link-get-parameter type :activate-func)))
  5206. (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
  5207. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5208. (add-text-properties (match-beginning 0) (match-end 0)
  5209. (list
  5210. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5211. 'highlight)
  5212. 'face (cond
  5213. ;; A function that returns a face
  5214. ((functionp link-face)
  5215. (funcall link-face path))
  5216. ;; a face
  5217. ((facep link-face)
  5218. link-face)
  5219. ;; An anonymous face
  5220. ((consp link-face)
  5221. link-face)
  5222. ;; default
  5223. (t
  5224. 'org-link))
  5225. 'help-echo (cond
  5226. ((stringp help-echo)
  5227. help-echo)
  5228. ((functionp help-echo)
  5229. help-echo)
  5230. (t
  5231. (concat "LINK: "
  5232. (save-match-data
  5233. (org-link-unescape link)))))
  5234. 'htmlize-link (cond
  5235. ((functionp htmlize-link)
  5236. (funcall htmlize-link path))
  5237. (t
  5238. `(:uri ,link)))
  5239. 'keymap (or (org-link-get-parameter type :keymap)
  5240. org-mouse-map)
  5241. 'org-link-start (match-beginning 0)))
  5242. (org-rear-nonsticky-at (match-end 0))
  5243. (when activate-func
  5244. (funcall activate-func link-start link-end path nil))
  5245. t))))
  5246. (defun org-activate-code (limit)
  5247. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5248. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5249. (remove-text-properties (match-beginning 0) (match-end 0)
  5250. '(display t invisible t intangible t))
  5251. t))
  5252. (defcustom org-src-fontify-natively t
  5253. "When non-nil, fontify code in code blocks.
  5254. See also the `org-block' face."
  5255. :type 'boolean
  5256. :version "24.4"
  5257. :package-version '(Org . "8.3")
  5258. :group 'org-appearance
  5259. :group 'org-babel)
  5260. (defcustom org-allow-promoting-top-level-subtree nil
  5261. "When non-nil, allow promoting a top level subtree.
  5262. The leading star of the top level headline will be replaced
  5263. by a #."
  5264. :type 'boolean
  5265. :version "24.1"
  5266. :group 'org-appearance)
  5267. (defun org-fontify-meta-lines-and-blocks (limit)
  5268. (condition-case nil
  5269. (org-fontify-meta-lines-and-blocks-1 limit)
  5270. (error (message "org-mode fontification error in %S at %d"
  5271. (current-buffer)
  5272. (line-number-at-pos)))))
  5273. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5274. "Fontify #+ lines and blocks."
  5275. (let ((case-fold-search t))
  5276. (when (re-search-forward
  5277. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5278. limit t)
  5279. (let ((beg (match-beginning 0))
  5280. (block-start (match-end 0))
  5281. (block-end nil)
  5282. (lang (match-string 7))
  5283. (beg1 (line-beginning-position 2))
  5284. (dc1 (downcase (match-string 2)))
  5285. (dc3 (downcase (match-string 3)))
  5286. end end1 quoting block-type)
  5287. (cond
  5288. ((and (match-end 4) (equal dc3 "+begin"))
  5289. ;; Truly a block
  5290. (setq block-type (downcase (match-string 5))
  5291. quoting (member block-type org-protecting-blocks))
  5292. (when (re-search-forward
  5293. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5294. nil t) ;; on purpose, we look further than LIMIT
  5295. (setq end (min (point-max) (match-end 0))
  5296. end1 (min (point-max) (1- (match-beginning 0))))
  5297. (setq block-end (match-beginning 0))
  5298. (when quoting
  5299. (org-remove-flyspell-overlays-in beg1 end1)
  5300. (remove-text-properties beg end
  5301. '(display t invisible t intangible t)))
  5302. (add-text-properties
  5303. beg end '(font-lock-fontified t font-lock-multiline t))
  5304. (add-text-properties beg beg1 '(face org-meta-line))
  5305. (org-remove-flyspell-overlays-in beg beg1)
  5306. (add-text-properties ; For end_src
  5307. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5308. (org-remove-flyspell-overlays-in end1 end)
  5309. (cond
  5310. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5311. (org-src-font-lock-fontify-block lang block-start block-end)
  5312. (add-text-properties beg1 block-end '(src-block t)))
  5313. (quoting
  5314. (add-text-properties beg1 (min (point-max) (1+ end1))
  5315. (list 'face
  5316. (list :inherit
  5317. (let ((face-name
  5318. (intern (format "org-block-%s" lang))))
  5319. (append (and (facep face-name) (list face-name))
  5320. '(org-block))))))) ; end of source block
  5321. ((not org-fontify-quote-and-verse-blocks))
  5322. ((string= block-type "quote")
  5323. (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
  5324. ((string= block-type "verse")
  5325. (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
  5326. (add-text-properties beg beg1 '(face org-block-begin-line))
  5327. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5328. '(face org-block-end-line))
  5329. t))
  5330. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5331. (org-remove-flyspell-overlays-in
  5332. (match-beginning 0)
  5333. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5334. (add-text-properties
  5335. beg (match-end 3)
  5336. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5337. '(font-lock-fontified t invisible t)
  5338. '(font-lock-fontified t face org-document-info-keyword)))
  5339. (add-text-properties
  5340. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5341. (if (string-equal dc1 "+title:")
  5342. '(font-lock-fontified t face org-document-title)
  5343. '(font-lock-fontified t face org-document-info))))
  5344. ((equal dc1 "+caption:")
  5345. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5346. (remove-text-properties (match-beginning 0) (match-end 0)
  5347. '(display t invisible t intangible t))
  5348. (add-text-properties (match-beginning 1) (match-end 3)
  5349. '(font-lock-fontified t face org-meta-line))
  5350. (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
  5351. '(font-lock-fontified t face org-block))
  5352. t)
  5353. ((member dc3 '(" " ""))
  5354. (org-remove-flyspell-overlays-in beg (match-end 0))
  5355. (add-text-properties
  5356. beg (match-end 0)
  5357. '(font-lock-fontified t face font-lock-comment-face)))
  5358. (t ;; just any other in-buffer setting, but not indented
  5359. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5360. (remove-text-properties (match-beginning 0) (match-end 0)
  5361. '(display t invisible t intangible t))
  5362. (add-text-properties beg (match-end 0)
  5363. '(font-lock-fontified t face org-meta-line))
  5364. t))))))
  5365. (defun org-fontify-drawers (limit)
  5366. "Fontify drawers."
  5367. (when (re-search-forward org-drawer-regexp limit t)
  5368. (add-text-properties
  5369. (match-beginning 0) (match-end 0)
  5370. '(font-lock-fontified t face org-special-keyword))
  5371. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5372. t))
  5373. (defun org-fontify-macros (limit)
  5374. "Fontify macros."
  5375. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5376. (add-text-properties
  5377. (match-beginning 0) (match-end 0)
  5378. '(font-lock-fontified t face org-macro))
  5379. (when org-hide-macro-markers
  5380. (add-text-properties (match-end 2) (match-beginning 2)
  5381. '(invisible t))
  5382. (add-text-properties (match-beginning 1) (match-end 1)
  5383. '(invisible t)))
  5384. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5385. t))
  5386. (defun org-activate-angle-links (limit)
  5387. "Add text properties for angle links."
  5388. (when (and (re-search-forward org-angle-link-re limit t)
  5389. (not (org-in-src-block-p)))
  5390. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5391. (add-text-properties (match-beginning 0) (match-end 0)
  5392. (list 'mouse-face 'highlight
  5393. 'keymap org-mouse-map
  5394. 'font-lock-multiline t))
  5395. (org-rear-nonsticky-at (match-end 0))
  5396. t))
  5397. (defun org-activate-footnote-links (limit)
  5398. "Add text properties for footnotes."
  5399. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5400. (when fn
  5401. (let* ((beg (nth 1 fn))
  5402. (end (nth 2 fn))
  5403. (label (car fn))
  5404. (referencep (/= (line-beginning-position) beg)))
  5405. (when (and referencep (nth 3 fn))
  5406. (save-excursion
  5407. (goto-char beg)
  5408. (search-forward (or label "fn:"))
  5409. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5410. (add-text-properties beg end
  5411. (list 'mouse-face 'highlight
  5412. 'keymap org-mouse-map
  5413. 'help-echo
  5414. (if referencep "Footnote reference"
  5415. "Footnote definition")
  5416. 'font-lock-fontified t
  5417. 'font-lock-multiline t
  5418. 'face 'org-footnote))))))
  5419. (defun org-activate-bracket-links (limit)
  5420. "Add text properties for bracketed links."
  5421. (when (and (re-search-forward org-bracket-link-regexp limit t)
  5422. (not (org-in-src-block-p)))
  5423. (let* ((hl (save-match-data
  5424. (org-link-expand-abbrev (match-string-no-properties 1))))
  5425. (type (save-match-data
  5426. (and (string-match org-plain-link-re hl)
  5427. (match-string-no-properties 1 hl))))
  5428. (path (save-match-data
  5429. (and (string-match org-plain-link-re hl)
  5430. (match-string-no-properties 2 hl))))
  5431. (link-start (match-beginning 0))
  5432. (link-end (match-end 0))
  5433. (bracketp t)
  5434. (help-echo (org-link-get-parameter type :help-echo))
  5435. (help (cond
  5436. ((stringp help-echo)
  5437. help-echo)
  5438. ((functionp help-echo)
  5439. help-echo)
  5440. (t
  5441. (concat "LINK: "
  5442. (save-match-data
  5443. (org-link-unescape hl))))))
  5444. (link-face (org-link-get-parameter type :face))
  5445. (face (cond
  5446. ;; A function that returns a face
  5447. ((functionp link-face)
  5448. (funcall link-face path))
  5449. ;; a face
  5450. ((facep link-face)
  5451. link-face)
  5452. ;; An anonymous face
  5453. ((consp link-face)
  5454. link-face)
  5455. ;; default
  5456. (t
  5457. 'org-link)))
  5458. (keymap (or (org-link-get-parameter type :keymap)
  5459. org-mouse-map))
  5460. (mouse-face (or (org-link-get-parameter type :mouse-face)
  5461. 'highlight))
  5462. (htmlize (org-link-get-parameter type :htmlize-link))
  5463. (htmlize-link (cond
  5464. ((functionp htmlize)
  5465. (funcall htmlize))
  5466. (t
  5467. `(:uri ,(format "%s:%s" type path)))))
  5468. (activate-func (org-link-get-parameter type :activate-func))
  5469. ;; invisible part
  5470. (ip (list 'invisible (or
  5471. (org-link-get-parameter type :display)
  5472. 'org-link)
  5473. 'face face
  5474. 'keymap keymap
  5475. 'mouse-face mouse-face
  5476. 'font-lock-multiline t
  5477. 'help-echo help
  5478. 'htmlize-link htmlize-link))
  5479. ;; visible part
  5480. (vp (list 'keymap keymap
  5481. 'face face
  5482. 'mouse-face mouse-face
  5483. 'font-lock-multiline t
  5484. 'help-echo help
  5485. 'htmlize-link htmlize-link)))
  5486. ;; We need to remove the invisible property here. Table narrowing
  5487. ;; may have made some of this invisible.
  5488. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5489. (remove-text-properties (match-beginning 0) (match-end 0)
  5490. '(invisible nil))
  5491. (if (match-end 3)
  5492. (progn
  5493. (add-text-properties (match-beginning 0) (match-beginning 3) ip)
  5494. (org-rear-nonsticky-at (match-beginning 3))
  5495. (add-text-properties (match-beginning 3) (match-end 3) vp)
  5496. (org-rear-nonsticky-at (match-end 3))
  5497. (add-text-properties (match-end 3) (match-end 0) ip)
  5498. (org-rear-nonsticky-at (match-end 0)))
  5499. (add-text-properties (match-beginning 0) (match-beginning 1) ip)
  5500. (org-rear-nonsticky-at (match-beginning 1))
  5501. (add-text-properties (match-beginning 1) (match-end 1) vp)
  5502. (org-rear-nonsticky-at (match-end 1))
  5503. (add-text-properties (match-end 1) (match-end 0) ip)
  5504. (org-rear-nonsticky-at (match-end 0)))
  5505. (when activate-func
  5506. (funcall activate-func link-start link-end path bracketp))
  5507. t)))
  5508. (defun org-activate-dates (limit)
  5509. "Add text properties for dates."
  5510. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5511. (not (equal (char-before (match-beginning 0)) 91)))
  5512. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5513. (add-text-properties (match-beginning 0) (match-end 0)
  5514. (list 'mouse-face 'highlight
  5515. 'keymap org-mouse-map))
  5516. (org-rear-nonsticky-at (match-end 0))
  5517. (when org-display-custom-times
  5518. (if (match-end 3)
  5519. (org-display-custom-time (match-beginning 3) (match-end 3))
  5520. (org-display-custom-time (match-beginning 1) (match-end 1))))
  5521. t))
  5522. (defvar-local org-target-link-regexp nil
  5523. "Regular expression matching radio targets in plain text.")
  5524. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5525. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5526. border border border))
  5527. "Regular expression matching a link target.")
  5528. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5529. "Regular expression matching a radio target.")
  5530. (defconst org-any-target-regexp
  5531. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5532. "Regular expression matching any target.")
  5533. (defun org-activate-target-links (limit)
  5534. "Add text properties for target matches."
  5535. (when org-target-link-regexp
  5536. (let ((case-fold-search t))
  5537. (when (re-search-forward org-target-link-regexp limit t)
  5538. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5539. (add-text-properties (match-beginning 1) (match-end 1)
  5540. (list 'mouse-face 'highlight
  5541. 'keymap org-mouse-map
  5542. 'help-echo "Radio target link"
  5543. 'org-linked-text t))
  5544. (org-rear-nonsticky-at (match-end 1))
  5545. t))))
  5546. (defun org-update-radio-target-regexp ()
  5547. "Find all radio targets in this file and update the regular expression.
  5548. Also refresh fontification if needed."
  5549. (interactive)
  5550. (let ((old-regexp org-target-link-regexp)
  5551. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5552. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5553. (targets
  5554. (org-with-wide-buffer
  5555. (goto-char (point-min))
  5556. (let (rtn)
  5557. (while (re-search-forward org-radio-target-regexp nil t)
  5558. ;; Make sure point is really within the object.
  5559. (backward-char)
  5560. (let ((obj (org-element-context)))
  5561. (when (eq (org-element-type obj) 'radio-target)
  5562. (cl-pushnew (org-element-property :value obj) rtn
  5563. :test #'equal))))
  5564. rtn))))
  5565. (setq org-target-link-regexp
  5566. (and targets
  5567. (concat before-re
  5568. (mapconcat
  5569. (lambda (x)
  5570. (replace-regexp-in-string
  5571. " +" "\\s-+" (regexp-quote x) t t))
  5572. targets
  5573. "\\|")
  5574. after-re)))
  5575. (unless (equal old-regexp org-target-link-regexp)
  5576. ;; Clean-up cache.
  5577. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5578. ((not org-target-link-regexp) old-regexp)
  5579. (t
  5580. (concat before-re
  5581. (mapconcat
  5582. (lambda (re)
  5583. (substring re (length before-re)
  5584. (- (length after-re))))
  5585. (list old-regexp org-target-link-regexp)
  5586. "\\|")
  5587. after-re)))))
  5588. (org-with-wide-buffer
  5589. (goto-char (point-min))
  5590. (while (re-search-forward regexp nil t)
  5591. (org-element-cache-refresh (match-beginning 1)))))
  5592. ;; Re fontify buffer.
  5593. (when (memq 'radio org-highlight-links)
  5594. (org-restart-font-lock)))))
  5595. (defun org-hide-wide-columns (limit)
  5596. (let (s e)
  5597. (setq s (text-property-any (point) (or limit (point-max))
  5598. 'org-cwidth t))
  5599. (when s
  5600. (setq e (next-single-property-change s 'org-cwidth))
  5601. (add-text-properties s e '(invisible org-cwidth))
  5602. (goto-char e)
  5603. t)))
  5604. (defvar org-latex-and-related-regexp nil
  5605. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5606. (defun org-compute-latex-and-related-regexp ()
  5607. "Compute regular expression for LaTeX, entities and sub/superscript.
  5608. Result depends on variable `org-highlight-latex-and-related'."
  5609. (setq-local
  5610. org-latex-and-related-regexp
  5611. (let* ((re-sub
  5612. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5613. ((eq org-use-sub-superscripts '{})
  5614. (list org-match-substring-with-braces-regexp))
  5615. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5616. (re-latex
  5617. (when (memq 'latex org-highlight-latex-and-related)
  5618. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5619. (delq nil
  5620. (mapcar (lambda (x)
  5621. (and (member (car x) matchers) (nth 1 x)))
  5622. org-latex-regexps)))))
  5623. (re-entities
  5624. (when (memq 'entities org-highlight-latex-and-related)
  5625. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5626. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5627. (defun org-do-latex-and-related (limit)
  5628. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5629. LIMIT bounds the search for syntax to highlight. Stop at first
  5630. highlighted object, if any. Return t if some highlighting was
  5631. done, nil otherwise."
  5632. (when (org-string-nw-p org-latex-and-related-regexp)
  5633. (catch 'found
  5634. (while (re-search-forward org-latex-and-related-regexp limit t)
  5635. (unless
  5636. (cl-some
  5637. (lambda (f)
  5638. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5639. (save-excursion
  5640. (goto-char (1+ (match-beginning 0)))
  5641. (face-at-point nil t)))
  5642. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5643. '(?_ ?^))
  5644. 1
  5645. 0)))
  5646. (font-lock-prepend-text-property
  5647. (+ offset (match-beginning 0)) (match-end 0)
  5648. 'face 'org-latex-and-related)
  5649. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5650. '(font-lock-multiline t)))
  5651. (throw 'found t)))
  5652. nil)))
  5653. (defun org-restart-font-lock ()
  5654. "Restart `font-lock-mode', to force refontification."
  5655. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5656. (font-lock-mode -1)
  5657. (font-lock-mode 1)))
  5658. (defun org-activate-tags (limit)
  5659. (when (re-search-forward
  5660. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5661. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5662. (add-text-properties (match-beginning 1) (match-end 1)
  5663. (list 'mouse-face 'highlight
  5664. 'keymap org-mouse-map))
  5665. (org-rear-nonsticky-at (match-end 1))
  5666. t))
  5667. (defun org-outline-level ()
  5668. "Compute the outline level of the heading at point.
  5669. If this is called at a normal headline, the level is the number
  5670. of stars. Use `org-reduced-level' to remove the effect of
  5671. `org-odd-levels'. Unlike to `org-current-level', this function
  5672. takes into consideration inlinetasks."
  5673. (org-with-wide-buffer
  5674. (end-of-line)
  5675. (if (re-search-backward org-outline-regexp-bol nil t)
  5676. (1- (- (match-end 0) (match-beginning 0)))
  5677. 0)))
  5678. (defvar org-font-lock-keywords nil)
  5679. (defsubst org-re-property (property &optional literal allow-null value)
  5680. "Return a regexp matching a PROPERTY line.
  5681. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5682. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5683. non-nil, match properties even without a value.
  5684. Match group 3 is set to the value when it exists. If there is no
  5685. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5686. With optional argument VALUE, match only property lines with
  5687. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5688. unless LITERAL is non-nil."
  5689. (concat
  5690. "^\\(?4:[ \t]*\\)"
  5691. (format "\\(?1::\\(?2:%s\\):\\)"
  5692. (if literal property (regexp-quote property)))
  5693. (cond (value
  5694. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5695. (if literal value (regexp-quote value))))
  5696. (allow-null
  5697. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5698. (t
  5699. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5700. (defconst org-property-re
  5701. (org-re-property "\\S-+" 'literal t)
  5702. "Regular expression matching a property line.
  5703. There are four matching groups:
  5704. 1: :PROPKEY: including the leading and trailing colon,
  5705. 2: PROPKEY without the leading and trailing colon,
  5706. 3: PROPVAL without leading or trailing spaces,
  5707. 4: the indentation of the current line,
  5708. 5: trailing whitespace.")
  5709. (defvar org-font-lock-hook nil
  5710. "Functions to be called for special font lock stuff.")
  5711. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5712. (defvar org-font-lock-set-keywords-hook nil
  5713. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5714. This is called after `org-font-lock-extra-keywords' is defined, but before
  5715. it is installed to be used by font lock. This can be useful if something
  5716. needs to be inserted at a specific position in the font-lock sequence.")
  5717. (defun org-font-lock-hook (limit)
  5718. "Run `org-font-lock-hook' within LIMIT."
  5719. (run-hook-with-args 'org-font-lock-hook limit))
  5720. (defun org-set-font-lock-defaults ()
  5721. "Set font lock defaults for the current buffer."
  5722. (let* ((em org-fontify-emphasized-text)
  5723. (lk org-highlight-links)
  5724. (org-font-lock-extra-keywords
  5725. (list
  5726. ;; Call the hook
  5727. '(org-font-lock-hook)
  5728. ;; Headlines
  5729. `(,(if org-fontify-whole-heading-line
  5730. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5731. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5732. (1 (org-get-level-face 1))
  5733. (2 (org-get-level-face 2))
  5734. (3 (org-get-level-face 3)))
  5735. ;; Table lines
  5736. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5737. (1 'org-table t))
  5738. ;; Table internals
  5739. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5740. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5741. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5742. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5743. ;; Drawers
  5744. '(org-fontify-drawers)
  5745. ;; Properties
  5746. (list org-property-re
  5747. '(1 'org-special-keyword t)
  5748. '(3 'org-property-value t))
  5749. ;; Links
  5750. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5751. (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
  5752. (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
  5753. (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
  5754. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5755. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5756. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5757. ;; Targets.
  5758. (list org-any-target-regexp '(0 'org-target t))
  5759. ;; Diary sexps.
  5760. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5761. ;; Macro
  5762. '(org-fontify-macros)
  5763. '(org-hide-wide-columns (0 nil append))
  5764. ;; TODO keyword
  5765. (list (format org-heading-keyword-regexp-format
  5766. org-todo-regexp)
  5767. '(2 (org-get-todo-face 2) t))
  5768. ;; DONE
  5769. (if org-fontify-done-headline
  5770. (list (format org-heading-keyword-regexp-format
  5771. (concat
  5772. "\\(?:"
  5773. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5774. "\\)"))
  5775. '(2 'org-headline-done t))
  5776. nil)
  5777. ;; Priorities
  5778. '(org-font-lock-add-priority-faces)
  5779. ;; Tags
  5780. '(org-font-lock-add-tag-faces)
  5781. ;; Tags groups
  5782. (when (and org-group-tags org-tag-groups-alist)
  5783. (list (concat org-outline-regexp-bol ".+\\(:"
  5784. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5785. ":\\).*$")
  5786. '(1 'org-tag-group prepend)))
  5787. ;; Special keywords
  5788. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5789. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5790. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5791. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5792. ;; Emphasis
  5793. (when em '(org-do-emphasis-faces))
  5794. ;; Checkboxes
  5795. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5796. 1 'org-checkbox prepend)
  5797. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5798. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5799. (0 (org-get-checkbox-statistics-face) t)))
  5800. ;; Description list items
  5801. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5802. 1 'org-list-dt prepend)
  5803. ;; ARCHIVEd headings
  5804. (list (concat
  5805. org-outline-regexp-bol
  5806. "\\(.*:" org-archive-tag ":.*\\)")
  5807. '(1 'org-archived prepend))
  5808. ;; Specials
  5809. '(org-do-latex-and-related)
  5810. '(org-fontify-entities)
  5811. '(org-raise-scripts)
  5812. ;; Code
  5813. '(org-activate-code (1 'org-code t))
  5814. ;; COMMENT
  5815. (list (format
  5816. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5817. org-todo-regexp
  5818. org-comment-string)
  5819. '(9 'org-special-keyword t))
  5820. ;; Blocks and meta lines
  5821. '(org-fontify-meta-lines-and-blocks))))
  5822. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5823. (run-hooks 'org-font-lock-set-keywords-hook)
  5824. ;; Now set the full font-lock-keywords
  5825. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5826. (setq-local font-lock-defaults
  5827. '(org-font-lock-keywords t nil nil backward-paragraph))
  5828. (kill-local-variable 'font-lock-keywords)
  5829. nil))
  5830. (defun org-toggle-pretty-entities ()
  5831. "Toggle the composition display of entities as UTF8 characters."
  5832. (interactive)
  5833. (setq-local org-pretty-entities (not org-pretty-entities))
  5834. (org-restart-font-lock)
  5835. (if org-pretty-entities
  5836. (message "Entities are now displayed as UTF8 characters")
  5837. (save-restriction
  5838. (widen)
  5839. (decompose-region (point-min) (point-max))
  5840. (message "Entities are now displayed as plain text"))))
  5841. (defvar-local org-custom-properties-overlays nil
  5842. "List of overlays used for custom properties.")
  5843. (defun org-toggle-custom-properties-visibility ()
  5844. "Display or hide properties in `org-custom-properties'."
  5845. (interactive)
  5846. (if org-custom-properties-overlays
  5847. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5848. (setq org-custom-properties-overlays nil))
  5849. (when org-custom-properties
  5850. (org-with-wide-buffer
  5851. (goto-char (point-min))
  5852. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5853. (while (re-search-forward regexp nil t)
  5854. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5855. (when (and end (< (point) end))
  5856. ;; Hide first custom property in current drawer.
  5857. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5858. (overlay-put o 'invisible t)
  5859. (overlay-put o 'org-custom-property t)
  5860. (push o org-custom-properties-overlays))
  5861. ;; Hide additional custom properties in the same drawer.
  5862. (while (re-search-forward regexp end t)
  5863. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5864. (overlay-put o 'invisible t)
  5865. (overlay-put o 'org-custom-property t)
  5866. (push o org-custom-properties-overlays)))))
  5867. ;; Each entry is limited to a single property drawer.
  5868. (outline-next-heading)))))))
  5869. (defun org-fontify-entities (limit)
  5870. "Find an entity to fontify."
  5871. (let (ee)
  5872. (when org-pretty-entities
  5873. (catch 'match
  5874. ;; "\_ "-family is left out on purpose. Only the first one,
  5875. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5876. ;; confusing when adding a second white space character.
  5877. (while (re-search-forward
  5878. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5879. limit t)
  5880. (when (and (not (org-at-comment-p))
  5881. (setq ee (org-entity-get (match-string 1)))
  5882. (= (length (nth 6 ee)) 1))
  5883. (let* ((end (if (equal (match-string 2) "{}")
  5884. (match-end 2)
  5885. (match-end 1))))
  5886. (add-text-properties
  5887. (match-beginning 0) end
  5888. (list 'font-lock-fontified t))
  5889. (compose-region (match-beginning 0) end
  5890. (nth 6 ee) nil)
  5891. (backward-char 1)
  5892. (throw 'match t))))
  5893. nil))))
  5894. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5895. "Fontify string S like in Org mode."
  5896. (with-temp-buffer
  5897. (insert s)
  5898. (let ((org-odd-levels-only odd-levels))
  5899. (org-mode)
  5900. (org-font-lock-ensure)
  5901. (buffer-string))))
  5902. (defvar org-m nil)
  5903. (defvar org-l nil)
  5904. (defvar org-f nil)
  5905. (defun org-get-level-face (n)
  5906. "Get the right face for match N in font-lock matching of headlines."
  5907. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5908. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5909. (if org-cycle-level-faces
  5910. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5911. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5912. (cond
  5913. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5914. ((eq n 2) org-f)
  5915. (t (unless org-level-color-stars-only org-f))))
  5916. (defun org-face-from-face-or-color (context inherit face-or-color)
  5917. "Create a face list that inherits INHERIT, but sets the foreground color.
  5918. When FACE-OR-COLOR is not a string, just return it."
  5919. (if (stringp face-or-color)
  5920. (list :inherit inherit
  5921. (cdr (assoc context org-faces-easy-properties))
  5922. face-or-color)
  5923. face-or-color))
  5924. (defun org-get-todo-face (kwd)
  5925. "Get the right face for a TODO keyword KWD.
  5926. If KWD is a number, get the corresponding match group."
  5927. (when (numberp kwd) (setq kwd (match-string kwd)))
  5928. (or (org-face-from-face-or-color
  5929. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5930. (and (member kwd org-done-keywords) 'org-done)
  5931. 'org-todo))
  5932. (defun org-get-priority-face (priority)
  5933. "Get the right face for PRIORITY.
  5934. PRIORITY is a character."
  5935. (or (org-face-from-face-or-color
  5936. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5937. 'org-priority))
  5938. (defun org-get-tag-face (tag)
  5939. "Get the right face for TAG.
  5940. If TAG is a number, get the corresponding match group."
  5941. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5942. (or (org-face-from-face-or-color
  5943. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5944. 'org-tag)))
  5945. (defun org-font-lock-add-priority-faces (limit)
  5946. "Add the special priority faces."
  5947. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5948. (add-text-properties
  5949. (match-beginning 1) (match-end 1)
  5950. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5951. 'font-lock-fontified t))))
  5952. (defun org-font-lock-add-tag-faces (limit)
  5953. "Add the special tag faces."
  5954. (when (and org-tag-faces org-tags-special-faces-re)
  5955. (while (re-search-forward org-tags-special-faces-re limit t)
  5956. (add-text-properties (match-beginning 1) (match-end 1)
  5957. (list 'face (org-get-tag-face 1)
  5958. 'font-lock-fontified t))
  5959. (backward-char 1))))
  5960. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5961. "Remove fontification and activation overlays from links."
  5962. (font-lock-default-unfontify-region beg end)
  5963. (let* ((buffer-undo-list t)
  5964. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5965. (inhibit-modification-hooks t)
  5966. deactivate-mark buffer-file-name buffer-file-truename)
  5967. (decompose-region beg end)
  5968. (remove-text-properties beg end
  5969. '(mouse-face t keymap t org-linked-text t
  5970. invisible t intangible t
  5971. org-emphasis t))
  5972. (org-remove-font-lock-display-properties beg end)))
  5973. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5974. ((raise 0.3) (height 0.7))
  5975. ((raise -0.5))
  5976. ((raise 0.5)))
  5977. "Display properties for showing superscripts and subscripts.")
  5978. (defun org-remove-font-lock-display-properties (beg end)
  5979. "Remove specific display properties that have been added by font lock.
  5980. The will remove the raise properties that are used to show superscripts
  5981. and subscripts."
  5982. (let (next prop)
  5983. (while (< beg end)
  5984. (setq next (next-single-property-change beg 'display nil end)
  5985. prop (get-text-property beg 'display))
  5986. (when (member prop org-script-display)
  5987. (put-text-property beg next 'display nil))
  5988. (setq beg next))))
  5989. (defun org-raise-scripts (limit)
  5990. "Add raise properties to sub/superscripts."
  5991. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5992. (re-search-forward
  5993. (if (eq org-use-sub-superscripts t)
  5994. org-match-substring-regexp
  5995. org-match-substring-with-braces-regexp)
  5996. limit t))
  5997. (let* ((pos (point)) table-p comment-p
  5998. (mpos (match-beginning 3))
  5999. (emph-p (get-text-property mpos 'org-emphasis))
  6000. (link-p (get-text-property mpos 'mouse-face))
  6001. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  6002. (goto-char (point-at-bol))
  6003. (setq table-p (looking-at-p org-table-dataline-regexp)
  6004. comment-p (looking-at-p "^[ \t]*#[ +]"))
  6005. (goto-char pos)
  6006. ;; Handle a_b^c
  6007. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  6008. (unless (or comment-p emph-p link-p keyw-p)
  6009. (put-text-property (match-beginning 3) (match-end 0)
  6010. 'display
  6011. (if (equal (char-after (match-beginning 2)) ?^)
  6012. (nth (if table-p 3 1) org-script-display)
  6013. (nth (if table-p 2 0) org-script-display)))
  6014. (add-text-properties (match-beginning 2) (match-end 2)
  6015. (list 'invisible t
  6016. 'org-dwidth t 'org-dwidth-n 1))
  6017. (if (and (eq (char-after (match-beginning 3)) ?{)
  6018. (eq (char-before (match-end 3)) ?}))
  6019. (progn
  6020. (add-text-properties
  6021. (match-beginning 3) (1+ (match-beginning 3))
  6022. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
  6023. (add-text-properties
  6024. (1- (match-end 3)) (match-end 3)
  6025. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
  6026. t)))
  6027. ;;;; Visibility cycling, including org-goto and indirect buffer
  6028. ;;; Cycling
  6029. (defvar-local org-cycle-global-status nil)
  6030. (put 'org-cycle-global-status 'org-state t)
  6031. (defvar-local org-cycle-subtree-status nil)
  6032. (put 'org-cycle-subtree-status 'org-state t)
  6033. (defvar org-inlinetask-min-level)
  6034. (defun org-unlogged-message (&rest args)
  6035. "Display a message, but avoid logging it in the *Messages* buffer."
  6036. (let ((message-log-max nil))
  6037. (apply 'message args)))
  6038. ;;;###autoload
  6039. (defun org-cycle (&optional arg)
  6040. "TAB-action and visibility cycling for Org mode.
  6041. This is the command invoked in Org mode by the `TAB' key. Its main
  6042. purpose is outline visibility cycling, but it also invokes other actions
  6043. in special contexts.
  6044. When this function is called with a `\\[universal-argument]' prefix, rotate \
  6045. the entire
  6046. buffer through 3 states (global cycling)
  6047. 1. OVERVIEW: Show only top-level headlines.
  6048. 2. CONTENTS: Show all headlines of all levels, but no body text.
  6049. 3. SHOW ALL: Show everything.
  6050. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  6051. switch to the startup visibility,
  6052. determined by the variable `org-startup-folded', and by any VISIBILITY
  6053. properties in the buffer.
  6054. With a `\\[universal-argument] \\[universal-argument] \
  6055. \\[universal-argument]' prefix argument, show the entire buffer, including
  6056. any drawers.
  6057. When inside a table, re-align the table and move to the next field.
  6058. When point is at the beginning of a headline, rotate the subtree started
  6059. by this line through 3 different states (local cycling)
  6060. 1. FOLDED: Only the main headline is shown.
  6061. 2. CHILDREN: The main headline and the direct children are shown.
  6062. From this state, you can move to one of the children
  6063. and zoom in further.
  6064. 3. SUBTREE: Show the entire subtree, including body text.
  6065. If there is no subtree, switch directly from CHILDREN to FOLDED.
  6066. When point is at the beginning of an empty headline and the variable
  6067. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  6068. of the headline by demoting and promoting it to likely levels. This
  6069. speeds up creation document structure by pressing `TAB' once or several
  6070. times right after creating a new headline.
  6071. When there is a numeric prefix, go up to a heading with level ARG, do
  6072. a `show-subtree' and return to the previous cursor position. If ARG
  6073. is negative, go up that many levels.
  6074. When point is not at the beginning of a headline, execute the global
  6075. binding for `TAB', which is re-indenting the line. See the option
  6076. `org-cycle-emulate-tab' for details.
  6077. As a special case, if point is at the beginning of the buffer and there is
  6078. no headline in line 1, this function will act as if called with prefix arg
  6079. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  6080. prefix arg, but only
  6081. if the variable `org-cycle-global-at-bob' is t."
  6082. (interactive "P")
  6083. (org-load-modules-maybe)
  6084. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  6085. (and org-cycle-level-after-item/entry-creation
  6086. (or (org-cycle-level)
  6087. (org-cycle-item-indentation))))
  6088. (let* ((limit-level
  6089. (or org-cycle-max-level
  6090. (and (boundp 'org-inlinetask-min-level)
  6091. org-inlinetask-min-level
  6092. (1- org-inlinetask-min-level))))
  6093. (nstars (and limit-level
  6094. (if org-odd-levels-only
  6095. (and limit-level (1- (* limit-level 2)))
  6096. limit-level)))
  6097. (org-outline-regexp
  6098. (if (not (derived-mode-p 'org-mode))
  6099. outline-regexp
  6100. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  6101. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  6102. (not (looking-at org-outline-regexp))))
  6103. (org-cycle-hook
  6104. (if bob-special
  6105. (delq 'org-optimize-window-after-visibility-change
  6106. (copy-sequence org-cycle-hook))
  6107. org-cycle-hook))
  6108. (pos (point)))
  6109. (cond
  6110. ((equal arg '(16))
  6111. (setq last-command 'dummy)
  6112. (org-set-startup-visibility)
  6113. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  6114. ((equal arg '(64))
  6115. (outline-show-all)
  6116. (org-unlogged-message "Entire buffer visible, including drawers"))
  6117. ((equal arg '(4)) (org-cycle-internal-global))
  6118. ;; Try hiding block at point.
  6119. ((org-hide-block-toggle-maybe))
  6120. ;; Try cdlatex TAB completion
  6121. ((org-try-cdlatex-tab))
  6122. ;; Table: enter it or move to the next field.
  6123. ((org-at-table-p 'any)
  6124. (if (org-at-table.el-p)
  6125. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6126. Use `\\[org-edit-special]' to edit table.el tables"))
  6127. (if arg (org-table-edit-field t)
  6128. (org-table-justify-field-maybe)
  6129. (call-interactively 'org-table-next-field))))
  6130. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  6131. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6132. (bob-special (org-cycle-internal-global))
  6133. ;; Drawers: delegate to `org-flag-drawer'.
  6134. ((save-excursion
  6135. (beginning-of-line 1)
  6136. (looking-at org-drawer-regexp))
  6137. (org-flag-drawer ; toggle block visibility
  6138. (not (get-char-property (match-end 0) 'invisible))))
  6139. ;; Show-subtree, ARG levels up from here.
  6140. ((integerp arg)
  6141. (save-excursion
  6142. (org-back-to-heading)
  6143. (outline-up-heading (if (< arg 0) (- arg)
  6144. (- (funcall outline-level) arg)))
  6145. (org-show-subtree)))
  6146. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6147. ((and (featurep 'org-inlinetask)
  6148. (org-inlinetask-at-task-p)
  6149. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6150. (org-inlinetask-toggle-visibility))
  6151. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6152. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6153. (save-excursion (move-beginning-of-line 1)
  6154. (looking-at org-outline-regexp)))
  6155. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6156. (org-cycle-internal-local))
  6157. ;; From there: TAB emulation and template completion.
  6158. (buffer-read-only (org-back-to-heading))
  6159. ((run-hook-with-args-until-success
  6160. 'org-tab-after-check-for-cycling-hook))
  6161. ((org-try-structure-completion))
  6162. ((run-hook-with-args-until-success
  6163. 'org-tab-before-tab-emulation-hook))
  6164. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6165. (or (not (bolp))
  6166. (not (looking-at org-outline-regexp))))
  6167. (call-interactively (global-key-binding "\t")))
  6168. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6169. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6170. (or (and (eq org-cycle-emulate-tab 'white)
  6171. (= (match-end 0) (point-at-eol)))
  6172. (and (eq org-cycle-emulate-tab 'whitestart)
  6173. (>= (match-end 0) pos))))
  6174. t
  6175. (eq org-cycle-emulate-tab t))
  6176. (call-interactively (global-key-binding "\t")))
  6177. (t (save-excursion
  6178. (org-back-to-heading)
  6179. (org-cycle)))))))
  6180. (defun org-cycle-internal-global ()
  6181. "Do the global cycling action."
  6182. ;; Hack to avoid display of messages for .org attachments in Gnus
  6183. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6184. (cond
  6185. ((and (eq last-command this-command)
  6186. (eq org-cycle-global-status 'overview))
  6187. ;; We just created the overview - now do table of contents
  6188. ;; This can be slow in very large buffers, so indicate action
  6189. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6190. (unless ga (org-unlogged-message "CONTENTS..."))
  6191. (org-content)
  6192. (unless ga (org-unlogged-message "CONTENTS...done"))
  6193. (setq org-cycle-global-status 'contents)
  6194. (run-hook-with-args 'org-cycle-hook 'contents))
  6195. ((and (eq last-command this-command)
  6196. (eq org-cycle-global-status 'contents))
  6197. ;; We just showed the table of contents - now show everything
  6198. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6199. (outline-show-all)
  6200. (unless ga (org-unlogged-message "SHOW ALL"))
  6201. (setq org-cycle-global-status 'all)
  6202. (run-hook-with-args 'org-cycle-hook 'all))
  6203. (t
  6204. ;; Default action: go to overview
  6205. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6206. (org-overview)
  6207. (unless ga (org-unlogged-message "OVERVIEW"))
  6208. (setq org-cycle-global-status 'overview)
  6209. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6210. (defvar org-called-with-limited-levels nil
  6211. "Non-nil when `org-with-limited-levels' is currently active.")
  6212. (defun org-cycle-internal-local ()
  6213. "Do the local cycling action."
  6214. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6215. ;; First, determine end of headline (EOH), end of subtree or item
  6216. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6217. (save-excursion
  6218. (if (org-at-item-p)
  6219. (progn
  6220. (beginning-of-line)
  6221. (setq struct (org-list-struct))
  6222. (setq eoh (point-at-eol))
  6223. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6224. (setq has-children (org-list-has-child-p (point) struct)))
  6225. (org-back-to-heading)
  6226. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6227. (setq eos (save-excursion (org-end-of-subtree t t)
  6228. (when (bolp) (backward-char)) (point)))
  6229. (setq has-children
  6230. (or (save-excursion
  6231. (let ((level (funcall outline-level)))
  6232. (outline-next-heading)
  6233. (and (org-at-heading-p t)
  6234. (> (funcall outline-level) level))))
  6235. (save-excursion
  6236. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6237. ;; Determine end invisible part of buffer (EOL)
  6238. (beginning-of-line 2)
  6239. (while (and (not (eobp)) ;This is like `next-line'.
  6240. (get-char-property (1- (point)) 'invisible))
  6241. (goto-char (next-single-char-property-change (point) 'invisible))
  6242. (and (eolp) (beginning-of-line 2)))
  6243. (setq eol (point)))
  6244. ;; Find out what to do next and set `this-command'
  6245. (cond
  6246. ((= eos eoh)
  6247. ;; Nothing is hidden behind this heading
  6248. (unless (org-before-first-heading-p)
  6249. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6250. (org-unlogged-message "EMPTY ENTRY")
  6251. (setq org-cycle-subtree-status nil)
  6252. (save-excursion
  6253. (goto-char eos)
  6254. (outline-next-heading)
  6255. (when (outline-invisible-p) (org-flag-heading nil))))
  6256. ((and (or (>= eol eos)
  6257. (not (string-match "\\S-" (buffer-substring eol eos))))
  6258. (or has-children
  6259. (not (setq children-skipped
  6260. org-cycle-skip-children-state-if-no-children))))
  6261. ;; Entire subtree is hidden in one line: children view
  6262. (unless (org-before-first-heading-p)
  6263. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6264. (if (org-at-item-p)
  6265. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6266. (org-show-entry)
  6267. (org-with-limited-levels (org-show-children))
  6268. ;; FIXME: This slows down the func way too much.
  6269. ;; How keep drawers hidden in subtree anyway?
  6270. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6271. ;; (org-cycle-hide-drawers 'subtree))
  6272. ;; Fold every list in subtree to top-level items.
  6273. (when (eq org-cycle-include-plain-lists 'integrate)
  6274. (save-excursion
  6275. (org-back-to-heading)
  6276. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6277. (beginning-of-line 1)
  6278. (let* ((struct (org-list-struct))
  6279. (prevs (org-list-prevs-alist struct))
  6280. (end (org-list-get-bottom-point struct)))
  6281. (dolist (e (org-list-get-all-items (point) struct prevs))
  6282. (org-list-set-item-visibility e struct 'folded))
  6283. (goto-char (if (< end eos) end eos)))))))
  6284. (org-unlogged-message "CHILDREN")
  6285. (save-excursion
  6286. (goto-char eos)
  6287. (outline-next-heading)
  6288. (when (outline-invisible-p) (org-flag-heading nil)))
  6289. (setq org-cycle-subtree-status 'children)
  6290. (unless (org-before-first-heading-p)
  6291. (run-hook-with-args 'org-cycle-hook 'children)))
  6292. ((or children-skipped
  6293. (and (eq last-command this-command)
  6294. (eq org-cycle-subtree-status 'children)))
  6295. ;; We just showed the children, or no children are there,
  6296. ;; now show everything.
  6297. (unless (org-before-first-heading-p)
  6298. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6299. (outline-flag-region eoh eos nil)
  6300. (org-unlogged-message
  6301. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6302. (setq org-cycle-subtree-status 'subtree)
  6303. (unless (org-before-first-heading-p)
  6304. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6305. (t
  6306. ;; Default action: hide the subtree.
  6307. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6308. (outline-flag-region eoh eos t)
  6309. (org-unlogged-message "FOLDED")
  6310. (setq org-cycle-subtree-status 'folded)
  6311. (unless (org-before-first-heading-p)
  6312. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6313. ;;;###autoload
  6314. (defun org-global-cycle (&optional arg)
  6315. "Cycle the global visibility. For details see `org-cycle'.
  6316. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6317. With a numeric prefix, show all headlines up to that level."
  6318. (interactive "P")
  6319. (let ((org-cycle-include-plain-lists
  6320. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6321. (cond
  6322. ((integerp arg)
  6323. (outline-show-all)
  6324. (outline-hide-sublevels arg)
  6325. (setq org-cycle-global-status 'contents))
  6326. ((equal arg '(4))
  6327. (org-set-startup-visibility)
  6328. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6329. (t
  6330. (org-cycle '(4))))))
  6331. (defun org-set-startup-visibility ()
  6332. "Set the visibility required by startup options and properties."
  6333. (cond
  6334. ((eq org-startup-folded t)
  6335. (org-overview))
  6336. ((eq org-startup-folded 'content)
  6337. (org-content))
  6338. ((or (eq org-startup-folded 'showeverything)
  6339. (eq org-startup-folded nil))
  6340. (outline-show-all)))
  6341. (unless (eq org-startup-folded 'showeverything)
  6342. (when org-hide-block-startup (org-hide-block-all))
  6343. (org-set-visibility-according-to-property 'no-cleanup)
  6344. (org-cycle-hide-archived-subtrees 'all)
  6345. (org-cycle-hide-drawers 'all)
  6346. (org-cycle-show-empty-lines t)))
  6347. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6348. "Switch subtree visibilities according to :VISIBILITY: property."
  6349. (interactive)
  6350. (org-with-wide-buffer
  6351. (goto-char (point-min))
  6352. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6353. (if (not (org-at-property-p)) (outline-next-heading)
  6354. (let ((state (match-string 3)))
  6355. (save-excursion
  6356. (org-back-to-heading t)
  6357. (outline-hide-subtree)
  6358. (org-reveal)
  6359. (cond
  6360. ((equal state "folded")
  6361. (outline-hide-subtree))
  6362. ((equal state "children")
  6363. (org-show-hidden-entry)
  6364. (org-show-children))
  6365. ((equal state "content")
  6366. (save-excursion
  6367. (save-restriction
  6368. (org-narrow-to-subtree)
  6369. (org-content))))
  6370. ((member state '("all" "showall"))
  6371. (outline-show-subtree)))))))
  6372. (unless no-cleanup
  6373. (org-cycle-hide-archived-subtrees 'all)
  6374. (org-cycle-hide-drawers 'all)
  6375. (org-cycle-show-empty-lines 'all))))
  6376. ;; This function uses outline-regexp instead of the more fundamental
  6377. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6378. ;; buffers, where outline-regexp is needed.
  6379. (defun org-overview ()
  6380. "Switch to overview mode, showing only top-level headlines.
  6381. This shows all headlines with a level equal or greater than the level
  6382. of the first headline in the buffer. This is important, because if the
  6383. first headline is not level one, then (hide-sublevels 1) gives confusing
  6384. results."
  6385. (interactive)
  6386. (save-excursion
  6387. (let ((level
  6388. (save-excursion
  6389. (goto-char (point-min))
  6390. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6391. (goto-char (match-beginning 0))
  6392. (funcall outline-level)))))
  6393. (and level (outline-hide-sublevels level)))))
  6394. (defun org-content (&optional arg)
  6395. "Show all headlines in the buffer, like a table of contents.
  6396. With numerical argument N, show content up to level N."
  6397. (interactive "P")
  6398. (org-overview)
  6399. (save-excursion
  6400. ;; Visit all headings and show their offspring
  6401. (and (integerp arg) (org-overview))
  6402. (goto-char (point-max))
  6403. (catch 'exit
  6404. (while (and (progn (condition-case nil
  6405. (outline-previous-visible-heading 1)
  6406. (error (goto-char (point-min))))
  6407. t)
  6408. (looking-at org-outline-regexp))
  6409. (if (integerp arg)
  6410. (org-show-children (1- arg))
  6411. (outline-show-branches))
  6412. (when (bobp) (throw 'exit nil))))))
  6413. (defun org-optimize-window-after-visibility-change (state)
  6414. "Adjust the window after a change in outline visibility.
  6415. This function is the default value of the hook `org-cycle-hook'."
  6416. (when (get-buffer-window (current-buffer))
  6417. (cond
  6418. ((eq state 'content) nil)
  6419. ((eq state 'all) nil)
  6420. ((eq state 'folded) nil)
  6421. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6422. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6423. (defun org-remove-empty-overlays-at (pos)
  6424. "Remove outline overlays that do not contain non-white stuff."
  6425. (dolist (o (overlays-at pos))
  6426. (and (eq 'outline (overlay-get o 'invisible))
  6427. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6428. (overlay-end o))))
  6429. (delete-overlay o))))
  6430. (defun org-clean-visibility-after-subtree-move ()
  6431. "Fix visibility issues after moving a subtree."
  6432. ;; First, find a reasonable region to look at:
  6433. ;; Start two siblings above, end three below
  6434. (let* ((beg (save-excursion
  6435. (and (org-get-last-sibling)
  6436. (org-get-last-sibling))
  6437. (point)))
  6438. (end (save-excursion
  6439. (and (org-get-next-sibling)
  6440. (org-get-next-sibling)
  6441. (org-get-next-sibling))
  6442. (if (org-at-heading-p)
  6443. (point-at-eol)
  6444. (point))))
  6445. (level (looking-at "\\*+"))
  6446. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6447. (save-excursion
  6448. (save-restriction
  6449. (narrow-to-region beg end)
  6450. (when re
  6451. ;; Properly fold already folded siblings
  6452. (goto-char (point-min))
  6453. (while (re-search-forward re nil t)
  6454. (when (and (not (outline-invisible-p))
  6455. (save-excursion
  6456. (goto-char (point-at-eol)) (outline-invisible-p)))
  6457. (outline-hide-entry))))
  6458. (org-cycle-show-empty-lines 'overview)
  6459. (org-cycle-hide-drawers 'overview)))))
  6460. (defun org-cycle-show-empty-lines (state)
  6461. "Show empty lines above all visible headlines.
  6462. The region to be covered depends on STATE when called through
  6463. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6464. entire buffer covered. Note that an empty line is only shown if there
  6465. are at least `org-cycle-separator-lines' empty lines before the headline."
  6466. (when (/= org-cycle-separator-lines 0)
  6467. (save-excursion
  6468. (let* ((n (abs org-cycle-separator-lines))
  6469. (re (cond
  6470. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6471. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6472. (t (let ((ns (number-to-string (- n 2))))
  6473. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6474. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6475. beg end)
  6476. (cond
  6477. ((memq state '(overview contents t))
  6478. (setq beg (point-min) end (point-max)))
  6479. ((memq state '(children folded))
  6480. (setq beg (point)
  6481. end (progn (org-end-of-subtree t t)
  6482. (line-beginning-position 2)))))
  6483. (when beg
  6484. (goto-char beg)
  6485. (while (re-search-forward re end t)
  6486. (unless (get-char-property (match-end 1) 'invisible)
  6487. (let ((e (match-end 1))
  6488. (b (if (>= org-cycle-separator-lines 0)
  6489. (match-beginning 1)
  6490. (save-excursion
  6491. (goto-char (match-beginning 0))
  6492. (skip-chars-backward " \t\n")
  6493. (line-end-position)))))
  6494. (outline-flag-region b e nil))))))))
  6495. ;; Never hide empty lines at the end of the file.
  6496. (save-excursion
  6497. (goto-char (point-max))
  6498. (outline-previous-heading)
  6499. (outline-end-of-heading)
  6500. (when (and (looking-at "[ \t\n]+")
  6501. (= (match-end 0) (point-max)))
  6502. (outline-flag-region (point) (match-end 0) nil))))
  6503. (defun org-show-empty-lines-in-parent ()
  6504. "Move to the parent and re-show empty lines before visible headlines."
  6505. (save-excursion
  6506. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6507. (org-cycle-show-empty-lines context))))
  6508. (defun org-files-list ()
  6509. "Return `org-agenda-files' list, plus all open Org files.
  6510. This is useful for operations that need to scan all of a user's
  6511. open and agenda-wise Org files."
  6512. (let ((files (mapcar 'expand-file-name (org-agenda-files))))
  6513. (dolist (buf (buffer-list))
  6514. (with-current-buffer buf
  6515. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6516. (cl-pushnew (expand-file-name (buffer-file-name)) files))))
  6517. files))
  6518. (defsubst org-entry-beginning-position ()
  6519. "Return the beginning position of the current entry."
  6520. (save-excursion (org-back-to-heading t) (point)))
  6521. (defsubst org-entry-end-position ()
  6522. "Return the end position of the current entry."
  6523. (save-excursion (outline-next-heading) (point)))
  6524. (defun org-cycle-hide-drawers (state &optional exceptions)
  6525. "Re-hide all drawers after a visibility state change.
  6526. When non-nil, optional argument EXCEPTIONS is a list of strings
  6527. specifying which drawers should not be hidden."
  6528. (when (and (derived-mode-p 'org-mode)
  6529. (not (memq state '(overview folded contents))))
  6530. (save-excursion
  6531. (let* ((globalp (memq state '(contents all)))
  6532. (beg (if globalp (point-min) (point)))
  6533. (end (if globalp (point-max)
  6534. (if (eq state 'children)
  6535. (save-excursion (outline-next-heading) (point))
  6536. (org-end-of-subtree t)))))
  6537. (goto-char beg)
  6538. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6539. (unless (member-ignore-case (match-string 1) exceptions)
  6540. (let ((drawer (org-element-at-point)))
  6541. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6542. (org-flag-drawer t drawer)
  6543. ;; Make sure to skip drawer entirely or we might flag
  6544. ;; it another time when matching its ending line with
  6545. ;; `org-drawer-regexp'.
  6546. (goto-char (org-element-property :end drawer))))))))))
  6547. (defun org-flag-drawer (flag &optional element)
  6548. "When FLAG is non-nil, hide the drawer we are at.
  6549. Otherwise make it visible. When optional argument ELEMENT is
  6550. a parsed drawer, as returned by `org-element-at-point', hide or
  6551. show that drawer instead."
  6552. (let ((drawer (or element
  6553. (and (save-excursion
  6554. (beginning-of-line)
  6555. (looking-at-p org-drawer-regexp))
  6556. (org-element-at-point)))))
  6557. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6558. (let ((post (org-element-property :post-affiliated drawer)))
  6559. (save-excursion
  6560. (outline-flag-region
  6561. (progn (goto-char post) (line-end-position))
  6562. (progn (goto-char (org-element-property :end drawer))
  6563. (skip-chars-backward " \r\t\n")
  6564. (line-end-position))
  6565. flag))
  6566. ;; When the drawer is hidden away, make sure point lies in
  6567. ;; a visible part of the buffer.
  6568. (when (and flag (> (line-beginning-position) post))
  6569. (goto-char post))))))
  6570. (defun org-subtree-end-visible-p ()
  6571. "Is the end of the current subtree visible?"
  6572. (pos-visible-in-window-p
  6573. (save-excursion (org-end-of-subtree t) (point))))
  6574. (defun org-first-headline-recenter ()
  6575. "Move cursor to the first headline and recenter the headline."
  6576. (let ((window (get-buffer-window)))
  6577. (when window
  6578. (goto-char (point-min))
  6579. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6580. (set-window-start window (line-beginning-position))))))
  6581. ;;; Saving and restoring visibility
  6582. (defun org-outline-overlay-data (&optional use-markers)
  6583. "Return a list of the locations of all outline overlays.
  6584. These are overlays with the `invisible' property value `outline'.
  6585. The return value is a list of cons cells, with start and stop
  6586. positions for each overlay.
  6587. If USE-MARKERS is set, return the positions as markers."
  6588. (let (beg end)
  6589. (org-with-wide-buffer
  6590. (delq nil
  6591. (mapcar (lambda (o)
  6592. (when (eq (overlay-get o 'invisible) 'outline)
  6593. (setq beg (overlay-start o)
  6594. end (overlay-end o))
  6595. (and beg end (> end beg)
  6596. (if use-markers
  6597. (cons (copy-marker beg)
  6598. (copy-marker end t))
  6599. (cons beg end)))))
  6600. (overlays-in (point-min) (point-max)))))))
  6601. (defun org-set-outline-overlay-data (data)
  6602. "Create visibility overlays for all positions in DATA.
  6603. DATA should have been made by `org-outline-overlay-data'."
  6604. (org-with-wide-buffer
  6605. (outline-show-all)
  6606. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6607. ;;; Folding of blocks
  6608. (defvar-local org-hide-block-overlays nil
  6609. "Overlays hiding blocks.")
  6610. (defun org-block-map (function &optional start end)
  6611. "Call FUNCTION at the head of all source blocks in the current buffer.
  6612. Optional arguments START and END can be used to limit the range."
  6613. (let ((start (or start (point-min)))
  6614. (end (or end (point-max))))
  6615. (save-excursion
  6616. (goto-char start)
  6617. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6618. (save-excursion
  6619. (save-match-data
  6620. (goto-char (match-beginning 0))
  6621. (funcall function)))))))
  6622. (defun org-hide-block-toggle-all ()
  6623. "Toggle the visibility of all blocks in the current buffer."
  6624. (org-block-map 'org-hide-block-toggle))
  6625. (defun org-hide-block-all ()
  6626. "Fold all blocks in the current buffer."
  6627. (interactive)
  6628. (org-show-block-all)
  6629. (org-block-map 'org-hide-block-toggle-maybe))
  6630. (defun org-show-block-all ()
  6631. "Unfold all blocks in the current buffer."
  6632. (interactive)
  6633. (mapc #'delete-overlay org-hide-block-overlays)
  6634. (setq org-hide-block-overlays nil))
  6635. (defun org-hide-block-toggle-maybe ()
  6636. "Toggle visibility of block at point.
  6637. Unlike to `org-hide-block-toggle', this function does not throw
  6638. an error. Return a non-nil value when toggling is successful."
  6639. (interactive)
  6640. (ignore-errors (org-hide-block-toggle)))
  6641. (defun org-hide-block-toggle (&optional force)
  6642. "Toggle the visibility of the current block.
  6643. When optional argument FORCE is `off', make block visible. If it
  6644. is non-nil, hide it unconditionally. Throw an error when not at
  6645. a block. Return a non-nil value when toggling is successful."
  6646. (interactive)
  6647. (let ((element (org-element-at-point)))
  6648. (unless (memq (org-element-type element)
  6649. '(center-block comment-block dynamic-block example-block
  6650. export-block quote-block special-block
  6651. src-block verse-block))
  6652. (user-error "Not at a block"))
  6653. (let* ((start (save-excursion
  6654. (goto-char (org-element-property :post-affiliated element))
  6655. (line-end-position)))
  6656. (end (save-excursion
  6657. (goto-char (org-element-property :end element))
  6658. (skip-chars-backward " \r\t\n")
  6659. (line-end-position)))
  6660. (overlays (overlays-at start)))
  6661. (cond
  6662. ;; Do nothing when not before or at the block opening line or
  6663. ;; at the block closing line.
  6664. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6665. ((and (not (eq force 'off))
  6666. (not (memq t (mapcar
  6667. (lambda (o)
  6668. (eq (overlay-get o 'invisible) 'org-hide-block))
  6669. overlays))))
  6670. (let ((ov (make-overlay start end)))
  6671. (overlay-put ov 'invisible 'org-hide-block)
  6672. ;; Make the block accessible to `isearch'.
  6673. (overlay-put
  6674. ov 'isearch-open-invisible
  6675. (lambda (ov)
  6676. (when (memq ov org-hide-block-overlays)
  6677. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6678. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6679. (delete-overlay ov))))
  6680. (push ov org-hide-block-overlays)
  6681. ;; When the block is hidden away, make sure point is left in
  6682. ;; a visible part of the buffer.
  6683. (when (> (line-beginning-position) start)
  6684. (goto-char start)
  6685. (beginning-of-line))
  6686. ;; Signal successful toggling.
  6687. t))
  6688. ((or (not force) (eq force 'off))
  6689. (dolist (ov overlays t)
  6690. (when (memq ov org-hide-block-overlays)
  6691. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6692. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6693. (delete-overlay ov))))))))
  6694. ;; Remove overlays when changing major mode
  6695. (add-hook 'org-mode-hook
  6696. (lambda () (add-hook 'change-major-mode-hook
  6697. 'org-show-block-all 'append 'local)))
  6698. ;;; Org-goto
  6699. (defvar org-goto-window-configuration nil)
  6700. (defvar org-goto-marker nil)
  6701. (defvar org-goto-map)
  6702. (defun org-goto-map ()
  6703. "Set the keymap `org-goto'."
  6704. (setq org-goto-map
  6705. (let ((map (make-sparse-keymap)))
  6706. (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
  6707. mouse-drag-region universal-argument org-occur)))
  6708. (dolist (cmd cmds)
  6709. (substitute-key-definition cmd cmd map global-map)))
  6710. (suppress-keymap map)
  6711. (org-defkey map "\C-m" 'org-goto-ret)
  6712. (org-defkey map [(return)] 'org-goto-ret)
  6713. (org-defkey map [(left)] 'org-goto-left)
  6714. (org-defkey map [(right)] 'org-goto-right)
  6715. (org-defkey map [(control ?g)] 'org-goto-quit)
  6716. (org-defkey map "\C-i" 'org-cycle)
  6717. (org-defkey map [(tab)] 'org-cycle)
  6718. (org-defkey map [(down)] 'outline-next-visible-heading)
  6719. (org-defkey map [(up)] 'outline-previous-visible-heading)
  6720. (if org-goto-auto-isearch
  6721. (if (fboundp 'define-key-after)
  6722. (define-key-after map [t] 'org-goto-local-auto-isearch)
  6723. nil)
  6724. (org-defkey map "q" 'org-goto-quit)
  6725. (org-defkey map "n" 'outline-next-visible-heading)
  6726. (org-defkey map "p" 'outline-previous-visible-heading)
  6727. (org-defkey map "f" 'outline-forward-same-level)
  6728. (org-defkey map "b" 'outline-backward-same-level)
  6729. (org-defkey map "u" 'outline-up-heading))
  6730. (org-defkey map "/" 'org-occur)
  6731. (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
  6732. (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
  6733. (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
  6734. (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
  6735. (org-defkey map "\C-c\C-u" 'outline-up-heading)
  6736. map)))
  6737. (defconst org-goto-help
  6738. "Browse buffer copy, to find location or copy text.%s
  6739. RET=jump to location C-g=quit and return to previous location
  6740. \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
  6741. (defvar org-goto-start-pos) ; dynamically scoped parameter
  6742. (defun org-goto (&optional alternative-interface)
  6743. "Look up a different location in the current file, keeping current visibility.
  6744. When you want look-up or go to a different location in a
  6745. document, the fastest way is often to fold the entire buffer and
  6746. then dive into the tree. This method has the disadvantage, that
  6747. the previous location will be folded, which may not be what you
  6748. want.
  6749. This command works around this by showing a copy of the current
  6750. buffer in an indirect buffer, in overview mode. You can dive
  6751. into the tree in that copy, use org-occur and incremental search
  6752. to find a location. When pressing RET or `Q', the command
  6753. returns to the original buffer in which the visibility is still
  6754. unchanged. After RET it will also jump to the location selected
  6755. in the indirect buffer and expose the headline hierarchy above.
  6756. With a prefix argument, use the alternative interface: e.g., if
  6757. `org-goto-interface' is `outline' use `outline-path-completion'."
  6758. (interactive "P")
  6759. (org-goto-map)
  6760. (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
  6761. (org-refile-use-outline-path t)
  6762. (org-refile-target-verify-function nil)
  6763. (interface
  6764. (if (not alternative-interface)
  6765. org-goto-interface
  6766. (if (eq org-goto-interface 'outline)
  6767. 'outline-path-completion
  6768. 'outline)))
  6769. (org-goto-start-pos (point))
  6770. (selected-point
  6771. (if (eq interface 'outline)
  6772. (car (org-get-location (current-buffer) org-goto-help))
  6773. (let ((pa (org-refile-get-location "Goto")))
  6774. (org-refile-check-position pa)
  6775. (nth 3 pa)))))
  6776. (if selected-point
  6777. (progn
  6778. (org-mark-ring-push org-goto-start-pos)
  6779. (goto-char selected-point)
  6780. (when (or (outline-invisible-p) (org-invisible-p2))
  6781. (org-show-context 'org-goto)))
  6782. (message "Quit"))))
  6783. (defvar org-goto-selected-point nil) ; dynamically scoped parameter
  6784. (defvar org-goto-exit-command nil) ; dynamically scoped parameter
  6785. (defvar org-goto-local-auto-isearch-map) ; defined below
  6786. (defun org-get-location (_buf help)
  6787. "Let the user select a location in current buffer.
  6788. This function uses a recursive edit. It returns the selected position
  6789. or nil."
  6790. (org-no-popups
  6791. (let ((isearch-mode-map org-goto-local-auto-isearch-map)
  6792. (isearch-hide-immediately nil)
  6793. (isearch-search-fun-function
  6794. (lambda () 'org-goto-local-search-headings))
  6795. (org-goto-selected-point org-goto-exit-command))
  6796. (save-excursion
  6797. (save-window-excursion
  6798. (delete-other-windows)
  6799. (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
  6800. (pop-to-buffer-same-window
  6801. (condition-case nil
  6802. (make-indirect-buffer (current-buffer) "*org-goto*")
  6803. (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
  6804. (with-output-to-temp-buffer "*Org Help*"
  6805. (princ (format help (if org-goto-auto-isearch
  6806. " Just type for auto-isearch."
  6807. " n/p/f/b/u to navigate, q to quit."))))
  6808. (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
  6809. (setq buffer-read-only nil)
  6810. (let ((org-startup-truncated t)
  6811. (org-startup-folded nil)
  6812. (org-startup-align-all-tables nil))
  6813. (org-mode)
  6814. (org-overview))
  6815. (setq buffer-read-only t)
  6816. (if (and (boundp 'org-goto-start-pos)
  6817. (integer-or-marker-p org-goto-start-pos))
  6818. (progn (goto-char org-goto-start-pos)
  6819. (when (outline-invisible-p)
  6820. (org-show-set-visibility 'lineage)))
  6821. (goto-char (point-min)))
  6822. (let (org-special-ctrl-a/e) (org-beginning-of-line))
  6823. (message "Select location and press RET")
  6824. (use-local-map org-goto-map)
  6825. (recursive-edit)))
  6826. (kill-buffer "*org-goto*")
  6827. (cons org-goto-selected-point org-goto-exit-command))))
  6828. (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
  6829. (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
  6830. ;; `isearch-other-control-char' was removed in Emacs 24.4.
  6831. (if (fboundp 'isearch-other-control-char)
  6832. (progn
  6833. (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
  6834. (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
  6835. (define-key org-goto-local-auto-isearch-map "\C-i" nil)
  6836. (define-key org-goto-local-auto-isearch-map "\C-m" nil)
  6837. (define-key org-goto-local-auto-isearch-map [return] nil))
  6838. (defun org-goto-local-search-headings (string bound noerror)
  6839. "Search and make sure that any matches are in headlines."
  6840. (catch 'return
  6841. (while (if isearch-forward
  6842. (search-forward string bound noerror)
  6843. (search-backward string bound noerror))
  6844. (when (save-match-data
  6845. (and (save-excursion
  6846. (beginning-of-line)
  6847. (looking-at org-complex-heading-regexp))
  6848. (or (not (match-beginning 5))
  6849. (< (point) (match-beginning 5)))))
  6850. (throw 'return (point))))))
  6851. (defun org-goto-local-auto-isearch ()
  6852. "Start isearch."
  6853. (interactive)
  6854. (goto-char (point-min))
  6855. (let ((keys (this-command-keys)))
  6856. (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
  6857. (isearch-mode t)
  6858. (isearch-process-search-char (string-to-char keys)))))
  6859. (defun org-goto-ret (&optional _arg)
  6860. "Finish `org-goto' by going to the new location."
  6861. (interactive "P")
  6862. (setq org-goto-selected-point (point))
  6863. (setq org-goto-exit-command 'return)
  6864. (throw 'exit nil))
  6865. (defun org-goto-left ()
  6866. "Finish `org-goto' by going to the new location."
  6867. (interactive)
  6868. (if (org-at-heading-p)
  6869. (progn
  6870. (beginning-of-line 1)
  6871. (setq org-goto-selected-point (point)
  6872. org-goto-exit-command 'left)
  6873. (throw 'exit nil))
  6874. (user-error "Not on a heading")))
  6875. (defun org-goto-right ()
  6876. "Finish `org-goto' by going to the new location."
  6877. (interactive)
  6878. (if (org-at-heading-p)
  6879. (progn
  6880. (setq org-goto-selected-point (point)
  6881. org-goto-exit-command 'right)
  6882. (throw 'exit nil))
  6883. (user-error "Not on a heading")))
  6884. (defun org-goto-quit ()
  6885. "Finish `org-goto' without cursor motion."
  6886. (interactive)
  6887. (setq org-goto-selected-point nil)
  6888. (setq org-goto-exit-command 'quit)
  6889. (throw 'exit nil))
  6890. ;;; Indirect buffer display of subtrees
  6891. (defvar org-indirect-dedicated-frame nil
  6892. "This is the frame being used for indirect tree display.")
  6893. (defvar org-last-indirect-buffer nil)
  6894. (defun org-tree-to-indirect-buffer (&optional arg)
  6895. "Create indirect buffer and narrow it to current subtree.
  6896. With a numerical prefix ARG, go up to this level and then take that tree.
  6897. If ARG is negative, go up that many levels.
  6898. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6899. indirect buffer previously made with this command, to avoid proliferation of
  6900. indirect buffers. However, when you call the command with a \
  6901. `\\[universal-argument]' prefix, or
  6902. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6903. so that you can work with several indirect buffers at the same time. If
  6904. `org-indirect-buffer-display' is `dedicated-frame', the \
  6905. `\\[universal-argument]' prefix also
  6906. requests that a new frame be made for the new buffer, so that the dedicated
  6907. frame is not changed."
  6908. (interactive "P")
  6909. (let ((cbuf (current-buffer))
  6910. (cwin (selected-window))
  6911. (pos (point))
  6912. beg end level heading ibuf)
  6913. (save-excursion
  6914. (org-back-to-heading t)
  6915. (when (numberp arg)
  6916. (setq level (org-outline-level))
  6917. (when (< arg 0) (setq arg (+ level arg)))
  6918. (while (> (setq level (org-outline-level)) arg)
  6919. (org-up-heading-safe)))
  6920. (setq beg (point)
  6921. heading (org-get-heading 'no-tags))
  6922. (org-end-of-subtree t t)
  6923. (when (org-at-heading-p) (backward-char 1))
  6924. (setq end (point)))
  6925. (when (and (buffer-live-p org-last-indirect-buffer)
  6926. (not (eq org-indirect-buffer-display 'new-frame))
  6927. (not arg))
  6928. (kill-buffer org-last-indirect-buffer))
  6929. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6930. org-last-indirect-buffer ibuf)
  6931. (cond
  6932. ((or (eq org-indirect-buffer-display 'new-frame)
  6933. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6934. (select-frame (make-frame))
  6935. (delete-other-windows)
  6936. (pop-to-buffer-same-window ibuf)
  6937. (org-set-frame-title heading))
  6938. ((eq org-indirect-buffer-display 'dedicated-frame)
  6939. (raise-frame
  6940. (select-frame (or (and org-indirect-dedicated-frame
  6941. (frame-live-p org-indirect-dedicated-frame)
  6942. org-indirect-dedicated-frame)
  6943. (setq org-indirect-dedicated-frame (make-frame)))))
  6944. (delete-other-windows)
  6945. (pop-to-buffer-same-window ibuf)
  6946. (org-set-frame-title (concat "Indirect: " heading)))
  6947. ((eq org-indirect-buffer-display 'current-window)
  6948. (pop-to-buffer-same-window ibuf))
  6949. ((eq org-indirect-buffer-display 'other-window)
  6950. (pop-to-buffer ibuf))
  6951. (t (error "Invalid value")))
  6952. (narrow-to-region beg end)
  6953. (outline-show-all)
  6954. (goto-char pos)
  6955. (run-hook-with-args 'org-cycle-hook 'all)
  6956. (and (window-live-p cwin) (select-window cwin))))
  6957. (defun org-get-indirect-buffer (&optional buffer heading)
  6958. (setq buffer (or buffer (current-buffer)))
  6959. (let ((n 1) (base (buffer-name buffer)) bname)
  6960. (while (buffer-live-p
  6961. (get-buffer
  6962. (setq bname
  6963. (concat base "-"
  6964. (if heading (concat heading "-" (number-to-string n))
  6965. (number-to-string n))))))
  6966. (setq n (1+ n)))
  6967. (condition-case nil
  6968. (make-indirect-buffer buffer bname 'clone)
  6969. (error (make-indirect-buffer buffer bname)))))
  6970. (defun org-set-frame-title (title)
  6971. "Set the title of the current frame to the string TITLE."
  6972. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6973. ;;;; Structure editing
  6974. ;;; Inserting headlines
  6975. (defun org--line-empty-p (n)
  6976. "Is the Nth next line empty?
  6977. Counts the current line as N = 1 and the previous line as N = 0;
  6978. see `beginning-of-line'."
  6979. (save-excursion
  6980. (and (not (bobp))
  6981. (or (beginning-of-line n) t)
  6982. (save-match-data
  6983. (looking-at "[ \t]*$")))))
  6984. (defun org-previous-line-empty-p ()
  6985. "Is the previous line a blank line?
  6986. When NEXT is non-nil, check the next line instead."
  6987. (org--line-empty-p 0))
  6988. (defun org-next-line-empty-p ()
  6989. "Is the previous line a blank line?
  6990. When NEXT is non-nil, check the next line instead."
  6991. (org--line-empty-p 2))
  6992. (defun org-insert-heading (&optional arg invisible-ok top)
  6993. "Insert a new heading or an item with the same depth at point.
  6994. If point is at the beginning of a heading or a list item, insert
  6995. a new heading or a new item above the current one. When at the
  6996. beginning of a regular line of text, turn it into a heading.
  6997. If point is in the middle of a line, split it and create a new
  6998. headline/item with the text in the current line after point (see
  6999. `org-M-RET-may-split-line' on how to modify this behavior). As
  7000. a special case, on a headline, splitting can only happen on the
  7001. title itself. E.g., this excludes breaking stars or tags.
  7002. With a `\\[universal-argument]' prefix, set \
  7003. `org-insert-heading-respect-content' to
  7004. a non-nil value for the duration of the command. This forces the
  7005. insertion of a heading after the current subtree, independently
  7006. on the location of point.
  7007. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  7008. insert the heading at the end of the tree
  7009. above the current heading. For example, if point is within a
  7010. 2nd-level heading, then it will insert a 2nd-level heading at
  7011. the end of the 1st-level parent subtree.
  7012. When INVISIBLE-OK is set, stop at invisible headlines when going
  7013. back. This is important for non-interactive uses of the
  7014. command.
  7015. When optional argument TOP is non-nil, insert a level 1 heading,
  7016. unconditionally."
  7017. (interactive "P")
  7018. (let ((itemp (and (not top) (org-in-item-p)))
  7019. (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
  7020. (respect-content (or org-insert-heading-respect-content
  7021. (equal arg '(4))))
  7022. (initial-content ""))
  7023. (cond
  7024. ((or (= (buffer-size) 0)
  7025. (and (not (save-excursion
  7026. (and (ignore-errors (org-back-to-heading invisible-ok))
  7027. (org-at-heading-p))))
  7028. (or arg (not itemp))))
  7029. ;; At beginning of buffer or so high up that only a heading
  7030. ;; makes sense.
  7031. (cond ((and (bolp) (not respect-content)) (insert "* "))
  7032. ((not respect-content)
  7033. (unless may-split (end-of-line))
  7034. (insert "\n* "))
  7035. ((re-search-forward org-outline-regexp-bol nil t)
  7036. (beginning-of-line)
  7037. (insert "* \n")
  7038. (backward-char))
  7039. (t (goto-char (point-max))
  7040. (insert "\n* ")))
  7041. (run-hooks 'org-insert-heading-hook))
  7042. ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
  7043. (t
  7044. ;; Maybe move at the end of the subtree
  7045. (when (equal arg '(16))
  7046. (org-up-heading-safe)
  7047. (org-end-of-subtree t))
  7048. ;; Insert a heading
  7049. (save-restriction
  7050. (widen)
  7051. (let* ((level nil)
  7052. (on-heading (org-at-heading-p))
  7053. (empty-line-p (if on-heading
  7054. (org-previous-line-empty-p)
  7055. ;; We will decide later
  7056. nil))
  7057. ;; Get a level string to fall back on.
  7058. (fix-level
  7059. (if (org-before-first-heading-p) "*"
  7060. (save-excursion
  7061. (org-back-to-heading t)
  7062. (when (org-previous-line-empty-p) (setq empty-line-p t))
  7063. (looking-at org-outline-regexp)
  7064. (make-string (1- (length (match-string 0))) ?*))))
  7065. (stars
  7066. (save-excursion
  7067. (condition-case nil
  7068. (if top "* "
  7069. (org-back-to-heading invisible-ok)
  7070. (when (and (not on-heading)
  7071. (featurep 'org-inlinetask)
  7072. (integerp org-inlinetask-min-level)
  7073. (>= (length (match-string 0))
  7074. org-inlinetask-min-level))
  7075. ;; Find a heading level before the inline
  7076. ;; task.
  7077. (while (and (setq level (org-up-heading-safe))
  7078. (>= level org-inlinetask-min-level)))
  7079. (if (org-at-heading-p)
  7080. (org-back-to-heading invisible-ok)
  7081. (error "This should not happen")))
  7082. (unless (and (save-excursion
  7083. (save-match-data
  7084. (org-backward-heading-same-level
  7085. 1 invisible-ok))
  7086. (= (point) (match-beginning 0)))
  7087. (not (org-next-line-empty-p)))
  7088. (setq empty-line-p (or empty-line-p
  7089. (org-previous-line-empty-p))))
  7090. (match-string 0))
  7091. (error (or fix-level "* ")))))
  7092. (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
  7093. (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
  7094. ;; If we insert after content, move there and clean up
  7095. ;; whitespace.
  7096. (when respect-content
  7097. (if (not (org-before-first-heading-p))
  7098. (org-end-of-subtree nil t)
  7099. (re-search-forward org-outline-regexp-bol)
  7100. (beginning-of-line 0))
  7101. (skip-chars-backward " \r\t\n")
  7102. (and (not (looking-back "^\\*+" (line-beginning-position)))
  7103. (looking-at "[ \t]+") (replace-match ""))
  7104. (unless (eobp) (forward-char 1))
  7105. (when (looking-at "^\\*")
  7106. (unless (bobp) (backward-char 1))
  7107. (insert "\n")))
  7108. ;; If we are splitting, grab the text that should be moved
  7109. ;; to the new headline.
  7110. (when may-split
  7111. (if (org-at-heading-p)
  7112. ;; This is a heading: split intelligently (keeping
  7113. ;; tags).
  7114. (let ((pos (point)))
  7115. (beginning-of-line)
  7116. (unless (looking-at org-complex-heading-regexp)
  7117. (error "This should not happen"))
  7118. (when (and (match-beginning 4)
  7119. (> pos (match-beginning 4))
  7120. (< pos (match-end 4)))
  7121. (setq initial-content (buffer-substring pos (match-end 4)))
  7122. (goto-char pos)
  7123. (delete-region (point) (match-end 4))
  7124. (if (looking-at "[ \t]*$")
  7125. (replace-match "")
  7126. (insert (make-string (length initial-content) ?\s)))
  7127. (setq initial-content (org-trim initial-content)))
  7128. (goto-char pos))
  7129. ;; A normal line.
  7130. (setq initial-content
  7131. (org-trim
  7132. (delete-and-extract-region (point) (line-end-position))))))
  7133. ;; If we are at the beginning of the line, insert before it.
  7134. ;; Otherwise, after it.
  7135. (cond
  7136. ((and (bolp) (looking-at "[ \t]*$")))
  7137. ((bolp) (save-excursion (insert "\n")))
  7138. (t (end-of-line)
  7139. (insert "\n")))
  7140. ;; Insert the new heading
  7141. (insert stars)
  7142. (just-one-space)
  7143. (insert initial-content)
  7144. (unless (and blank (org-previous-line-empty-p))
  7145. (org-N-empty-lines-before-current (if blank 1 0)))
  7146. ;; Adjust visibility, which may be messed up if we removed
  7147. ;; blank lines while previous entry was hidden.
  7148. (let ((bol (line-beginning-position)))
  7149. (dolist (o (overlays-at (1- bol)))
  7150. (when (and (eq (overlay-get o 'invisible) 'outline)
  7151. (eq (overlay-end o) bol))
  7152. (move-overlay o (overlay-start o) (1- bol)))))
  7153. (run-hooks 'org-insert-heading-hook)))))))
  7154. (defun org-N-empty-lines-before-current (N)
  7155. "Make the number of empty lines before current exactly N.
  7156. So this will delete or add empty lines."
  7157. (save-excursion
  7158. (beginning-of-line)
  7159. (let ((p (point)))
  7160. (skip-chars-backward " \r\t\n")
  7161. (unless (bolp) (forward-line))
  7162. (delete-region (point) p))
  7163. (when (> N 0) (insert (make-string N ?\n)))))
  7164. (defun org-get-heading (&optional no-tags no-todo)
  7165. "Return the heading of the current entry, without the stars.
  7166. When NO-TAGS is non-nil, don't include tags.
  7167. When NO-TODO is non-nil, don't include TODO keywords."
  7168. (save-excursion
  7169. (org-back-to-heading t)
  7170. (let ((case-fold-search nil))
  7171. (cond
  7172. ((and no-tags no-todo)
  7173. (looking-at org-complex-heading-regexp)
  7174. ;; Return value has to be a string, but match group 4 is
  7175. ;; optional.
  7176. (or (match-string 4) ""))
  7177. (no-tags
  7178. (looking-at (concat org-outline-regexp
  7179. "\\(.*?\\)"
  7180. "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
  7181. (match-string 1))
  7182. (no-todo
  7183. (looking-at org-todo-line-regexp)
  7184. (match-string 3))
  7185. (t (looking-at org-heading-regexp)
  7186. (match-string 2))))))
  7187. (defvar orgstruct-mode) ; defined below
  7188. (defun org-heading-components ()
  7189. "Return the components of the current heading.
  7190. This is a list with the following elements:
  7191. - the level as an integer
  7192. - the reduced level, different if `org-odd-levels-only' is set.
  7193. - the TODO keyword, or nil
  7194. - the priority character, like ?A, or nil if no priority is given
  7195. - the headline text itself, or the tags string if no headline text
  7196. - the tags string, or nil."
  7197. (save-excursion
  7198. (org-back-to-heading t)
  7199. (when (let (case-fold-search)
  7200. (looking-at
  7201. (if orgstruct-mode
  7202. org-heading-regexp
  7203. org-complex-heading-regexp)))
  7204. (if orgstruct-mode
  7205. (list (length (match-string 1))
  7206. (org-reduced-level (length (match-string 1)))
  7207. nil
  7208. nil
  7209. (match-string 2)
  7210. nil)
  7211. (list (length (match-string 1))
  7212. (org-reduced-level (length (match-string 1)))
  7213. (match-string-no-properties 2)
  7214. (and (match-end 3) (aref (match-string 3) 2))
  7215. (match-string-no-properties 4)
  7216. (match-string-no-properties 5))))))
  7217. (defun org-get-entry ()
  7218. "Get the entry text, after heading, entire subtree."
  7219. (save-excursion
  7220. (org-back-to-heading t)
  7221. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  7222. (defun org-edit-headline (&optional heading)
  7223. "Edit the current headline.
  7224. Set it to HEADING when provided."
  7225. (interactive)
  7226. (org-with-wide-buffer
  7227. (org-back-to-heading t)
  7228. (when (looking-at org-complex-heading-regexp)
  7229. (let* ((old (match-string-no-properties 4))
  7230. (new (save-match-data
  7231. (org-trim (or heading (read-string "Edit: " old))))))
  7232. (unless (equal old new)
  7233. (if old (replace-match new t t nil 4)
  7234. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  7235. (insert " " new))
  7236. (org-set-tags nil t)
  7237. (when (looking-at "[ \t]*$") (replace-match "")))))))
  7238. (defun org-insert-heading-after-current ()
  7239. "Insert a new heading with same level as current, after current subtree."
  7240. (interactive)
  7241. (org-back-to-heading)
  7242. (org-insert-heading)
  7243. (org-move-subtree-down)
  7244. (end-of-line 1))
  7245. (defun org-insert-heading-respect-content (&optional invisible-ok)
  7246. "Insert heading with `org-insert-heading-respect-content' set to t."
  7247. (interactive)
  7248. (org-insert-heading '(4) invisible-ok))
  7249. (defun org-insert-todo-heading-respect-content (&optional force-state)
  7250. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  7251. (interactive)
  7252. (org-insert-todo-heading force-state '(4)))
  7253. (defun org-insert-todo-heading (arg &optional force-heading)
  7254. "Insert a new heading with the same level and TODO state as current heading.
  7255. If the heading has no TODO state, or if the state is DONE, use
  7256. the first state (TODO by default). Also with one prefix arg,
  7257. force first state. With two prefix args, force inserting at the
  7258. end of the parent subtree.
  7259. When called at a plain list item, insert a new item with an
  7260. unchecked check box."
  7261. (interactive "P")
  7262. (when (or force-heading (not (org-insert-item 'checkbox)))
  7263. (org-insert-heading (or (and (equal arg '(16)) '(16))
  7264. force-heading))
  7265. (save-excursion
  7266. (org-back-to-heading)
  7267. (outline-previous-heading)
  7268. (looking-at org-todo-line-regexp))
  7269. (let* ((new-mark-x
  7270. (if (or (equal arg '(4))
  7271. (not (match-beginning 2))
  7272. (member (match-string 2) org-done-keywords))
  7273. (car org-todo-keywords-1)
  7274. (match-string 2)))
  7275. (new-mark
  7276. (or
  7277. (run-hook-with-args-until-success
  7278. 'org-todo-get-default-hook new-mark-x nil)
  7279. new-mark-x)))
  7280. (beginning-of-line 1)
  7281. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  7282. (if org-treat-insert-todo-heading-as-state-change
  7283. (org-todo new-mark)
  7284. (insert new-mark " "))))
  7285. (when org-provide-todo-statistics
  7286. (org-update-parent-todo-statistics))))
  7287. (defun org-insert-subheading (arg)
  7288. "Insert a new subheading and demote it.
  7289. Works for outline headings and for plain lists alike."
  7290. (interactive "P")
  7291. (org-insert-heading arg)
  7292. (cond
  7293. ((org-at-heading-p) (org-do-demote))
  7294. ((org-at-item-p) (org-indent-item))))
  7295. (defun org-insert-todo-subheading (arg)
  7296. "Insert a new subheading with TODO keyword or checkbox and demote it.
  7297. Works for outline headings and for plain lists alike."
  7298. (interactive "P")
  7299. (org-insert-todo-heading arg)
  7300. (cond
  7301. ((org-at-heading-p) (org-do-demote))
  7302. ((org-at-item-p) (org-indent-item))))
  7303. ;;; Promotion and Demotion
  7304. (defvar org-after-demote-entry-hook nil
  7305. "Hook run after an entry has been demoted.
  7306. The cursor will be at the beginning of the entry.
  7307. When a subtree is being demoted, the hook will be called for each node.")
  7308. (defvar org-after-promote-entry-hook nil
  7309. "Hook run after an entry has been promoted.
  7310. The cursor will be at the beginning of the entry.
  7311. When a subtree is being promoted, the hook will be called for each node.")
  7312. (defun org-promote-subtree ()
  7313. "Promote the entire subtree.
  7314. See also `org-promote'."
  7315. (interactive)
  7316. (save-excursion
  7317. (org-with-limited-levels (org-map-tree 'org-promote)))
  7318. (org-fix-position-after-promote))
  7319. (defun org-demote-subtree ()
  7320. "Demote the entire subtree.
  7321. See `org-demote' and `org-promote'."
  7322. (interactive)
  7323. (save-excursion
  7324. (org-with-limited-levels (org-map-tree 'org-demote)))
  7325. (org-fix-position-after-promote))
  7326. (defun org-do-promote ()
  7327. "Promote the current heading higher up the tree.
  7328. If the region is active in `transient-mark-mode', promote all
  7329. headings in the region."
  7330. (interactive)
  7331. (save-excursion
  7332. (if (org-region-active-p)
  7333. (org-map-region 'org-promote (region-beginning) (region-end))
  7334. (org-promote)))
  7335. (org-fix-position-after-promote))
  7336. (defun org-do-demote ()
  7337. "Demote the current heading lower down the tree.
  7338. If the region is active in `transient-mark-mode', demote all
  7339. headings in the region."
  7340. (interactive)
  7341. (save-excursion
  7342. (if (org-region-active-p)
  7343. (org-map-region 'org-demote (region-beginning) (region-end))
  7344. (org-demote)))
  7345. (org-fix-position-after-promote))
  7346. (defun org-fix-position-after-promote ()
  7347. "Fix cursor position and indentation after demoting/promoting."
  7348. (let ((pos (point)))
  7349. (when (save-excursion
  7350. (beginning-of-line 1)
  7351. (looking-at org-todo-line-regexp)
  7352. (or (equal pos (match-end 1)) (equal pos (match-end 2))))
  7353. (cond ((eobp) (insert " "))
  7354. ((eolp) (insert " "))
  7355. ((equal (char-after) ?\ ) (forward-char 1))))))
  7356. (defun org-current-level ()
  7357. "Return the level of the current entry, or nil if before the first headline.
  7358. The level is the number of stars at the beginning of the
  7359. headline. Use `org-reduced-level' to remove the effect of
  7360. `org-odd-levels'. Unlike to `org-outline-level', this function
  7361. ignores inlinetasks."
  7362. (let ((level (org-with-limited-levels (org-outline-level))))
  7363. (and (> level 0) level)))
  7364. (defun org-get-previous-line-level ()
  7365. "Return the outline depth of the last headline before the current line.
  7366. Returns 0 for the first headline in the buffer, and nil if before the
  7367. first headline."
  7368. (and (org-current-level)
  7369. (or (and (/= (line-beginning-position) (point-min))
  7370. (save-excursion (beginning-of-line 0) (org-current-level)))
  7371. 0)))
  7372. (defun org-reduced-level (l)
  7373. "Compute the effective level of a heading.
  7374. This takes into account the setting of `org-odd-levels-only'."
  7375. (cond
  7376. ((zerop l) 0)
  7377. (org-odd-levels-only (1+ (floor (/ l 2))))
  7378. (t l)))
  7379. (defun org-level-increment ()
  7380. "Return the number of stars that will be added or removed at a
  7381. time to headlines when structure editing, based on the value of
  7382. `org-odd-levels-only'."
  7383. (if org-odd-levels-only 2 1))
  7384. (defun org-get-valid-level (level &optional change)
  7385. "Rectify a level change under the influence of `org-odd-levels-only'
  7386. LEVEL is a current level, CHANGE is by how much the level should be
  7387. modified. Even if CHANGE is nil, LEVEL may be returned modified because
  7388. even level numbers will become the next higher odd number."
  7389. (if org-odd-levels-only
  7390. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7391. ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
  7392. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7393. (max 1 (+ level (or change 0)))))
  7394. (defun org-promote ()
  7395. "Promote the current heading higher up the tree."
  7396. (org-with-wide-buffer
  7397. (org-back-to-heading t)
  7398. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7399. after-change-functions))
  7400. (level (save-match-data (funcall outline-level)))
  7401. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7402. (diff (abs (- level (length up-head) -1))))
  7403. (cond
  7404. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7405. (replace-match "# " nil t))
  7406. ((= level 1)
  7407. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7408. (t (replace-match up-head nil t)))
  7409. (unless (= level 1)
  7410. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7411. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7412. (run-hooks 'org-after-promote-entry-hook))))
  7413. (defun org-demote ()
  7414. "Demote the current heading lower down the tree."
  7415. (org-with-wide-buffer
  7416. (org-back-to-heading t)
  7417. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7418. after-change-functions))
  7419. (level (save-match-data (funcall outline-level)))
  7420. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7421. (diff (abs (- level (length down-head) -1))))
  7422. (replace-match down-head nil t)
  7423. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7424. (when org-adapt-indentation (org-fixup-indentation diff))
  7425. (run-hooks 'org-after-demote-entry-hook))))
  7426. (defun org-cycle-level ()
  7427. "Cycle the level of an empty headline through possible states.
  7428. This goes first to child, then to parent, level, then up the hierarchy.
  7429. After top level, it switches back to sibling level."
  7430. (interactive)
  7431. (let ((org-adapt-indentation nil))
  7432. (when (org-point-at-end-of-empty-headline)
  7433. (setq this-command 'org-cycle-level) ; Only needed for caching
  7434. (let ((cur-level (org-current-level))
  7435. (prev-level (org-get-previous-line-level)))
  7436. (cond
  7437. ;; If first headline in file, promote to top-level.
  7438. ((= prev-level 0)
  7439. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7440. do (org-do-promote)))
  7441. ;; If same level as prev, demote one.
  7442. ((= prev-level cur-level)
  7443. (org-do-demote))
  7444. ;; If parent is top-level, promote to top level if not already.
  7445. ((= prev-level 1)
  7446. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7447. do (org-do-promote)))
  7448. ;; If top-level, return to prev-level.
  7449. ((= cur-level 1)
  7450. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7451. do (org-do-demote)))
  7452. ;; If less than prev-level, promote one.
  7453. ((< cur-level prev-level)
  7454. (org-do-promote))
  7455. ;; If deeper than prev-level, promote until higher than
  7456. ;; prev-level.
  7457. ((> cur-level prev-level)
  7458. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7459. do (org-do-promote))))
  7460. t))))
  7461. (defun org-map-tree (fun)
  7462. "Call FUN for every heading underneath the current one."
  7463. (org-back-to-heading t)
  7464. (let ((level (funcall outline-level)))
  7465. (save-excursion
  7466. (funcall fun)
  7467. (while (and (progn
  7468. (outline-next-heading)
  7469. (> (funcall outline-level) level))
  7470. (not (eobp)))
  7471. (funcall fun)))))
  7472. (defun org-map-region (fun beg end)
  7473. "Call FUN for every heading between BEG and END."
  7474. (let ((org-ignore-region t))
  7475. (save-excursion
  7476. (setq end (copy-marker end))
  7477. (goto-char beg)
  7478. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7479. (< (point) end))
  7480. (funcall fun))
  7481. (while (and (progn
  7482. (outline-next-heading)
  7483. (< (point) end))
  7484. (not (eobp)))
  7485. (funcall fun)))))
  7486. (defun org-fixup-indentation (diff)
  7487. "Change the indentation in the current entry by DIFF.
  7488. DIFF is an integer. Indentation is done according to the
  7489. following rules:
  7490. - Planning information and property drawers are always indented
  7491. according to the new level of the headline;
  7492. - Footnote definitions and their contents are ignored;
  7493. - Inlinetasks' boundaries are not shifted;
  7494. - Empty lines are ignored;
  7495. - Other lines' indentation are shifted by DIFF columns, unless
  7496. it would introduce a structural change in the document, in
  7497. which case no shifting is done at all.
  7498. Assume point is at a heading or an inlinetask beginning."
  7499. (org-with-wide-buffer
  7500. (narrow-to-region (line-beginning-position)
  7501. (save-excursion
  7502. (if (org-with-limited-levels (org-at-heading-p))
  7503. (org-with-limited-levels (outline-next-heading))
  7504. (org-inlinetask-goto-end))
  7505. (point)))
  7506. (forward-line)
  7507. ;; Indent properly planning info and property drawer.
  7508. (when (looking-at-p org-planning-line-re)
  7509. (org-indent-line)
  7510. (forward-line))
  7511. (when (looking-at org-property-drawer-re)
  7512. (goto-char (match-end 0))
  7513. (forward-line)
  7514. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7515. (catch 'no-shift
  7516. (when (zerop diff) (throw 'no-shift nil))
  7517. ;; If DIFF is negative, first check if a shift is possible at all
  7518. ;; (e.g., it doesn't break structure). This can only happen if
  7519. ;; some contents are not properly indented.
  7520. (let ((case-fold-search t))
  7521. (when (< diff 0)
  7522. (let ((diff (- diff))
  7523. (forbidden-re (concat org-outline-regexp
  7524. "\\|"
  7525. (substring org-footnote-definition-re 1))))
  7526. (save-excursion
  7527. (while (not (eobp))
  7528. (cond
  7529. ((looking-at-p "[ \t]*$") (forward-line))
  7530. ((and (looking-at-p org-footnote-definition-re)
  7531. (let ((e (org-element-at-point)))
  7532. (and (eq (org-element-type e) 'footnote-definition)
  7533. (goto-char (org-element-property :end e))))))
  7534. ((looking-at-p org-outline-regexp) (forward-line))
  7535. ;; Give up if shifting would move before column 0 or
  7536. ;; if it would introduce a headline or a footnote
  7537. ;; definition.
  7538. (t
  7539. (skip-chars-forward " \t")
  7540. (let ((ind (current-column)))
  7541. (when (or (< ind diff)
  7542. (and (= ind diff) (looking-at-p forbidden-re)))
  7543. (throw 'no-shift nil)))
  7544. ;; Ignore contents of example blocks and source
  7545. ;; blocks if their indentation is meant to be
  7546. ;; preserved. Jump to block's closing line.
  7547. (beginning-of-line)
  7548. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7549. (let ((e (org-element-at-point)))
  7550. (and (memq (org-element-type e)
  7551. '(example-block src-block))
  7552. (or org-src-preserve-indentation
  7553. (org-element-property :preserve-indent e))
  7554. (goto-char (org-element-property :end e))
  7555. (progn (skip-chars-backward " \r\t\n")
  7556. (beginning-of-line)
  7557. t))))
  7558. (forward-line))))))))
  7559. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7560. ;; by DIFF. Also skip contents of source or example blocks
  7561. ;; when indentation is meant to be preserved.
  7562. (while (not (eobp))
  7563. (cond
  7564. ((and (looking-at-p org-footnote-definition-re)
  7565. (let ((e (org-element-at-point)))
  7566. (and (eq (org-element-type e) 'footnote-definition)
  7567. (goto-char (org-element-property :end e))))))
  7568. ((looking-at-p org-outline-regexp) (forward-line))
  7569. ((looking-at-p "[ \t]*$") (forward-line))
  7570. (t
  7571. (indent-line-to (+ (org-get-indentation) diff))
  7572. (beginning-of-line)
  7573. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7574. (let ((e (org-element-at-point)))
  7575. (and (memq (org-element-type e)
  7576. '(example-block src-block))
  7577. (or org-src-preserve-indentation
  7578. (org-element-property :preserve-indent e))
  7579. (goto-char (org-element-property :end e))
  7580. (progn (skip-chars-backward " \r\t\n")
  7581. (beginning-of-line)
  7582. t))))
  7583. (forward-line)))))))))
  7584. (defun org-convert-to-odd-levels ()
  7585. "Convert an Org file with all levels allowed to one with odd levels.
  7586. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7587. level 5 etc."
  7588. (interactive)
  7589. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7590. (let ((outline-level 'org-outline-level)
  7591. (org-odd-levels-only nil) n)
  7592. (save-excursion
  7593. (goto-char (point-min))
  7594. (while (re-search-forward "^\\*\\*+ " nil t)
  7595. (setq n (- (length (match-string 0)) 2))
  7596. (while (>= (setq n (1- n)) 0)
  7597. (org-demote))
  7598. (end-of-line 1))))))
  7599. (defun org-convert-to-oddeven-levels ()
  7600. "Convert an Org file with only odd levels to one with odd/even levels.
  7601. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7602. file contains a section with an even level, conversion would
  7603. destroy the structure of the file. An error is signaled in this
  7604. case."
  7605. (interactive)
  7606. (goto-char (point-min))
  7607. ;; First check if there are no even levels
  7608. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7609. (org-show-set-visibility 'canonical)
  7610. (error "Not all levels are odd in this file. Conversion not possible"))
  7611. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7612. (let ((outline-regexp org-outline-regexp)
  7613. (outline-level 'org-outline-level)
  7614. (org-odd-levels-only nil) n)
  7615. (save-excursion
  7616. (goto-char (point-min))
  7617. (while (re-search-forward "^\\*\\*+ " nil t)
  7618. (setq n (/ (1- (length (match-string 0))) 2))
  7619. (while (>= (setq n (1- n)) 0)
  7620. (org-promote))
  7621. (end-of-line 1))))))
  7622. (defun org-tr-level (n)
  7623. "Make N odd if required."
  7624. (if org-odd-levels-only (1+ (/ n 2)) n))
  7625. ;;; Vertical tree motion, cutting and pasting of subtrees
  7626. (defun org-move-subtree-up (&optional arg)
  7627. "Move the current subtree up past ARG headlines of the same level."
  7628. (interactive "p")
  7629. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7630. (defun org-move-subtree-down (&optional arg)
  7631. "Move the current subtree down past ARG headlines of the same level."
  7632. (interactive "p")
  7633. (setq arg (prefix-numeric-value arg))
  7634. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7635. 'org-get-last-sibling))
  7636. (ins-point (make-marker))
  7637. (cnt (abs arg))
  7638. (col (current-column))
  7639. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7640. ;; Select the tree
  7641. (org-back-to-heading)
  7642. (setq beg0 (point))
  7643. (save-excursion
  7644. (setq ne-beg (org-back-over-empty-lines))
  7645. (setq beg (point)))
  7646. (save-match-data
  7647. (save-excursion (outline-end-of-heading)
  7648. (setq folded (outline-invisible-p)))
  7649. (progn (org-end-of-subtree nil t)
  7650. (unless (eobp) (backward-char))))
  7651. (outline-next-heading)
  7652. (setq ne-end (org-back-over-empty-lines))
  7653. (setq end (point))
  7654. (goto-char beg0)
  7655. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7656. ;; include less whitespace
  7657. (save-excursion
  7658. (goto-char beg)
  7659. (forward-line (- ne-beg ne-end))
  7660. (setq beg (point))))
  7661. ;; Find insertion point, with error handling
  7662. (while (> cnt 0)
  7663. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7664. (progn (goto-char beg0)
  7665. (user-error "Cannot move past superior level or buffer limit")))
  7666. (setq cnt (1- cnt)))
  7667. (when (> arg 0)
  7668. ;; Moving forward - still need to move over subtree
  7669. (org-end-of-subtree t t)
  7670. (save-excursion
  7671. (org-back-over-empty-lines)
  7672. (or (bolp) (newline))))
  7673. (setq ne-ins (org-back-over-empty-lines))
  7674. (move-marker ins-point (point))
  7675. (setq txt (buffer-substring beg end))
  7676. (org-save-markers-in-region beg end)
  7677. (delete-region beg end)
  7678. (org-remove-empty-overlays-at beg)
  7679. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7680. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7681. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7682. (let ((bbb (point)))
  7683. (insert-before-markers txt)
  7684. (org-reinstall-markers-in-region bbb)
  7685. (move-marker ins-point bbb))
  7686. (or (bolp) (insert "\n"))
  7687. (setq ins-end (point))
  7688. (goto-char ins-point)
  7689. (org-skip-whitespace)
  7690. (when (and (< arg 0)
  7691. (org-first-sibling-p)
  7692. (> ne-ins ne-beg))
  7693. ;; Move whitespace back to beginning
  7694. (save-excursion
  7695. (goto-char ins-end)
  7696. (let ((kill-whole-line t))
  7697. (kill-line (- ne-ins ne-beg)) (point)))
  7698. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7699. (move-marker ins-point nil)
  7700. (if folded
  7701. (outline-hide-subtree)
  7702. (org-show-entry)
  7703. (org-show-children)
  7704. (org-cycle-hide-drawers 'children))
  7705. (org-clean-visibility-after-subtree-move)
  7706. ;; move back to the initial column we were at
  7707. (move-to-column col)))
  7708. (defvar org-subtree-clip ""
  7709. "Clipboard for cut and paste of subtrees.
  7710. This is actually only a copy of the kill, because we use the normal kill
  7711. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7712. (defvar org-subtree-clip-folded nil
  7713. "Was the last copied subtree folded?
  7714. This is used to fold the tree back after pasting.")
  7715. (defun org-cut-subtree (&optional n)
  7716. "Cut the current subtree into the clipboard.
  7717. With prefix arg N, cut this many sequential subtrees.
  7718. This is a short-hand for marking the subtree and then cutting it."
  7719. (interactive "p")
  7720. (org-copy-subtree n 'cut))
  7721. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7722. "Copy the current subtree it in the clipboard.
  7723. With prefix arg N, copy this many sequential subtrees.
  7724. This is a short-hand for marking the subtree and then copying it.
  7725. If CUT is non-nil, actually cut the subtree.
  7726. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7727. of some markers in the region, even if CUT is non-nil. This is
  7728. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7729. (interactive "p")
  7730. (let (beg end folded (beg0 (point)))
  7731. (if (called-interactively-p 'any)
  7732. (org-back-to-heading nil) ; take what looks like a subtree
  7733. (org-back-to-heading t)) ; take what is really there
  7734. (setq beg (point))
  7735. (skip-chars-forward " \t\r\n")
  7736. (save-match-data
  7737. (if nosubtrees
  7738. (outline-next-heading)
  7739. (save-excursion (outline-end-of-heading)
  7740. (setq folded (outline-invisible-p)))
  7741. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7742. (org-end-of-subtree t t)))
  7743. ;; Include the end of an inlinetask
  7744. (when (and (featurep 'org-inlinetask)
  7745. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7746. "END[ \t]*$")))
  7747. (end-of-line))
  7748. (setq end (point))
  7749. (goto-char beg0)
  7750. (when (> end beg)
  7751. (setq org-subtree-clip-folded folded)
  7752. (when (or cut force-store-markers)
  7753. (org-save-markers-in-region beg end))
  7754. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7755. (setq org-subtree-clip (current-kill 0))
  7756. (message "%s: Subtree(s) with %d characters"
  7757. (if cut "Cut" "Copied")
  7758. (length org-subtree-clip)))))
  7759. (defun org-paste-subtree (&optional level tree for-yank remove)
  7760. "Paste the clipboard as a subtree, with modification of headline level.
  7761. The entire subtree is promoted or demoted in order to match a new headline
  7762. level.
  7763. If the cursor is at the beginning of a headline, the same level as
  7764. that headline is used to paste the tree.
  7765. If not, the new level is derived from the *visible* headings
  7766. before and after the insertion point, and taken to be the inferior headline
  7767. level of the two. So if the previous visible heading is level 3 and the
  7768. next is level 4 (or vice versa), level 4 will be used for insertion.
  7769. This makes sure that the subtree remains an independent subtree and does
  7770. not swallow low level entries.
  7771. You can also force a different level, either by using a numeric prefix
  7772. argument, or by inserting the heading marker by hand. For example, if the
  7773. cursor is after \"*****\", then the tree will be shifted to level 5.
  7774. If optional TREE is given, use this text instead of the kill ring.
  7775. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7776. move back over whitespace before inserting, and move point to the end of
  7777. the inserted text when done.
  7778. When REMOVE is non-nil, remove the subtree from the clipboard."
  7779. (interactive "P")
  7780. (setq tree (or tree (and kill-ring (current-kill 0))))
  7781. (unless (org-kill-is-subtree-p tree)
  7782. (user-error "%s"
  7783. (substitute-command-keys
  7784. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7785. (org-with-limited-levels
  7786. (let* ((visp (not (outline-invisible-p)))
  7787. (txt tree)
  7788. (^re_ "\\(\\*+\\)[ \t]*")
  7789. (old-level (if (string-match org-outline-regexp-bol txt)
  7790. (- (match-end 0) (match-beginning 0) 1)
  7791. -1))
  7792. (force-level (cond (level (prefix-numeric-value level))
  7793. ((and (looking-at "[ \t]*$")
  7794. (string-match
  7795. "^\\*+$" (buffer-substring
  7796. (point-at-bol) (point))))
  7797. (- (match-end 0) (match-beginning 0)))
  7798. ((and (bolp)
  7799. (looking-at org-outline-regexp))
  7800. (- (match-end 0) (point) 1))))
  7801. (previous-level (save-excursion
  7802. (condition-case nil
  7803. (progn
  7804. (outline-previous-visible-heading 1)
  7805. (if (looking-at ^re_)
  7806. (- (match-end 0) (match-beginning 0) 1)
  7807. 1))
  7808. (error 1))))
  7809. (next-level (save-excursion
  7810. (condition-case nil
  7811. (progn
  7812. (or (looking-at org-outline-regexp)
  7813. (outline-next-visible-heading 1))
  7814. (if (looking-at ^re_)
  7815. (- (match-end 0) (match-beginning 0) 1)
  7816. 1))
  7817. (error 1))))
  7818. (new-level (or force-level (max previous-level next-level)))
  7819. (shift (if (or (= old-level -1)
  7820. (= new-level -1)
  7821. (= old-level new-level))
  7822. 0
  7823. (- new-level old-level)))
  7824. (delta (if (> shift 0) -1 1))
  7825. (func (if (> shift 0) 'org-demote 'org-promote))
  7826. (org-odd-levels-only nil)
  7827. beg end newend)
  7828. ;; Remove the forced level indicator
  7829. (when force-level
  7830. (delete-region (point-at-bol) (point)))
  7831. ;; Paste
  7832. (beginning-of-line (if (bolp) 1 2))
  7833. (setq beg (point))
  7834. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7835. (insert-before-markers txt)
  7836. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7837. (setq newend (point))
  7838. (org-reinstall-markers-in-region beg)
  7839. (setq end (point))
  7840. (goto-char beg)
  7841. (skip-chars-forward " \t\n\r")
  7842. (setq beg (point))
  7843. (when (and (outline-invisible-p) visp)
  7844. (save-excursion (outline-show-heading)))
  7845. ;; Shift if necessary
  7846. (unless (= shift 0)
  7847. (save-restriction
  7848. (narrow-to-region beg end)
  7849. (while (not (= shift 0))
  7850. (org-map-region func (point-min) (point-max))
  7851. (setq shift (+ delta shift)))
  7852. (goto-char (point-min))
  7853. (setq newend (point-max))))
  7854. (when (or (called-interactively-p 'interactive) for-yank)
  7855. (message "Clipboard pasted as level %d subtree" new-level))
  7856. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7857. kill-ring
  7858. (eq org-subtree-clip (current-kill 0))
  7859. org-subtree-clip-folded)
  7860. ;; The tree was folded before it was killed/copied
  7861. (outline-hide-subtree))
  7862. (and for-yank (goto-char newend))
  7863. (and remove (setq kill-ring (cdr kill-ring))))))
  7864. (defun org-kill-is-subtree-p (&optional txt)
  7865. "Check if the current kill is an outline subtree, or a set of trees.
  7866. Returns nil if kill does not start with a headline, or if the first
  7867. headline level is not the largest headline level in the tree.
  7868. So this will actually accept several entries of equal levels as well,
  7869. which is OK for `org-paste-subtree'.
  7870. If optional TXT is given, check this string instead of the current kill."
  7871. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7872. (re (org-get-limited-outline-regexp))
  7873. (^re (concat "^" re))
  7874. (start-level (and kill
  7875. (string-match
  7876. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7877. kill)
  7878. (- (match-end 2) (match-beginning 2) 1)))
  7879. (start (1+ (or (match-beginning 2) -1))))
  7880. (if (not start-level)
  7881. (progn
  7882. nil) ;; does not even start with a heading
  7883. (catch 'exit
  7884. (while (setq start (string-match ^re kill (1+ start)))
  7885. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7886. (throw 'exit nil)))
  7887. t))))
  7888. (defvar org-markers-to-move nil
  7889. "Markers that should be moved with a cut-and-paste operation.
  7890. Those markers are stored together with their positions relative to
  7891. the start of the region.")
  7892. (defun org-save-markers-in-region (beg end)
  7893. "Check markers in region.
  7894. If these markers are between BEG and END, record their position relative
  7895. to BEG, so that after moving the block of text, we can put the markers back
  7896. into place.
  7897. This function gets called just before an entry or tree gets cut from the
  7898. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7899. called immediately, to move the markers with the entries."
  7900. (setq org-markers-to-move nil)
  7901. (when (featurep 'org-clock)
  7902. (org-clock-save-markers-for-cut-and-paste beg end))
  7903. (when (featurep 'org-agenda)
  7904. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7905. (defun org-check-and-save-marker (marker beg end)
  7906. "Check if MARKER is between BEG and END.
  7907. If yes, remember the marker and the distance to BEG."
  7908. (when (and (marker-buffer marker)
  7909. (equal (marker-buffer marker) (current-buffer))
  7910. (>= marker beg) (< marker end))
  7911. (push (cons marker (- marker beg)) org-markers-to-move)))
  7912. (defun org-reinstall-markers-in-region (beg)
  7913. "Move all remembered markers to their position relative to BEG."
  7914. (dolist (x org-markers-to-move)
  7915. (move-marker (car x) (+ beg (cdr x))))
  7916. (setq org-markers-to-move nil))
  7917. (defun org-narrow-to-subtree ()
  7918. "Narrow buffer to the current subtree."
  7919. (interactive)
  7920. (save-excursion
  7921. (save-match-data
  7922. (org-with-limited-levels
  7923. (narrow-to-region
  7924. (progn (org-back-to-heading t) (point))
  7925. (progn (org-end-of-subtree t t)
  7926. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7927. (point)))))))
  7928. (defun org-narrow-to-block ()
  7929. "Narrow buffer to the current block."
  7930. (interactive)
  7931. (let* ((case-fold-search t)
  7932. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7933. "^[ \t]*#\\+end_.*")))
  7934. (if blockp
  7935. (narrow-to-region (car blockp) (cdr blockp))
  7936. (user-error "Not in a block"))))
  7937. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7938. "Clone the task (subtree) at point N times.
  7939. The clones will be inserted as siblings.
  7940. In interactive use, the user will be prompted for the number of
  7941. clones to be produced. If the entry has a timestamp, the user
  7942. will also be prompted for a time shift, which may be a repeater
  7943. as used in time stamps, for example `+3d'. To disable this,
  7944. you can call the function with a universal prefix argument.
  7945. When a valid repeater is given and the entry contains any time
  7946. stamps, the clones will become a sequence in time, with time
  7947. stamps in the subtree shifted for each clone produced. If SHIFT
  7948. is nil or the empty string, time stamps will be left alone. The
  7949. ID property of the original subtree is removed.
  7950. In each clone, all the CLOCK entries will be removed. This
  7951. prevents Org from considering that the clocked times overlap.
  7952. If the original subtree did contain time stamps with a repeater,
  7953. the following will happen:
  7954. - the repeater will be removed in each clone
  7955. - an additional clone will be produced, with the current, unshifted
  7956. date(s) in the entry.
  7957. - the original entry will be placed *after* all the clones, with
  7958. repeater intact.
  7959. - the start days in the repeater in the original entry will be shifted
  7960. to past the last clone.
  7961. In this way you can spell out a number of instances of a repeating task,
  7962. and still retain the repeater to cover future instances of the task.
  7963. As described above, N+1 clones are produced when the original
  7964. subtree has a repeater. Setting N to 0, then, can be used to
  7965. remove the repeater from a subtree and create a shifted clone
  7966. with the original repeater."
  7967. (interactive "nNumber of clones to produce: ")
  7968. (let ((shift
  7969. (or shift
  7970. (if (and (not (equal current-prefix-arg '(4)))
  7971. (save-excursion
  7972. (re-search-forward org-ts-regexp-both
  7973. (save-excursion
  7974. (org-end-of-subtree t)
  7975. (point)) t)))
  7976. (read-from-minibuffer
  7977. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7978. ""))) ;; No time shift
  7979. (n-no-remove -1)
  7980. (drawer-re org-drawer-regexp)
  7981. (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
  7982. beg end template task idprop
  7983. shift-n shift-what doshift nmin nmax)
  7984. (unless (wholenump n)
  7985. (user-error "Invalid number of replications %s" n))
  7986. (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
  7987. (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  7988. shift)))
  7989. (user-error "Invalid shift specification %s" shift))
  7990. (when doshift
  7991. (setq shift-n (string-to-number (match-string 1 shift))
  7992. shift-what (cdr (assoc (match-string 2 shift)
  7993. '(("d" . day) ("w" . week)
  7994. ("m" . month) ("y" . year))))))
  7995. (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
  7996. (setq nmin 1 nmax n)
  7997. (org-back-to-heading t)
  7998. (setq beg (point))
  7999. (setq idprop (org-entry-get nil "ID"))
  8000. (org-end-of-subtree t t)
  8001. (or (bolp) (insert "\n"))
  8002. (setq end (point))
  8003. (setq template (buffer-substring beg end))
  8004. (when (and doshift
  8005. (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
  8006. (delete-region beg end)
  8007. (setq end beg)
  8008. (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
  8009. (goto-char end)
  8010. (cl-loop for n from nmin to nmax do
  8011. ;; prepare clone
  8012. (with-temp-buffer
  8013. (insert template)
  8014. (org-mode)
  8015. (goto-char (point-min))
  8016. (org-show-subtree)
  8017. (and idprop (if org-clone-delete-id
  8018. (org-entry-delete nil "ID")
  8019. (org-id-get-create t)))
  8020. (unless (= n 0)
  8021. (while (re-search-forward org-clock-re nil t)
  8022. (kill-whole-line))
  8023. (goto-char (point-min))
  8024. (while (re-search-forward drawer-re nil t)
  8025. (org-remove-empty-drawer-at (point))))
  8026. (goto-char (point-min))
  8027. (when doshift
  8028. (while (re-search-forward org-ts-regexp-both nil t)
  8029. (org-timestamp-change (* n shift-n) shift-what))
  8030. (unless (= n n-no-remove)
  8031. (goto-char (point-min))
  8032. (while (re-search-forward org-ts-regexp nil t)
  8033. (save-excursion
  8034. (goto-char (match-beginning 0))
  8035. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  8036. (delete-region (match-beginning 1) (match-end 1)))))))
  8037. (setq task (buffer-string)))
  8038. (insert task))
  8039. (goto-char beg)))
  8040. ;;; Outline Sorting
  8041. (defun org-sort (with-case)
  8042. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  8043. Optional argument WITH-CASE means sort case-sensitively."
  8044. (interactive "P")
  8045. (cond
  8046. ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
  8047. ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
  8048. (t
  8049. (org-call-with-arg 'org-sort-entries with-case))))
  8050. (defun org-sort-remove-invisible (s)
  8051. "Remove invisible links from string S."
  8052. (remove-text-properties 0 (length s) org-rm-props s)
  8053. (while (string-match org-bracket-link-regexp s)
  8054. (setq s (replace-match (if (match-end 2)
  8055. (match-string 3 s)
  8056. (match-string 1 s))
  8057. t t s)))
  8058. (let ((st (format " %s " s)))
  8059. (while (string-match org-emph-re st)
  8060. (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
  8061. (setq s (substring st 1 -1)))
  8062. s)
  8063. (defvar org-priority-regexp) ; defined later in the file
  8064. (defvar org-after-sorting-entries-or-items-hook nil
  8065. "Hook that is run after a bunch of entries or items have been sorted.
  8066. When children are sorted, the cursor is in the parent line when this
  8067. hook gets called. When a region or a plain list is sorted, the cursor
  8068. will be in the first entry of the sorted region/list.")
  8069. (defun org-sort-entries
  8070. (&optional with-case sorting-type getkey-func compare-func property)
  8071. "Sort entries on a certain level of an outline tree.
  8072. If there is an active region, the entries in the region are sorted.
  8073. Else, if the cursor is before the first entry, sort the top-level items.
  8074. Else, the children of the entry at point are sorted.
  8075. Sorting can be alphabetically, numerically, by date/time as given by
  8076. a time stamp, by a property, by priority order, or by a custom function.
  8077. The command prompts for the sorting type unless it has been given to the
  8078. function through the SORTING-TYPE argument, which needs to be a character,
  8079. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  8080. the precise meaning of each character:
  8081. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  8082. c By creation time, which is assumed to be the first inactive time stamp
  8083. at the beginning of a line.
  8084. d By deadline date/time.
  8085. k By clocking time.
  8086. n Numerically, by converting the beginning of the entry/item to a number.
  8087. o By order of TODO keywords.
  8088. p By priority according to the cookie.
  8089. r By the value of a property.
  8090. s By scheduled date/time.
  8091. t By date/time, either the first active time stamp in the entry, or, if
  8092. none exist, by the first inactive one.
  8093. Capital letters will reverse the sort order.
  8094. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  8095. called with point at the beginning of the record. It must return either
  8096. a string or a number that should serve as the sorting key for that record.
  8097. Comparing entries ignores case by default. However, with an optional argument
  8098. WITH-CASE, the sorting considers case as well.
  8099. Sorting is done against the visible part of the headlines, it ignores hidden
  8100. links.
  8101. When sorting is done, call `org-after-sorting-entries-or-items-hook'."
  8102. (interactive "P")
  8103. (let ((case-func (if with-case 'identity 'downcase))
  8104. (cmstr
  8105. ;; The clock marker is lost when using `sort-subr', let's
  8106. ;; store the clocking string.
  8107. (when (equal (marker-buffer org-clock-marker) (current-buffer))
  8108. (save-excursion
  8109. (goto-char org-clock-marker)
  8110. (buffer-substring-no-properties (line-beginning-position)
  8111. (point)))))
  8112. start beg end stars re re2
  8113. txt what tmp)
  8114. ;; Find beginning and end of region to sort
  8115. (cond
  8116. ((org-region-active-p)
  8117. ;; we will sort the region
  8118. (setq end (region-end)
  8119. what "region")
  8120. (goto-char (region-beginning))
  8121. (unless (org-at-heading-p) (outline-next-heading))
  8122. (setq start (point)))
  8123. ((or (org-at-heading-p)
  8124. (ignore-errors (progn (org-back-to-heading) t)))
  8125. ;; we will sort the children of the current headline
  8126. (org-back-to-heading)
  8127. (setq start (point)
  8128. end (progn (org-end-of-subtree t t)
  8129. (or (bolp) (insert "\n"))
  8130. (when (>= (org-back-over-empty-lines) 1)
  8131. (forward-line 1))
  8132. (point))
  8133. what "children")
  8134. (goto-char start)
  8135. (outline-show-subtree)
  8136. (outline-next-heading))
  8137. (t
  8138. ;; we will sort the top-level entries in this file
  8139. (goto-char (point-min))
  8140. (or (org-at-heading-p) (outline-next-heading))
  8141. (setq start (point))
  8142. (goto-char (point-max))
  8143. (beginning-of-line 1)
  8144. (when (looking-at ".*?\\S-")
  8145. ;; File ends in a non-white line
  8146. (end-of-line 1)
  8147. (insert "\n"))
  8148. (setq end (point-max))
  8149. (setq what "top-level")
  8150. (goto-char start)
  8151. (outline-show-all)))
  8152. (setq beg (point))
  8153. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  8154. (looking-at "\\(\\*+\\)")
  8155. (setq stars (match-string 1)
  8156. re (concat "^" (regexp-quote stars) " +")
  8157. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  8158. txt (buffer-substring beg end))
  8159. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  8160. (when (and (not (equal stars "*")) (string-match re2 txt))
  8161. (user-error "Region to sort contains a level above the first entry"))
  8162. (unless sorting-type
  8163. (message
  8164. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  8165. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  8166. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  8167. what)
  8168. (setq sorting-type (read-char-exclusive))
  8169. (unless getkey-func
  8170. (and (= (downcase sorting-type) ?f)
  8171. (setq getkey-func
  8172. (completing-read "Sort using function: "
  8173. obarray 'fboundp t nil nil))
  8174. (setq getkey-func (intern getkey-func))))
  8175. (and (= (downcase sorting-type) ?r)
  8176. (not property)
  8177. (setq property
  8178. (completing-read "Property: "
  8179. (mapcar #'list (org-buffer-property-keys t))
  8180. nil t))))
  8181. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  8182. (message "Sorting entries...")
  8183. (save-restriction
  8184. (narrow-to-region start end)
  8185. (let ((dcst (downcase sorting-type))
  8186. (case-fold-search nil)
  8187. (now (current-time)))
  8188. (sort-subr
  8189. (/= dcst sorting-type)
  8190. ;; This function moves to the beginning character of the "record" to
  8191. ;; be sorted.
  8192. (lambda nil
  8193. (if (re-search-forward re nil t)
  8194. (goto-char (match-beginning 0))
  8195. (goto-char (point-max))))
  8196. ;; This function moves to the last character of the "record" being
  8197. ;; sorted.
  8198. (lambda nil
  8199. (save-match-data
  8200. (condition-case nil
  8201. (outline-forward-same-level 1)
  8202. (error
  8203. (goto-char (point-max))))))
  8204. ;; This function returns the value that gets sorted against.
  8205. (lambda nil
  8206. (cond
  8207. ((= dcst ?n)
  8208. (if (looking-at org-complex-heading-regexp)
  8209. (string-to-number (org-sort-remove-invisible (match-string 4)))
  8210. nil))
  8211. ((= dcst ?a)
  8212. (if (looking-at org-complex-heading-regexp)
  8213. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  8214. nil))
  8215. ((= dcst ?k)
  8216. (or (get-text-property (point) :org-clock-minutes) 0))
  8217. ((= dcst ?t)
  8218. (let ((end (save-excursion (outline-next-heading) (point))))
  8219. (if (or (re-search-forward org-ts-regexp end t)
  8220. (re-search-forward org-ts-regexp-both end t))
  8221. (org-time-string-to-seconds (match-string 0))
  8222. (float-time now))))
  8223. ((= dcst ?c)
  8224. (let ((end (save-excursion (outline-next-heading) (point))))
  8225. (if (re-search-forward
  8226. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  8227. end t)
  8228. (org-time-string-to-seconds (match-string 0))
  8229. (float-time now))))
  8230. ((= dcst ?s)
  8231. (let ((end (save-excursion (outline-next-heading) (point))))
  8232. (if (re-search-forward org-scheduled-time-regexp end t)
  8233. (org-time-string-to-seconds (match-string 1))
  8234. (float-time now))))
  8235. ((= dcst ?d)
  8236. (let ((end (save-excursion (outline-next-heading) (point))))
  8237. (if (re-search-forward org-deadline-time-regexp end t)
  8238. (org-time-string-to-seconds (match-string 1))
  8239. (float-time now))))
  8240. ((= dcst ?p)
  8241. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  8242. (string-to-char (match-string 2))
  8243. org-default-priority))
  8244. ((= dcst ?r)
  8245. (or (org-entry-get nil property) ""))
  8246. ((= dcst ?o)
  8247. (when (looking-at org-complex-heading-regexp)
  8248. (let* ((m (match-string 2))
  8249. (s (if (member m org-done-keywords) '- '+)))
  8250. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  8251. ((= dcst ?f)
  8252. (if getkey-func
  8253. (progn
  8254. (setq tmp (funcall getkey-func))
  8255. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  8256. tmp)
  8257. (error "Invalid key function `%s'" getkey-func)))
  8258. (t (error "Invalid sorting type `%c'" sorting-type))))
  8259. nil
  8260. (cond
  8261. ((= dcst ?a) 'string<)
  8262. ((= dcst ?f) compare-func)
  8263. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
  8264. (run-hooks 'org-after-sorting-entries-or-items-hook)
  8265. ;; Reset the clock marker if needed
  8266. (when cmstr
  8267. (save-excursion
  8268. (goto-char start)
  8269. (search-forward cmstr nil t)
  8270. (move-marker org-clock-marker (point))))
  8271. (message "Sorting entries...done")))
  8272. ;;; The orgstruct minor mode
  8273. ;; Define a minor mode which can be used in other modes in order to
  8274. ;; integrate the Org mode structure editing commands.
  8275. ;; This is really a hack, because the Org mode structure commands use
  8276. ;; keys which normally belong to the major mode. Here is how it
  8277. ;; works: The minor mode defines all the keys necessary to operate the
  8278. ;; structure commands, but wraps the commands into a function which
  8279. ;; tests if the cursor is currently at a headline or a plain list
  8280. ;; item. If that is the case, the structure command is used,
  8281. ;; temporarily setting many Org mode variables like regular
  8282. ;; expressions for filling etc. However, when any of those keys is
  8283. ;; used at a different location, function uses `key-binding' to look
  8284. ;; up if the key has an associated command in another currently active
  8285. ;; keymap (minor modes, major mode, global), and executes that
  8286. ;; command. There might be problems if any of the keys is otherwise
  8287. ;; used as a prefix key.
  8288. (defcustom orgstruct-heading-prefix-regexp ""
  8289. "Regexp that matches the custom prefix of Org headlines in
  8290. orgstruct(++)-mode."
  8291. :group 'org
  8292. :version "24.4"
  8293. :package-version '(Org . "8.3")
  8294. :type 'regexp)
  8295. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  8296. (defcustom orgstruct-setup-hook nil
  8297. "Hook run after orgstruct-mode-map is filled."
  8298. :group 'org
  8299. :version "24.4"
  8300. :package-version '(Org . "8.0")
  8301. :type 'hook)
  8302. (defvar orgstruct-initialized nil)
  8303. (defvar org-local-vars nil
  8304. "List of local variables, for use by `orgstruct-mode'.")
  8305. ;;;###autoload
  8306. (define-minor-mode orgstruct-mode
  8307. "Toggle the minor mode `orgstruct-mode'.
  8308. This mode is for using Org mode structure commands in other
  8309. modes. The following keys behave as if Org mode were active, if
  8310. the cursor is on a headline, or on a plain list item (both as
  8311. defined by Org mode)."
  8312. nil " OrgStruct" (make-sparse-keymap)
  8313. (funcall (if orgstruct-mode
  8314. 'add-to-invisibility-spec
  8315. 'remove-from-invisibility-spec)
  8316. '(outline . t))
  8317. (when orgstruct-mode
  8318. (org-load-modules-maybe)
  8319. (unless orgstruct-initialized
  8320. (orgstruct-setup)
  8321. (setq orgstruct-initialized t))))
  8322. ;;;###autoload
  8323. (defun turn-on-orgstruct ()
  8324. "Unconditionally turn on `orgstruct-mode'."
  8325. (orgstruct-mode 1))
  8326. (defvar-local orgstruct-is-++ nil
  8327. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  8328. (defvar-local org-fb-vars nil)
  8329. (defun orgstruct++-mode (&optional arg)
  8330. "Toggle `orgstruct-mode', the enhanced version of it.
  8331. In addition to setting orgstruct-mode, this also exports all
  8332. indentation and autofilling variables from Org mode into the
  8333. buffer. It will also recognize item context in multiline items."
  8334. (interactive "P")
  8335. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  8336. (if (< arg 1)
  8337. (progn (orgstruct-mode -1)
  8338. (dolist (v org-fb-vars)
  8339. (set (make-local-variable (car v))
  8340. (if (eq (car-safe (cadr v)) 'quote)
  8341. (cl-cadadr v)
  8342. (nth 1 v)))))
  8343. (orgstruct-mode 1)
  8344. (setq org-fb-vars nil)
  8345. (unless org-local-vars
  8346. (setq org-local-vars (org-get-local-variables)))
  8347. (let (var val)
  8348. (dolist (x org-local-vars)
  8349. (when (string-match
  8350. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
  8351. \\|fill-prefix\\|indent-\\)"
  8352. (symbol-name (car x)))
  8353. (setq var (car x) val (nth 1 x))
  8354. (push (list var `(quote ,(eval var))) org-fb-vars)
  8355. (set (make-local-variable var)
  8356. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  8357. (setq-local orgstruct-is-++ t))))
  8358. ;;;###autoload
  8359. (defun turn-on-orgstruct++ ()
  8360. "Unconditionally turn on `orgstruct++-mode'."
  8361. (orgstruct++-mode 1))
  8362. (defun orgstruct-error ()
  8363. "Error when there is no default binding for a structure key."
  8364. (interactive)
  8365. (funcall (if (fboundp 'user-error)
  8366. 'user-error
  8367. 'error)
  8368. "This key has no function outside structure elements"))
  8369. (defun orgstruct-setup ()
  8370. "Setup orgstruct keymap."
  8371. (dolist (cell '((org-demote . t)
  8372. (org-metaleft . t)
  8373. (org-metaright . t)
  8374. (org-promote . t)
  8375. (org-shiftmetaleft . t)
  8376. (org-shiftmetaright . t)
  8377. org-backward-element
  8378. org-backward-heading-same-level
  8379. org-ctrl-c-ret
  8380. org-ctrl-c-minus
  8381. org-ctrl-c-star
  8382. org-cycle
  8383. org-force-cycle-archived
  8384. org-forward-heading-same-level
  8385. org-insert-heading
  8386. org-insert-heading-respect-content
  8387. org-kill-note-or-show-branches
  8388. org-mark-subtree
  8389. org-meta-return
  8390. org-metadown
  8391. org-metaup
  8392. org-narrow-to-subtree
  8393. org-promote-subtree
  8394. org-reveal
  8395. org-shiftdown
  8396. org-shiftleft
  8397. org-shiftmetadown
  8398. org-shiftmetaup
  8399. org-shiftright
  8400. org-shifttab
  8401. org-shifttab
  8402. org-shiftup
  8403. org-show-children
  8404. org-show-subtree
  8405. org-sort
  8406. org-up-element
  8407. outline-demote
  8408. outline-next-visible-heading
  8409. outline-previous-visible-heading
  8410. outline-promote
  8411. outline-up-heading))
  8412. (let ((f (or (car-safe cell) cell))
  8413. (disable-when-heading-prefix (cdr-safe cell)))
  8414. (when (fboundp f)
  8415. (let ((new-bindings))
  8416. (dolist (binding (nconc (where-is-internal f org-mode-map)
  8417. (where-is-internal f outline-mode-map)))
  8418. (push binding new-bindings)
  8419. ;; TODO use local-function-key-map
  8420. (dolist (rep '(("<tab>" . "TAB")
  8421. ("<return>" . "RET")
  8422. ("<escape>" . "ESC")
  8423. ("<delete>" . "DEL")))
  8424. (setq binding (read-kbd-macro
  8425. (let ((case-fold-search))
  8426. (replace-regexp-in-string
  8427. (regexp-quote (cdr rep))
  8428. (car rep)
  8429. (key-description binding)))))
  8430. (cl-pushnew binding new-bindings :test 'equal)))
  8431. (dolist (binding new-bindings)
  8432. (let ((key (lookup-key orgstruct-mode-map binding)))
  8433. (when (or (not key) (numberp key))
  8434. (ignore-errors
  8435. (org-defkey orgstruct-mode-map
  8436. binding
  8437. (orgstruct-make-binding
  8438. f binding disable-when-heading-prefix))))))))))
  8439. (run-hooks 'orgstruct-setup-hook))
  8440. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  8441. "Create a function for binding in the structure minor mode.
  8442. FUN is the command to call inside a table. KEY is the key that
  8443. should be checked in for a command to execute outside of tables.
  8444. Non-nil `disable-when-heading-prefix' means to disable the command
  8445. if `orgstruct-heading-prefix-regexp' is not empty."
  8446. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  8447. (let ((nname name)
  8448. (i 0))
  8449. (while (fboundp (intern nname))
  8450. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  8451. (setq name (intern nname)))
  8452. (eval
  8453. (let ((bindings '((org-heading-regexp
  8454. (concat "^"
  8455. orgstruct-heading-prefix-regexp
  8456. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  8457. (org-outline-regexp
  8458. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  8459. (org-outline-regexp-bol
  8460. (concat "^" org-outline-regexp))
  8461. (outline-regexp org-outline-regexp)
  8462. (outline-heading-end-regexp "\n")
  8463. (outline-level 'org-outline-level)
  8464. (outline-heading-alist))))
  8465. `(defun ,name (arg)
  8466. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8467. "Outside of structure, run the binding of `"
  8468. (key-description key) "'."
  8469. (when disable-when-heading-prefix
  8470. (concat
  8471. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8472. "back to the default binding due to limitations of Org's implementation of\n"
  8473. "`" (symbol-name fun) "'.")))
  8474. (interactive "p")
  8475. (let* ((disable
  8476. ,(and disable-when-heading-prefix
  8477. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8478. (fallback
  8479. (or disable
  8480. (not
  8481. (let* ,bindings
  8482. (org-context-p 'headline 'item
  8483. ,(when (memq fun
  8484. '(org-insert-heading
  8485. org-insert-heading-respect-content
  8486. org-meta-return))
  8487. '(when orgstruct-is-++
  8488. 'item-body))))))))
  8489. (if fallback
  8490. (let* ((orgstruct-mode)
  8491. (binding
  8492. (let ((key ,key))
  8493. (catch 'exit
  8494. (dolist
  8495. (rep
  8496. '(nil
  8497. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8498. ("<\\([^>]*\\)return>" . "\\1RET")
  8499. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8500. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8501. nil)
  8502. (when rep
  8503. (setq key (read-kbd-macro
  8504. (let ((case-fold-search))
  8505. (replace-regexp-in-string
  8506. (car rep)
  8507. (cdr rep)
  8508. (key-description key))))))
  8509. (when (key-binding key)
  8510. (throw 'exit (key-binding key))))))))
  8511. (if (keymapp binding)
  8512. (org-set-transient-map binding)
  8513. (let ((func (or binding
  8514. (unless disable
  8515. 'orgstruct-error))))
  8516. (when func
  8517. (call-interactively func)))))
  8518. (org-run-like-in-org-mode
  8519. (lambda ()
  8520. (interactive)
  8521. (let* ,bindings
  8522. (call-interactively ',fun)))))))))
  8523. name))
  8524. (defun org-contextualize-keys (alist contexts)
  8525. "Return valid elements in ALIST depending on CONTEXTS.
  8526. `org-agenda-custom-commands' or `org-capture-templates' are the
  8527. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8528. or `org-capture-templates-contexts' are the associated contexts
  8529. definitions."
  8530. (let ((contexts
  8531. ;; normalize contexts
  8532. (mapcar
  8533. (lambda(c) (cond ((listp (cadr c))
  8534. (list (car c) (car c) (nth 1 c)))
  8535. ((string= "" (cadr c))
  8536. (list (car c) (car c) (nth 2 c)))
  8537. (t c)))
  8538. contexts))
  8539. (a alist) r s)
  8540. ;; loop over all commands or templates
  8541. (dolist (c a)
  8542. (let (vrules repl)
  8543. (cond
  8544. ((not (assoc (car c) contexts))
  8545. (push c r))
  8546. ((and (assoc (car c) contexts)
  8547. (setq vrules (org-contextualize-validate-key
  8548. (car c) contexts)))
  8549. (mapc (lambda (vr)
  8550. (unless (equal (car vr) (cadr vr))
  8551. (setq repl vr)))
  8552. vrules)
  8553. (if (not repl) (push c r)
  8554. (push (cadr repl) s)
  8555. (push
  8556. (cons (car c)
  8557. (cdr (or (assoc (cadr repl) alist)
  8558. (error "Undefined key `%s' as contextual replacement for `%s'"
  8559. (cadr repl) (car c)))))
  8560. r))))))
  8561. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8562. (delq
  8563. nil
  8564. (delete-dups
  8565. (mapcar (lambda (x)
  8566. (let ((tpl (car x)))
  8567. (unless (delq
  8568. nil
  8569. (mapcar (lambda (y)
  8570. (equal y tpl))
  8571. s))
  8572. x)))
  8573. (reverse r))))))
  8574. (defun org-contextualize-validate-key (key contexts)
  8575. "Check CONTEXTS for agenda or capture KEY."
  8576. (let (res)
  8577. (dolist (r contexts)
  8578. (dolist (rr (car (last r)))
  8579. (when
  8580. (and (equal key (car r))
  8581. (if (functionp rr) (funcall rr)
  8582. (or (and (eq (car rr) 'in-file)
  8583. (buffer-file-name)
  8584. (string-match (cdr rr) (buffer-file-name)))
  8585. (and (eq (car rr) 'in-mode)
  8586. (string-match (cdr rr) (symbol-name major-mode)))
  8587. (and (eq (car rr) 'in-buffer)
  8588. (string-match (cdr rr) (buffer-name)))
  8589. (when (and (eq (car rr) 'not-in-file)
  8590. (buffer-file-name))
  8591. (not (string-match (cdr rr) (buffer-file-name))))
  8592. (when (eq (car rr) 'not-in-mode)
  8593. (not (string-match (cdr rr) (symbol-name major-mode))))
  8594. (when (eq (car rr) 'not-in-buffer)
  8595. (not (string-match (cdr rr) (buffer-name)))))))
  8596. (push r res))))
  8597. (delete-dups (delq nil res))))
  8598. (defun org-context-p (&rest contexts)
  8599. "Check if local context is any of CONTEXTS.
  8600. Possible values in the list of contexts are `table', `headline', and `item'."
  8601. (let ((pos (point)))
  8602. (goto-char (point-at-bol))
  8603. (prog1 (or (and (memq 'table contexts)
  8604. (looking-at "[ \t]*|"))
  8605. (and (memq 'headline contexts)
  8606. (looking-at org-outline-regexp))
  8607. (and (memq 'item contexts)
  8608. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8609. (and (memq 'item-body contexts)
  8610. (org-in-item-p)))
  8611. (goto-char pos))))
  8612. (defconst org-unique-local-variables
  8613. '(org-element--cache
  8614. org-element--cache-objects
  8615. org-element--cache-sync-keys
  8616. org-element--cache-sync-requests
  8617. org-element--cache-sync-timer)
  8618. "List of local variables that cannot be transferred to another buffer.")
  8619. (defun org-get-local-variables ()
  8620. "Return a list of all local variables in an Org mode buffer."
  8621. (delq nil
  8622. (mapcar
  8623. (lambda (x)
  8624. (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
  8625. (name (car binding)))
  8626. (and (not (get name 'org-state))
  8627. (not (memq name org-unique-local-variables))
  8628. (string-match-p
  8629. "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
  8630. auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
  8631. (symbol-name name))
  8632. binding)))
  8633. (with-temp-buffer
  8634. (org-mode)
  8635. (buffer-local-variables)))))
  8636. (defun org-clone-local-variables (from-buffer &optional regexp)
  8637. "Clone local variables from FROM-BUFFER.
  8638. Optional argument REGEXP selects variables to clone."
  8639. (dolist (pair (buffer-local-variables from-buffer))
  8640. (let ((name (car pair)))
  8641. (when (and (symbolp name)
  8642. (not (memq name org-unique-local-variables))
  8643. (or (null regexp) (string-match regexp (symbol-name name))))
  8644. (set (make-local-variable name) (cdr pair))))))
  8645. ;;;###autoload
  8646. (defun org-run-like-in-org-mode (cmd)
  8647. "Run a command, pretending that the current buffer is in Org mode.
  8648. This will temporarily bind local variables that are typically bound in
  8649. Org mode to the values they have in Org mode, and then interactively
  8650. call CMD."
  8651. (org-load-modules-maybe)
  8652. (unless org-local-vars
  8653. (setq org-local-vars (org-get-local-variables)))
  8654. (let (binds)
  8655. (dolist (var org-local-vars)
  8656. (when (or (not (boundp (car var)))
  8657. (eq (symbol-value (car var))
  8658. (default-value (car var))))
  8659. (push (list (car var) `(quote ,(cadr var))) binds)))
  8660. (eval `(let ,binds
  8661. (call-interactively (quote ,cmd))))))
  8662. (defun org-get-category (&optional pos force-refresh)
  8663. "Get the category applying to position POS."
  8664. (save-match-data
  8665. (when force-refresh (org-refresh-category-properties))
  8666. (let ((pos (or pos (point))))
  8667. (or (get-text-property pos 'org-category)
  8668. (progn (org-refresh-category-properties)
  8669. (get-text-property pos 'org-category))))))
  8670. ;;; Refresh properties
  8671. (defun org-refresh-properties (dprop tprop)
  8672. "Refresh buffer text properties.
  8673. DPROP is the drawer property and TPROP is either the
  8674. corresponding text property to set, or an alist with each element
  8675. being a text property (as a symbol) and a function to apply to
  8676. the value of the drawer property."
  8677. (let ((case-fold-search t)
  8678. (inhibit-read-only t))
  8679. (org-with-silent-modifications
  8680. (org-with-wide-buffer
  8681. (goto-char (point-min))
  8682. (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
  8683. (org-refresh-property tprop (match-string-no-properties 1)))))))
  8684. (defun org-refresh-property (tprop p)
  8685. "Refresh the buffer text property TPROP from the drawer property P.
  8686. The refresh happens only for the current tree (not subtree)."
  8687. (unless (org-before-first-heading-p)
  8688. (save-excursion
  8689. (org-back-to-heading t)
  8690. (if (symbolp tprop)
  8691. ;; TPROP is a text property symbol
  8692. (put-text-property
  8693. (point) (or (outline-next-heading) (point-max)) tprop p)
  8694. ;; TPROP is an alist with (properties . function) elements
  8695. (dolist (al tprop)
  8696. (save-excursion
  8697. (put-text-property
  8698. (line-beginning-position) (or (outline-next-heading) (point-max))
  8699. (car al)
  8700. (funcall (cdr al) p))))))))
  8701. (defun org-refresh-category-properties ()
  8702. "Refresh category text properties in the buffer."
  8703. (let ((case-fold-search t)
  8704. (inhibit-read-only t)
  8705. (default-category
  8706. (cond ((null org-category)
  8707. (if buffer-file-name
  8708. (file-name-sans-extension
  8709. (file-name-nondirectory buffer-file-name))
  8710. "???"))
  8711. ((symbolp org-category) (symbol-name org-category))
  8712. (t org-category))))
  8713. (org-with-silent-modifications
  8714. (org-with-wide-buffer
  8715. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8716. ;; This is the default category for the buffer. If none is
  8717. ;; found, fall-back to `org-category' or buffer file name.
  8718. (put-text-property
  8719. (point-min) (point-max)
  8720. 'org-category
  8721. (catch 'buffer-category
  8722. (goto-char (point-max))
  8723. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8724. (let ((element (org-element-at-point)))
  8725. (when (eq (org-element-type element) 'keyword)
  8726. (throw 'buffer-category
  8727. (org-element-property :value element)))))
  8728. default-category))
  8729. ;; Set sub-tree specific categories.
  8730. (goto-char (point-min))
  8731. (let ((regexp (org-re-property "CATEGORY")))
  8732. (while (re-search-forward regexp nil t)
  8733. (let ((value (match-string-no-properties 3)))
  8734. (when (org-at-property-p)
  8735. (put-text-property
  8736. (save-excursion (org-back-to-heading t) (point))
  8737. (save-excursion (org-end-of-subtree t t) (point))
  8738. 'org-category
  8739. value)))))))))
  8740. (defun org-refresh-stats-properties ()
  8741. "Refresh stats text properties in the buffer."
  8742. (let (stats)
  8743. (org-with-silent-modifications
  8744. (org-with-wide-buffer
  8745. (goto-char (point-min))
  8746. (while (re-search-forward
  8747. (concat org-outline-regexp-bol ".*"
  8748. "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
  8749. nil t)
  8750. (setq stats (cond ((equal (match-string 3) "0") 0)
  8751. ((match-string 2)
  8752. (/ (* (string-to-number (match-string 2)) 100)
  8753. (string-to-number (match-string 3))))
  8754. (t (string-to-number (match-string 1)))))
  8755. (org-back-to-heading t)
  8756. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8757. 'org-stats stats))))))
  8758. (defun org-refresh-effort-properties ()
  8759. "Refresh effort properties"
  8760. (org-refresh-properties
  8761. org-effort-property
  8762. '((effort . identity)
  8763. (effort-minutes . org-duration-string-to-minutes))))
  8764. ;;;; Link Stuff
  8765. ;;; Link abbreviations
  8766. (defun org-link-expand-abbrev (link)
  8767. "Apply replacements as defined in `org-link-abbrev-alist'."
  8768. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8769. (let* ((key (match-string 1 link))
  8770. (as (or (assoc key org-link-abbrev-alist-local)
  8771. (assoc key org-link-abbrev-alist)))
  8772. (tag (and (match-end 2) (match-string 3 link)))
  8773. rpl)
  8774. (if (not as)
  8775. link
  8776. (setq rpl (cdr as))
  8777. (cond
  8778. ((symbolp rpl) (funcall rpl tag))
  8779. ((string-match "%(\\([^)]+\\))" rpl)
  8780. (replace-match
  8781. (save-match-data
  8782. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8783. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8784. ((string-match "%h" rpl)
  8785. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8786. (t (concat rpl tag)))))
  8787. link))
  8788. ;;; Storing and inserting links
  8789. (defvar org-insert-link-history nil
  8790. "Minibuffer history for links inserted with `org-insert-link'.")
  8791. (defvar org-stored-links nil
  8792. "Contains the links stored with `org-store-link'.")
  8793. (defvar org-store-link-plist nil
  8794. "Plist with info about the most recently link created with `org-store-link'.")
  8795. (defun org-store-link-functions ()
  8796. "Return a list of functions that are called to create and store a link.
  8797. The functions defined in the :store property of
  8798. `org-link-parameters'.
  8799. Each function will be called in turn until one returns a non-nil
  8800. value. Each function should check if it is responsible for
  8801. creating this link (for example by looking at the major mode).
  8802. If not, it must exit and return nil. If yes, it should return
  8803. a non-nil value after calling `org-store-link-props' with a list
  8804. of properties and values. Special properties are:
  8805. :type The link prefix, like \"http\". This must be given.
  8806. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8807. This is obligatory as well.
  8808. :description Optional default description for the second pair
  8809. of brackets in an Org mode link. The user can still change
  8810. this when inserting this link into an Org mode buffer.
  8811. In addition to these, any additional properties can be specified
  8812. and then used in capture templates."
  8813. (cl-loop for link in org-link-parameters
  8814. with store-func
  8815. do (setq store-func (org-link-get-parameter (car link) :store))
  8816. if store-func
  8817. collect store-func))
  8818. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8819. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8820. ;;;###autoload
  8821. (defun org-store-link (arg)
  8822. "Store an org-link to the current location.
  8823. \\<org-mode-map>
  8824. This link is added to `org-stored-links' and can later be inserted
  8825. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8826. For some link types, a `\\[universal-argument]' prefix ARG is interpreted.
  8827. For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
  8828. For file links, ARG negates `org-context-in-file-links'.
  8829. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8830. skipping storing functions that are not
  8831. part of Org core.
  8832. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8833. prefix ARG forces storing a link for each line in the
  8834. active region."
  8835. (interactive "P")
  8836. (org-load-modules-maybe)
  8837. (if (and (equal arg '(64)) (org-region-active-p))
  8838. (save-excursion
  8839. (let ((end (region-end)))
  8840. (goto-char (region-beginning))
  8841. (set-mark (point))
  8842. (while (< (point-at-eol) end)
  8843. (move-end-of-line 1) (activate-mark)
  8844. (let (current-prefix-arg)
  8845. (call-interactively 'org-store-link))
  8846. (move-beginning-of-line 2)
  8847. (set-mark (point)))))
  8848. (setq org-store-link-plist nil)
  8849. (let (link cpltxt desc description search
  8850. txt custom-id agenda-link sfuns sfunsn)
  8851. (cond
  8852. ;; Store a link using an external link type
  8853. ((and (not (equal arg '(16)))
  8854. (setq sfuns
  8855. (delq
  8856. nil (mapcar (lambda (f)
  8857. (let (fs) (if (funcall f) (push f fs))))
  8858. (org-store-link-functions)))
  8859. sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
  8860. (or (and (cdr sfuns)
  8861. (funcall (intern
  8862. (completing-read
  8863. "Which function for creating the link? "
  8864. sfunsn nil t (car sfunsn)))))
  8865. (funcall (caar sfuns)))
  8866. (setq link (plist-get org-store-link-plist :link)
  8867. desc (or (plist-get org-store-link-plist
  8868. :description)
  8869. link))))
  8870. ;; Store a link from a source code buffer.
  8871. ((org-src-edit-buffer-p)
  8872. (let ((coderef-format (org-src-coderef-format)))
  8873. (cond ((save-excursion
  8874. (beginning-of-line)
  8875. (looking-at (org-src-coderef-regexp coderef-format)))
  8876. (setq link (format "(%s)" (match-string-no-properties 3))))
  8877. ((called-interactively-p 'any)
  8878. (let ((label (read-string "Code line label: ")))
  8879. (end-of-line)
  8880. (setq link (format coderef-format label))
  8881. (let ((gc (- 79 (length link))))
  8882. (if (< (current-column) gc)
  8883. (org-move-to-column gc t)
  8884. (insert " ")))
  8885. (insert link)
  8886. (setq link (concat "(" label ")"))
  8887. (setq desc nil)))
  8888. (t (setq link nil)))))
  8889. ;; We are in the agenda, link to referenced location
  8890. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8891. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8892. (get-text-property (point) 'org-marker))))
  8893. (when m
  8894. (org-with-point-at m
  8895. (setq agenda-link
  8896. (if (called-interactively-p 'any)
  8897. (call-interactively 'org-store-link)
  8898. (org-store-link nil)))))))
  8899. ((eq major-mode 'calendar-mode)
  8900. (let ((cd (calendar-cursor-to-date)))
  8901. (setq link
  8902. (format-time-string
  8903. (car org-time-stamp-formats)
  8904. (apply 'encode-time
  8905. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8906. nil nil nil))))
  8907. (org-store-link-props :type "calendar" :date cd)))
  8908. ((eq major-mode 'help-mode)
  8909. (setq link (concat "help:" (save-excursion
  8910. (goto-char (point-min))
  8911. (looking-at "^[^ ]+")
  8912. (match-string 0))))
  8913. (org-store-link-props :type "help"))
  8914. ((eq major-mode 'w3-mode)
  8915. (setq cpltxt (if (and (buffer-name)
  8916. (not (string-match "Untitled" (buffer-name))))
  8917. (buffer-name)
  8918. (url-view-url t))
  8919. link (url-view-url t))
  8920. (org-store-link-props :type "w3" :url (url-view-url t)))
  8921. ((eq major-mode 'image-mode)
  8922. (setq cpltxt (concat "file:"
  8923. (abbreviate-file-name buffer-file-name))
  8924. link cpltxt)
  8925. (org-store-link-props :type "image" :file buffer-file-name))
  8926. ;; In dired, store a link to the file of the current line
  8927. ((derived-mode-p 'dired-mode)
  8928. (let ((file (dired-get-filename nil t)))
  8929. (setq file (if file
  8930. (abbreviate-file-name
  8931. (expand-file-name (dired-get-filename nil t)))
  8932. ;; otherwise, no file so use current directory.
  8933. default-directory))
  8934. (setq cpltxt (concat "file:" file)
  8935. link cpltxt)))
  8936. ((setq search (run-hook-with-args-until-success
  8937. 'org-create-file-search-functions))
  8938. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8939. "::" search))
  8940. (setq cpltxt (or description link)))
  8941. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8942. (org-with-limited-levels
  8943. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8944. (cond
  8945. ;; Store a link using the target at point
  8946. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8947. (setq cpltxt
  8948. (concat "file:"
  8949. (abbreviate-file-name
  8950. (buffer-file-name (buffer-base-buffer)))
  8951. "::" (match-string 1))
  8952. link cpltxt))
  8953. ((and (featurep 'org-id)
  8954. (or (eq org-id-link-to-org-use-id t)
  8955. (and (called-interactively-p 'any)
  8956. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8957. (and (eq org-id-link-to-org-use-id
  8958. 'create-if-interactive-and-no-custom-id)
  8959. (not custom-id))))
  8960. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8961. ;; Store a link using the ID at point
  8962. (setq link (condition-case nil
  8963. (prog1 (org-id-store-link)
  8964. (setq desc (or (plist-get org-store-link-plist
  8965. :description)
  8966. "")))
  8967. (error
  8968. ;; Probably before first headline, link only to file
  8969. (concat "file:"
  8970. (abbreviate-file-name
  8971. (buffer-file-name (buffer-base-buffer))))))))
  8972. (t
  8973. ;; Just link to current headline
  8974. (setq cpltxt (concat "file:"
  8975. (abbreviate-file-name
  8976. (buffer-file-name (buffer-base-buffer)))))
  8977. ;; Add a context search string
  8978. (when (org-xor org-context-in-file-links arg)
  8979. (let* ((element (org-element-at-point))
  8980. (name (org-element-property :name element)))
  8981. (setq txt (cond
  8982. ((org-at-heading-p) nil)
  8983. (name)
  8984. ((org-region-active-p)
  8985. (buffer-substring (region-beginning) (region-end)))))
  8986. (when (or (null txt) (string-match "\\S-" txt))
  8987. (setq cpltxt
  8988. (concat cpltxt "::"
  8989. (condition-case nil
  8990. (org-make-org-heading-search-string txt)
  8991. (error "")))
  8992. desc (or name
  8993. (nth 4 (ignore-errors (org-heading-components)))
  8994. "NONE")))))
  8995. (when (string-match "::\\'" cpltxt)
  8996. (setq cpltxt (substring cpltxt 0 -2)))
  8997. (setq link cpltxt)))))
  8998. ((buffer-file-name (buffer-base-buffer))
  8999. ;; Just link to this file here.
  9000. (setq cpltxt (concat "file:"
  9001. (abbreviate-file-name
  9002. (buffer-file-name (buffer-base-buffer)))))
  9003. ;; Add a context string.
  9004. (when (org-xor org-context-in-file-links arg)
  9005. (setq txt (if (org-region-active-p)
  9006. (buffer-substring (region-beginning) (region-end))
  9007. (buffer-substring (point-at-bol) (point-at-eol))))
  9008. ;; Only use search option if there is some text.
  9009. (when (string-match "\\S-" txt)
  9010. (setq cpltxt
  9011. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  9012. desc "NONE")))
  9013. (setq link cpltxt))
  9014. ((called-interactively-p 'interactive)
  9015. (user-error "No method for storing a link from this buffer"))
  9016. (t (setq link nil)))
  9017. ;; We're done setting link and desc, clean up
  9018. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  9019. (setq link (or link cpltxt)
  9020. desc (or desc cpltxt))
  9021. (cond ((not desc))
  9022. ((equal desc "NONE") (setq desc nil))
  9023. (t (setq desc
  9024. (replace-regexp-in-string
  9025. org-bracket-link-analytic-regexp
  9026. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  9027. desc))))
  9028. ;; Return the link
  9029. (if (not (and (or (called-interactively-p 'any)
  9030. executing-kbd-macro)
  9031. link))
  9032. (or agenda-link (and link (org-make-link-string link desc)))
  9033. (push (list link desc) org-stored-links)
  9034. (message "Stored: %s" (or desc link))
  9035. (when custom-id
  9036. (setq link (concat "file:" (abbreviate-file-name
  9037. (buffer-file-name)) "::#" custom-id))
  9038. (push (list link desc) org-stored-links))
  9039. (car org-stored-links)))))
  9040. (defun org-store-link-props (&rest plist)
  9041. "Store link properties, extract names, addresses and dates."
  9042. (let ((x (plist-get plist :from)))
  9043. (when x
  9044. (let ((adr (mail-extract-address-components x)))
  9045. (setq plist (plist-put plist :fromname (car adr)))
  9046. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  9047. (let ((x (plist-get plist :to)))
  9048. (when x
  9049. (let ((adr (mail-extract-address-components x)))
  9050. (setq plist (plist-put plist :toname (car adr)))
  9051. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  9052. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  9053. (when x
  9054. (setq plist (plist-put plist :date-timestamp
  9055. (format-time-string
  9056. (org-time-stamp-format t) x)))
  9057. (setq plist (plist-put plist :date-timestamp-inactive
  9058. (format-time-string
  9059. (org-time-stamp-format t t) x)))))
  9060. (let ((from (plist-get plist :from))
  9061. (to (plist-get plist :to)))
  9062. (when (and from to org-from-is-user-regexp)
  9063. (setq plist
  9064. (plist-put plist :fromto
  9065. (if (string-match org-from-is-user-regexp from)
  9066. (concat "to %t")
  9067. (concat "from %f"))))))
  9068. (setq org-store-link-plist plist))
  9069. (defun org-add-link-props (&rest plist)
  9070. "Add these properties to the link property list."
  9071. (let (key value)
  9072. (while plist
  9073. (setq key (pop plist) value (pop plist))
  9074. (setq org-store-link-plist
  9075. (plist-put org-store-link-plist key value)))))
  9076. (defun org-email-link-description (&optional fmt)
  9077. "Return the description part of an email link.
  9078. This takes information from `org-store-link-plist' and formats it
  9079. according to FMT (default from `org-email-link-description-format')."
  9080. (setq fmt (or fmt org-email-link-description-format))
  9081. (let* ((p org-store-link-plist)
  9082. (to (plist-get p :toaddress))
  9083. (from (plist-get p :fromaddress))
  9084. (table
  9085. (list
  9086. (cons "%c" (plist-get p :fromto))
  9087. (cons "%F" (plist-get p :from))
  9088. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  9089. (cons "%T" (plist-get p :to))
  9090. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  9091. (cons "%s" (plist-get p :subject))
  9092. (cons "%d" (plist-get p :date))
  9093. (cons "%m" (plist-get p :message-id)))))
  9094. (when (string-match "%c" fmt)
  9095. ;; Check if the user wrote this message
  9096. (if (and org-from-is-user-regexp from to
  9097. (save-match-data (string-match org-from-is-user-regexp from)))
  9098. (setq fmt (replace-match "to %t" t t fmt))
  9099. (setq fmt (replace-match "from %f" t t fmt))))
  9100. (org-replace-escapes fmt table)))
  9101. (defun org-make-org-heading-search-string (&optional string)
  9102. "Make search string for the current headline or STRING."
  9103. (let ((s (or string
  9104. (and (derived-mode-p 'org-mode)
  9105. (save-excursion
  9106. (org-back-to-heading t)
  9107. (org-element-property :raw-value (org-element-at-point))))))
  9108. (lines org-context-in-file-links))
  9109. (or string (setq s (concat "*" s))) ; Add * for headlines
  9110. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  9111. (when (and string (integerp lines) (> lines 0))
  9112. (let ((slines (org-split-string s "\n")))
  9113. (when (< lines (length slines))
  9114. (setq s (mapconcat
  9115. 'identity
  9116. (reverse (nthcdr (- (length slines) lines)
  9117. (reverse slines))) "\n")))))
  9118. (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
  9119. (defun org-make-link-string (link &optional description)
  9120. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  9121. (unless (org-string-nw-p link) (error "Empty link"))
  9122. (let ((uri (cond ((string-match org-link-types-re link)
  9123. (concat (match-string 1 link)
  9124. (org-link-escape (substring link (match-end 1)))))
  9125. ;; For readability, url-encode internal links only
  9126. ;; when absolutely needed (i.e, when they contain
  9127. ;; square brackets). File links however, are
  9128. ;; encoded since, e.g., spaces are significant.
  9129. ((or (file-name-absolute-p link)
  9130. (string-match-p "\\`\\.\\.?/\\|[][]" link))
  9131. (org-link-escape link))
  9132. (t link)))
  9133. (description
  9134. (and (org-string-nw-p description)
  9135. ;; Remove brackets from description, as they are fatal.
  9136. (replace-regexp-in-string
  9137. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  9138. (org-trim description)))))
  9139. (format "[[%s]%s]"
  9140. uri
  9141. (if description (format "[%s]" description) ""))))
  9142. (defconst org-link-escape-chars
  9143. ;;%20 %5B %5D %25
  9144. '(?\s ?\[ ?\] ?%)
  9145. "List of characters that should be escaped in a link when stored to Org.
  9146. This is the list that is used for internal purposes.")
  9147. (defun org-link-escape (text &optional table merge)
  9148. "Return percent escaped representation of TEXT.
  9149. TEXT is a string with the text to escape.
  9150. Optional argument TABLE is a list with characters that should be
  9151. escaped. When nil, `org-link-escape-chars' is used.
  9152. If optional argument MERGE is set, merge TABLE into
  9153. `org-link-escape-chars'."
  9154. (let ((characters-to-encode
  9155. (cond ((null table) org-link-escape-chars)
  9156. (merge (append org-link-escape-chars table))
  9157. (t table))))
  9158. (mapconcat
  9159. (lambda (c)
  9160. (if (or (memq c characters-to-encode)
  9161. (and org-url-hexify-p (or (< c 32) (> c 126))))
  9162. (mapconcat (lambda (e) (format "%%%.2X" e))
  9163. (or (encode-coding-char c 'utf-8)
  9164. (error "Unable to percent escape character: %c" c))
  9165. "")
  9166. (char-to-string c)))
  9167. text "")))
  9168. (defun org-link-unescape (str)
  9169. "Unhex hexified Unicode parts in string STR.
  9170. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  9171. reciprocal of `org-link-escape', which see."
  9172. (if (org-string-nw-p str)
  9173. (replace-regexp-in-string
  9174. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  9175. str))
  9176. (defun org-link-unescape-compound (hex)
  9177. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  9178. Note: this function also decodes single byte encodings like
  9179. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  9180. (save-match-data
  9181. (let* ((bytes (cdr (split-string hex "%")))
  9182. (ret "")
  9183. (eat 0)
  9184. (sum 0))
  9185. (while bytes
  9186. (let* ((val (string-to-number (pop bytes) 16))
  9187. (shift-xor
  9188. (if (= 0 eat)
  9189. (cond
  9190. ((>= val 252) (cons 6 252))
  9191. ((>= val 248) (cons 5 248))
  9192. ((>= val 240) (cons 4 240))
  9193. ((>= val 224) (cons 3 224))
  9194. ((>= val 192) (cons 2 192))
  9195. (t (cons 0 0)))
  9196. (cons 6 128))))
  9197. (when (>= val 192) (setq eat (car shift-xor)))
  9198. (setq val (logxor val (cdr shift-xor)))
  9199. (setq sum (+ (lsh sum (car shift-xor)) val))
  9200. (when (> eat 0) (setq eat (- eat 1)))
  9201. (cond
  9202. ((= 0 eat) ;multi byte
  9203. (setq ret (concat ret (char-to-string sum)))
  9204. (setq sum 0))
  9205. ((not bytes) ; single byte(s)
  9206. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  9207. ret)))
  9208. (defun org-link-unescape-single-byte-sequence (hex)
  9209. "Unhexify hex-encoded single byte character sequences."
  9210. (mapconcat (lambda (byte)
  9211. (char-to-string (string-to-number byte 16)))
  9212. (cdr (split-string hex "%")) ""))
  9213. (defun org-xor (a b)
  9214. "Exclusive or."
  9215. (if a (not b) b))
  9216. (defun org-fixup-message-id-for-http (s)
  9217. "Replace special characters in a message id, so it can be used in an http query."
  9218. (when (string-match "%" s)
  9219. (setq s (mapconcat (lambda (c)
  9220. (if (eq c ?%)
  9221. "%25"
  9222. (char-to-string c)))
  9223. s "")))
  9224. (while (string-match "<" s)
  9225. (setq s (replace-match "%3C" t t s)))
  9226. (while (string-match ">" s)
  9227. (setq s (replace-match "%3E" t t s)))
  9228. (while (string-match "@" s)
  9229. (setq s (replace-match "%40" t t s)))
  9230. s)
  9231. (defun org-link-prettify (link)
  9232. "Return a human-readable representation of LINK.
  9233. The car of LINK must be a raw link.
  9234. The cdr of LINK must be either a link description or nil."
  9235. (let ((desc (or (cadr link) "<no description>")))
  9236. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  9237. "<" (car link) ">")))
  9238. ;;;###autoload
  9239. (defun org-insert-link-global ()
  9240. "Insert a link like Org mode does.
  9241. This command can be called in any mode to insert a link in Org syntax."
  9242. (interactive)
  9243. (org-load-modules-maybe)
  9244. (org-run-like-in-org-mode 'org-insert-link))
  9245. (defun org-insert-all-links (arg &optional pre post)
  9246. "Insert all links in `org-stored-links'.
  9247. When a universal prefix, do not delete the links from `org-stored-links'.
  9248. When `ARG' is a number, insert the last N link(s).
  9249. `PRE' and `POST' are optional arguments to define a string to
  9250. prepend or to append."
  9251. (interactive "P")
  9252. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  9253. (links (copy-sequence org-stored-links))
  9254. (pr (or pre "- "))
  9255. (po (or post "\n"))
  9256. (cnt 1) l)
  9257. (if (null org-stored-links)
  9258. (message "No link to insert")
  9259. (while (and (or (listp arg) (>= arg cnt))
  9260. (setq l (if (listp arg)
  9261. (pop links)
  9262. (pop org-stored-links))))
  9263. (setq cnt (1+ cnt))
  9264. (insert pr)
  9265. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  9266. (insert po)))))
  9267. (defun org-insert-last-stored-link (arg)
  9268. "Insert the last link stored in `org-stored-links'."
  9269. (interactive "p")
  9270. (org-insert-all-links arg "" "\n"))
  9271. (defun org-link-fontify-links-to-this-file ()
  9272. "Fontify links to the current file in `org-stored-links'."
  9273. (let ((f (buffer-file-name)) a b)
  9274. (setq a (mapcar (lambda(l)
  9275. (let ((ll (car l)))
  9276. (when (and (string-match "^file:\\(.+\\)::" ll)
  9277. (equal f (expand-file-name (match-string 1 ll))))
  9278. ll)))
  9279. org-stored-links))
  9280. (when (featurep 'org-id)
  9281. (setq b (mapcar (lambda(l)
  9282. (let ((ll (car l)))
  9283. (when (and (string-match "^id:\\(.+\\)$" ll)
  9284. (equal f (expand-file-name
  9285. (or (org-id-find-id-file
  9286. (match-string 1 ll)) ""))))
  9287. ll)))
  9288. org-stored-links)))
  9289. (mapcar (lambda(l)
  9290. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  9291. (delq nil (append a b)))))
  9292. (defvar org--links-history nil)
  9293. (defun org-insert-link (&optional complete-file link-location default-description)
  9294. "Insert a link. At the prompt, enter the link.
  9295. Completion can be used to insert any of the link protocol prefixes in use.
  9296. The history can be used to select a link previously stored with
  9297. `org-store-link'. When the empty string is entered (i.e. if you just
  9298. press `RET' at the prompt), the link defaults to the most recently
  9299. stored link. As `SPC' triggers completion in the minibuffer, you need to
  9300. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  9301. You will also be prompted for a description, and if one is given, it will
  9302. be displayed in the buffer instead of the link.
  9303. If there is already a link at point, this command will allow you to edit
  9304. link and description parts.
  9305. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  9306. file name can be
  9307. selected using completion. The path to the file will be relative to the
  9308. current directory if the file is in the current directory or a subdirectory.
  9309. Otherwise, the link will be the absolute path as completed in the minibuffer
  9310. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  9311. option `org-link-file-path-type'.
  9312. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  9313. absolute path even if the file is in
  9314. the current directory or below.
  9315. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  9316. prefix negates `org-keep-stored-link-after-insertion'.
  9317. If `org-make-link-description-function' is non-nil, this function will be
  9318. called with the link target, and the result will be the default
  9319. link description.
  9320. If the LINK-LOCATION parameter is non-nil, this value will be used as
  9321. the link location instead of reading one interactively.
  9322. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
  9323. as the default description."
  9324. (interactive "P")
  9325. (let* ((wcf (current-window-configuration))
  9326. (origbuf (current-buffer))
  9327. (region (when (org-region-active-p)
  9328. (buffer-substring (region-beginning) (region-end))))
  9329. (remove (and region (list (region-beginning) (region-end))))
  9330. (desc region)
  9331. (link link-location)
  9332. (abbrevs org-link-abbrev-alist-local)
  9333. entry all-prefixes auto-desc)
  9334. (cond
  9335. (link-location) ; specified by arg, just use it.
  9336. ((org-in-regexp org-bracket-link-regexp 1)
  9337. ;; We do have a link at point, and we are going to edit it.
  9338. (setq remove (list (match-beginning 0) (match-end 0)))
  9339. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  9340. (setq link (read-string "Link: "
  9341. (org-link-unescape
  9342. (match-string-no-properties 1)))))
  9343. ((or (org-in-regexp org-angle-link-re)
  9344. (org-in-regexp org-plain-link-re))
  9345. ;; Convert to bracket link
  9346. (setq remove (list (match-beginning 0) (match-end 0))
  9347. link (read-string "Link: "
  9348. (org-unbracket-string "<" ">" (match-string 0)))))
  9349. ((member complete-file '((4) (16)))
  9350. ;; Completing read for file names.
  9351. (setq link (org-file-complete-link complete-file)))
  9352. (t
  9353. ;; Read link, with completion for stored links.
  9354. (org-link-fontify-links-to-this-file)
  9355. (org-switch-to-buffer-other-window "*Org Links*")
  9356. (with-current-buffer "*Org Links*"
  9357. (erase-buffer)
  9358. (insert "Insert a link.
  9359. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  9360. (when org-stored-links
  9361. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  9362. (insert (mapconcat 'org-link-prettify
  9363. (reverse org-stored-links) "\n")))
  9364. (goto-char (point-min)))
  9365. (let ((cw (selected-window)))
  9366. (select-window (get-buffer-window "*Org Links*" 'visible))
  9367. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  9368. (unless (pos-visible-in-window-p (point-max))
  9369. (org-fit-window-to-buffer))
  9370. (and (window-live-p cw) (select-window cw)))
  9371. (setq all-prefixes (append (mapcar 'car abbrevs)
  9372. (mapcar 'car org-link-abbrev-alist)
  9373. (org-link-types)))
  9374. (unwind-protect
  9375. ;; Fake a link history, containing the stored links.
  9376. (let ((org--links-history
  9377. (append (mapcar #'car org-stored-links)
  9378. org-insert-link-history)))
  9379. (setq link
  9380. (org-completing-read
  9381. "Link: "
  9382. (append
  9383. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  9384. (mapcar #'car org-stored-links))
  9385. nil nil nil
  9386. 'org--links-history
  9387. (caar org-stored-links)))
  9388. (unless (org-string-nw-p link) (user-error "No link selected"))
  9389. (dolist (l org-stored-links)
  9390. (when (equal link (cadr l))
  9391. (setq link (car l))
  9392. (setq auto-desc t)))
  9393. (when (or (member link all-prefixes)
  9394. (and (equal ":" (substring link -1))
  9395. (member (substring link 0 -1) all-prefixes)
  9396. (setq link (substring link 0 -1))))
  9397. (setq link (with-current-buffer origbuf
  9398. (org-link-try-special-completion link)))))
  9399. (set-window-configuration wcf)
  9400. (kill-buffer "*Org Links*"))
  9401. (setq entry (assoc link org-stored-links))
  9402. (or entry (push link org-insert-link-history))
  9403. (setq desc (or desc (nth 1 entry)))))
  9404. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  9405. (not org-keep-stored-link-after-insertion))
  9406. (setq org-stored-links (delq (assoc link org-stored-links)
  9407. org-stored-links)))
  9408. (when (and (string-match org-plain-link-re link)
  9409. (not (string-match org-ts-regexp link)))
  9410. ;; URL-like link, normalize the use of angular brackets.
  9411. (setq link (org-unbracket-string "<" ">" link)))
  9412. ;; Check if we are linking to the current file with a search
  9413. ;; option If yes, simplify the link by using only the search
  9414. ;; option.
  9415. (when (and buffer-file-name
  9416. (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
  9417. (let* ((path (match-string 1 link))
  9418. (case-fold-search nil)
  9419. (search (match-string 2 link)))
  9420. (save-match-data
  9421. (when (equal (file-truename buffer-file-name) (file-truename path))
  9422. ;; We are linking to this same file, with a search option
  9423. (setq link search)))))
  9424. ;; Check if we can/should use a relative path. If yes, simplify the link
  9425. (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
  9426. (let* ((type (match-string 1 link))
  9427. (path (match-string 2 link))
  9428. (origpath path)
  9429. (case-fold-search nil))
  9430. (cond
  9431. ((or (eq org-link-file-path-type 'absolute)
  9432. (equal complete-file '(16)))
  9433. (setq path (abbreviate-file-name (expand-file-name path))))
  9434. ((eq org-link-file-path-type 'noabbrev)
  9435. (setq path (expand-file-name path)))
  9436. ((eq org-link-file-path-type 'relative)
  9437. (setq path (file-relative-name path)))
  9438. (t
  9439. (save-match-data
  9440. (if (string-match (concat "^" (regexp-quote
  9441. (expand-file-name
  9442. (file-name-as-directory
  9443. default-directory))))
  9444. (expand-file-name path))
  9445. ;; We are linking a file with relative path name.
  9446. (setq path (substring (expand-file-name path)
  9447. (match-end 0)))
  9448. (setq path (abbreviate-file-name (expand-file-name path)))))))
  9449. (setq link (concat type path))
  9450. (when (equal desc origpath)
  9451. (setq desc path))))
  9452. (if org-make-link-description-function
  9453. (setq desc
  9454. (or (condition-case nil
  9455. (funcall org-make-link-description-function link desc)
  9456. (error (progn (message "Can't get link description from `%s'"
  9457. (symbol-name org-make-link-description-function))
  9458. (sit-for 2) nil)))
  9459. (read-string "Description: " default-description)))
  9460. (if default-description (setq desc default-description)
  9461. (setq desc (or (and auto-desc desc)
  9462. (read-string "Description: " desc)))))
  9463. (unless (string-match "\\S-" desc) (setq desc nil))
  9464. (when remove (apply 'delete-region remove))
  9465. (insert (org-make-link-string link desc))
  9466. ;; Redisplay so as the new link has proper invisible characters.
  9467. (sit-for 0)))
  9468. (defun org-link-try-special-completion (type)
  9469. "If there is completion support for link type TYPE, offer it."
  9470. (let ((fun (org-link-get-parameter type :complete)))
  9471. (if (functionp fun)
  9472. (funcall fun)
  9473. (read-string "Link (no completion support): " (concat type ":")))))
  9474. (defun org-file-complete-link (&optional arg)
  9475. "Create a file link using completion."
  9476. (let ((file (read-file-name "File: "))
  9477. (pwd (file-name-as-directory (expand-file-name ".")))
  9478. (pwd1 (file-name-as-directory (abbreviate-file-name
  9479. (expand-file-name ".")))))
  9480. (cond ((equal arg '(16))
  9481. (concat "file:"
  9482. (abbreviate-file-name (expand-file-name file))))
  9483. ((string-match
  9484. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9485. (concat "file:" (match-string 1 file)))
  9486. ((string-match
  9487. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9488. (expand-file-name file))
  9489. (concat "file:"
  9490. (match-string 1 (expand-file-name file))))
  9491. (t (concat "file:" file)))))
  9492. (defun org-completing-read (&rest args)
  9493. "Completing-read with SPACE being a normal character."
  9494. (let ((enable-recursive-minibuffers t)
  9495. (minibuffer-local-completion-map
  9496. (copy-keymap minibuffer-local-completion-map)))
  9497. (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
  9498. (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
  9499. (org-defkey minibuffer-local-completion-map (kbd "C-c !")
  9500. 'org-time-stamp-inactive)
  9501. (apply #'completing-read args)))
  9502. ;;; Opening/following a link
  9503. (defvar org-link-search-failed nil)
  9504. (defvar org-open-link-functions nil
  9505. "Hook for functions finding a plain text link.
  9506. These functions must take a single argument, the link content.
  9507. They will be called for links that look like [[link text][description]]
  9508. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9509. like a filename (e.g. \"./blue.png\").
  9510. These functions will be called *before* Org attempts to resolve the
  9511. link by doing text searches in the current buffer - so if you want a
  9512. link \"[[target]]\" to still find \"<<target>>\", your function should
  9513. handle this as a special case.
  9514. When the function does handle the link, it must return a non-nil value.
  9515. If it decides that it is not responsible for this link, it must return
  9516. nil to indicate that that Org can continue with other options like
  9517. exact and fuzzy text search.")
  9518. (defun org-next-link (&optional search-backward)
  9519. "Move forward to the next link.
  9520. If the link is in hidden text, expose it."
  9521. (interactive "P")
  9522. (when (and org-link-search-failed (eq this-command last-command))
  9523. (goto-char (point-min))
  9524. (message "Link search wrapped back to beginning of buffer"))
  9525. (setq org-link-search-failed nil)
  9526. (let* ((pos (point))
  9527. (ct (org-context))
  9528. (a (assq :link ct))
  9529. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9530. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9531. ((looking-at org-any-link-re)
  9532. ;; Don't stay stuck at link without an org-link face
  9533. (forward-char (if search-backward -1 1))))
  9534. (if (funcall srch-fun org-any-link-re nil t)
  9535. (progn
  9536. (goto-char (match-beginning 0))
  9537. (when (outline-invisible-p) (org-show-context)))
  9538. (goto-char pos)
  9539. (setq org-link-search-failed t)
  9540. (message "No further link found"))))
  9541. (defun org-previous-link ()
  9542. "Move backward to the previous link.
  9543. If the link is in hidden text, expose it."
  9544. (interactive)
  9545. (funcall 'org-next-link t))
  9546. (defun org-translate-link (s)
  9547. "Translate a link string if a translation function has been defined."
  9548. (with-temp-buffer
  9549. (insert (org-trim s))
  9550. (org-trim (org-element-interpret-data (org-element-context)))))
  9551. (defun org-translate-link-from-planner (type path)
  9552. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9553. This is still an experimental function, your mileage may vary."
  9554. (cond
  9555. ((member type '("http" "https" "news" "ftp"))
  9556. ;; standard Internet links are the same.
  9557. nil)
  9558. ((and (equal type "irc") (string-match "^//" path))
  9559. ;; Planner has two / at the beginning of an irc link, we have 1.
  9560. ;; We should have zero, actually....
  9561. (setq path (substring path 1)))
  9562. ((and (equal type "lisp") (string-match "^/" path))
  9563. ;; Planner has a slash, we do not.
  9564. (setq type "elisp" path (substring path 1)))
  9565. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9566. ;; A typical message link. Planner has the id after the final slash,
  9567. ;; we separate it with a hash mark
  9568. (setq path (concat (match-string 1 path) "#"
  9569. (org-unbracket-string "<" ">" (match-string 2 path))))))
  9570. (cons type path))
  9571. (defun org-find-file-at-mouse (ev)
  9572. "Open file link or URL at mouse."
  9573. (interactive "e")
  9574. (mouse-set-point ev)
  9575. (org-open-at-point 'in-emacs))
  9576. (defun org-open-at-mouse (ev)
  9577. "Open file link or URL at mouse.
  9578. See the docstring of `org-open-file' for details."
  9579. (interactive "e")
  9580. (mouse-set-point ev)
  9581. (when (eq major-mode 'org-agenda-mode)
  9582. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9583. (org-open-at-point))
  9584. (defvar org-window-config-before-follow-link nil
  9585. "The window configuration before following a link.
  9586. This is saved in case the need arises to restore it.")
  9587. ;;;###autoload
  9588. (defun org-open-at-point-global ()
  9589. "Follow a link or time-stamp like Org mode does.
  9590. This command can be called in any mode to follow an external link
  9591. or a time-stamp that has Org mode syntax. Its behavior is
  9592. undefined when called on internal links (e.g., fuzzy links).
  9593. Raise an error when there is nothing to follow. "
  9594. (interactive)
  9595. (cond ((org-in-regexp org-any-link-re)
  9596. (org-open-link-from-string (match-string-no-properties 0)))
  9597. ((or (org-in-regexp org-ts-regexp-both nil t)
  9598. (org-in-regexp org-tsr-regexp-both nil t))
  9599. (org-follow-timestamp-link))
  9600. (t (user-error "No link found"))))
  9601. ;;;###autoload
  9602. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9603. "Open a link in the string S, as if it was in Org mode."
  9604. (interactive "sLink: \nP")
  9605. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9606. (with-temp-buffer
  9607. (let ((org-inhibit-startup (not reference-buffer)))
  9608. (org-mode)
  9609. (insert s)
  9610. (goto-char (point-min))
  9611. (when reference-buffer
  9612. (setq org-link-abbrev-alist-local
  9613. (with-current-buffer reference-buffer
  9614. org-link-abbrev-alist-local)))
  9615. (org-open-at-point arg reference-buffer)))))
  9616. (defvar org-open-at-point-functions nil
  9617. "Hook that is run when following a link at point.
  9618. Functions in this hook must return t if they identify and follow
  9619. a link at point. If they don't find anything interesting at point,
  9620. they must return nil.")
  9621. (defvar org-link-search-inhibit-query nil)
  9622. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9623. (defun org--open-doi-link (path)
  9624. "Open a \"doi\" type link.
  9625. PATH is a the path to search for, as a string."
  9626. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9627. (defun org--open-elisp-link (path)
  9628. "Open a \"elisp\" type link.
  9629. PATH is the sexp to evaluate, as a string."
  9630. (let ((cmd path))
  9631. (if (or (and (org-string-nw-p
  9632. org-confirm-elisp-link-not-regexp)
  9633. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9634. (not org-confirm-elisp-link-function)
  9635. (funcall org-confirm-elisp-link-function
  9636. (format "Execute \"%s\" as elisp? "
  9637. (org-add-props cmd nil 'face 'org-warning))))
  9638. (message "%s => %s" cmd
  9639. (if (eq (string-to-char cmd) ?\()
  9640. (eval (read cmd))
  9641. (call-interactively (read cmd))))
  9642. (user-error "Abort"))))
  9643. (defun org--open-help-link (path)
  9644. "Open a \"help\" type link.
  9645. PATH is a symbol name, as a string."
  9646. (pcase (intern path)
  9647. ((and (pred fboundp) variable) (describe-function variable))
  9648. ((and (pred boundp) function) (describe-variable function))
  9649. (name (user-error "Unknown function or variable: %s" name))))
  9650. (defun org--open-shell-link (path)
  9651. "Open a \"shell\" type link.
  9652. PATH is the command to execute, as a string."
  9653. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9654. (cmd path))
  9655. (if (or (and (org-string-nw-p
  9656. org-confirm-shell-link-not-regexp)
  9657. (string-match
  9658. org-confirm-shell-link-not-regexp cmd))
  9659. (not org-confirm-shell-link-function)
  9660. (funcall org-confirm-shell-link-function
  9661. (format "Execute \"%s\" in shell? "
  9662. (org-add-props cmd nil
  9663. 'face 'org-warning))))
  9664. (progn
  9665. (message "Executing %s" cmd)
  9666. (shell-command cmd buf)
  9667. (when (featurep 'midnight)
  9668. (setq clean-buffer-list-kill-buffer-names
  9669. (cons (buffer-name buf)
  9670. clean-buffer-list-kill-buffer-names))))
  9671. (user-error "Abort"))))
  9672. (defun org-open-at-point (&optional arg reference-buffer)
  9673. "Open link, timestamp, footnote or tags at point.
  9674. When point is on a link, follow it. Normally, files will be
  9675. opened by an appropriate application. If the optional prefix
  9676. argument ARG is non-nil, Emacs will visit the file. With
  9677. a double prefix argument, try to open outside of Emacs, in the
  9678. application the system uses for this file type.
  9679. When point is on a timestamp, open the agenda at the day
  9680. specified.
  9681. When point is a footnote definition, move to the first reference
  9682. found. If it is on a reference, move to the associated
  9683. definition.
  9684. When point is on a headline, display a list of every link in the
  9685. entry, so it is possible to pick one, or all, of them. If point
  9686. is on a tag, call `org-tags-view' instead.
  9687. When optional argument REFERENCE-BUFFER is non-nil, it should
  9688. specify a buffer from where the link search should happen. This
  9689. is used internally by `org-open-link-from-string'.
  9690. On top of syntactically correct links, this function will open
  9691. the link at point in comments or comment blocks and the first
  9692. link in a property drawer line."
  9693. (interactive "P")
  9694. ;; On a code block, open block's results.
  9695. (unless (call-interactively 'org-babel-open-src-block-result)
  9696. (org-load-modules-maybe)
  9697. (setq org-window-config-before-follow-link (current-window-configuration))
  9698. (org-remove-occur-highlights nil nil t)
  9699. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9700. (let* ((context
  9701. ;; Only consider supported types, even if they are not
  9702. ;; the closest one.
  9703. (org-element-lineage
  9704. (org-element-context)
  9705. '(clock comment comment-block footnote-definition
  9706. footnote-reference headline inlinetask keyword link
  9707. node-property timestamp)
  9708. t))
  9709. (type (org-element-type context))
  9710. (value (org-element-property :value context)))
  9711. (cond
  9712. ((not context) (user-error "No link found"))
  9713. ;; Exception: open timestamps and links in properties
  9714. ;; drawers, keywords and comments.
  9715. ((memq type '(comment comment-block keyword node-property))
  9716. (call-interactively #'org-open-at-point-global))
  9717. ;; On a headline or an inlinetask, but not on a timestamp,
  9718. ;; a link, a footnote reference or on tags.
  9719. ((and (memq type '(headline inlinetask))
  9720. ;; Not on tags.
  9721. (progn (save-excursion (beginning-of-line)
  9722. (looking-at org-complex-heading-regexp))
  9723. (or (not (match-beginning 5))
  9724. (< (point) (match-beginning 5)))))
  9725. (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
  9726. (links (car data))
  9727. (links-end (cdr data)))
  9728. (if links
  9729. (dolist (link (if (stringp links) (list links) links))
  9730. (search-forward link nil links-end)
  9731. (goto-char (match-beginning 0))
  9732. (org-open-at-point))
  9733. (require 'org-attach)
  9734. (org-attach-reveal 'if-exists))))
  9735. ;; On a clock line, make sure point is on the timestamp
  9736. ;; before opening it.
  9737. ((and (eq type 'clock)
  9738. value
  9739. (>= (point) (org-element-property :begin value))
  9740. (<= (point) (org-element-property :end value)))
  9741. (org-follow-timestamp-link))
  9742. ;; Do nothing on white spaces after an object.
  9743. ((>= (point)
  9744. (save-excursion
  9745. (goto-char (org-element-property :end context))
  9746. (skip-chars-backward " \t")
  9747. (point)))
  9748. (user-error "No link found"))
  9749. ((eq type 'timestamp) (org-follow-timestamp-link))
  9750. ;; On tags within a headline or an inlinetask.
  9751. ((and (memq type '(headline inlinetask))
  9752. (progn (save-excursion (beginning-of-line)
  9753. (looking-at org-complex-heading-regexp))
  9754. (and (match-beginning 5)
  9755. (>= (point) (match-beginning 5)))))
  9756. (org-tags-view arg (substring (match-string 5) 0 -1)))
  9757. ((eq type 'link)
  9758. ;; When link is located within the description of another
  9759. ;; link (e.g., an inline image), always open the parent
  9760. ;; link.
  9761. (let* ((link (let ((up (org-element-property :parent context)))
  9762. (if (eq (org-element-type up) 'link) up context)))
  9763. (type (org-element-property :type link))
  9764. (path (org-link-unescape (org-element-property :path link))))
  9765. ;; Switch back to REFERENCE-BUFFER needed when called in
  9766. ;; a temporary buffer through `org-open-link-from-string'.
  9767. (with-current-buffer (or reference-buffer (current-buffer))
  9768. (cond
  9769. ((equal type "file")
  9770. (if (string-match "[*?{]" (file-name-nondirectory path))
  9771. (dired path)
  9772. ;; Look into `org-link-parameters' in order to find
  9773. ;; a DEDICATED-FUNCTION to open file. The function
  9774. ;; will be applied on raw link instead of parsed
  9775. ;; link due to the limitation in `org-add-link-type'
  9776. ;; ("open" function called with a single argument).
  9777. ;; If no such function is found, fallback to
  9778. ;; `org-open-file'.
  9779. (let* ((option (org-element-property :search-option link))
  9780. (app (org-element-property :application link))
  9781. (dedicated-function
  9782. (org-link-get-parameter
  9783. (if app (concat type "+" app) type)
  9784. :follow)))
  9785. (if dedicated-function
  9786. (funcall dedicated-function
  9787. (concat path
  9788. (and option (concat "::" option))))
  9789. (apply #'org-open-file
  9790. path
  9791. (cond (arg)
  9792. ((equal app "emacs") 'emacs)
  9793. ((equal app "sys") 'system))
  9794. (cond ((not option) nil)
  9795. ((string-match-p "\\`[0-9]+\\'" option)
  9796. (list (string-to-number option)))
  9797. (t (list nil
  9798. (org-link-unescape option)))))))))
  9799. ((functionp (org-link-get-parameter type :follow))
  9800. (funcall (org-link-get-parameter type :follow) path))
  9801. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9802. (unless (run-hook-with-args-until-success
  9803. 'org-open-link-functions path)
  9804. (if (not arg) (org-mark-ring-push)
  9805. (switch-to-buffer-other-window
  9806. (org-get-buffer-for-internal-link (current-buffer))))
  9807. (let ((destination
  9808. (org-with-wide-buffer
  9809. (if (equal type "radio")
  9810. (org-search-radio-target
  9811. (org-element-property :path link))
  9812. (org-link-search
  9813. (if (member type '("custom-id" "coderef"))
  9814. (org-element-property :raw-link link)
  9815. path)
  9816. ;; Prevent fuzzy links from matching
  9817. ;; themselves.
  9818. (and (equal type "fuzzy")
  9819. (+ 2 (org-element-property :begin link)))))
  9820. (point))))
  9821. (unless (and (<= (point-min) destination)
  9822. (>= (point-max) destination))
  9823. (widen))
  9824. (goto-char destination))))
  9825. (t (browse-url-at-point))))))
  9826. ;; On a footnote reference or at a footnote definition's label.
  9827. ((or (eq type 'footnote-reference)
  9828. (and (eq type 'footnote-definition)
  9829. (save-excursion
  9830. ;; Do not validate action when point is on the
  9831. ;; spaces right after the footnote label, in
  9832. ;; order to be on par with behaviour on links.
  9833. (skip-chars-forward " \t")
  9834. (let ((begin
  9835. (org-element-property :contents-begin context)))
  9836. (if begin (< (point) begin)
  9837. (= (org-element-property :post-affiliated context)
  9838. (line-beginning-position)))))))
  9839. (org-footnote-action))
  9840. (t (user-error "No link found")))))
  9841. (run-hook-with-args 'org-follow-link-hook)))
  9842. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9843. "Offer links in the current entry and return the selected link.
  9844. If there is only one link, return it.
  9845. If NTH is an integer, return the NTH link found.
  9846. If ZERO is a string, check also this string for a link, and if
  9847. there is one, return it."
  9848. (with-current-buffer buffer
  9849. (org-with-wide-buffer
  9850. (goto-char marker)
  9851. (let ((cnt ?0)
  9852. have-zero end links link c)
  9853. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9854. (push (match-string 0 zero) links)
  9855. (setq cnt (1- cnt) have-zero t))
  9856. (save-excursion
  9857. (org-back-to-heading t)
  9858. (setq end (save-excursion (outline-next-heading) (point)))
  9859. (while (re-search-forward org-any-link-re end t)
  9860. (push (match-string 0) links))
  9861. (setq links (org-uniquify (reverse links))))
  9862. (cond
  9863. ((null links)
  9864. (message "No links"))
  9865. ((equal (length links) 1)
  9866. (setq link (car links)))
  9867. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9868. (setq link (nth (if have-zero nth (1- nth)) links)))
  9869. (t ; we have to select a link
  9870. (save-excursion
  9871. (save-window-excursion
  9872. (delete-other-windows)
  9873. (with-output-to-temp-buffer "*Select Link*"
  9874. (dolist (l links)
  9875. (cond
  9876. ((not (string-match org-bracket-link-regexp l))
  9877. (princ (format "[%c] %s\n" (cl-incf cnt)
  9878. (org-unbracket-string "<" ">" l))))
  9879. ((match-end 3)
  9880. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9881. (match-string 3 l) (match-string 1 l))))
  9882. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9883. (match-string 1 l)))))))
  9884. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9885. (message "Select link to open, RET to open all:")
  9886. (setq c (read-char-exclusive))
  9887. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9888. (when (equal c ?q) (user-error "Abort"))
  9889. (if (equal c ?\C-m)
  9890. (setq link links)
  9891. (setq nth (- c ?0))
  9892. (when have-zero (setq nth (1+ nth)))
  9893. (unless (and (integerp nth) (>= (length links) nth))
  9894. (user-error "Invalid link selection"))
  9895. (setq link (nth (1- nth) links)))))
  9896. (cons link end)))))
  9897. ;; TODO: These functions are deprecated since `org-open-at-point'
  9898. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9899. (defun org-open-file-with-system (path)
  9900. "Open file at PATH using the system way of opening it."
  9901. (org-open-file path 'system))
  9902. (defun org-open-file-with-emacs (path)
  9903. "Open file at PATH in Emacs."
  9904. (org-open-file path 'emacs))
  9905. ;;; File search
  9906. (defvar org-create-file-search-functions nil
  9907. "List of functions to construct the right search string for a file link.
  9908. These functions are called in turn with point at the location to
  9909. which the link should point.
  9910. A function in the hook should first test if it would like to
  9911. handle this file type, for example by checking the `major-mode'
  9912. or the file extension. If it decides not to handle this file, it
  9913. should just return nil to give other functions a chance. If it
  9914. does handle the file, it must return the search string to be used
  9915. when following the link. The search string will be part of the
  9916. file link, given after a double colon, and `org-open-at-point'
  9917. will automatically search for it. If special measures must be
  9918. taken to make the search successful, another function should be
  9919. added to the companion hook `org-execute-file-search-functions',
  9920. which see.
  9921. A function in this hook may also use `setq' to set the variable
  9922. `description' to provide a suggestion for the descriptive text to
  9923. be used for this link when it gets inserted into an Org buffer
  9924. with \\[org-insert-link].")
  9925. (defvar org-execute-file-search-functions nil
  9926. "List of functions to execute a file search triggered by a link.
  9927. Functions added to this hook must accept a single argument, the
  9928. search string that was part of the file link, the part after the
  9929. double colon. The function must first check if it would like to
  9930. handle this search, for example by checking the `major-mode' or
  9931. the file extension. If it decides not to handle this search, it
  9932. should just return nil to give other functions a chance. If it
  9933. does handle the search, it must return a non-nil value to keep
  9934. other functions from trying.
  9935. Each function can access the current prefix argument through the
  9936. variable `current-prefix-arg'. Note that a single prefix is used
  9937. to force opening a link in Emacs, so it may be good to only use a
  9938. numeric or double prefix to guide the search function.
  9939. In case this is needed, a function in this hook can also restore
  9940. the window configuration before `org-open-at-point' was called using:
  9941. \(set-window-configuration org-window-config-before-follow-link)")
  9942. (defun org-search-radio-target (target)
  9943. "Search a radio target matching TARGET in current buffer.
  9944. White spaces are not significant."
  9945. (let ((re (format "<<<%s>>>"
  9946. (mapconcat #'regexp-quote
  9947. (org-split-string target "[ \t\n]+")
  9948. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9949. (origin (point)))
  9950. (goto-char (point-min))
  9951. (catch :radio-match
  9952. (while (re-search-forward re nil t)
  9953. (backward-char)
  9954. (let ((object (org-element-context)))
  9955. (when (eq (org-element-type object) 'radio-target)
  9956. (goto-char (org-element-property :begin object))
  9957. (org-show-context 'link-search)
  9958. (throw :radio-match nil))))
  9959. (goto-char origin)
  9960. (user-error "No match for radio target: %s" target))))
  9961. (defun org-link-search (s &optional avoid-pos stealth)
  9962. "Search for a search string S.
  9963. If S starts with \"#\", it triggers a custom ID search.
  9964. If S is enclosed within parenthesis, it initiates a coderef
  9965. search.
  9966. If S is surrounded by forward slashes, it is interpreted as
  9967. a regular expression. In Org mode files, this will create an
  9968. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9969. to list matches. If the current buffer is in `dired-mode', grep
  9970. will be used to search in all files.
  9971. When AVOID-POS is given, ignore matches near that position.
  9972. When optional argument STEALTH is non-nil, do not modify
  9973. visibility around point, thus ignoring `org-show-context-detail'
  9974. variable.
  9975. Search is case-insensitive and ignores white spaces. Return type
  9976. of matched result, which is either `dedicated' or `fuzzy'."
  9977. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9978. (let* ((case-fold-search t)
  9979. (origin (point))
  9980. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9981. (words (org-split-string s "[ \t\n]+"))
  9982. (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
  9983. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9984. type)
  9985. (cond
  9986. ;; Check if there are any special search functions.
  9987. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9988. ((eq (string-to-char s) ?#)
  9989. ;; Look for a custom ID S if S starts with "#".
  9990. (let* ((id (substring normalized 1))
  9991. (match (org-find-property "CUSTOM_ID" id)))
  9992. (if match (progn (goto-char match) (setf type 'dedicated))
  9993. (error "No match for custom ID: %s" id))))
  9994. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9995. ;; Look for coderef targets if S is enclosed within parenthesis.
  9996. (let ((coderef (match-string-no-properties 1 normalized))
  9997. (re (substring s-single-re 1 -1)))
  9998. (goto-char (point-min))
  9999. (catch :coderef-match
  10000. (while (re-search-forward re nil t)
  10001. (let ((element (org-element-at-point)))
  10002. (when (and (memq (org-element-type element)
  10003. '(example-block src-block))
  10004. ;; Build proper regexp according to current
  10005. ;; block's label format.
  10006. (let ((label-fmt
  10007. (regexp-quote
  10008. (or (org-element-property :label-fmt element)
  10009. org-coderef-label-format))))
  10010. (save-excursion
  10011. (beginning-of-line)
  10012. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  10013. (format label-fmt coderef))))))
  10014. (setq type 'dedicated)
  10015. (goto-char (match-beginning 1))
  10016. (throw :coderef-match nil))))
  10017. (goto-char origin)
  10018. (error "No match for coderef: %s" coderef))))
  10019. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  10020. ;; Look for a regular expression.
  10021. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  10022. (match-string 1 s)))
  10023. ;; Fuzzy links.
  10024. (t
  10025. (let ((starred (eq (string-to-char normalized) ?*)))
  10026. (cond
  10027. ;; Look for targets, only if not in a headline search.
  10028. ((and (not starred)
  10029. (let ((target (format "<<%s>>" s-multi-re)))
  10030. (catch :target-match
  10031. (goto-char (point-min))
  10032. (while (re-search-forward target nil t)
  10033. (backward-char)
  10034. (let ((context (org-element-context)))
  10035. (when (eq (org-element-type context) 'target)
  10036. (setq type 'dedicated)
  10037. (goto-char (org-element-property :begin context))
  10038. (throw :target-match t))))
  10039. nil))))
  10040. ;; Look for elements named after S, only if not in a headline
  10041. ;; search.
  10042. ((and (not starred)
  10043. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  10044. (catch :name-match
  10045. (goto-char (point-min))
  10046. (while (re-search-forward name nil t)
  10047. (let ((element (org-element-at-point)))
  10048. (when (equal (org-split-string
  10049. (org-element-property :name element)
  10050. "[ \t]+")
  10051. words)
  10052. (setq type 'dedicated)
  10053. (beginning-of-line)
  10054. (throw :name-match t))))
  10055. nil))))
  10056. ;; Regular text search. Prefer headlines in Org mode
  10057. ;; buffers.
  10058. ((and (derived-mode-p 'org-mode)
  10059. (let* ((wspace "[ \t]")
  10060. (wspaceopt (concat wspace "*"))
  10061. (cookie (concat "\\(?:"
  10062. wspaceopt
  10063. "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
  10064. wspaceopt
  10065. "\\)"))
  10066. (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
  10067. (re (concat
  10068. org-outline-regexp-bol
  10069. "\\(?:" org-todo-regexp "[ \t]+\\)?"
  10070. "\\(?:\\[#.\\][ \t]+\\)?"
  10071. "\\(?:" org-comment-string "[ \t]+\\)?"
  10072. sep "?"
  10073. (let ((title (mapconcat #'regexp-quote
  10074. words
  10075. sep)))
  10076. (if starred (substring title 1) title))
  10077. sep "?"
  10078. "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?"
  10079. "[ \t]*$")))
  10080. (goto-char (point-min))
  10081. (re-search-forward re nil t)))
  10082. (goto-char (match-beginning 0))
  10083. (setq type 'dedicated))
  10084. ;; Offer to create non-existent headline depending on
  10085. ;; `org-link-search-must-match-exact-headline'.
  10086. ((and (derived-mode-p 'org-mode)
  10087. (not org-link-search-inhibit-query)
  10088. (eq org-link-search-must-match-exact-headline 'query-to-create)
  10089. (yes-or-no-p "No match - create this as a new heading? "))
  10090. (goto-char (point-max))
  10091. (unless (bolp) (newline))
  10092. (org-insert-heading nil t t)
  10093. (insert s "\n")
  10094. (beginning-of-line 0))
  10095. ;; Only headlines are looked after. No need to process
  10096. ;; further: throw an error.
  10097. ((and (derived-mode-p 'org-mode)
  10098. (or starred org-link-search-must-match-exact-headline))
  10099. (goto-char origin)
  10100. (error "No match for fuzzy expression: %s" normalized))
  10101. ;; Regular text search.
  10102. ((catch :fuzzy-match
  10103. (goto-char (point-min))
  10104. (while (re-search-forward s-multi-re nil t)
  10105. ;; Skip match if it contains AVOID-POS or it is included
  10106. ;; in a link with a description but outside the
  10107. ;; description.
  10108. (unless (or (and avoid-pos
  10109. (<= (match-beginning 0) avoid-pos)
  10110. (> (match-end 0) avoid-pos))
  10111. (and (save-match-data
  10112. (org-in-regexp org-bracket-link-regexp))
  10113. (match-beginning 3)
  10114. (or (> (match-beginning 3) (point))
  10115. (<= (match-end 3) (point)))
  10116. (org-element-lineage
  10117. (save-match-data (org-element-context))
  10118. '(link) t)))
  10119. (goto-char (match-beginning 0))
  10120. (setq type 'fuzzy)
  10121. (throw :fuzzy-match t)))
  10122. nil))
  10123. ;; All failed. Throw an error.
  10124. (t (goto-char origin)
  10125. (error "No match for fuzzy expression: %s" normalized))))))
  10126. ;; Disclose surroundings of match, if appropriate.
  10127. (when (and (derived-mode-p 'org-mode) (not stealth))
  10128. (org-show-context 'link-search))
  10129. type))
  10130. (defun org-get-buffer-for-internal-link (buffer)
  10131. "Return a buffer to be used for displaying the link target of internal links."
  10132. (cond
  10133. ((not org-display-internal-link-with-indirect-buffer)
  10134. buffer)
  10135. ((string-suffix-p "(Clone)" (buffer-name buffer))
  10136. (message "Buffer is already a clone, not making another one")
  10137. ;; we also do not modify visibility in this case
  10138. buffer)
  10139. (t ; make a new indirect buffer for displaying the link
  10140. (let* ((bn (buffer-name buffer))
  10141. (ibn (concat bn "(Clone)"))
  10142. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  10143. (with-current-buffer ib (org-overview))
  10144. ib))))
  10145. (defun org-do-occur (regexp &optional cleanup)
  10146. "Call the Emacs command `occur'.
  10147. If CLEANUP is non-nil, remove the printout of the regular expression
  10148. in the *Occur* buffer. This is useful if the regex is long and not useful
  10149. to read."
  10150. (occur regexp)
  10151. (when cleanup
  10152. (let ((cwin (selected-window)) win beg end)
  10153. (when (setq win (get-buffer-window "*Occur*"))
  10154. (select-window win))
  10155. (goto-char (point-min))
  10156. (when (re-search-forward "match[a-z]+" nil t)
  10157. (setq beg (match-end 0))
  10158. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  10159. (setq end (1- (match-beginning 0)))))
  10160. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  10161. (goto-char (point-min))
  10162. (select-window cwin))))
  10163. ;;; The mark ring for links jumps
  10164. (defvar org-mark-ring nil
  10165. "Mark ring for positions before jumps in Org mode.")
  10166. (defvar org-mark-ring-last-goto nil
  10167. "Last position in the mark ring used to go back.")
  10168. ;; Fill and close the ring
  10169. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  10170. (dotimes (_ org-mark-ring-length)
  10171. (push (make-marker) org-mark-ring))
  10172. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  10173. org-mark-ring)
  10174. (defun org-mark-ring-push (&optional pos buffer)
  10175. "Put the current position or POS into the mark ring and rotate it."
  10176. (interactive)
  10177. (setq pos (or pos (point)))
  10178. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  10179. (move-marker (car org-mark-ring)
  10180. (or pos (point))
  10181. (or buffer (current-buffer)))
  10182. (message "%s"
  10183. (substitute-command-keys
  10184. "Position saved to mark ring, go back with \
  10185. `\\[org-mark-ring-goto]'.")))
  10186. (defun org-mark-ring-goto (&optional n)
  10187. "Jump to the previous position in the mark ring.
  10188. With prefix arg N, jump back that many stored positions. When
  10189. called several times in succession, walk through the entire ring.
  10190. Org mode commands jumping to a different position in the current file,
  10191. or to another Org file, automatically push the old position onto the ring."
  10192. (interactive "p")
  10193. (let (p m)
  10194. (if (eq last-command this-command)
  10195. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  10196. (setq p org-mark-ring))
  10197. (setq org-mark-ring-last-goto p)
  10198. (setq m (car p))
  10199. (pop-to-buffer-same-window (marker-buffer m))
  10200. (goto-char m)
  10201. (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  10202. (defun org-add-angle-brackets (s)
  10203. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  10204. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  10205. s)
  10206. ;;; Following specific links
  10207. (defvar org-agenda-buffer-tmp-name)
  10208. (defvar org-agenda-start-on-weekday)
  10209. (defun org-follow-timestamp-link ()
  10210. "Open an agenda view for the time-stamp date/range at point."
  10211. (cond
  10212. ((org-at-date-range-p t)
  10213. (let ((org-agenda-start-on-weekday)
  10214. (t1 (match-string 1))
  10215. (t2 (match-string 2)) tt1 tt2)
  10216. (setq tt1 (time-to-days (org-time-string-to-time t1))
  10217. tt2 (time-to-days (org-time-string-to-time t2)))
  10218. (let ((org-agenda-buffer-tmp-name
  10219. (format "*Org Agenda(a:%s)"
  10220. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  10221. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  10222. ((org-at-timestamp-p t)
  10223. (let ((org-agenda-buffer-tmp-name
  10224. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  10225. (org-agenda-list nil (time-to-days (org-time-string-to-time
  10226. (substring (match-string 1) 0 10)))
  10227. 1)))
  10228. (t (error "This should not happen"))))
  10229. ;;; Following file links
  10230. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  10231. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  10232. (declare-function mailcap-mime-info
  10233. "mailcap" (string &optional request no-decode))
  10234. (defvar org-wait nil)
  10235. (defun org-open-file (path &optional in-emacs line search)
  10236. "Open the file at PATH.
  10237. First, this expands any special file name abbreviations. Then the
  10238. configuration variable `org-file-apps' is checked if it contains an
  10239. entry for this file type, and if yes, the corresponding command is launched.
  10240. If no application is found, Emacs simply visits the file.
  10241. With optional prefix argument IN-EMACS, Emacs will visit the file.
  10242. With a double \\[universal-argument] \\[universal-argument] \
  10243. prefix arg, Org tries to avoid opening in Emacs
  10244. and to use an external application to visit the file.
  10245. Optional LINE specifies a line to go to, optional SEARCH a string
  10246. to search for. If LINE or SEARCH is given, the file will be
  10247. opened in Emacs, unless an entry from org-file-apps that makes
  10248. use of groups in a regexp matches.
  10249. If you want to change the way frames are used when following a
  10250. link, please customize `org-link-frame-setup'.
  10251. If the file does not exist, an error is thrown."
  10252. (let* ((file (if (equal path "")
  10253. buffer-file-name
  10254. (substitute-in-file-name (expand-file-name path))))
  10255. (file-apps (append org-file-apps (org-default-apps)))
  10256. (apps (cl-remove-if
  10257. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10258. (apps-dlink (cl-remove-if-not
  10259. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10260. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  10261. (dirp (unless remp (file-directory-p file)))
  10262. (file (if (and dirp org-open-directory-means-index-dot-org)
  10263. (concat (file-name-as-directory file) "index.org")
  10264. file))
  10265. (a-m-a-p (assq 'auto-mode apps))
  10266. (dfile (downcase file))
  10267. ;; Reconstruct the original link from the PATH, LINE and
  10268. ;; SEARCH args.
  10269. (link (cond (line (concat file "::" (number-to-string line)))
  10270. (search (concat file "::" search))
  10271. (t file)))
  10272. (dlink (downcase link))
  10273. (old-buffer (current-buffer))
  10274. (old-pos (point))
  10275. (old-mode major-mode)
  10276. (ext
  10277. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  10278. (match-string 1 dfile)))
  10279. cmd link-match-data)
  10280. (cond
  10281. ((member in-emacs '((16) system))
  10282. (setq cmd (cdr (assq 'system apps))))
  10283. (in-emacs (setq cmd 'emacs))
  10284. (t
  10285. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  10286. (and dirp (cdr (assq 'directory apps)))
  10287. ;; First, try matching against apps-dlink if we
  10288. ;; get a match here, store the match data for
  10289. ;; later.
  10290. (let ((match (assoc-default dlink apps-dlink
  10291. 'string-match)))
  10292. (if match
  10293. (progn (setq link-match-data (match-data))
  10294. match)
  10295. (progn (setq in-emacs (or in-emacs line search))
  10296. nil))) ; if we have no match in apps-dlink,
  10297. ; always open the file in emacs if line or search
  10298. ; is given (for backwards compatibility)
  10299. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  10300. 'string-match)
  10301. (cdr (assoc ext apps))
  10302. (cdr (assq t apps))))))
  10303. (when (eq cmd 'system)
  10304. (setq cmd (cdr (assq 'system apps))))
  10305. (when (eq cmd 'default)
  10306. (setq cmd (cdr (assoc t apps))))
  10307. (when (eq cmd 'mailcap)
  10308. (require 'mailcap)
  10309. (mailcap-parse-mailcaps)
  10310. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  10311. (command (mailcap-mime-info mime-type)))
  10312. (if (stringp command)
  10313. (setq cmd command)
  10314. (setq cmd 'emacs))))
  10315. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  10316. (not (file-exists-p file))
  10317. (not org-open-non-existing-files))
  10318. (user-error "No such file: %s" file))
  10319. (cond
  10320. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  10321. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  10322. (while (string-match "['\"]%s['\"]" cmd)
  10323. (setq cmd (replace-match "%s" t t cmd)))
  10324. (setq cmd (replace-regexp-in-string
  10325. "%s"
  10326. (shell-quote-argument (convert-standard-filename file))
  10327. cmd
  10328. nil t))
  10329. ;; Replace "%1", "%2" etc. in command with group matches from regex
  10330. (save-match-data
  10331. (let ((match-index 1)
  10332. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  10333. (set-match-data link-match-data)
  10334. (while (<= match-index number-of-groups)
  10335. (let ((regex (concat "%" (number-to-string match-index)))
  10336. (replace-with (match-string match-index dlink)))
  10337. (while (string-match regex cmd)
  10338. (setq cmd (replace-match replace-with t t cmd))))
  10339. (setq match-index (+ match-index 1)))))
  10340. (save-window-excursion
  10341. (message "Running %s...done" cmd)
  10342. (start-process-shell-command cmd nil cmd)
  10343. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  10344. ((or (stringp cmd)
  10345. (eq cmd 'emacs))
  10346. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  10347. (widen)
  10348. (cond (line (org-goto-line line)
  10349. (when (derived-mode-p 'org-mode) (org-reveal)))
  10350. (search (org-link-search search))))
  10351. ((functionp cmd)
  10352. (save-match-data
  10353. (set-match-data link-match-data)
  10354. (condition-case nil
  10355. (funcall cmd file link)
  10356. ;; FIXME: Remove this check when most default installations
  10357. ;; of Emacs have at least Org 9.0.
  10358. ((debug wrong-number-of-arguments wrong-type-argument
  10359. invalid-function)
  10360. (user-error "Please see Org News for version 9.0 about \
  10361. `org-file-apps'--Lisp error: %S" cmd)))))
  10362. ((consp cmd)
  10363. ;; FIXME: Remove this check when most default installations of
  10364. ;; Emacs have at least Org 9.0.
  10365. ;; Heads-up instead of silently fall back to
  10366. ;; `org-link-frame-setup' for an old usage of `org-file-apps'
  10367. ;; with sexp instead of a function for `cmd'.
  10368. (user-error "Please see Org News for version 9.0 about \
  10369. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  10370. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  10371. (and (derived-mode-p 'org-mode)
  10372. (eq old-mode 'org-mode)
  10373. (or (not (eq old-buffer (current-buffer)))
  10374. (not (eq old-pos (point))))
  10375. (org-mark-ring-push old-pos old-buffer))))
  10376. (defun org-file-apps-entry-match-against-dlink-p (entry)
  10377. "This function returns non-nil if `entry' uses a regular
  10378. expression which should be matched against the whole link by
  10379. org-open-file.
  10380. It assumes that is the case when the entry uses a regular
  10381. expression which has at least one grouping construct and the
  10382. action is either a lisp form or a command string containing
  10383. `%1', i.e. using at least one subexpression match as a
  10384. parameter."
  10385. (let ((selector (car entry))
  10386. (action (cdr entry)))
  10387. (if (stringp selector)
  10388. (and (> (regexp-opt-depth selector) 0)
  10389. (or (and (stringp action)
  10390. (string-match "%[0-9]" action))
  10391. (consp action)))
  10392. nil)))
  10393. (defun org-default-apps ()
  10394. "Return the default applications for this operating system."
  10395. (cond
  10396. ((eq system-type 'darwin)
  10397. org-file-apps-defaults-macosx)
  10398. ((eq system-type 'windows-nt)
  10399. org-file-apps-defaults-windowsnt)
  10400. (t org-file-apps-defaults-gnu)))
  10401. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  10402. "Convert extensions to regular expressions in the cars of LIST.
  10403. Also, weed out any non-string entries, because the return value is used
  10404. only for regexp matching.
  10405. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  10406. point to the symbol `emacs', indicating that the file should
  10407. be opened in Emacs."
  10408. (append
  10409. (delq nil
  10410. (mapcar (lambda (x)
  10411. (unless (not (stringp (car x)))
  10412. (if (string-match "\\W" (car x))
  10413. x
  10414. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  10415. list))
  10416. (when add-auto-mode
  10417. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  10418. (defvar ange-ftp-name-format)
  10419. (defun org-file-remote-p (file)
  10420. "Test whether FILE specifies a location on a remote system.
  10421. Return non-nil if the location is indeed remote.
  10422. For example, the filename \"/user@host:/foo\" specifies a location
  10423. on the system \"/user@host:\"."
  10424. (cond ((fboundp 'file-remote-p)
  10425. (file-remote-p file))
  10426. ((fboundp 'tramp-handle-file-remote-p)
  10427. (tramp-handle-file-remote-p file))
  10428. ((and (boundp 'ange-ftp-name-format)
  10429. (string-match (car ange-ftp-name-format) file))
  10430. t)))
  10431. ;;;; Refiling
  10432. (defun org-get-org-file ()
  10433. "Read a filename, with default directory `org-directory'."
  10434. (let ((default (or org-default-notes-file remember-data-file)))
  10435. (read-file-name (format "File name [%s]: " default)
  10436. (file-name-as-directory org-directory)
  10437. default)))
  10438. (defun org-notes-order-reversed-p ()
  10439. "Check if the current file should receive notes in reversed order."
  10440. (cond
  10441. ((not org-reverse-note-order) nil)
  10442. ((eq t org-reverse-note-order) t)
  10443. ((not (listp org-reverse-note-order)) nil)
  10444. (t (catch 'exit
  10445. (dolist (entry org-reverse-note-order)
  10446. (when (string-match (car entry) buffer-file-name)
  10447. (throw 'exit (cdr entry))))))))
  10448. (defvar org-refile-target-table nil
  10449. "The list of refile targets, created by `org-refile'.")
  10450. (defvar org-agenda-new-buffers nil
  10451. "Buffers created to visit agenda files.")
  10452. (defvar org-refile-cache nil
  10453. "Cache for refile targets.")
  10454. (defvar org-refile-markers nil
  10455. "All the markers used for caching refile locations.")
  10456. (defun org-refile-marker (pos)
  10457. "Get a new refile marker, but only if caching is in use."
  10458. (if (not org-refile-use-cache)
  10459. pos
  10460. (let ((m (make-marker)))
  10461. (move-marker m pos)
  10462. (push m org-refile-markers)
  10463. m)))
  10464. (defun org-refile-cache-clear ()
  10465. "Clear the refile cache and disable all the markers."
  10466. (dolist (m org-refile-markers) (move-marker m nil))
  10467. (setq org-refile-markers nil)
  10468. (setq org-refile-cache nil)
  10469. (message "Refile cache has been cleared"))
  10470. (defun org-refile-cache-check-set (set)
  10471. "Check if all the markers in the cache still have live buffers."
  10472. (let (marker)
  10473. (catch 'exit
  10474. (while (and set (setq marker (nth 3 (pop set))))
  10475. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  10476. (when (and marker (null (marker-buffer marker)))
  10477. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  10478. (sit-for 3)
  10479. (throw 'exit nil)))
  10480. t)))
  10481. (defun org-refile-cache-put (set &rest identifiers)
  10482. "Push the refile targets SET into the cache, under IDENTIFIERS."
  10483. (let* ((key (sha1 (prin1-to-string identifiers)))
  10484. (entry (assoc key org-refile-cache)))
  10485. (if entry
  10486. (setcdr entry set)
  10487. (push (cons key set) org-refile-cache))))
  10488. (defun org-refile-cache-get (&rest identifiers)
  10489. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  10490. (cond
  10491. ((not org-refile-cache) nil)
  10492. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  10493. (t
  10494. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  10495. org-refile-cache))))
  10496. (and set (org-refile-cache-check-set set) set)))))
  10497. (defvar org-outline-path-cache nil
  10498. "Alist between buffer positions and outline paths.
  10499. It value is an alist (POSITION . PATH) where POSITION is the
  10500. buffer position at the beginning of an entry and PATH is a list
  10501. of strings describing the outline path for that entry, in reverse
  10502. order.")
  10503. (defun org-refile-get-targets (&optional default-buffer)
  10504. "Produce a table with refile targets."
  10505. (let ((case-fold-search nil)
  10506. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10507. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10508. targets tgs files desc descre)
  10509. (message "Getting targets...")
  10510. (with-current-buffer (or default-buffer (current-buffer))
  10511. (dolist (entry entries)
  10512. (setq files (car entry) desc (cdr entry))
  10513. (cond
  10514. ((null files) (setq files (list (current-buffer))))
  10515. ((eq files 'org-agenda-files)
  10516. (setq files (org-agenda-files 'unrestricted)))
  10517. ((and (symbolp files) (fboundp files))
  10518. (setq files (funcall files)))
  10519. ((and (symbolp files) (boundp files))
  10520. (setq files (symbol-value files))))
  10521. (when (stringp files) (setq files (list files)))
  10522. (cond
  10523. ((eq (car desc) :tag)
  10524. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10525. ((eq (car desc) :todo)
  10526. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10527. ((eq (car desc) :regexp)
  10528. (setq descre (cdr desc)))
  10529. ((eq (car desc) :level)
  10530. (setq descre (concat "^\\*\\{" (number-to-string
  10531. (if org-odd-levels-only
  10532. (1- (* 2 (cdr desc)))
  10533. (cdr desc)))
  10534. "\\}[ \t]")))
  10535. ((eq (car desc) :maxlevel)
  10536. (setq descre (concat "^\\*\\{1," (number-to-string
  10537. (if org-odd-levels-only
  10538. (1- (* 2 (cdr desc)))
  10539. (cdr desc)))
  10540. "\\}[ \t]")))
  10541. (t (error "Bad refiling target description %s" desc)))
  10542. (dolist (f files)
  10543. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  10544. (or
  10545. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10546. (progn
  10547. (when (bufferp f)
  10548. (setq f (buffer-file-name (buffer-base-buffer f))))
  10549. (setq f (and f (expand-file-name f)))
  10550. (when (eq org-refile-use-outline-path 'file)
  10551. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10552. (org-with-wide-buffer
  10553. (goto-char (point-min))
  10554. (setq org-outline-path-cache nil)
  10555. (while (re-search-forward descre nil t)
  10556. (beginning-of-line)
  10557. (looking-at org-complex-heading-regexp)
  10558. (let ((begin (point))
  10559. (heading (match-string-no-properties 4)))
  10560. (unless (or (and
  10561. org-refile-target-verify-function
  10562. (not
  10563. (funcall org-refile-target-verify-function)))
  10564. (not heading))
  10565. (let ((re (format org-complex-heading-regexp-format
  10566. (regexp-quote heading)))
  10567. (target
  10568. (if (not org-refile-use-outline-path) heading
  10569. (mapconcat
  10570. #'org-protect-slash
  10571. (append
  10572. (pcase org-refile-use-outline-path
  10573. (`file (list (file-name-nondirectory
  10574. (buffer-file-name
  10575. (buffer-base-buffer)))))
  10576. (`full-file-path
  10577. (list (buffer-file-name
  10578. (buffer-base-buffer))))
  10579. (_ nil))
  10580. (org-get-outline-path t t))
  10581. "/"))))
  10582. (push (list target f re (org-refile-marker (point)))
  10583. tgs)))
  10584. (when (= (point) begin)
  10585. ;; Verification function has not moved point.
  10586. (end-of-line)))))))
  10587. (when org-refile-use-cache
  10588. (org-refile-cache-put tgs (buffer-file-name) descre))
  10589. (setq targets (append tgs targets))))))
  10590. (message "Getting targets...done")
  10591. (nreverse targets)))
  10592. (defun org-protect-slash (s)
  10593. (replace-regexp-in-string "/" "\\/" s nil t))
  10594. (defun org--get-outline-path-1 (&optional use-cache)
  10595. "Return outline path to current headline.
  10596. Outline path is a list of strings, in reverse order. When
  10597. optional argument USE-CACHE is non-nil, make use of a cache. See
  10598. `org-get-outline-path' for details.
  10599. Assume buffer is widened and point is on a headline."
  10600. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10601. (let ((p (point))
  10602. (heading (progn
  10603. (looking-at org-complex-heading-regexp)
  10604. (if (not (match-end 4)) ""
  10605. ;; Remove statistics cookies.
  10606. (org-trim
  10607. (org-link-display-format
  10608. (replace-regexp-in-string
  10609. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10610. (match-string-no-properties 4))))))))
  10611. (if (org-up-heading-safe)
  10612. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10613. (when use-cache
  10614. (push (cons p path) org-outline-path-cache))
  10615. path)
  10616. ;; This is a new root node. Since we assume we are moving
  10617. ;; forward, we can drop previous cache so as to limit number
  10618. ;; of associations there.
  10619. (let ((path (list heading)))
  10620. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10621. path)))))
  10622. (defun org-get-outline-path (&optional with-self use-cache)
  10623. "Return the outline path to the current entry.
  10624. An outline path is a list of ancestors for current headline, as
  10625. a list of strings. Statistics cookies are removed and links are
  10626. replaced with their description, if any, or their path otherwise.
  10627. When optional argument WITH-SELF is non-nil, the path also
  10628. includes the current headline.
  10629. When optional argument USE-CACHE is non-nil, cache outline paths
  10630. between calls to this function so as to avoid backtracking. This
  10631. argument is useful when planning to find more than one outline
  10632. path in the same document. In that case, there are two
  10633. conditions to satisfy:
  10634. - `org-outline-path-cache' is set to nil before starting the
  10635. process;
  10636. - outline paths are computed by increasing buffer positions."
  10637. (org-with-wide-buffer
  10638. (and (or (and with-self (org-back-to-heading t))
  10639. (org-up-heading-safe))
  10640. (reverse (org--get-outline-path-1 use-cache)))))
  10641. (defun org-format-outline-path (path &optional width prefix separator)
  10642. "Format the outline path PATH for display.
  10643. WIDTH is the maximum number of characters that is available.
  10644. PREFIX is a prefix to be included in the returned string,
  10645. such as the file name.
  10646. SEPARATOR is inserted between the different parts of the path,
  10647. the default is \"/\"."
  10648. (setq width (or width 79))
  10649. (setq path (delq nil path))
  10650. (unless (> width 0)
  10651. (user-error "Argument `width' must be positive"))
  10652. (setq separator (or separator "/"))
  10653. (let* ((org-odd-levels-only nil)
  10654. (fpath (concat
  10655. prefix (and prefix path separator)
  10656. (mapconcat
  10657. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10658. (cl-loop for head in path
  10659. for n from 0
  10660. collect (org-add-props
  10661. head nil 'face
  10662. (nth (% n org-n-level-faces) org-level-faces)))
  10663. separator))))
  10664. (when (> (length fpath) width)
  10665. (if (< width 7)
  10666. ;; It's unlikely that `width' will be this small, but don't
  10667. ;; waste characters by adding ".." if it is.
  10668. (setq fpath (substring fpath 0 width))
  10669. (setf (substring fpath (- width 2)) "..")))
  10670. fpath))
  10671. (defun org-display-outline-path (&optional file current separator just-return-string)
  10672. "Display the current outline path in the echo area.
  10673. If FILE is non-nil, prepend the output with the file name.
  10674. If CURRENT is non-nil, append the current heading to the output.
  10675. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10676. the different parts of the path and defaults to \"/\".
  10677. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10678. (interactive "P")
  10679. (let* (case-fold-search
  10680. (bfn (buffer-file-name (buffer-base-buffer)))
  10681. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10682. res)
  10683. (when current (setq path (append path
  10684. (save-excursion
  10685. (org-back-to-heading t)
  10686. (when (looking-at org-complex-heading-regexp)
  10687. (list (match-string 4)))))))
  10688. (setq res
  10689. (org-format-outline-path
  10690. path
  10691. (1- (frame-width))
  10692. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10693. separator))
  10694. (if just-return-string
  10695. (org-no-properties res)
  10696. (org-unlogged-message "%s" res))))
  10697. (defvar org-refile-history nil
  10698. "History for refiling operations.")
  10699. (defvar org-after-refile-insert-hook nil
  10700. "Hook run after `org-refile' has inserted its stuff at the new location.
  10701. Note that this is still *before* the stuff will be removed from
  10702. the *old* location.")
  10703. (defvar org-capture-last-stored-marker)
  10704. (defvar org-refile-keep nil
  10705. "Non-nil means `org-refile' will copy instead of refile.")
  10706. (defun org-copy ()
  10707. "Like `org-refile', but copy."
  10708. (interactive)
  10709. (let ((org-refile-keep t))
  10710. (funcall 'org-refile nil nil nil "Copy")))
  10711. (defun org-refile (&optional arg default-buffer rfloc msg)
  10712. "Move the entry or entries at point to another heading.
  10713. The list of target headings is compiled using the information in
  10714. `org-refile-targets', which see.
  10715. At the target location, the entry is filed as a subitem of the
  10716. target heading. Depending on `org-reverse-note-order', the new
  10717. subitem will either be the first or the last subitem.
  10718. If there is an active region, all entries in that region will be
  10719. refiled. However, the region must fulfill the requirement that
  10720. the first heading sets the top-level of the moved text.
  10721. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10722. location
  10723. and not actually move anything.
  10724. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10725. location where the last
  10726. refiling operation has put the subtree.
  10727. With a numeric prefix argument of `2', refile to the running clock.
  10728. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10729. being set to t and copy to the target location, don't move it.
  10730. Beware that keeping refiled entries may result in duplicated ID
  10731. properties.
  10732. RFLOC can be a refile location obtained in a different way.
  10733. MSG is a string to replace \"Refile\" in the default prompt with
  10734. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10735. See also `org-refile-use-outline-path'.
  10736. If you are using target caching (see `org-refile-use-cache'), you
  10737. have to clear the target cache in order to find new targets.
  10738. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10739. prefix argument (`C-u C-u C-u C-c C-w')."
  10740. (interactive "P")
  10741. (if (member arg '(0 (64)))
  10742. (org-refile-cache-clear)
  10743. (let* ((actionmsg (cond (msg msg)
  10744. ((equal arg 3) "Refile (and keep)")
  10745. (t "Refile")))
  10746. (regionp (org-region-active-p))
  10747. (region-start (and regionp (region-beginning)))
  10748. (region-end (and regionp (region-end)))
  10749. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10750. pos it nbuf file level reversed)
  10751. (setq last-command nil)
  10752. (when regionp
  10753. (goto-char region-start)
  10754. (or (bolp) (goto-char (point-at-bol)))
  10755. (setq region-start (point))
  10756. (unless (or (org-kill-is-subtree-p
  10757. (buffer-substring region-start region-end))
  10758. (prog1 org-refile-active-region-within-subtree
  10759. (let ((s (point-at-eol)))
  10760. (org-toggle-heading)
  10761. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10762. (user-error "The region is not a (sequence of) subtree(s)")))
  10763. (if (equal arg '(16))
  10764. (org-refile-goto-last-stored)
  10765. (when (or
  10766. (and (equal arg 2)
  10767. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10768. (prog1
  10769. (setq it (list (or org-clock-heading "running clock")
  10770. (buffer-file-name
  10771. (marker-buffer org-clock-hd-marker))
  10772. ""
  10773. (marker-position org-clock-hd-marker)))
  10774. (setq arg nil)))
  10775. (setq it
  10776. (or rfloc
  10777. (let (heading-text)
  10778. (save-excursion
  10779. (unless (and arg (listp arg))
  10780. (org-back-to-heading t)
  10781. (setq heading-text
  10782. (replace-regexp-in-string
  10783. org-bracket-link-regexp
  10784. "\\3"
  10785. (or (nth 4 (org-heading-components))
  10786. ""))))
  10787. (org-refile-get-location
  10788. (cond ((and arg (listp arg)) "Goto")
  10789. (regionp (concat actionmsg " region to"))
  10790. (t (concat actionmsg " subtree \""
  10791. heading-text "\" to")))
  10792. default-buffer
  10793. (and (not (equal '(4) arg))
  10794. org-refile-allow-creating-parent-nodes)))))))
  10795. (setq file (nth 1 it)
  10796. pos (nth 3 it))
  10797. (when (and (not arg)
  10798. pos
  10799. (equal (buffer-file-name) file)
  10800. (if regionp
  10801. (and (>= pos region-start)
  10802. (<= pos region-end))
  10803. (and (>= pos (point))
  10804. (< pos (save-excursion
  10805. (org-end-of-subtree t t))))))
  10806. (error "Cannot refile to position inside the tree or region"))
  10807. (setq nbuf (or (find-buffer-visiting file)
  10808. (find-file-noselect file)))
  10809. (if (and arg (not (equal arg 3)))
  10810. (progn
  10811. (pop-to-buffer-same-window nbuf)
  10812. (goto-char pos)
  10813. (org-show-context 'org-goto))
  10814. (if regionp
  10815. (progn
  10816. (org-kill-new (buffer-substring region-start region-end))
  10817. (org-save-markers-in-region region-start region-end))
  10818. (org-copy-subtree 1 nil t))
  10819. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10820. (find-file-noselect file)))
  10821. (setq reversed (org-notes-order-reversed-p))
  10822. (org-with-wide-buffer
  10823. (if pos
  10824. (progn
  10825. (goto-char pos)
  10826. (looking-at org-outline-regexp)
  10827. (setq level (org-get-valid-level (funcall outline-level) 1))
  10828. (goto-char
  10829. (if reversed
  10830. (or (outline-next-heading) (point-max))
  10831. (or (save-excursion (org-get-next-sibling))
  10832. (org-end-of-subtree t t)
  10833. (point-max)))))
  10834. (setq level 1)
  10835. (if (not reversed)
  10836. (goto-char (point-max))
  10837. (goto-char (point-min))
  10838. (or (outline-next-heading) (goto-char (point-max)))))
  10839. (unless (bolp) (newline))
  10840. (org-paste-subtree level nil nil t)
  10841. (when org-log-refile
  10842. (org-add-log-setup 'refile nil nil org-log-refile)
  10843. (unless (eq org-log-refile 'note)
  10844. (save-excursion (org-add-log-note))))
  10845. (and org-auto-align-tags
  10846. (let ((org-loop-over-headlines-in-active-region nil))
  10847. (org-set-tags nil t)))
  10848. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10849. :last-refile)))
  10850. (when bookmark-name
  10851. (with-demoted-errors
  10852. (bookmark-set bookmark-name))))
  10853. ;; If we are refiling for capture, make sure that the
  10854. ;; last-capture pointers point here
  10855. (when (bound-and-true-p org-capture-is-refiling)
  10856. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10857. :last-capture-marker)))
  10858. (when bookmark-name
  10859. (with-demoted-errors
  10860. (bookmark-set bookmark-name))))
  10861. (move-marker org-capture-last-stored-marker (point)))
  10862. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10863. (run-hooks 'org-after-refile-insert-hook)))
  10864. (unless org-refile-keep
  10865. (if regionp
  10866. (delete-region (point) (+ (point) (- region-end region-start)))
  10867. (delete-region
  10868. (and (org-back-to-heading t) (point))
  10869. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10870. (when (featurep 'org-inlinetask)
  10871. (org-inlinetask-remove-END-maybe))
  10872. (setq org-markers-to-move nil)
  10873. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10874. (defun org-refile-goto-last-stored ()
  10875. "Go to the location where the last refile was stored."
  10876. (interactive)
  10877. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10878. (message "This is the location of the last refile"))
  10879. (defun org-refile--get-location (refloc tbl)
  10880. "When user refile to REFLOC, find the associated target in TBL.
  10881. Also check `org-refile-target-table'."
  10882. (car (delq
  10883. nil
  10884. (mapcar
  10885. (lambda (r) (or (assoc r tbl)
  10886. (assoc r org-refile-target-table)))
  10887. (list (replace-regexp-in-string "/$" "" refloc)
  10888. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10889. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10890. "Prompt the user for a refile location, using PROMPT.
  10891. PROMPT should not be suffixed with a colon and a space, because
  10892. this function appends the default value from
  10893. `org-refile-history' automatically, if that is not empty."
  10894. (let ((org-refile-targets org-refile-targets)
  10895. (org-refile-use-outline-path org-refile-use-outline-path))
  10896. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10897. (unless org-refile-target-table
  10898. (user-error "No refile targets"))
  10899. (let* ((cbuf (current-buffer))
  10900. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10901. (cfunc (if (and org-refile-use-outline-path
  10902. org-outline-path-complete-in-steps)
  10903. #'org-olpath-completing-read
  10904. #'completing-read))
  10905. (extra (if org-refile-use-outline-path "/" ""))
  10906. (cbnex (concat (buffer-name) extra))
  10907. (filename (and cfn (expand-file-name cfn)))
  10908. (tbl (mapcar
  10909. (lambda (x)
  10910. (if (and (not (member org-refile-use-outline-path
  10911. '(file full-file-path)))
  10912. (not (equal filename (nth 1 x))))
  10913. (cons (concat (car x) extra " ("
  10914. (file-name-nondirectory (nth 1 x)) ")")
  10915. (cdr x))
  10916. (cons (concat (car x) extra) (cdr x))))
  10917. org-refile-target-table))
  10918. (completion-ignore-case t)
  10919. cdef
  10920. (prompt (concat prompt
  10921. (or (and (car org-refile-history)
  10922. (concat " (default " (car org-refile-history) ")"))
  10923. (and (assoc cbnex tbl) (setq cdef cbnex)
  10924. (concat " (default " cbnex ")"))) ": "))
  10925. pa answ parent-target child parent old-hist)
  10926. (setq old-hist org-refile-history)
  10927. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10928. nil 'org-refile-history (or cdef (car org-refile-history))))
  10929. (if (setq pa (org-refile--get-location answ tbl))
  10930. (progn
  10931. (org-refile-check-position pa)
  10932. (when (or (not org-refile-history)
  10933. (not (eq old-hist org-refile-history))
  10934. (not (equal (car pa) (car org-refile-history))))
  10935. (setq org-refile-history
  10936. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10937. org-refile-history
  10938. (cdr org-refile-history))))
  10939. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10940. (pop org-refile-history)))
  10941. pa)
  10942. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10943. (progn
  10944. (setq parent (match-string 1 answ)
  10945. child (match-string 2 answ))
  10946. (setq parent-target (org-refile--get-location parent tbl))
  10947. (when (and parent-target
  10948. (or (eq new-nodes t)
  10949. (and (eq new-nodes 'confirm)
  10950. (y-or-n-p (format "Create new node \"%s\"? "
  10951. child)))))
  10952. (org-refile-new-child parent-target child)))
  10953. (user-error "Invalid target location")))))
  10954. (declare-function org-string-nw-p "org-macs" (s))
  10955. (defun org-refile-check-position (refile-pointer)
  10956. "Check if the refile pointer matches the headline to which it points."
  10957. (let* ((file (nth 1 refile-pointer))
  10958. (re (nth 2 refile-pointer))
  10959. (pos (nth 3 refile-pointer))
  10960. buffer)
  10961. (if (and (not (markerp pos)) (not file))
  10962. (user-error "Please indicate a target file in the refile path")
  10963. (when (org-string-nw-p re)
  10964. (setq buffer (if (markerp pos)
  10965. (marker-buffer pos)
  10966. (or (find-buffer-visiting file)
  10967. (find-file-noselect file))))
  10968. (with-current-buffer buffer
  10969. (org-with-wide-buffer
  10970. (goto-char pos)
  10971. (beginning-of-line 1)
  10972. (unless (looking-at-p re)
  10973. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10974. (defun org-refile-new-child (parent-target child)
  10975. "Use refile target PARENT-TARGET to add new CHILD below it."
  10976. (unless parent-target
  10977. (error "Cannot find parent for new node"))
  10978. (let ((file (nth 1 parent-target))
  10979. (pos (nth 3 parent-target))
  10980. level)
  10981. (with-current-buffer (or (find-buffer-visiting file)
  10982. (find-file-noselect file))
  10983. (org-with-wide-buffer
  10984. (if pos
  10985. (goto-char pos)
  10986. (goto-char (point-max))
  10987. (unless (bolp) (newline)))
  10988. (when (looking-at org-outline-regexp)
  10989. (setq level (funcall outline-level))
  10990. (org-end-of-subtree t t))
  10991. (org-back-over-empty-lines)
  10992. (insert "\n" (make-string
  10993. (if pos (org-get-valid-level level 1) 1) ?*)
  10994. " " child "\n")
  10995. (beginning-of-line 0)
  10996. (list (concat (car parent-target) "/" child) file "" (point))))))
  10997. (defun org-olpath-completing-read (prompt collection &rest args)
  10998. "Read an outline path like a file name."
  10999. (let ((thetable collection))
  11000. (apply #'completing-read
  11001. prompt
  11002. (lambda (string predicate &optional flag)
  11003. (cond
  11004. ((eq flag nil) (try-completion string thetable))
  11005. ((eq flag t)
  11006. (let ((l (length string)))
  11007. (mapcar (lambda (x)
  11008. (let ((r (substring x l))
  11009. (f (if (string-match " ([^)]*)$" x)
  11010. (match-string 0 x)
  11011. "")))
  11012. (if (string-match "/" r)
  11013. (concat string (substring r 0 (match-end 0)) f)
  11014. x)))
  11015. (all-completions string thetable predicate))))
  11016. ;; Exact match?
  11017. ((eq flag 'lambda) (assoc string thetable))))
  11018. args)))
  11019. ;;;; Dynamic blocks
  11020. (defun org-find-dblock (name)
  11021. "Find the first dynamic block with name NAME in the buffer.
  11022. If not found, stay at current position and return nil."
  11023. (let ((case-fold-search t) pos)
  11024. (save-excursion
  11025. (goto-char (point-min))
  11026. (setq pos (and (re-search-forward
  11027. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  11028. (match-beginning 0))))
  11029. (when pos (goto-char pos))
  11030. pos))
  11031. (defun org-create-dblock (plist)
  11032. "Create a dynamic block section, with parameters taken from PLIST.
  11033. PLIST must contain a :name entry which is used as the name of the block."
  11034. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  11035. (end-of-line 1)
  11036. (newline))
  11037. (let ((col (current-column))
  11038. (name (plist-get plist :name)))
  11039. (insert "#+BEGIN: " name)
  11040. (while plist
  11041. (if (eq (car plist) :name)
  11042. (setq plist (cddr plist))
  11043. (insert " " (prin1-to-string (pop plist)))))
  11044. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  11045. (beginning-of-line -2)))
  11046. (defun org-prepare-dblock ()
  11047. "Prepare dynamic block for refresh.
  11048. This empties the block, puts the cursor at the insert position and returns
  11049. the property list including an extra property :name with the block name."
  11050. (unless (looking-at org-dblock-start-re)
  11051. (user-error "Not at a dynamic block"))
  11052. (let* ((begdel (1+ (match-end 0)))
  11053. (name (org-no-properties (match-string 1)))
  11054. (params (append (list :name name)
  11055. (read (concat "(" (match-string 3) ")")))))
  11056. (save-excursion
  11057. (beginning-of-line 1)
  11058. (skip-chars-forward " \t")
  11059. (setq params (plist-put params :indentation-column (current-column))))
  11060. (unless (re-search-forward org-dblock-end-re nil t)
  11061. (error "Dynamic block not terminated"))
  11062. (setq params
  11063. (append params
  11064. (list :content (buffer-substring
  11065. begdel (match-beginning 0)))))
  11066. (delete-region begdel (match-beginning 0))
  11067. (goto-char begdel)
  11068. (open-line 1)
  11069. params))
  11070. (defun org-map-dblocks (&optional command)
  11071. "Apply COMMAND to all dynamic blocks in the current buffer.
  11072. If COMMAND is not given, use `org-update-dblock'."
  11073. (let ((cmd (or command 'org-update-dblock)))
  11074. (save-excursion
  11075. (goto-char (point-min))
  11076. (while (re-search-forward org-dblock-start-re nil t)
  11077. (goto-char (match-beginning 0))
  11078. (save-excursion
  11079. (condition-case nil
  11080. (funcall cmd)
  11081. (error (message "Error during update of dynamic block"))))
  11082. (unless (re-search-forward org-dblock-end-re nil t)
  11083. (error "Dynamic block not terminated"))))))
  11084. (defun org-dblock-update (&optional arg)
  11085. "User command for updating dynamic blocks.
  11086. Update the dynamic block at point. With prefix ARG, update all dynamic
  11087. blocks in the buffer."
  11088. (interactive "P")
  11089. (if arg
  11090. (org-update-all-dblocks)
  11091. (or (looking-at org-dblock-start-re)
  11092. (org-beginning-of-dblock))
  11093. (org-update-dblock)))
  11094. (defun org-update-dblock ()
  11095. "Update the dynamic block at point.
  11096. This means to empty the block, parse for parameters and then call
  11097. the correct writing function."
  11098. (interactive)
  11099. (save-excursion
  11100. (let* ((win (selected-window))
  11101. (pos (point))
  11102. (line (org-current-line))
  11103. (params (org-prepare-dblock))
  11104. (name (plist-get params :name))
  11105. (indent (plist-get params :indentation-column))
  11106. (cmd (intern (concat "org-dblock-write:" name))))
  11107. (message "Updating dynamic block `%s' at line %d..." name line)
  11108. (funcall cmd params)
  11109. (message "Updating dynamic block `%s' at line %d...done" name line)
  11110. (goto-char pos)
  11111. (when (and indent (> indent 0))
  11112. (setq indent (make-string indent ?\ ))
  11113. (save-excursion
  11114. (select-window win)
  11115. (org-beginning-of-dblock)
  11116. (forward-line 1)
  11117. (while (not (looking-at org-dblock-end-re))
  11118. (insert indent)
  11119. (beginning-of-line 2))
  11120. (when (looking-at org-dblock-end-re)
  11121. (and (looking-at "[ \t]+")
  11122. (replace-match ""))
  11123. (insert indent)))))))
  11124. (defun org-beginning-of-dblock ()
  11125. "Find the beginning of the dynamic block at point.
  11126. Error if there is no such block at point."
  11127. (let ((pos (point))
  11128. beg)
  11129. (end-of-line 1)
  11130. (if (and (re-search-backward org-dblock-start-re nil t)
  11131. (setq beg (match-beginning 0))
  11132. (re-search-forward org-dblock-end-re nil t)
  11133. (> (match-end 0) pos))
  11134. (goto-char beg)
  11135. (goto-char pos)
  11136. (error "Not in a dynamic block"))))
  11137. (defun org-update-all-dblocks ()
  11138. "Update all dynamic blocks in the buffer.
  11139. This function can be used in a hook."
  11140. (interactive)
  11141. (when (derived-mode-p 'org-mode)
  11142. (org-map-dblocks 'org-update-dblock)))
  11143. ;;;; Completion
  11144. (declare-function org-export-backend-options "ox" (cl-x) t)
  11145. (defun org-get-export-keywords ()
  11146. "Return a list of all currently understood export keywords.
  11147. Export keywords include options, block names, attributes and
  11148. keywords relative to each registered export back-end."
  11149. (let (keywords)
  11150. (dolist (backend
  11151. (bound-and-true-p org-export-registered-backends)
  11152. (delq nil keywords))
  11153. ;; Back-end name (for keywords, like #+LATEX:)
  11154. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  11155. (dolist (option-entry (org-export-backend-options backend))
  11156. ;; Back-end options.
  11157. (push (nth 1 option-entry) keywords)))))
  11158. (defconst org-options-keywords
  11159. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  11160. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  11161. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  11162. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  11163. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  11164. (defcustom org-structure-template-alist
  11165. '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
  11166. ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
  11167. ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
  11168. ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
  11169. ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
  11170. ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
  11171. ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
  11172. ("L" "#+LaTeX: ")
  11173. ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
  11174. ("H" "#+HTML: ")
  11175. ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
  11176. ("A" "#+ASCII: ")
  11177. ("i" "#+INDEX: ?")
  11178. ("I" "#+INCLUDE: %file ?"))
  11179. "Structure completion elements.
  11180. This is a list of abbreviation keys and values. The value gets inserted
  11181. if you type `<' followed by the key and then press the completion key,
  11182. usually `TAB'. %file will be replaced by a file name after prompting
  11183. for the file using completion. The cursor will be placed at the position
  11184. of the `?' in the template.
  11185. There are two templates for each key, the first uses the original Org syntax,
  11186. the second uses Emacs Muse-like syntax tags. These Muse-like tags become
  11187. the default when the /org-mtags.el/ module has been loaded. See also the
  11188. variable `org-mtags-prefer-muse-templates'."
  11189. :group 'org-completion
  11190. :type '(repeat
  11191. (list
  11192. (string :tag "Key")
  11193. (string :tag "Template")))
  11194. :version "25.2"
  11195. :package-version '(Org . "8.3"))
  11196. (defun org-try-structure-completion ()
  11197. "Try to complete a structure template before point.
  11198. This looks for strings like \"<e\" on an otherwise empty line and
  11199. expands them."
  11200. (let ((l (buffer-substring (point-at-bol) (point)))
  11201. a)
  11202. (when (and (looking-at "[ \t]*$")
  11203. (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
  11204. (setq a (assoc (match-string 1 l) org-structure-template-alist)))
  11205. (org-complete-expand-structure-template (+ -1 (point-at-bol)
  11206. (match-beginning 1)) a)
  11207. t)))
  11208. (defun org-complete-expand-structure-template (start cell)
  11209. "Expand a structure template."
  11210. (let ((rpl (nth 1 cell))
  11211. (ind ""))
  11212. (delete-region start (point))
  11213. (when (string-match "\\`[ \t]*#\\+" rpl)
  11214. (cond
  11215. ((bolp))
  11216. ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
  11217. (setq ind (buffer-substring (point-at-bol) (point))))
  11218. (t (newline))))
  11219. (setq start (point))
  11220. (when (string-match "%file" rpl)
  11221. (setq rpl (replace-match
  11222. (concat
  11223. "\""
  11224. (save-match-data
  11225. (abbreviate-file-name (read-file-name "Include file: ")))
  11226. "\"")
  11227. t t rpl)))
  11228. (setq rpl (mapconcat 'identity (split-string rpl "\n")
  11229. (concat "\n" ind)))
  11230. (insert rpl)
  11231. (when (re-search-backward "\\?" start t) (delete-char 1))))
  11232. ;;;; TODO, DEADLINE, Comments
  11233. (defun org-toggle-comment ()
  11234. "Change the COMMENT state of an entry."
  11235. (interactive)
  11236. (save-excursion
  11237. (org-back-to-heading)
  11238. (looking-at org-complex-heading-regexp)
  11239. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  11240. (skip-chars-forward " \t")
  11241. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  11242. (if (org-in-commented-heading-p t)
  11243. (delete-region (point)
  11244. (progn (search-forward " " (line-end-position) 'move)
  11245. (skip-chars-forward " \t")
  11246. (point)))
  11247. (insert org-comment-string)
  11248. (unless (eolp) (insert " ")))))
  11249. (defvar org-last-todo-state-is-todo nil
  11250. "This is non-nil when the last TODO state change led to a TODO state.
  11251. If the last change removed the TODO tag or switched to DONE, then
  11252. this is nil.")
  11253. (defvar org-setting-tags nil) ; dynamically skipped
  11254. (defvar org-todo-setup-filter-hook nil
  11255. "Hook for functions that pre-filter todo specs.
  11256. Each function takes a todo spec and returns either nil or the spec
  11257. transformed into canonical form." )
  11258. (defvar org-todo-get-default-hook nil
  11259. "Hook for functions that get a default item for todo.
  11260. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  11261. nil or a string to be used for the todo mark." )
  11262. (defvar org-agenda-headline-snapshot-before-repeat)
  11263. (defun org-current-effective-time ()
  11264. "Return current time adjusted for `org-extend-today-until' variable."
  11265. (let* ((ct (org-current-time))
  11266. (dct (decode-time ct))
  11267. (ct1
  11268. (cond
  11269. (org-use-last-clock-out-time-as-effective-time
  11270. (or (org-clock-get-last-clock-out-time) ct))
  11271. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  11272. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  11273. (t ct))))
  11274. ct1))
  11275. (defun org-todo-yesterday (&optional arg)
  11276. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  11277. (interactive "P")
  11278. (if (eq major-mode 'org-agenda-mode)
  11279. (apply 'org-agenda-todo-yesterday arg)
  11280. (let* ((org-use-effective-time t)
  11281. (hour (nth 2 (decode-time (org-current-time))))
  11282. (org-extend-today-until (1+ hour)))
  11283. (org-todo arg))))
  11284. (defvar org-block-entry-blocking ""
  11285. "First entry preventing the TODO state change.")
  11286. (defun org-cancel-repeater ()
  11287. "Cancel a repeater by setting its numeric value to zero."
  11288. (interactive)
  11289. (save-excursion
  11290. (org-back-to-heading t)
  11291. (let ((bound1 (point))
  11292. (bound0 (save-excursion (outline-next-heading) (point))))
  11293. (when (and (re-search-forward
  11294. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  11295. org-deadline-time-regexp "\\)\\|\\("
  11296. org-ts-regexp "\\)")
  11297. bound0 t)
  11298. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  11299. bound1 t))
  11300. (replace-match "0" t nil nil 1)))))
  11301. (defvar org-state) ;; dynamically scoped into this function
  11302. (defun org-todo (&optional arg)
  11303. "Change the TODO state of an item.
  11304. The state of an item is given by a keyword at the start of the heading,
  11305. like
  11306. *** TODO Write paper
  11307. *** DONE Call mom
  11308. The different keywords are specified in the variable `org-todo-keywords'.
  11309. By default the available states are \"TODO\" and \"DONE\". So, for this
  11310. example: when the item starts with TODO, it is changed to DONE.
  11311. When it starts with DONE, the DONE is removed. And when neither TODO nor
  11312. DONE are present, add TODO at the beginning of the heading.
  11313. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  11314. state.
  11315. With numeric prefix ARG, switch to that state.
  11316. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  11317. next set of TODO \
  11318. keywords (nextset).
  11319. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  11320. prefix, circumvent any state blocking.
  11321. With a numeric prefix arg of 0, inhibit note taking for the change.
  11322. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  11323. When called through ELisp, arg is also interpreted in the following way:
  11324. `none' -> empty state
  11325. \"\" -> switch to empty state
  11326. `done' -> switch to DONE
  11327. `nextset' -> switch to the next set of keywords
  11328. `previousset' -> switch to the previous set of keywords
  11329. \"WAITING\" -> switch to the specified keyword, but only if it
  11330. really is a member of `org-todo-keywords'."
  11331. (interactive "P")
  11332. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11333. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11334. 'region-start-level 'region))
  11335. org-loop-over-headlines-in-active-region)
  11336. (org-map-entries
  11337. `(org-todo ,arg)
  11338. org-loop-over-headlines-in-active-region
  11339. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  11340. (when (equal arg '(16)) (setq arg 'nextset))
  11341. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  11342. (let ((org-blocker-hook org-blocker-hook)
  11343. commentp
  11344. case-fold-search)
  11345. (when (equal arg '(64))
  11346. (setq arg nil org-blocker-hook nil))
  11347. (when (and org-blocker-hook
  11348. (or org-inhibit-blocking
  11349. (org-entry-get nil "NOBLOCKING")))
  11350. (setq org-blocker-hook nil))
  11351. (save-excursion
  11352. (catch 'exit
  11353. (org-back-to-heading t)
  11354. (when (org-in-commented-heading-p t)
  11355. (org-toggle-comment)
  11356. (setq commentp t))
  11357. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  11358. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  11359. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  11360. (let* ((match-data (match-data))
  11361. (startpos (point-at-bol))
  11362. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  11363. (org-log-done org-log-done)
  11364. (org-log-repeat org-log-repeat)
  11365. (org-todo-log-states org-todo-log-states)
  11366. (org-inhibit-logging
  11367. (if (equal arg 0)
  11368. (progn (setq arg nil) 'note) org-inhibit-logging))
  11369. (this (match-string 1))
  11370. (hl-pos (match-beginning 0))
  11371. (head (org-get-todo-sequence-head this))
  11372. (ass (assoc head org-todo-kwd-alist))
  11373. (interpret (nth 1 ass))
  11374. (done-word (nth 3 ass))
  11375. (final-done-word (nth 4 ass))
  11376. (org-last-state (or this ""))
  11377. (completion-ignore-case t)
  11378. (member (member this org-todo-keywords-1))
  11379. (tail (cdr member))
  11380. (org-state (cond
  11381. ((and org-todo-key-trigger
  11382. (or (and (equal arg '(4))
  11383. (eq org-use-fast-todo-selection 'prefix))
  11384. (and (not arg) org-use-fast-todo-selection
  11385. (not (eq org-use-fast-todo-selection
  11386. 'prefix)))))
  11387. ;; Use fast selection
  11388. (org-fast-todo-selection))
  11389. ((and (equal arg '(4))
  11390. (or (not org-use-fast-todo-selection)
  11391. (not org-todo-key-trigger)))
  11392. ;; Read a state with completion
  11393. (completing-read
  11394. "State: " (mapcar #'list org-todo-keywords-1)
  11395. nil t))
  11396. ((eq arg 'right)
  11397. (if this
  11398. (if tail (car tail) nil)
  11399. (car org-todo-keywords-1)))
  11400. ((eq arg 'left)
  11401. (unless (equal member org-todo-keywords-1)
  11402. (if this
  11403. (nth (- (length org-todo-keywords-1)
  11404. (length tail) 2)
  11405. org-todo-keywords-1)
  11406. (org-last org-todo-keywords-1))))
  11407. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  11408. (setq arg nil))) ; hack to fall back to cycling
  11409. (arg
  11410. ;; user or caller requests a specific state
  11411. (cond
  11412. ((equal arg "") nil)
  11413. ((eq arg 'none) nil)
  11414. ((eq arg 'done) (or done-word (car org-done-keywords)))
  11415. ((eq arg 'nextset)
  11416. (or (car (cdr (member head org-todo-heads)))
  11417. (car org-todo-heads)))
  11418. ((eq arg 'previousset)
  11419. (let ((org-todo-heads (reverse org-todo-heads)))
  11420. (or (car (cdr (member head org-todo-heads)))
  11421. (car org-todo-heads))))
  11422. ((car (member arg org-todo-keywords-1)))
  11423. ((stringp arg)
  11424. (user-error "State `%s' not valid in this file" arg))
  11425. ((nth (1- (prefix-numeric-value arg))
  11426. org-todo-keywords-1))))
  11427. ((null member) (or head (car org-todo-keywords-1)))
  11428. ((equal this final-done-word) nil) ;; -> make empty
  11429. ((null tail) nil) ;; -> first entry
  11430. ((memq interpret '(type priority))
  11431. (if (eq this-command last-command)
  11432. (car tail)
  11433. (if (> (length tail) 0)
  11434. (or done-word (car org-done-keywords))
  11435. nil)))
  11436. (t
  11437. (car tail))))
  11438. (org-state (or
  11439. (run-hook-with-args-until-success
  11440. 'org-todo-get-default-hook org-state org-last-state)
  11441. org-state))
  11442. (next (if org-state (concat " " org-state " ") " "))
  11443. (change-plist (list :type 'todo-state-change :from this :to org-state
  11444. :position startpos))
  11445. dolog now-done-p)
  11446. (when org-blocker-hook
  11447. (setq org-last-todo-state-is-todo
  11448. (not (member this org-done-keywords)))
  11449. (unless (save-excursion
  11450. (save-match-data
  11451. (org-with-wide-buffer
  11452. (run-hook-with-args-until-failure
  11453. 'org-blocker-hook change-plist))))
  11454. (if (called-interactively-p 'interactive)
  11455. (user-error "TODO state change from %s to %s blocked (by \"%s\")"
  11456. this org-state org-block-entry-blocking)
  11457. ;; fail silently
  11458. (message "TODO state change from %s to %s blocked (by \"%s\")"
  11459. this org-state org-block-entry-blocking)
  11460. (throw 'exit nil))))
  11461. (store-match-data match-data)
  11462. (replace-match next t t)
  11463. (cond ((equal this org-state)
  11464. (message "TODO state was already %s" (org-trim next)))
  11465. ((pos-visible-in-window-p hl-pos)
  11466. (message "TODO state changed to %s" (org-trim next))))
  11467. (unless head
  11468. (setq head (org-get-todo-sequence-head org-state)
  11469. ass (assoc head org-todo-kwd-alist)
  11470. interpret (nth 1 ass)
  11471. done-word (nth 3 ass)
  11472. final-done-word (nth 4 ass)))
  11473. (when (memq arg '(nextset previousset))
  11474. (message "Keyword-Set %d/%d: %s"
  11475. (- (length org-todo-sets) -1
  11476. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  11477. (length org-todo-sets)
  11478. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  11479. (setq org-last-todo-state-is-todo
  11480. (not (member org-state org-done-keywords)))
  11481. (setq now-done-p (and (member org-state org-done-keywords)
  11482. (not (member this org-done-keywords))))
  11483. (and logging (org-local-logging logging))
  11484. (when (and (or org-todo-log-states org-log-done)
  11485. (not (eq org-inhibit-logging t))
  11486. (not (memq arg '(nextset previousset))))
  11487. ;; we need to look at recording a time and note
  11488. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11489. (nth 2 (assoc this org-todo-log-states))))
  11490. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11491. (setq dolog 'time))
  11492. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11493. (and org-state
  11494. (member org-state org-not-done-keywords)
  11495. (not (member this org-not-done-keywords))))
  11496. ;; This is now a todo state and was not one before
  11497. ;; If there was a CLOSED time stamp, get rid of it.
  11498. (org-add-planning-info nil nil 'closed))
  11499. (when (and now-done-p org-log-done)
  11500. ;; It is now done, and it was not done before
  11501. (org-add-planning-info 'closed (org-current-effective-time))
  11502. (when (and (not dolog) (eq 'note org-log-done))
  11503. (org-add-log-setup 'done org-state this 'note)))
  11504. (when (and org-state dolog)
  11505. ;; This is a non-nil state, and we need to log it
  11506. (org-add-log-setup 'state org-state this dolog)))
  11507. ;; Fixup tag positioning
  11508. (org-todo-trigger-tag-changes org-state)
  11509. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11510. (when org-provide-todo-statistics
  11511. (org-update-parent-todo-statistics))
  11512. (run-hooks 'org-after-todo-state-change-hook)
  11513. (when (and arg (not (member org-state org-done-keywords)))
  11514. (setq head (org-get-todo-sequence-head org-state)))
  11515. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11516. ;; Do we need to trigger a repeat?
  11517. (when now-done-p
  11518. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11519. ;; This is for the agenda, take a snapshot of the headline.
  11520. (save-match-data
  11521. (setq org-agenda-headline-snapshot-before-repeat
  11522. (org-get-heading))))
  11523. (org-auto-repeat-maybe org-state))
  11524. ;; Fixup cursor location if close to the keyword
  11525. (when (and (outline-on-heading-p)
  11526. (not (bolp))
  11527. (save-excursion (beginning-of-line 1)
  11528. (looking-at org-todo-line-regexp))
  11529. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11530. (goto-char (or (match-end 2) (match-end 1)))
  11531. (and (looking-at " ") (just-one-space)))
  11532. (when org-trigger-hook
  11533. (save-excursion
  11534. (run-hook-with-args 'org-trigger-hook change-plist)))
  11535. (when commentp (org-toggle-comment))))))))
  11536. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11537. "Block turning an entry into a TODO, using the hierarchy.
  11538. This checks whether the current task should be blocked from state
  11539. changes. Such blocking occurs when:
  11540. 1. The task has children which are not all in a completed state.
  11541. 2. A task has a parent with the property :ORDERED:, and there
  11542. are siblings prior to the current task with incomplete
  11543. status.
  11544. 3. The parent of the task is blocked because it has siblings that should
  11545. be done first, or is child of a block grandparent TODO entry."
  11546. (if (not org-enforce-todo-dependencies)
  11547. t ; if locally turned off don't block
  11548. (catch 'dont-block
  11549. ;; If this is not a todo state change, or if this entry is already DONE,
  11550. ;; do not block
  11551. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11552. (member (plist-get change-plist :from)
  11553. (cons 'done org-done-keywords))
  11554. (member (plist-get change-plist :to)
  11555. (cons 'todo org-not-done-keywords))
  11556. (not (plist-get change-plist :to)))
  11557. (throw 'dont-block t))
  11558. ;; If this task has children, and any are undone, it's blocked
  11559. (save-excursion
  11560. (org-back-to-heading t)
  11561. (let ((this-level (funcall outline-level)))
  11562. (outline-next-heading)
  11563. (let ((child-level (funcall outline-level)))
  11564. (while (and (not (eobp))
  11565. (> child-level this-level))
  11566. ;; this todo has children, check whether they are all
  11567. ;; completed
  11568. (when (and (not (org-entry-is-done-p))
  11569. (org-entry-is-todo-p))
  11570. (setq org-block-entry-blocking (org-get-heading))
  11571. (throw 'dont-block nil))
  11572. (outline-next-heading)
  11573. (setq child-level (funcall outline-level))))))
  11574. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11575. ;; any previous siblings are undone, it's blocked
  11576. (save-excursion
  11577. (org-back-to-heading t)
  11578. (let* ((pos (point))
  11579. (parent-pos (and (org-up-heading-safe) (point))))
  11580. (unless parent-pos (throw 'dont-block t)) ; no parent
  11581. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11582. (forward-line 1)
  11583. (re-search-forward org-not-done-heading-regexp pos t))
  11584. (setq org-block-entry-blocking (match-string 0))
  11585. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11586. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11587. (while t
  11588. (goto-char parent-pos)
  11589. (unless (looking-at org-not-done-heading-regexp)
  11590. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11591. (setq pos (point))
  11592. (setq parent-pos (and (org-up-heading-safe) (point)))
  11593. (unless parent-pos (throw 'dont-block t)) ; no parent
  11594. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11595. (forward-line 1)
  11596. (re-search-forward org-not-done-heading-regexp pos t)
  11597. (setq org-block-entry-blocking (org-get-heading)))
  11598. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11599. (defcustom org-track-ordered-property-with-tag nil
  11600. "Should the ORDERED property also be shown as a tag?
  11601. The ORDERED property decides if an entry should require subtasks to be
  11602. completed in sequence. Since a property is not very visible, setting
  11603. this option means that toggling the ORDERED property with the command
  11604. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11605. not relevant for the behavior, but it makes things more visible.
  11606. Note that toggling the tag with tags commands will not change the property
  11607. and therefore not influence behavior!
  11608. This can be t, meaning the tag ORDERED should be used, It can also be a
  11609. string to select a different tag for this task."
  11610. :group 'org-todo
  11611. :type '(choice
  11612. (const :tag "No tracking" nil)
  11613. (const :tag "Track with ORDERED tag" t)
  11614. (string :tag "Use other tag")))
  11615. (defun org-toggle-ordered-property ()
  11616. "Toggle the ORDERED property of the current entry.
  11617. For better visibility, you can track the value of this property with a tag.
  11618. See variable `org-track-ordered-property-with-tag'."
  11619. (interactive)
  11620. (let* ((t1 org-track-ordered-property-with-tag)
  11621. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11622. (save-excursion
  11623. (org-back-to-heading)
  11624. (if (org-entry-get nil "ORDERED")
  11625. (progn
  11626. (org-delete-property "ORDERED")
  11627. (and tag (org-toggle-tag tag 'off))
  11628. (message "Subtasks can be completed in arbitrary order"))
  11629. (org-entry-put nil "ORDERED" "t")
  11630. (and tag (org-toggle-tag tag 'on))
  11631. (message "Subtasks must be completed in sequence")))))
  11632. (defvar org-blocked-by-checkboxes) ; dynamically scoped
  11633. (defun org-block-todo-from-checkboxes (change-plist)
  11634. "Block turning an entry into a TODO, using checkboxes.
  11635. This checks whether the current task should be blocked from state
  11636. changes because there are unchecked boxes in this entry."
  11637. (if (not org-enforce-todo-checkbox-dependencies)
  11638. t ; if locally turned off don't block
  11639. (catch 'dont-block
  11640. ;; If this is not a todo state change, or if this entry is already DONE,
  11641. ;; do not block
  11642. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11643. (member (plist-get change-plist :from)
  11644. (cons 'done org-done-keywords))
  11645. (member (plist-get change-plist :to)
  11646. (cons 'todo org-not-done-keywords))
  11647. (not (plist-get change-plist :to)))
  11648. (throw 'dont-block t))
  11649. ;; If this task has checkboxes that are not checked, it's blocked
  11650. (save-excursion
  11651. (org-back-to-heading t)
  11652. (let ((beg (point)) end)
  11653. (outline-next-heading)
  11654. (setq end (point))
  11655. (goto-char beg)
  11656. (when (org-list-search-forward
  11657. (concat (org-item-beginning-re)
  11658. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11659. "\\[[- ]\\]")
  11660. end t)
  11661. (when (boundp 'org-blocked-by-checkboxes)
  11662. (setq org-blocked-by-checkboxes t))
  11663. (throw 'dont-block nil))))
  11664. t))) ; do not block
  11665. (defun org-entry-blocked-p ()
  11666. "Non-nil if entry at point is blocked."
  11667. (and (not (org-entry-get nil "NOBLOCKING"))
  11668. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11669. (not (run-hook-with-args-until-failure
  11670. 'org-blocker-hook
  11671. (list :type 'todo-state-change
  11672. :position (point)
  11673. :from 'todo
  11674. :to 'done)))))
  11675. (defun org-update-statistics-cookies (all)
  11676. "Update the statistics cookie, either from TODO or from checkboxes.
  11677. This should be called with the cursor in a line with a statistics
  11678. cookie. When called with a \\[universal-argument] prefix, update
  11679. all statistics cookies in the buffer."
  11680. (interactive "P")
  11681. (if all
  11682. (progn
  11683. (org-update-checkbox-count 'all)
  11684. (org-map-entries 'org-update-parent-todo-statistics))
  11685. (if (not (org-at-heading-p))
  11686. (org-update-checkbox-count)
  11687. (let ((pos (point-marker))
  11688. end l1 l2)
  11689. (ignore-errors (org-back-to-heading t))
  11690. (if (not (org-at-heading-p))
  11691. (org-update-checkbox-count)
  11692. (setq l1 (org-outline-level))
  11693. (setq end (save-excursion
  11694. (outline-next-heading)
  11695. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11696. (point)))
  11697. (if (and (save-excursion
  11698. (re-search-forward
  11699. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11700. (not (save-excursion (re-search-forward
  11701. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11702. (org-update-checkbox-count)
  11703. (if (and l2 (> l2 l1))
  11704. (progn
  11705. (goto-char end)
  11706. (org-update-parent-todo-statistics))
  11707. (goto-char pos)
  11708. (beginning-of-line 1)
  11709. (while (re-search-forward
  11710. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11711. (point-at-eol) t)
  11712. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11713. (goto-char pos)
  11714. (move-marker pos nil)))))
  11715. (defvar org-entry-property-inherited-from) ;; defined below
  11716. (defun org-update-parent-todo-statistics ()
  11717. "Update any statistics cookie in the parent of the current headline.
  11718. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11719. the entire subtree and this will travel up the hierarchy and update
  11720. statistics everywhere."
  11721. (let* ((prop (save-excursion (org-up-heading-safe)
  11722. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11723. (recursive (or (not org-hierarchical-todo-statistics)
  11724. (and prop (string-match "\\<recursive\\>" prop))))
  11725. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11726. 0))
  11727. (first t)
  11728. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11729. level ltoggle l1 new ndel
  11730. (cnt-all 0) (cnt-done 0) is-percent kwd
  11731. checkbox-beg cookie-present)
  11732. (catch 'exit
  11733. (save-excursion
  11734. (beginning-of-line 1)
  11735. (setq ltoggle (funcall outline-level))
  11736. ;; Three situations are to consider:
  11737. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11738. ;; to the top-level ancestor on the headline;
  11739. ;; 2. If parent has "recursive" property, repeat up to the
  11740. ;; headline setting that property, taking inheritance into
  11741. ;; account;
  11742. ;; 3. Else, move up to direct parent and proceed only once.
  11743. (while (and (setq level (org-up-heading-safe))
  11744. (or recursive first)
  11745. (>= (point) lim))
  11746. (setq first nil cookie-present nil)
  11747. (unless (and level
  11748. (not (string-match
  11749. "\\<checkbox\\>"
  11750. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11751. "")))))
  11752. (throw 'exit nil))
  11753. (while (re-search-forward box-re (point-at-eol) t)
  11754. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11755. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11756. (save-match-data
  11757. (unless (outline-next-heading) (throw 'exit nil))
  11758. (while (and (looking-at org-complex-heading-regexp)
  11759. (> (setq l1 (length (match-string 1))) level))
  11760. (setq kwd (and (or recursive (= l1 ltoggle))
  11761. (match-string 2)))
  11762. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11763. (and (eq org-provide-todo-statistics t)
  11764. (or (member kwd org-done-keywords)))
  11765. (and (listp org-provide-todo-statistics)
  11766. (stringp (car org-provide-todo-statistics))
  11767. (or (member kwd org-provide-todo-statistics)
  11768. (member kwd org-done-keywords)))
  11769. (and (listp org-provide-todo-statistics)
  11770. (listp (car org-provide-todo-statistics))
  11771. (or (member kwd (car org-provide-todo-statistics))
  11772. (and (member kwd org-done-keywords)
  11773. (member kwd (cadr org-provide-todo-statistics))))))
  11774. (setq cnt-all (1+ cnt-all))
  11775. (and (eq org-provide-todo-statistics t)
  11776. kwd
  11777. (setq cnt-all (1+ cnt-all))))
  11778. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11779. (member kwd org-done-keywords))
  11780. (and (listp org-provide-todo-statistics)
  11781. (listp (car org-provide-todo-statistics))
  11782. (member kwd org-done-keywords)
  11783. (member kwd (cadr org-provide-todo-statistics)))
  11784. (and (listp org-provide-todo-statistics)
  11785. (stringp (car org-provide-todo-statistics))
  11786. (member kwd org-done-keywords)))
  11787. (setq cnt-done (1+ cnt-done)))
  11788. (outline-next-heading)))
  11789. (setq new
  11790. (if is-percent
  11791. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11792. (max 1 cnt-all)))
  11793. (format "[%d/%d]" cnt-done cnt-all))
  11794. ndel (- (match-end 0) checkbox-beg))
  11795. (goto-char checkbox-beg)
  11796. (insert new)
  11797. (delete-region (point) (+ (point) ndel))
  11798. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11799. (when cookie-present
  11800. (run-hook-with-args 'org-after-todo-statistics-hook
  11801. cnt-done (- cnt-all cnt-done))))))
  11802. (run-hooks 'org-todo-statistics-hook)))
  11803. (defvar org-after-todo-statistics-hook nil
  11804. "Hook that is called after a TODO statistics cookie has been updated.
  11805. Each function is called with two arguments: the number of not-done entries
  11806. and the number of done entries.
  11807. For example, the following function, when added to this hook, will switch
  11808. an entry to DONE when all children are done, and back to TODO when new
  11809. entries are set to a TODO status. Note that this hook is only called
  11810. when there is a statistics cookie in the headline!
  11811. \(defun org-summary-todo (n-done n-not-done)
  11812. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11813. \(let (org-log-done org-log-states) ; turn off logging
  11814. \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11815. ")
  11816. (defvar org-todo-statistics-hook nil
  11817. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11818. This hook runs even if there is no statistics cookie present, in which case
  11819. `org-after-todo-statistics-hook' would not run.")
  11820. (defun org-todo-trigger-tag-changes (state)
  11821. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11822. (let ((l org-todo-state-tags-triggers)
  11823. changes)
  11824. (when (or (not state) (equal state ""))
  11825. (setq changes (append changes (cdr (assoc "" l)))))
  11826. (when (and (stringp state) (> (length state) 0))
  11827. (setq changes (append changes (cdr (assoc state l)))))
  11828. (when (member state org-not-done-keywords)
  11829. (setq changes (append changes (cdr (assq 'todo l)))))
  11830. (when (member state org-done-keywords)
  11831. (setq changes (append changes (cdr (assq 'done l)))))
  11832. (dolist (c changes)
  11833. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11834. (defun org-local-logging (value)
  11835. "Get logging settings from a property VALUE."
  11836. ;; Directly set the variables, they are already local.
  11837. (setq org-log-done nil
  11838. org-log-repeat nil
  11839. org-todo-log-states nil)
  11840. (dolist (w (org-split-string value))
  11841. (let (a)
  11842. (cond
  11843. ((setq a (assoc w org-startup-options))
  11844. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11845. (set (nth 1 a) (nth 2 a))))
  11846. ((setq a (org-extract-log-state-settings w))
  11847. (and (member (car a) org-todo-keywords-1)
  11848. (push a org-todo-log-states)))))))
  11849. (defun org-get-todo-sequence-head (kwd)
  11850. "Return the head of the TODO sequence to which KWD belongs.
  11851. If KWD is not set, check if there is a text property remembering the
  11852. right sequence."
  11853. (let (p)
  11854. (cond
  11855. ((not kwd)
  11856. (or (get-text-property (point-at-bol) 'org-todo-head)
  11857. (progn
  11858. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11859. nil (point-at-eol)))
  11860. (get-text-property p 'org-todo-head))))
  11861. ((not (member kwd org-todo-keywords-1))
  11862. (car org-todo-keywords-1))
  11863. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11864. (defun org-fast-todo-selection ()
  11865. "Fast TODO keyword selection with single keys.
  11866. Returns the new TODO keyword, or nil if no state change should occur."
  11867. (let* ((fulltable org-todo-key-alist)
  11868. (done-keywords org-done-keywords) ;; needed for the faces.
  11869. (maxlen (apply 'max (mapcar
  11870. (lambda (x)
  11871. (if (stringp (car x)) (string-width (car x)) 0))
  11872. fulltable)))
  11873. (expert nil)
  11874. (fwidth (+ maxlen 3 1 3))
  11875. (ncol (/ (- (window-width) 4) fwidth))
  11876. tg cnt e c tbl
  11877. groups ingroup)
  11878. (save-excursion
  11879. (save-window-excursion
  11880. (if expert
  11881. (set-buffer (get-buffer-create " *Org todo*"))
  11882. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11883. (erase-buffer)
  11884. (setq-local org-done-keywords done-keywords)
  11885. (setq tbl fulltable cnt 0)
  11886. (while (setq e (pop tbl))
  11887. (cond
  11888. ((equal e '(:startgroup))
  11889. (push '() groups) (setq ingroup t)
  11890. (unless (= cnt 0)
  11891. (setq cnt 0)
  11892. (insert "\n"))
  11893. (insert "{ "))
  11894. ((equal e '(:endgroup))
  11895. (setq ingroup nil cnt 0)
  11896. (insert "}\n"))
  11897. ((equal e '(:newline))
  11898. (unless (= cnt 0)
  11899. (setq cnt 0)
  11900. (insert "\n")
  11901. (setq e (car tbl))
  11902. (while (equal (car tbl) '(:newline))
  11903. (insert "\n")
  11904. (setq tbl (cdr tbl)))))
  11905. (t
  11906. (setq tg (car e) c (cdr e))
  11907. (when ingroup (push tg (car groups)))
  11908. (setq tg (org-add-props tg nil 'face
  11909. (org-get-todo-face tg)))
  11910. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11911. (insert "[" c "] " tg (make-string
  11912. (- fwidth 4 (length tg)) ?\ ))
  11913. (when (= (setq cnt (1+ cnt)) ncol)
  11914. (insert "\n")
  11915. (when ingroup (insert " "))
  11916. (setq cnt 0)))))
  11917. (insert "\n")
  11918. (goto-char (point-min))
  11919. (unless expert (org-fit-window-to-buffer))
  11920. (message "[a-z..]:Set [SPC]:clear")
  11921. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11922. (cond
  11923. ((or (= c ?\C-g)
  11924. (and (= c ?q) (not (rassoc c fulltable))))
  11925. (setq quit-flag t))
  11926. ((= c ?\ ) nil)
  11927. ((setq e (rassoc c fulltable) tg (car e))
  11928. tg)
  11929. (t (setq quit-flag t)))))))
  11930. (defun org-entry-is-todo-p ()
  11931. (member (org-get-todo-state) org-not-done-keywords))
  11932. (defun org-entry-is-done-p ()
  11933. (member (org-get-todo-state) org-done-keywords))
  11934. (defun org-get-todo-state ()
  11935. "Return the TODO keyword of the current subtree."
  11936. (save-excursion
  11937. (org-back-to-heading t)
  11938. (and (looking-at org-todo-line-regexp)
  11939. (match-end 2)
  11940. (match-string 2))))
  11941. (defun org-at-date-range-p (&optional inactive-ok)
  11942. "Non-nil if point is inside a date range.
  11943. When optional argument INACTIVE-OK is non-nil, also consider
  11944. inactive time ranges.
  11945. When this function returns a non-nil value, match data is set
  11946. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11947. on INACTIVE-OK."
  11948. (interactive)
  11949. (save-excursion
  11950. (catch 'exit
  11951. (let ((pos (point)))
  11952. (skip-chars-backward "^[<\r\n")
  11953. (skip-chars-backward "<[")
  11954. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11955. (>= (match-end 0) pos)
  11956. (throw 'exit t))
  11957. (skip-chars-backward "^<[\r\n")
  11958. (skip-chars-backward "<[")
  11959. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11960. (>= (match-end 0) pos)
  11961. (throw 'exit t)))
  11962. nil)))
  11963. (defun org-get-repeat (&optional tagline)
  11964. "Check if there is a deadline/schedule with repeater in this entry."
  11965. (save-match-data
  11966. (save-excursion
  11967. (org-back-to-heading t)
  11968. (and (re-search-forward (if tagline
  11969. (concat tagline "\\s-*" org-repeat-re)
  11970. org-repeat-re)
  11971. (org-entry-end-position) t)
  11972. (match-string-no-properties 1)))))
  11973. (defvar org-last-changed-timestamp)
  11974. (defvar org-last-inserted-timestamp)
  11975. (defvar org-log-post-message)
  11976. (defvar org-log-note-purpose)
  11977. (defvar org-log-note-how nil)
  11978. (defvar org-log-note-extra)
  11979. (defun org-auto-repeat-maybe (done-word)
  11980. "Check if the current headline contains a repeated time-stamp.
  11981. If yes, set TODO state back to what it was and change the base date
  11982. of repeating deadline/scheduled time stamps to new date.
  11983. This function is run automatically after each state change to a DONE state."
  11984. (let* ((repeat (org-get-repeat))
  11985. (aa (assoc org-last-state org-todo-kwd-alist))
  11986. (interpret (nth 1 aa))
  11987. (head (nth 2 aa))
  11988. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11989. (msg "Entry repeats: ")
  11990. (org-log-done nil)
  11991. (org-todo-log-states nil))
  11992. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11993. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11994. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11995. org-todo-repeat-to-state)))
  11996. (unless (and to-state (member to-state org-todo-keywords-1))
  11997. (setq to-state (if (eq interpret 'type) org-last-state head)))
  11998. (org-todo to-state))
  11999. (when (or org-log-repeat (org-entry-get nil "CLOCK"))
  12000. (org-entry-put nil "LAST_REPEAT" (format-time-string
  12001. (org-time-stamp-format t t))))
  12002. (when org-log-repeat
  12003. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  12004. (memq 'org-add-log-note post-command-hook))
  12005. ;; We are already setup for some record.
  12006. (when (eq org-log-repeat 'note)
  12007. ;; Make sure we take a note, not only a time stamp.
  12008. (setq org-log-note-how 'note))
  12009. ;; Set up for taking a record.
  12010. (org-add-log-setup 'state
  12011. (or done-word (car org-done-keywords))
  12012. org-last-state
  12013. org-log-repeat)))
  12014. (org-back-to-heading t)
  12015. (org-add-planning-info nil nil 'closed)
  12016. (let ((end (save-excursion (outline-next-heading) (point))))
  12017. (while (re-search-forward org-ts-regexp end t)
  12018. (when (save-match-data
  12019. (or (org-at-planning-p)
  12020. (org-at-property-p)
  12021. (eq (org-element-type (save-excursion
  12022. (backward-char)
  12023. (org-element-context)))
  12024. 'timestamp)))
  12025. (let ((type (cond ((match-end 1) org-scheduled-string)
  12026. ((match-end 3) org-deadline-string)
  12027. (t "Plain:")))
  12028. (ts (or (match-string 2) (match-string 4) (match-string 0))))
  12029. (cond
  12030. ((not
  12031. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  12032. ;; Time-stamps without a repeater are usually skipped.
  12033. ;; However, a SCHEDULED time-stamp without one is
  12034. ;; removed, as it is considered as no longer relevant.
  12035. (when (equal type org-scheduled-string)
  12036. (org-remove-timestamp-with-keyword type)))
  12037. (t
  12038. (let ((n (string-to-number (match-string 2 ts)))
  12039. (what (match-string 3 ts)))
  12040. (when (equal what "w") (setq n (* n 7) what "d"))
  12041. (when (and (equal what "h")
  12042. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  12043. ts)))
  12044. (user-error
  12045. "Cannot repeat in Repeat in %d hour(s) because no hour \
  12046. has been set"
  12047. n))
  12048. ;; Preparation, see if we need to modify the start
  12049. ;; date for the change.
  12050. (when (match-end 1)
  12051. (let ((time (save-match-data (org-time-string-to-time ts))))
  12052. (cond
  12053. ((equal (match-string 1 ts) ".")
  12054. ;; Shift starting date to today
  12055. (org-timestamp-change
  12056. (- (org-today) (time-to-days time))
  12057. 'day))
  12058. ((equal (match-string 1 ts) "+")
  12059. (let ((nshiftmax 10)
  12060. (nshift 0))
  12061. (while (or (= nshift 0)
  12062. (not (time-less-p (current-time) time)))
  12063. (when (= (cl-incf nshift) nshiftmax)
  12064. (or (y-or-n-p
  12065. (format "%d repeater intervals were not \
  12066. enough to shift date past today. Continue? "
  12067. nshift))
  12068. (user-error "Abort")))
  12069. (org-timestamp-change n (cdr (assoc what whata)))
  12070. (org-at-timestamp-p t)
  12071. (setq ts (match-string 1))
  12072. (setq time
  12073. (save-match-data
  12074. (org-time-string-to-time ts)))))
  12075. (org-timestamp-change (- n) (cdr (assoc what whata)))
  12076. ;; Rematch, so that we have everything in
  12077. ;; place for the real shift.
  12078. (org-at-timestamp-p t)
  12079. (setq ts (match-string 1))
  12080. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  12081. ts)))))
  12082. (save-excursion
  12083. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  12084. (setq msg
  12085. (concat
  12086. msg type " " org-last-changed-timestamp " ")))))))))
  12087. (setq org-log-post-message msg)
  12088. (message "%s" msg))))
  12089. (defun org-show-todo-tree (arg)
  12090. "Make a compact tree which shows all headlines marked with TODO.
  12091. The tree will show the lines where the regexp matches, and all higher
  12092. headlines above the match.
  12093. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  12094. With a numeric prefix N, construct a sparse tree for the Nth element
  12095. of `org-todo-keywords-1'."
  12096. (interactive "P")
  12097. (let ((case-fold-search nil)
  12098. (kwd-re
  12099. (cond ((null arg) org-not-done-regexp)
  12100. ((equal arg '(4))
  12101. (let ((kwd
  12102. (completing-read "Keyword (or KWD1|KWD2|...): "
  12103. (mapcar #'list org-todo-keywords-1))))
  12104. (concat "\\("
  12105. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  12106. "\\)\\>")))
  12107. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  12108. (regexp-quote (nth (1- (prefix-numeric-value arg))
  12109. org-todo-keywords-1)))
  12110. (t (user-error "Invalid prefix argument: %s" arg)))))
  12111. (message "%d TODO entries found"
  12112. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  12113. (defun org-deadline (arg &optional time)
  12114. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  12115. With one universal prefix argument, remove any deadline from the item.
  12116. With two universal prefix arguments, prompt for a warning delay.
  12117. With argument TIME, set the deadline at the corresponding date. TIME
  12118. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12119. (interactive "P")
  12120. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12121. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12122. 'region-start-level 'region))
  12123. org-loop-over-headlines-in-active-region)
  12124. (org-map-entries
  12125. `(org-deadline ',arg ,time)
  12126. org-loop-over-headlines-in-active-region
  12127. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12128. (let* ((old-date (org-entry-get nil "DEADLINE"))
  12129. (old-date-time (when old-date (org-time-string-to-time old-date)))
  12130. (repeater (and old-date
  12131. (string-match
  12132. "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
  12133. old-date)
  12134. (match-string 1 old-date))))
  12135. (cond
  12136. ((equal arg '(4))
  12137. (when (and old-date org-log-redeadline)
  12138. (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
  12139. (org-remove-timestamp-with-keyword org-deadline-string)
  12140. (message "Item no longer has a deadline."))
  12141. ((equal arg '(16))
  12142. (save-excursion
  12143. (org-back-to-heading t)
  12144. (if (re-search-forward
  12145. org-deadline-time-regexp
  12146. (save-excursion (outline-next-heading) (point)) t)
  12147. (let* ((rpl0 (match-string 1))
  12148. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
  12149. (replace-match
  12150. (concat org-deadline-string
  12151. " <" rpl
  12152. (format " -%dd"
  12153. (abs
  12154. (- (time-to-days
  12155. (save-match-data
  12156. (org-read-date nil t nil "Warn starting from" old-date-time)))
  12157. (time-to-days old-date-time))))
  12158. ">") t t))
  12159. (user-error "No deadline information to update"))))
  12160. (t
  12161. (org-add-planning-info 'deadline time 'closed)
  12162. (when (and old-date
  12163. org-log-redeadline
  12164. (not (equal old-date org-last-inserted-timestamp)))
  12165. (org-add-log-setup
  12166. 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
  12167. (when repeater
  12168. (save-excursion
  12169. (org-back-to-heading t)
  12170. (when (re-search-forward (concat org-deadline-string " "
  12171. org-last-inserted-timestamp)
  12172. (save-excursion
  12173. (outline-next-heading) (point)) t)
  12174. (goto-char (1- (match-end 0)))
  12175. (insert " " repeater)
  12176. (setq org-last-inserted-timestamp
  12177. (concat (substring org-last-inserted-timestamp 0 -1)
  12178. " " repeater
  12179. (substring org-last-inserted-timestamp -1))))))
  12180. (message "Deadline on %s" org-last-inserted-timestamp))))))
  12181. (defun org-schedule (arg &optional time)
  12182. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  12183. With one universal prefix argument, remove any scheduling date from the item.
  12184. With two universal prefix arguments, prompt for a delay cookie.
  12185. With argument TIME, scheduled at the corresponding date. TIME can
  12186. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12187. (interactive "P")
  12188. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12189. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12190. 'region-start-level 'region))
  12191. org-loop-over-headlines-in-active-region)
  12192. (org-map-entries
  12193. `(org-schedule ',arg ,time)
  12194. org-loop-over-headlines-in-active-region
  12195. cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
  12196. (let* ((old-date (org-entry-get nil "SCHEDULED"))
  12197. (old-date-time (when old-date (org-time-string-to-time old-date)))
  12198. (repeater (and old-date
  12199. (string-match
  12200. "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
  12201. old-date)
  12202. (match-string 1 old-date))))
  12203. (cond
  12204. ((equal arg '(4))
  12205. (progn
  12206. (when (and old-date org-log-reschedule)
  12207. (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
  12208. (org-remove-timestamp-with-keyword org-scheduled-string)
  12209. (message "Item is no longer scheduled.")))
  12210. ((equal arg '(16))
  12211. (save-excursion
  12212. (org-back-to-heading t)
  12213. (if (re-search-forward
  12214. org-scheduled-time-regexp
  12215. (save-excursion (outline-next-heading) (point)) t)
  12216. (let* ((rpl0 (match-string 1))
  12217. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
  12218. (replace-match
  12219. (concat org-scheduled-string
  12220. " <" rpl
  12221. (format " -%dd"
  12222. (abs
  12223. (- (time-to-days
  12224. (save-match-data
  12225. (org-read-date nil t nil "Delay until" old-date-time)))
  12226. (time-to-days old-date-time))))
  12227. ">") t t))
  12228. (user-error "No scheduled information to update"))))
  12229. (t
  12230. (org-add-planning-info 'scheduled time 'closed)
  12231. (when (and old-date
  12232. org-log-reschedule
  12233. (not (equal old-date org-last-inserted-timestamp)))
  12234. (org-add-log-setup
  12235. 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
  12236. (when repeater
  12237. (save-excursion
  12238. (org-back-to-heading t)
  12239. (when (re-search-forward (concat org-scheduled-string " "
  12240. org-last-inserted-timestamp)
  12241. (save-excursion
  12242. (outline-next-heading) (point)) t)
  12243. (goto-char (1- (match-end 0)))
  12244. (insert " " repeater)
  12245. (setq org-last-inserted-timestamp
  12246. (concat (substring org-last-inserted-timestamp 0 -1)
  12247. " " repeater
  12248. (substring org-last-inserted-timestamp -1))))))
  12249. (message "Scheduled to %s" org-last-inserted-timestamp))))))
  12250. (defun org-get-scheduled-time (pom &optional inherit)
  12251. "Get the scheduled time as a time tuple, of a format suitable
  12252. for calling org-schedule with, or if there is no scheduling,
  12253. returns nil."
  12254. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  12255. (when time
  12256. (apply 'encode-time (org-parse-time-string time)))))
  12257. (defun org-get-deadline-time (pom &optional inherit)
  12258. "Get the deadline as a time tuple, of a format suitable for
  12259. calling org-deadline with, or if there is no scheduling, returns
  12260. nil."
  12261. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  12262. (when time
  12263. (apply 'encode-time (org-parse-time-string time)))))
  12264. (defun org-remove-timestamp-with-keyword (keyword)
  12265. "Remove all time stamps with KEYWORD in the current entry."
  12266. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  12267. beg)
  12268. (save-excursion
  12269. (org-back-to-heading t)
  12270. (setq beg (point))
  12271. (outline-next-heading)
  12272. (while (re-search-backward re beg t)
  12273. (replace-match "")
  12274. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  12275. (equal (char-before) ?\ ))
  12276. (backward-delete-char 1)
  12277. (when (string-match "^[ \t]*$" (buffer-substring
  12278. (point-at-bol) (point-at-eol)))
  12279. (delete-region (point-at-bol)
  12280. (min (point-max) (1+ (point-at-eol))))))))))
  12281. (defvar org-time-was-given) ; dynamically scoped parameter
  12282. (defvar org-end-time-was-given) ; dynamically scoped parameter
  12283. (defun org-at-planning-p ()
  12284. "Non-nil when point is on a planning info line."
  12285. ;; This is as accurate and faster than `org-element-at-point' since
  12286. ;; planning info location is fixed in the section.
  12287. (org-with-wide-buffer
  12288. (beginning-of-line)
  12289. (and (looking-at-p org-planning-line-re)
  12290. (eq (point)
  12291. (ignore-errors
  12292. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  12293. (org-back-to-heading t)
  12294. (org-with-limited-levels (org-back-to-heading t)))
  12295. (line-beginning-position 2))))))
  12296. (defun org-add-planning-info (what &optional time &rest remove)
  12297. "Insert new timestamp with keyword in the planning line.
  12298. WHAT indicates what kind of time stamp to add. It is a symbol
  12299. among `closed', `deadline', `scheduled' and nil. TIME indicates
  12300. the time to use. If none is given, the user is prompted for
  12301. a date. REMOVE indicates what kind of entries to remove. An old
  12302. WHAT entry will also be removed."
  12303. (let (org-time-was-given org-end-time-was-given default-time default-input)
  12304. (catch 'exit
  12305. (when (and (memq what '(scheduled deadline))
  12306. (or (not time)
  12307. (and (stringp time)
  12308. (string-match "^[-+]+[0-9]" time))))
  12309. ;; Try to get a default date/time from existing timestamp
  12310. (save-excursion
  12311. (org-back-to-heading t)
  12312. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  12313. (when (re-search-forward (if (eq what 'scheduled)
  12314. org-scheduled-time-regexp
  12315. org-deadline-time-regexp)
  12316. end t)
  12317. (setq ts (match-string 1)
  12318. default-time (apply 'encode-time (org-parse-time-string ts))
  12319. default-input (and ts (org-get-compact-tod ts)))))))
  12320. (when what
  12321. (setq time
  12322. (if (stringp time)
  12323. ;; This is a string (relative or absolute), set
  12324. ;; proper date.
  12325. (apply #'encode-time
  12326. (org-read-date-analyze
  12327. time default-time (decode-time default-time)))
  12328. ;; If necessary, get the time from the user
  12329. (or time (org-read-date nil 'to-time nil nil
  12330. default-time default-input)))))
  12331. (org-with-wide-buffer
  12332. (org-back-to-heading t)
  12333. (forward-line)
  12334. (unless (bolp) (insert "\n"))
  12335. (cond ((looking-at-p org-planning-line-re)
  12336. ;; Move to current indentation.
  12337. (skip-chars-forward " \t")
  12338. ;; Check if we have to remove something.
  12339. (dolist (type (if what (cons what remove) remove))
  12340. (save-excursion
  12341. (when (re-search-forward
  12342. (cl-case type
  12343. (closed org-closed-time-regexp)
  12344. (deadline org-deadline-time-regexp)
  12345. (scheduled org-scheduled-time-regexp)
  12346. (otherwise
  12347. (error "Invalid planning type: %s" type)))
  12348. (line-end-position) t)
  12349. ;; Delete until next keyword or end of line.
  12350. (delete-region
  12351. (match-beginning 0)
  12352. (if (re-search-forward org-keyword-time-not-clock-regexp
  12353. (line-end-position)
  12354. t)
  12355. (match-beginning 0)
  12356. (line-end-position))))))
  12357. ;; If there is nothing more to add and no more keyword
  12358. ;; is left, remove the line completely.
  12359. (if (and (looking-at-p "[ \t]*$") (not what))
  12360. (delete-region (line-beginning-position)
  12361. (line-beginning-position 2))
  12362. ;; If we removed last keyword, do not leave trailing
  12363. ;; white space at the end of line.
  12364. (let ((p (point)))
  12365. (save-excursion
  12366. (end-of-line)
  12367. (unless (= (skip-chars-backward " \t" p) 0)
  12368. (delete-region (point) (line-end-position)))))))
  12369. ((not what) (throw 'exit nil)) ; Nothing to do.
  12370. (t (insert-before-markers "\n")
  12371. (backward-char 1)
  12372. (when org-adapt-indentation
  12373. (indent-to-column (1+ (org-outline-level))))))
  12374. (when what
  12375. ;; Insert planning keyword.
  12376. (insert (cl-case what
  12377. (closed org-closed-string)
  12378. (deadline org-deadline-string)
  12379. (scheduled org-scheduled-string)
  12380. (otherwise (error "Invalid planning type: %s" what)))
  12381. " ")
  12382. ;; Insert associated timestamp.
  12383. (let ((ts (org-insert-time-stamp
  12384. time
  12385. (or org-time-was-given
  12386. (and (eq what 'closed) org-log-done-with-time))
  12387. (eq what 'closed)
  12388. nil nil (list org-end-time-was-given))))
  12389. (unless (eolp) (insert " "))
  12390. ts))))))
  12391. (defvar org-log-note-marker (make-marker)
  12392. "Marker pointing at the entry where the note is to be inserted.")
  12393. (defvar org-log-note-purpose nil)
  12394. (defvar org-log-note-state nil)
  12395. (defvar org-log-note-previous-state nil)
  12396. (defvar org-log-note-extra nil)
  12397. (defvar org-log-note-window-configuration nil)
  12398. (defvar org-log-note-return-to (make-marker))
  12399. (defvar org-log-note-effective-time nil
  12400. "Remembered current time so that dynamically scoped
  12401. `org-extend-today-until' affects timestamps in state change log")
  12402. (defvar org-log-post-message nil
  12403. "Message to be displayed after a log note has been stored.
  12404. The auto-repeater uses this.")
  12405. (defun org-add-note ()
  12406. "Add a note to the current entry.
  12407. This is done in the same way as adding a state change note."
  12408. (interactive)
  12409. (org-add-log-setup 'note))
  12410. (defun org-log-beginning (&optional create)
  12411. "Return expected start of log notes in current entry.
  12412. When optional argument CREATE is non-nil, the function creates
  12413. a drawer to store notes, if necessary. Returned position ignores
  12414. narrowing."
  12415. (org-with-wide-buffer
  12416. (let ((drawer (org-log-into-drawer)))
  12417. (cond
  12418. (drawer
  12419. (org-end-of-meta-data)
  12420. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  12421. (end (if (org-at-heading-p) (point)
  12422. (save-excursion (outline-next-heading) (point))))
  12423. (case-fold-search t))
  12424. (catch 'exit
  12425. ;; Try to find existing drawer.
  12426. (while (re-search-forward regexp end t)
  12427. (let ((element (org-element-at-point)))
  12428. (when (eq (org-element-type element) 'drawer)
  12429. (let ((cend (org-element-property :contents-end element)))
  12430. (when (and (not org-log-states-order-reversed) cend)
  12431. (goto-char cend)))
  12432. (throw 'exit nil))))
  12433. ;; No drawer found. Create one, if permitted.
  12434. (when create
  12435. (unless (bolp) (insert "\n"))
  12436. (let ((beg (point)))
  12437. (insert ":" drawer ":\n:END:\n")
  12438. (org-indent-region beg (point)))
  12439. (end-of-line -1)))))
  12440. (t
  12441. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  12442. (skip-chars-forward " \t\n")
  12443. (beginning-of-line)
  12444. (unless org-log-states-order-reversed
  12445. (org-skip-over-state-notes)
  12446. (skip-chars-backward " \t\n")
  12447. (forward-line)))))
  12448. (if (bolp) (point) (line-beginning-position 2))))
  12449. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  12450. "Set up the post command hook to take a note.
  12451. If this is about to TODO state change, the new state is expected in STATE.
  12452. HOW is an indicator what kind of note should be created.
  12453. EXTRA is additional text that will be inserted into the notes buffer."
  12454. (move-marker org-log-note-marker (point))
  12455. (setq org-log-note-purpose purpose
  12456. org-log-note-state state
  12457. org-log-note-previous-state prev-state
  12458. org-log-note-how how
  12459. org-log-note-extra extra
  12460. org-log-note-effective-time (org-current-effective-time))
  12461. (add-hook 'post-command-hook 'org-add-log-note 'append))
  12462. (defun org-skip-over-state-notes ()
  12463. "Skip past the list of State notes in an entry."
  12464. (when (ignore-errors (goto-char (org-in-item-p)))
  12465. (let* ((struct (org-list-struct))
  12466. (prevs (org-list-prevs-alist struct))
  12467. (regexp
  12468. (concat "[ \t]*- +"
  12469. (replace-regexp-in-string
  12470. " +" " +"
  12471. (org-replace-escapes
  12472. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  12473. `(("%d" . ,org-ts-regexp-inactive)
  12474. ("%D" . ,org-ts-regexp)
  12475. ("%s" . "\"\\S-+\"")
  12476. ("%S" . "\"\\S-+\"")
  12477. ("%t" . ,org-ts-regexp-inactive)
  12478. ("%T" . ,org-ts-regexp)
  12479. ("%u" . ".*?")
  12480. ("%U" . ".*?")))))))
  12481. (while (looking-at-p regexp)
  12482. (goto-char (or (org-list-get-next-item (point) struct prevs)
  12483. (org-list-get-item-end (point) struct)))))))
  12484. (defun org-add-log-note (&optional _purpose)
  12485. "Pop up a window for taking a note, and add this note later."
  12486. (remove-hook 'post-command-hook 'org-add-log-note)
  12487. (setq org-log-note-window-configuration (current-window-configuration))
  12488. (delete-other-windows)
  12489. (move-marker org-log-note-return-to (point))
  12490. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12491. (goto-char org-log-note-marker)
  12492. (org-switch-to-buffer-other-window "*Org Note*")
  12493. (erase-buffer)
  12494. (if (memq org-log-note-how '(time state))
  12495. (let (current-prefix-arg) (org-store-log-note))
  12496. (let ((org-inhibit-startup t)) (org-mode))
  12497. (insert (format "# Insert note for %s.
  12498. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12499. (cond
  12500. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12501. ((eq org-log-note-purpose 'done) "closed todo item")
  12502. ((eq org-log-note-purpose 'state)
  12503. (format "state change from \"%s\" to \"%s\""
  12504. (or org-log-note-previous-state "")
  12505. (or org-log-note-state "")))
  12506. ((eq org-log-note-purpose 'reschedule)
  12507. "rescheduling")
  12508. ((eq org-log-note-purpose 'delschedule)
  12509. "no longer scheduled")
  12510. ((eq org-log-note-purpose 'redeadline)
  12511. "changing deadline")
  12512. ((eq org-log-note-purpose 'deldeadline)
  12513. "removing deadline")
  12514. ((eq org-log-note-purpose 'refile)
  12515. "refiling")
  12516. ((eq org-log-note-purpose 'note)
  12517. "this entry")
  12518. (t (error "This should not happen")))))
  12519. (when org-log-note-extra (insert org-log-note-extra))
  12520. (setq-local org-finish-function 'org-store-log-note)
  12521. (run-hooks 'org-log-buffer-setup-hook)))
  12522. (defvar org-note-abort nil) ; dynamically scoped
  12523. (defun org-store-log-note ()
  12524. "Finish taking a log note, and insert it to where it belongs."
  12525. (let ((txt (prog1 (buffer-string)
  12526. (kill-buffer)))
  12527. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12528. lines)
  12529. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12530. (setq txt (replace-match "" t t txt)))
  12531. (when (string-match "\\s-+\\'" txt)
  12532. (setq txt (replace-match "" t t txt)))
  12533. (setq lines (org-split-string txt "\n"))
  12534. (when (org-string-nw-p note)
  12535. (setq note
  12536. (org-replace-escapes
  12537. note
  12538. (list (cons "%u" (user-login-name))
  12539. (cons "%U" user-full-name)
  12540. (cons "%t" (format-time-string
  12541. (org-time-stamp-format 'long 'inactive)
  12542. org-log-note-effective-time))
  12543. (cons "%T" (format-time-string
  12544. (org-time-stamp-format 'long nil)
  12545. org-log-note-effective-time))
  12546. (cons "%d" (format-time-string
  12547. (org-time-stamp-format nil 'inactive)
  12548. org-log-note-effective-time))
  12549. (cons "%D" (format-time-string
  12550. (org-time-stamp-format nil nil)
  12551. org-log-note-effective-time))
  12552. (cons "%s" (cond
  12553. ((not org-log-note-state) "")
  12554. ((string-match-p org-ts-regexp
  12555. org-log-note-state)
  12556. (format "\"[%s]\""
  12557. (substring org-log-note-state 1 -1)))
  12558. (t (format "\"%s\"" org-log-note-state))))
  12559. (cons "%S"
  12560. (cond
  12561. ((not org-log-note-previous-state) "")
  12562. ((string-match-p org-ts-regexp
  12563. org-log-note-previous-state)
  12564. (format "\"[%s]\""
  12565. (substring
  12566. org-log-note-previous-state 1 -1)))
  12567. (t (format "\"%s\""
  12568. org-log-note-previous-state)))))))
  12569. (when lines (setq note (concat note " \\\\")))
  12570. (push note lines))
  12571. (when (and lines (not (or current-prefix-arg org-note-abort)))
  12572. (with-current-buffer (marker-buffer org-log-note-marker)
  12573. (org-with-wide-buffer
  12574. ;; Find location for the new note.
  12575. (goto-char org-log-note-marker)
  12576. (set-marker org-log-note-marker nil)
  12577. (goto-char (org-log-beginning t))
  12578. ;; Make sure point is at the beginning of an empty line.
  12579. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12580. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12581. ;; In an existing list, add a new item at the top level.
  12582. ;; Otherwise, indent line like a regular one.
  12583. (let ((itemp (org-in-item-p)))
  12584. (if itemp
  12585. (indent-line-to
  12586. (let ((struct (save-excursion
  12587. (goto-char itemp) (org-list-struct))))
  12588. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12589. (org-indent-line)))
  12590. (insert (org-list-bullet-string "-") (pop lines))
  12591. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12592. (dolist (line lines)
  12593. (insert "\n")
  12594. (indent-line-to ind)
  12595. (insert line)))
  12596. (message "Note stored")
  12597. (org-back-to-heading t)
  12598. (org-cycle-hide-drawers 'children))
  12599. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12600. ;; from within `org-add-log-note' because `buffer-undo-list'
  12601. ;; is then modified outside of `org-with-remote-undo'.
  12602. (when (eq this-command 'org-agenda-todo)
  12603. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12604. ;; Don't add undo information when called from `org-agenda-todo'.
  12605. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12606. (set-window-configuration org-log-note-window-configuration)
  12607. (with-current-buffer (marker-buffer org-log-note-return-to)
  12608. (goto-char org-log-note-return-to))
  12609. (move-marker org-log-note-return-to nil)
  12610. (when org-log-post-message (message "%s" org-log-post-message))))
  12611. (defun org-remove-empty-drawer-at (pos)
  12612. "Remove an empty drawer at position POS.
  12613. POS may also be a marker."
  12614. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12615. (org-with-wide-buffer
  12616. (goto-char pos)
  12617. (let ((drawer (org-element-at-point)))
  12618. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12619. (not (org-element-property :contents-begin drawer)))
  12620. (delete-region (org-element-property :begin drawer)
  12621. (progn (goto-char (org-element-property :end drawer))
  12622. (skip-chars-backward " \r\t\n")
  12623. (forward-line)
  12624. (point))))))))
  12625. (defvar org-ts-type nil)
  12626. (defun org-sparse-tree (&optional arg type)
  12627. "Create a sparse tree, prompt for the details.
  12628. This command can create sparse trees. You first need to select the type
  12629. of match used to create the tree:
  12630. t Show all TODO entries.
  12631. T Show entries with a specific TODO keyword.
  12632. m Show entries selected by a tags/property match.
  12633. p Enter a property name and its value (both with completion on existing
  12634. names/values) and show entries with that property.
  12635. r Show entries matching a regular expression (`/' can be used as well).
  12636. b Show deadlines and scheduled items before a date.
  12637. a Show deadlines and scheduled items after a date.
  12638. d Show deadlines due within `org-deadline-warning-days'.
  12639. D Show deadlines and scheduled items between a date range."
  12640. (interactive "P")
  12641. (setq type (or type org-sparse-tree-default-date-type))
  12642. (setq org-ts-type type)
  12643. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12644. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12645. \[c]ycle through date types: %s"
  12646. (cl-case type
  12647. (all "all timestamps")
  12648. (scheduled "only scheduled")
  12649. (deadline "only deadline")
  12650. (active "only active timestamps")
  12651. (inactive "only inactive timestamps")
  12652. (closed "with a closed time-stamp")
  12653. (otherwise "scheduled/deadline")))
  12654. (let ((answer (read-char-exclusive)))
  12655. (cl-case answer
  12656. (?c
  12657. (org-sparse-tree
  12658. arg
  12659. (cadr
  12660. (memq type '(nil all scheduled deadline active inactive closed)))))
  12661. (?d (call-interactively 'org-check-deadlines))
  12662. (?b (call-interactively 'org-check-before-date))
  12663. (?a (call-interactively 'org-check-after-date))
  12664. (?D (call-interactively 'org-check-dates-range))
  12665. (?t (call-interactively 'org-show-todo-tree))
  12666. (?T (org-show-todo-tree '(4)))
  12667. (?m (call-interactively 'org-match-sparse-tree))
  12668. ((?p ?P)
  12669. (let* ((kwd (completing-read
  12670. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12671. (value (completing-read
  12672. "Value: " (mapcar #'list (org-property-values kwd)))))
  12673. (unless (string-match "\\`{.*}\\'" value)
  12674. (setq value (concat "\"" value "\"")))
  12675. (org-match-sparse-tree arg (concat kwd "=" value))))
  12676. ((?r ?R ?/) (call-interactively 'org-occur))
  12677. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12678. (defvar-local org-occur-highlights nil
  12679. "List of overlays used for occur matches.")
  12680. (defvar-local org-occur-parameters nil
  12681. "Parameters of the active org-occur calls.
  12682. This is a list, each call to org-occur pushes as cons cell,
  12683. containing the regular expression and the callback, onto the list.
  12684. The list can contain several entries if `org-occur' has been called
  12685. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12686. will only contain one set of parameters. When the highlights are
  12687. removed (for example with `C-c C-c', or with the next edit (depending
  12688. on `org-remove-highlights-with-change'), this variable is emptied
  12689. as well.")
  12690. (defun org-occur (regexp &optional keep-previous callback)
  12691. "Make a compact tree which shows all matches of REGEXP.
  12692. The tree will show the lines where the regexp matches, and any other context
  12693. defined in `org-show-context-detail', which see.
  12694. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12695. done by a previous call to `org-occur' will be kept, to allow stacking of
  12696. calls to this command.
  12697. Optional argument CALLBACK can be a function of no argument. In this case,
  12698. it is called with point at the end of the match, match data being set
  12699. accordingly. Current match is shown only if the return value is non-nil.
  12700. The function must neither move point nor alter narrowing."
  12701. (interactive "sRegexp: \nP")
  12702. (when (equal regexp "")
  12703. (user-error "Regexp cannot be empty"))
  12704. (unless keep-previous
  12705. (org-remove-occur-highlights nil nil t))
  12706. (push (cons regexp callback) org-occur-parameters)
  12707. (let ((cnt 0))
  12708. (save-excursion
  12709. (goto-char (point-min))
  12710. (when (or (not keep-previous) ; do not want to keep
  12711. (not org-occur-highlights)) ; no previous matches
  12712. ;; hide everything
  12713. (org-overview))
  12714. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12715. (isearch-no-upper-case-p regexp t)
  12716. org-occur-case-fold-search)))
  12717. (while (re-search-forward regexp nil t)
  12718. (when (or (not callback)
  12719. (save-match-data (funcall callback)))
  12720. (setq cnt (1+ cnt))
  12721. (when org-highlight-sparse-tree-matches
  12722. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12723. (org-show-context 'occur-tree)))))
  12724. (when org-remove-highlights-with-change
  12725. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12726. nil 'local))
  12727. (unless org-sparse-tree-open-archived-trees
  12728. (org-hide-archived-subtrees (point-min) (point-max)))
  12729. (run-hooks 'org-occur-hook)
  12730. (when (called-interactively-p 'interactive)
  12731. (message "%d match(es) for regexp %s" cnt regexp))
  12732. cnt))
  12733. (defun org-occur-next-match (&optional n _reset)
  12734. "Function for `next-error-function' to find sparse tree matches.
  12735. N is the number of matches to move, when negative move backwards.
  12736. This function always goes back to the starting point when no
  12737. match is found."
  12738. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12739. (search-func (if (< n 0)
  12740. 'previous-single-char-property-change
  12741. 'next-single-char-property-change))
  12742. (n (abs n))
  12743. (pos (point))
  12744. p1)
  12745. (catch 'exit
  12746. (while (setq p1 (funcall search-func (point) 'org-type))
  12747. (when (equal p1 limit)
  12748. (goto-char pos)
  12749. (user-error "No more matches"))
  12750. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12751. (setq n (1- n))
  12752. (when (= n 0)
  12753. (goto-char p1)
  12754. (throw 'exit (point))))
  12755. (goto-char p1))
  12756. (goto-char p1)
  12757. (user-error "No more matches"))))
  12758. (defun org-show-context (&optional key)
  12759. "Make sure point and context are visible.
  12760. Optional argument KEY, when non-nil, is a symbol. See
  12761. `org-show-context-detail' for allowed values and how much is to
  12762. be shown."
  12763. (org-show-set-visibility
  12764. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12765. ((cdr (assq key org-show-context-detail)))
  12766. (t (cdr (assq 'default org-show-context-detail))))))
  12767. (defun org-show-set-visibility (detail)
  12768. "Set visibility around point according to DETAIL.
  12769. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12770. `tree', `canonical' or t. See `org-show-context-detail' for more
  12771. information."
  12772. ;; Show current heading and possibly its entry, following headline
  12773. ;; or all children.
  12774. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12775. (org-flag-heading nil)
  12776. (org-show-entry)
  12777. ;; If point is hidden within a drawer or a block, make sure to
  12778. ;; expose it.
  12779. (dolist (o (overlays-at (point)))
  12780. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  12781. (delete-overlay o)))
  12782. (unless (org-before-first-heading-p)
  12783. (org-with-limited-levels
  12784. (cl-case detail
  12785. ((tree canonical t) (org-show-children))
  12786. ((nil minimal ancestors))
  12787. (t (save-excursion
  12788. (outline-next-heading)
  12789. (org-flag-heading nil)))))))
  12790. ;; Show all siblings.
  12791. (when (eq detail 'lineage) (org-show-siblings))
  12792. ;; Show ancestors, possibly with their children.
  12793. (when (memq detail '(ancestors lineage tree canonical t))
  12794. (save-excursion
  12795. (while (org-up-heading-safe)
  12796. (org-flag-heading nil)
  12797. (when (memq detail '(canonical t)) (org-show-entry))
  12798. (when (memq detail '(tree canonical t)) (org-show-children))))))
  12799. (defvar org-reveal-start-hook nil
  12800. "Hook run before revealing a location.")
  12801. (defun org-reveal (&optional siblings)
  12802. "Show current entry, hierarchy above it, and the following headline.
  12803. This can be used to show a consistent set of context around
  12804. locations exposed with `org-show-context'.
  12805. With optional argument SIBLINGS, on each level of the hierarchy all
  12806. siblings are shown. This repairs the tree structure to what it would
  12807. look like when opened with hierarchical calls to `org-cycle'.
  12808. With a \\[universal-argument] \\[universal-argument] prefix, \
  12809. go to the parent and show the entire tree."
  12810. (interactive "P")
  12811. (run-hooks 'org-reveal-start-hook)
  12812. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12813. ((equal siblings '(16))
  12814. (save-excursion
  12815. (when (org-up-heading-safe)
  12816. (org-show-subtree)
  12817. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12818. (t (org-show-set-visibility 'lineage))))
  12819. (defun org-highlight-new-match (beg end)
  12820. "Highlight from BEG to END and mark the highlight is an occur headline."
  12821. (let ((ov (make-overlay beg end)))
  12822. (overlay-put ov 'face 'secondary-selection)
  12823. (overlay-put ov 'org-type 'org-occur)
  12824. (push ov org-occur-highlights)))
  12825. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12826. "Remove the occur highlights from the buffer.
  12827. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12828. from the `before-change-functions' in the current buffer."
  12829. (interactive)
  12830. (unless org-inhibit-highlight-removal
  12831. (mapc #'delete-overlay org-occur-highlights)
  12832. (setq org-occur-highlights nil)
  12833. (setq org-occur-parameters nil)
  12834. (unless noremove
  12835. (remove-hook 'before-change-functions
  12836. 'org-remove-occur-highlights 'local))))
  12837. ;;;; Priorities
  12838. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12839. "Regular expression matching the priority indicator.")
  12840. (defvar org-remove-priority-next-time nil)
  12841. (defun org-priority-up ()
  12842. "Increase the priority of the current item."
  12843. (interactive)
  12844. (org-priority 'up))
  12845. (defun org-priority-down ()
  12846. "Decrease the priority of the current item."
  12847. (interactive)
  12848. (org-priority 'down))
  12849. (defun org-priority (&optional action _show)
  12850. "Change the priority of an item.
  12851. ACTION can be `set', `up', `down', or a character."
  12852. (interactive "P")
  12853. (if (equal action '(4))
  12854. (org-show-priority)
  12855. (unless org-enable-priority-commands
  12856. (user-error "Priority commands are disabled"))
  12857. (setq action (or action 'set))
  12858. (let (current new news have remove)
  12859. (save-excursion
  12860. (org-back-to-heading t)
  12861. (when (looking-at org-priority-regexp)
  12862. (setq current (string-to-char (match-string 2))
  12863. have t))
  12864. (cond
  12865. ((eq action 'remove)
  12866. (setq remove t new ?\ ))
  12867. ((or (eq action 'set)
  12868. (integerp action))
  12869. (if (not (eq action 'set))
  12870. (setq new action)
  12871. (message "Priority %c-%c, SPC to remove: "
  12872. org-highest-priority org-lowest-priority)
  12873. (save-match-data
  12874. (setq new (read-char-exclusive))))
  12875. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12876. (= (upcase org-lowest-priority) org-lowest-priority))
  12877. (setq new (upcase new)))
  12878. (cond ((equal new ?\ ) (setq remove t))
  12879. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12880. (user-error "Priority must be between `%c' and `%c'"
  12881. org-highest-priority org-lowest-priority))))
  12882. ((eq action 'up)
  12883. (setq new (if have
  12884. (1- current) ; normal cycling
  12885. ;; last priority was empty
  12886. (if (eq last-command this-command)
  12887. org-lowest-priority ; wrap around empty to lowest
  12888. ;; default
  12889. (if org-priority-start-cycle-with-default
  12890. org-default-priority
  12891. (1- org-default-priority))))))
  12892. ((eq action 'down)
  12893. (setq new (if have
  12894. (1+ current) ; normal cycling
  12895. ;; last priority was empty
  12896. (if (eq last-command this-command)
  12897. org-highest-priority ; wrap around empty to highest
  12898. ;; default
  12899. (if org-priority-start-cycle-with-default
  12900. org-default-priority
  12901. (1+ org-default-priority))))))
  12902. (t (user-error "Invalid action")))
  12903. (when (or (< (upcase new) org-highest-priority)
  12904. (> (upcase new) org-lowest-priority))
  12905. (if (and (memq action '(up down))
  12906. (not have) (not (eq last-command this-command)))
  12907. ;; `new' is from default priority
  12908. (error
  12909. "The default can not be set, see `org-default-priority' why")
  12910. ;; normal cycling: `new' is beyond highest/lowest priority
  12911. ;; and is wrapped around to the empty priority
  12912. (setq remove t)))
  12913. (setq news (format "%c" new))
  12914. (if have
  12915. (if remove
  12916. (replace-match "" t t nil 1)
  12917. (replace-match news t t nil 2))
  12918. (if remove
  12919. (user-error "No priority cookie found in line")
  12920. (let ((case-fold-search nil))
  12921. (looking-at org-todo-line-regexp))
  12922. (if (match-end 2)
  12923. (progn
  12924. (goto-char (match-end 2))
  12925. (insert " [#" news "]"))
  12926. (goto-char (match-beginning 3))
  12927. (insert "[#" news "] "))))
  12928. (org-set-tags nil 'align))
  12929. (if remove
  12930. (message "Priority removed")
  12931. (message "Priority of current item set to %s" news)))))
  12932. (defun org-show-priority ()
  12933. "Show the priority of the current item.
  12934. This priority is composed of the main priority given with the [#A] cookies,
  12935. and by additional input from the age of a schedules or deadline entry."
  12936. (interactive)
  12937. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12938. (org-get-at-bol 'priority)
  12939. (save-excursion
  12940. (save-match-data
  12941. (beginning-of-line)
  12942. (and (looking-at org-heading-regexp)
  12943. (org-get-priority (match-string 0))))))))
  12944. (message "Priority is %d" (if pri pri -1000))))
  12945. (defun org-get-priority (s)
  12946. "Find priority cookie and return priority."
  12947. (save-match-data
  12948. (if (functionp org-get-priority-function)
  12949. (funcall org-get-priority-function)
  12950. (if (not (string-match org-priority-regexp s))
  12951. (* 1000 (- org-lowest-priority org-default-priority))
  12952. (* 1000 (- org-lowest-priority
  12953. (string-to-char (match-string 2 s))))))))
  12954. ;;;; Tags
  12955. (defvar org-agenda-archives-mode)
  12956. (defvar org-map-continue-from nil
  12957. "Position from where mapping should continue.
  12958. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12959. (defvar org-scanner-tags nil
  12960. "The current tag list while the tags scanner is running.")
  12961. (defvar org-trust-scanner-tags nil
  12962. "Should `org-get-tags-at' use the tags for the scanner.
  12963. This is for internal dynamical scoping only.
  12964. When this is non-nil, the function `org-get-tags-at' will return the value
  12965. of `org-scanner-tags' instead of building the list by itself. This
  12966. can lead to large speed-ups when the tags scanner is used in a file with
  12967. many entries, and when the list of tags is retrieved, for example to
  12968. obtain a list of properties. Building the tags list for each entry in such
  12969. a file becomes an N^2 operation - but with this variable set, it scales
  12970. as N.")
  12971. (defvar org--matcher-tags-todo-only nil)
  12972. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12973. "Scan headline tags with inheritance and produce output ACTION.
  12974. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12975. or `agenda' to produce an entry list for an agenda view. It can also be
  12976. a Lisp form or a function that should be called at each matched headline, in
  12977. this case the return value is a list of all return values from these calls.
  12978. MATCHER is a function accepting three arguments, returning
  12979. a non-nil value whenever a given set of tags qualifies a headline
  12980. for inclusion. See `org-make-tags-matcher' for more information.
  12981. As a special case, it can also be set to t (respectively nil) in
  12982. order to match all (respectively none) headline.
  12983. When TODO-ONLY is non-nil, only lines with a not-done TODO
  12984. keyword are included in the output.
  12985. START-LEVEL can be a string with asterisks, reducing the scope to
  12986. headlines matching this string."
  12987. (require 'org-agenda)
  12988. (let* ((re (concat "^"
  12989. (if start-level
  12990. ;; Get the correct level to match
  12991. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12992. org-outline-regexp)
  12993. " *\\(\\<\\("
  12994. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  12995. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  12996. (props (list 'face 'default
  12997. 'done-face 'org-agenda-done
  12998. 'undone-face 'default
  12999. 'mouse-face 'highlight
  13000. 'org-not-done-regexp org-not-done-regexp
  13001. 'org-todo-regexp org-todo-regexp
  13002. 'org-complex-heading-regexp org-complex-heading-regexp
  13003. 'help-echo
  13004. (format "mouse-2 or RET jump to org file %s"
  13005. (abbreviate-file-name
  13006. (or (buffer-file-name (buffer-base-buffer))
  13007. (buffer-name (buffer-base-buffer)))))))
  13008. (org-map-continue-from nil)
  13009. lspos tags tags-list
  13010. (tags-alist (list (cons 0 org-file-tags)))
  13011. (llast 0) rtn rtn1 level category i txt
  13012. todo marker entry priority
  13013. ts-date ts-date-type ts-date-pair)
  13014. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  13015. (setq action (list 'lambda nil action)))
  13016. (save-excursion
  13017. (goto-char (point-min))
  13018. (when (eq action 'sparse-tree)
  13019. (org-overview)
  13020. (org-remove-occur-highlights))
  13021. (while (let (case-fold-search)
  13022. (re-search-forward re nil t))
  13023. (setq org-map-continue-from nil)
  13024. (catch :skip
  13025. (setq todo
  13026. ;; TODO: is the 1-2 difference a bug?
  13027. (when (match-end 1) (match-string-no-properties 2))
  13028. tags (when (match-end 4) (match-string-no-properties 4)))
  13029. (goto-char (setq lspos (match-beginning 0)))
  13030. (setq level (org-reduced-level (org-outline-level))
  13031. category (org-get-category))
  13032. (when (eq action 'agenda)
  13033. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  13034. ts-date (car ts-date-pair)
  13035. ts-date-type (cdr ts-date-pair)))
  13036. (setq i llast llast level)
  13037. ;; remove tag lists from same and sublevels
  13038. (while (>= i level)
  13039. (when (setq entry (assoc i tags-alist))
  13040. (setq tags-alist (delete entry tags-alist)))
  13041. (setq i (1- i)))
  13042. ;; add the next tags
  13043. (when tags
  13044. (setq tags (org-split-string tags ":")
  13045. tags-alist
  13046. (cons (cons level tags) tags-alist)))
  13047. ;; compile tags for current headline
  13048. (setq tags-list
  13049. (if org-use-tag-inheritance
  13050. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  13051. tags)
  13052. org-scanner-tags tags-list)
  13053. (when org-use-tag-inheritance
  13054. (setcdr (car tags-alist)
  13055. (mapcar (lambda (x)
  13056. (setq x (copy-sequence x))
  13057. (org-add-prop-inherited x))
  13058. (cdar tags-alist))))
  13059. (when (and tags org-use-tag-inheritance
  13060. (or (not (eq t org-use-tag-inheritance))
  13061. org-tags-exclude-from-inheritance))
  13062. ;; Selective inheritance, remove uninherited ones.
  13063. (setcdr (car tags-alist)
  13064. (org-remove-uninherited-tags (cdar tags-alist))))
  13065. (when (and
  13066. ;; eval matcher only when the todo condition is OK
  13067. (and (or (not todo-only) (member todo org-not-done-keywords))
  13068. (if (functionp matcher)
  13069. (let ((case-fold-search t) (org-trust-scanner-tags t))
  13070. (funcall matcher todo tags-list level))
  13071. matcher))
  13072. ;; Call the skipper, but return t if it does not
  13073. ;; skip, so that the `and' form continues evaluating.
  13074. (progn
  13075. (unless (eq action 'sparse-tree) (org-agenda-skip))
  13076. t)
  13077. ;; Check if timestamps are deselecting this entry
  13078. (or (not todo-only)
  13079. (and (member todo org-not-done-keywords)
  13080. (or (not org-agenda-tags-todo-honor-ignore-options)
  13081. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  13082. ;; select this headline
  13083. (cond
  13084. ((eq action 'sparse-tree)
  13085. (and org-highlight-sparse-tree-matches
  13086. (org-get-heading) (match-end 0)
  13087. (org-highlight-new-match
  13088. (match-beginning 1) (match-end 1)))
  13089. (org-show-context 'tags-tree))
  13090. ((eq action 'agenda)
  13091. (setq txt (org-agenda-format-item
  13092. ""
  13093. (concat
  13094. (if (eq org-tags-match-list-sublevels 'indented)
  13095. (make-string (1- level) ?.) "")
  13096. (org-get-heading))
  13097. (make-string level ?\s)
  13098. category
  13099. tags-list)
  13100. priority (org-get-priority txt))
  13101. (goto-char lspos)
  13102. (setq marker (org-agenda-new-marker))
  13103. (org-add-props txt props
  13104. 'org-marker marker 'org-hd-marker marker 'org-category category
  13105. 'todo-state todo
  13106. 'ts-date ts-date
  13107. 'priority priority
  13108. 'type (concat "tagsmatch" ts-date-type))
  13109. (push txt rtn))
  13110. ((functionp action)
  13111. (setq org-map-continue-from nil)
  13112. (save-excursion
  13113. (setq rtn1 (funcall action))
  13114. (push rtn1 rtn)))
  13115. (t (user-error "Invalid action")))
  13116. ;; if we are to skip sublevels, jump to end of subtree
  13117. (unless org-tags-match-list-sublevels
  13118. (org-end-of-subtree t)
  13119. (backward-char 1))))
  13120. ;; Get the correct position from where to continue
  13121. (if org-map-continue-from
  13122. (goto-char org-map-continue-from)
  13123. (and (= (point) lspos) (end-of-line 1)))))
  13124. (when (and (eq action 'sparse-tree)
  13125. (not org-sparse-tree-open-archived-trees))
  13126. (org-hide-archived-subtrees (point-min) (point-max)))
  13127. (nreverse rtn)))
  13128. (defun org-remove-uninherited-tags (tags)
  13129. "Remove all tags that are not inherited from the list TAGS."
  13130. (cond
  13131. ((eq org-use-tag-inheritance t)
  13132. (if org-tags-exclude-from-inheritance
  13133. (org-delete-all org-tags-exclude-from-inheritance tags)
  13134. tags))
  13135. ((not org-use-tag-inheritance) nil)
  13136. ((stringp org-use-tag-inheritance)
  13137. (delq nil (mapcar
  13138. (lambda (x)
  13139. (if (and (string-match org-use-tag-inheritance x)
  13140. (not (member x org-tags-exclude-from-inheritance)))
  13141. x nil))
  13142. tags)))
  13143. ((listp org-use-tag-inheritance)
  13144. (delq nil (mapcar
  13145. (lambda (x)
  13146. (if (member x org-use-tag-inheritance) x nil))
  13147. tags)))))
  13148. (defun org-match-sparse-tree (&optional todo-only match)
  13149. "Create a sparse tree according to tags string MATCH.
  13150. MATCH can contain positive and negative selection of tags, like
  13151. \"+WORK+URGENT-WITHBOSS\".
  13152. If optional argument TODO-ONLY is non-nil, only select lines that are
  13153. also TODO lines."
  13154. (interactive "P")
  13155. (org-agenda-prepare-buffers (list (current-buffer)))
  13156. (let ((org--matcher-tags-todo-only todo-only))
  13157. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  13158. org--matcher-tags-todo-only)))
  13159. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  13160. (defvar org-cached-props nil)
  13161. (defun org-cached-entry-get (pom property)
  13162. (if (or (eq t org-use-property-inheritance)
  13163. (and (stringp org-use-property-inheritance)
  13164. (let ((case-fold-search t))
  13165. (string-match-p org-use-property-inheritance property)))
  13166. (and (listp org-use-property-inheritance)
  13167. (member-ignore-case property org-use-property-inheritance)))
  13168. ;; Caching is not possible, check it directly.
  13169. (org-entry-get pom property 'inherit)
  13170. ;; Get all properties, so we can do complicated checks easily.
  13171. (cdr (assoc-string property
  13172. (or org-cached-props
  13173. (setq org-cached-props (org-entry-properties pom)))
  13174. t))))
  13175. (defun org-global-tags-completion-table (&optional files)
  13176. "Return the list of all tags in all agenda buffer/files.
  13177. Optional FILES argument is a list of files which can be used
  13178. instead of the agenda files."
  13179. (save-excursion
  13180. (org-uniquify
  13181. (delq nil
  13182. (apply #'append
  13183. (mapcar
  13184. (lambda (file)
  13185. (set-buffer (find-file-noselect file))
  13186. (mapcar (lambda (x)
  13187. (and (stringp (car-safe x))
  13188. (list (car-safe x))))
  13189. (or org-current-tag-alist (org-get-buffer-tags))))
  13190. (if (car-safe files) files
  13191. (org-agenda-files))))))))
  13192. (defun org-make-tags-matcher (match)
  13193. "Create the TAGS/TODO matcher form for the selection string MATCH.
  13194. Returns a cons of the selection string MATCH and a function
  13195. implementing the matcher.
  13196. The matcher is to be called at an Org entry, with point on the
  13197. headline, and returns non-nil if the entry matches the selection
  13198. string MATCH. It must be called with three arguments: the TODO
  13199. keyword at the entry (or nil if none), the list of all tags at
  13200. the entry including inherited ones and the reduced level of the
  13201. headline. Additionally, the category of the entry, if any, must
  13202. be specified as the text property `org-category' on the headline.
  13203. This function sets the variable `org--matcher-tags-todo-only' to
  13204. a non-nil value if the matcher restricts matching to TODO
  13205. entries, otherwise it is not touched.
  13206. See also `org-scan-tags'."
  13207. (unless match
  13208. ;; Get a new match request, with completion against the global
  13209. ;; tags table and the local tags in current buffer.
  13210. (let ((org-last-tags-completion-table
  13211. (org-uniquify
  13212. (delq nil (append (org-get-buffer-tags)
  13213. (org-global-tags-completion-table))))))
  13214. (setq match
  13215. (completing-read
  13216. "Match: "
  13217. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  13218. (let ((match0 match)
  13219. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  13220. (start 0)
  13221. tagsmatch todomatch tagsmatcher todomatcher)
  13222. ;; Expand group tags.
  13223. (setq match (org-tags-expand match))
  13224. ;; Check if there is a TODO part of this match, which would be the
  13225. ;; part after a "/". To make sure that this slash is not part of
  13226. ;; a property value to be matched against, we also check that
  13227. ;; there is no / after that slash. First, find the last slash.
  13228. (let ((s 0))
  13229. (while (string-match "/+" match s)
  13230. (setq start (match-beginning 0))
  13231. (setq s (match-end 0))))
  13232. (if (and (string-match "/+" match start)
  13233. (not (string-match-p "\"" match start)))
  13234. ;; Match contains also a TODO-matching request.
  13235. (progn
  13236. (setq tagsmatch (substring match 0 (match-beginning 0)))
  13237. (setq todomatch (substring match (match-end 0)))
  13238. (when (string-prefix-p "!" todomatch)
  13239. (setq org--matcher-tags-todo-only t)
  13240. (setq todomatch (substring todomatch 1)))
  13241. (when (string-match "\\`\\s-*\\'" todomatch)
  13242. (setq todomatch nil)))
  13243. ;; Only matching tags.
  13244. (setq tagsmatch match)
  13245. (setq todomatch nil))
  13246. ;; Make the tags matcher.
  13247. (when (org-string-nw-p tagsmatch)
  13248. (let ((orlist nil)
  13249. (orterms (org-split-string tagsmatch "|"))
  13250. term)
  13251. (while (setq term (pop orterms))
  13252. (while (and (equal (substring term -1) "\\") orterms)
  13253. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  13254. (while (string-match re term)
  13255. (let* ((rest (substring term (match-end 0)))
  13256. (minus (and (match-end 1)
  13257. (equal (match-string 1 term) "-")))
  13258. (tag (save-match-data
  13259. (replace-regexp-in-string
  13260. "\\\\-" "-" (match-string 2 term))))
  13261. (regexp (eq (string-to-char tag) ?{))
  13262. (levelp (match-end 4))
  13263. (propp (match-end 5))
  13264. (mm
  13265. (cond
  13266. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  13267. (levelp
  13268. `(,(org-op-to-function (match-string 3 term))
  13269. level
  13270. ,(string-to-number (match-string 4 term))))
  13271. (propp
  13272. (let* ((gv (pcase (upcase (match-string 5 term))
  13273. ("CATEGORY"
  13274. '(get-text-property (point) 'org-category))
  13275. ("TODO" 'todo)
  13276. (p `(org-cached-entry-get nil ,p))))
  13277. (pv (match-string 7 term))
  13278. (regexp (eq (string-to-char pv) ?{))
  13279. (strp (eq (string-to-char pv) ?\"))
  13280. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  13281. (po (org-op-to-function (match-string 6 term)
  13282. (if timep 'time strp))))
  13283. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  13284. (when timep (setq pv (org-matcher-time pv)))
  13285. (cond ((and regexp (eq po 'org<>))
  13286. `(not (string-match ,pv (or ,gv ""))))
  13287. (regexp `(string-match ,pv (or ,gv "")))
  13288. (strp `(,po (or ,gv "") ,pv))
  13289. (t
  13290. `(,po
  13291. (string-to-number (or ,gv ""))
  13292. ,(string-to-number pv))))))
  13293. (t `(member ,tag tags-list)))))
  13294. (push (if minus `(not ,mm) mm) tagsmatcher)
  13295. (setq term rest)))
  13296. (push `(and ,@tagsmatcher) orlist)
  13297. (setq tagsmatcher nil))
  13298. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  13299. ;; Make the TODO matcher.
  13300. (when (org-string-nw-p todomatch)
  13301. (let ((orlist nil))
  13302. (dolist (term (org-split-string todomatch "|"))
  13303. (while (string-match re term)
  13304. (let* ((minus (and (match-end 1)
  13305. (equal (match-string 1 term) "-")))
  13306. (kwd (match-string 2 term))
  13307. (regexp (eq (string-to-char kwd) ?{))
  13308. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  13309. `(equal todo ,kwd))))
  13310. (push (if minus `(not ,mm) mm) todomatcher))
  13311. (setq term (substring term (match-end 0))))
  13312. (push (if (> (length todomatcher) 1)
  13313. (cons 'and todomatcher)
  13314. (car todomatcher))
  13315. orlist)
  13316. (setq todomatcher nil))
  13317. (setq todomatcher (cons 'or orlist))))
  13318. ;; Return the string and function of the matcher. If no
  13319. ;; tags-specific or todo-specific matcher exists, match
  13320. ;; everything.
  13321. (let ((matcher (if (and tagsmatcher todomatcher)
  13322. `(and ,tagsmatcher ,todomatcher)
  13323. (or tagsmatcher todomatcher t))))
  13324. (when org--matcher-tags-todo-only
  13325. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  13326. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  13327. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  13328. "Expand group tags in MATCH.
  13329. This replaces every group tag in MATCH with a regexp tag search.
  13330. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  13331. will be replaced like this:
  13332. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13333. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13334. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13335. Replacing by a regexp preserves the structure of the match.
  13336. E.g., this expansion
  13337. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  13338. will match anything tagged with \"Lab\" and \"Home\", or tagged
  13339. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  13340. A group tag in MATCH can contain regular expressions of its own.
  13341. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  13342. will be replaced like this:
  13343. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  13344. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  13345. assumed to be a single group tag, and the function will return
  13346. the list of tags in this group.
  13347. When DOWNCASE is non-nil, expand downcased TAGS."
  13348. (if org-group-tags
  13349. (let* ((case-fold-search t)
  13350. (stable org-mode-syntax-table)
  13351. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  13352. (taggroups (if downcased
  13353. (mapcar (lambda (tg) (mapcar #'downcase tg))
  13354. taggroups)
  13355. taggroups))
  13356. (taggroups-keys (mapcar #'car taggroups))
  13357. (return-match (if downcased (downcase match) match))
  13358. (count 0)
  13359. (work-already-expanded tags-already-expanded)
  13360. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  13361. ;; @ and _ are allowed as word-components in tags.
  13362. (modify-syntax-entry ?@ "w" stable)
  13363. (modify-syntax-entry ?_ "w" stable)
  13364. ;; Temporarily replace regexp-expressions in the match-expression.
  13365. (while (string-match "{.+?}" return-match)
  13366. (cl-incf count)
  13367. (push (match-string 0 return-match) regexps-in-match)
  13368. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  13369. (while (and taggroups-keys
  13370. (with-syntax-table stable
  13371. (string-match
  13372. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  13373. (regexp-opt taggroups-keys) "\\>\\)")
  13374. return-match)))
  13375. (let* ((dir (match-string 1 return-match))
  13376. (tag (match-string 2 return-match))
  13377. (tag (if downcased (downcase tag) tag)))
  13378. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  13379. (member tag work-already-expanded))
  13380. (setq tags-in-group (assoc tag taggroups))
  13381. (push tag work-already-expanded)
  13382. ;; Recursively expand each tag in the group, if the tag hasn't
  13383. ;; already been expanded. Restore the match-data after all recursive calls.
  13384. (save-match-data
  13385. (let (tags-expanded)
  13386. (dolist (x (cdr tags-in-group))
  13387. (if (and (member x taggroups-keys)
  13388. (not (member x work-already-expanded)))
  13389. (setq tags-expanded
  13390. (delete-dups
  13391. (append
  13392. (org-tags-expand x t downcased
  13393. work-already-expanded)
  13394. tags-expanded)))
  13395. (setq tags-expanded
  13396. (append (list x) tags-expanded)))
  13397. (setq work-already-expanded
  13398. (delete-dups
  13399. (append tags-expanded
  13400. work-already-expanded))))
  13401. (setq tags-in-group
  13402. (delete-dups (cons (car tags-in-group)
  13403. tags-expanded)))))
  13404. ;; Filter tag-regexps from tags.
  13405. (setq regexp-in-group-escaped
  13406. (delq nil (mapcar (lambda (x)
  13407. (if (stringp x)
  13408. (and (equal "{" (substring x 0 1))
  13409. (equal "}" (substring x -1))
  13410. x)
  13411. x))
  13412. tags-in-group))
  13413. regexp-in-group
  13414. (mapcar (lambda (x)
  13415. (substring x 1 -1))
  13416. regexp-in-group-escaped)
  13417. tags-in-group
  13418. (delq nil (mapcar (lambda (x)
  13419. (if (stringp x)
  13420. (and (not (equal "{" (substring x 0 1)))
  13421. (not (equal "}" (substring x -1)))
  13422. x)
  13423. x))
  13424. tags-in-group)))
  13425. ;; If single-as-list, do no more in the while-loop.
  13426. (if (not single-as-list)
  13427. (progn
  13428. (when regexp-in-group
  13429. (setq regexp-in-group
  13430. (concat "\\|"
  13431. (mapconcat 'identity regexp-in-group
  13432. "\\|"))))
  13433. (setq tags-in-group
  13434. (concat dir
  13435. "{\\<"
  13436. (regexp-opt tags-in-group)
  13437. "\\>"
  13438. regexp-in-group
  13439. "}"))
  13440. (when (stringp tags-in-group)
  13441. (org-add-props tags-in-group '(grouptag t)))
  13442. (setq return-match
  13443. (replace-match tags-in-group t t return-match)))
  13444. (setq tags-in-group
  13445. (append regexp-in-group-escaped tags-in-group))))
  13446. (setq taggroups-keys (delete tag taggroups-keys))))
  13447. ;; Add the regular expressions back into the match-expression again.
  13448. (while regexps-in-match
  13449. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  13450. (pop regexps-in-match)
  13451. return-match t t))
  13452. (cl-decf count))
  13453. (if single-as-list
  13454. (if tags-in-group tags-in-group (list return-match))
  13455. return-match))
  13456. (if single-as-list
  13457. (list (if downcased (downcase match) match))
  13458. match)))
  13459. (defun org-op-to-function (op &optional stringp)
  13460. "Turn an operator into the appropriate function."
  13461. (setq op
  13462. (cond
  13463. ((equal op "<" ) '(< string< org-time<))
  13464. ((equal op ">" ) '(> org-string> org-time>))
  13465. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  13466. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  13467. ((member op '("=" "==")) '(= string= org-time=))
  13468. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  13469. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  13470. (defun org<> (a b) (not (= a b)))
  13471. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  13472. (defun org-string>= (a b) (not (string< a b)))
  13473. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  13474. (defun org-string<> (a b) (not (string= a b)))
  13475. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  13476. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  13477. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  13478. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  13479. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  13480. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  13481. (defun org-2ft (s)
  13482. "Convert S to a floating point time.
  13483. If S is already a number, just return it. If it is a string, parse
  13484. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  13485. (cond
  13486. ((numberp s) s)
  13487. ((stringp s)
  13488. (condition-case nil
  13489. (float-time (apply 'encode-time (org-parse-time-string s)))
  13490. (error 0.)))
  13491. (t 0.)))
  13492. (defun org-time-today ()
  13493. "Time in seconds today at 0:00.
  13494. Returns the float number of seconds since the beginning of the
  13495. epoch to the beginning of today (00:00)."
  13496. (float-time (apply 'encode-time
  13497. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13498. (defun org-matcher-time (s)
  13499. "Interpret a time comparison value."
  13500. (save-match-data
  13501. (cond
  13502. ((string= s "<now>") (float-time))
  13503. ((string= s "<today>") (org-time-today))
  13504. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13505. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13506. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13507. (+ (org-time-today)
  13508. (* (string-to-number (match-string 1 s))
  13509. (cdr (assoc (match-string 2 s)
  13510. '(("d" . 86400.0) ("w" . 604800.0)
  13511. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13512. (t (org-2ft s)))))
  13513. (defun org-match-any-p (re list)
  13514. "Does re match any element of list?"
  13515. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13516. (delq nil list))
  13517. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13518. (defvar org-tags-overlay (make-overlay 1 1))
  13519. (delete-overlay org-tags-overlay)
  13520. (defun org-get-local-tags-at (&optional pos)
  13521. "Get a list of tags defined in the current headline."
  13522. (org-get-tags-at pos 'local))
  13523. (defun org-get-local-tags ()
  13524. "Get a list of tags defined in the current headline."
  13525. (org-get-tags-at nil 'local))
  13526. (defun org-get-tags-at (&optional pos local)
  13527. "Get a list of all headline tags applicable at POS.
  13528. POS defaults to point. If tags are inherited, the list contains
  13529. the targets in the same sequence as the headlines appear, i.e.
  13530. the tags of the current headline come last.
  13531. When LOCAL is non-nil, only return tags from the current headline,
  13532. ignore inherited ones."
  13533. (interactive)
  13534. (if (and org-trust-scanner-tags
  13535. (or (not pos) (equal pos (point)))
  13536. (not local))
  13537. org-scanner-tags
  13538. (let (tags ltags lastpos parent)
  13539. (save-excursion
  13540. (save-restriction
  13541. (widen)
  13542. (goto-char (or pos (point)))
  13543. (save-match-data
  13544. (catch 'done
  13545. (condition-case nil
  13546. (progn
  13547. (org-back-to-heading t)
  13548. (while (not (equal lastpos (point)))
  13549. (setq lastpos (point))
  13550. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13551. (setq ltags (org-split-string
  13552. (match-string-no-properties 1) ":"))
  13553. (when parent
  13554. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13555. (setq tags (append
  13556. (if parent
  13557. (org-remove-uninherited-tags ltags)
  13558. ltags)
  13559. tags)))
  13560. (or org-use-tag-inheritance (throw 'done t))
  13561. (when local (throw 'done t))
  13562. (or (org-up-heading-safe) (error nil))
  13563. (setq parent t)))
  13564. (error nil)))))
  13565. (if local
  13566. tags
  13567. (reverse (delete-dups
  13568. (reverse (append
  13569. (org-remove-uninherited-tags
  13570. org-file-tags)
  13571. tags)))))))))
  13572. (defun org-add-prop-inherited (s)
  13573. (add-text-properties 0 (length s) '(inherited t) s)
  13574. s)
  13575. (defun org-toggle-tag (tag &optional onoff)
  13576. "Toggle the tag TAG for the current line.
  13577. If ONOFF is `on' or `off', don't toggle but set to this state."
  13578. (let (res current)
  13579. (save-excursion
  13580. (org-back-to-heading t)
  13581. (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  13582. (point-at-eol) t)
  13583. (progn
  13584. (setq current (match-string 1))
  13585. (replace-match ""))
  13586. (setq current ""))
  13587. (setq current (nreverse (org-split-string current ":")))
  13588. (cond
  13589. ((eq onoff 'on)
  13590. (setq res t)
  13591. (or (member tag current) (push tag current)))
  13592. ((eq onoff 'off)
  13593. (or (not (member tag current)) (setq current (delete tag current))))
  13594. (t (if (member tag current)
  13595. (setq current (delete tag current))
  13596. (setq res t)
  13597. (push tag current))))
  13598. (end-of-line 1)
  13599. (if current
  13600. (progn
  13601. (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
  13602. (org-set-tags nil t))
  13603. (delete-horizontal-space))
  13604. (run-hooks 'org-after-tags-change-hook))
  13605. res))
  13606. (defun org--align-tags-here (to-col)
  13607. "Align tags on the current headline to TO-COL.
  13608. Assume point is on a headline."
  13609. (let ((pos (point)))
  13610. (beginning-of-line)
  13611. (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13612. (>= pos (match-beginning 2)))
  13613. ;; No tags or point within tags: do not align.
  13614. (goto-char pos)
  13615. (goto-char (match-beginning 1))
  13616. (let ((shift (max (- (if (>= to-col 0) to-col
  13617. (- (abs to-col) (string-width (match-string 2))))
  13618. (current-column))
  13619. 1)))
  13620. (replace-match (make-string shift ?\s) nil nil nil 1)
  13621. ;; Preserve initial position, if possible. In any case, stop
  13622. ;; before tags.
  13623. (when (< pos (point)) (goto-char pos))))))
  13624. (defun org-set-tags-command (&optional arg just-align)
  13625. "Call the set-tags command for the current entry."
  13626. (interactive "P")
  13627. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13628. (org-set-tags arg just-align)
  13629. (save-excursion
  13630. (unless (and (org-region-active-p)
  13631. org-loop-over-headlines-in-active-region)
  13632. (org-back-to-heading t))
  13633. (org-set-tags arg just-align))))
  13634. (defun org-set-tags-to (data)
  13635. "Set the tags of the current entry to DATA, replacing the current tags.
  13636. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13637. If DATA is nil or the empty string, any tags will be removed."
  13638. (interactive "sTags: ")
  13639. (setq data
  13640. (cond
  13641. ((eq data nil) "")
  13642. ((equal data "") "")
  13643. ((stringp data)
  13644. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13645. ":"))
  13646. ((listp data)
  13647. (concat ":" (mapconcat 'identity data ":") ":"))))
  13648. (when data
  13649. (save-excursion
  13650. (org-back-to-heading t)
  13651. (when (looking-at org-complex-heading-regexp)
  13652. (if (match-end 5)
  13653. (progn
  13654. (goto-char (match-beginning 5))
  13655. (insert data)
  13656. (delete-region (point) (point-at-eol))
  13657. (org-set-tags nil 'align))
  13658. (goto-char (point-at-eol))
  13659. (insert " " data)
  13660. (org-set-tags nil 'align)))
  13661. (beginning-of-line 1)
  13662. (when (looking-at ".*?\\([ \t]+\\)$")
  13663. (delete-region (match-beginning 1) (match-end 1))))))
  13664. (defun org-align-all-tags ()
  13665. "Align the tags in all headings."
  13666. (interactive)
  13667. (save-excursion
  13668. (or (ignore-errors (org-back-to-heading t))
  13669. (outline-next-heading))
  13670. (if (org-at-heading-p)
  13671. (org-set-tags t)
  13672. (message "No headings"))))
  13673. (defvar org-indent-indentation-per-level)
  13674. (defun org-set-tags (&optional arg just-align)
  13675. "Set the tags for the current headline.
  13676. With prefix ARG, realign all tags in headings in the current buffer.
  13677. When JUST-ALIGN is non-nil, only align tags."
  13678. (interactive "P")
  13679. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13680. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13681. 'region-start-level
  13682. 'region))
  13683. org-loop-over-headlines-in-active-region)
  13684. (org-map-entries
  13685. ;; We don't use ARG and JUST-ALIGN here because these args
  13686. ;; are not useful when looping over headlines.
  13687. #'org-set-tags
  13688. org-loop-over-headlines-in-active-region
  13689. cl
  13690. '(when (outline-invisible-p) (org-end-of-subtree nil t))))
  13691. (let ((org-setting-tags t))
  13692. (if arg
  13693. (save-excursion
  13694. (goto-char (point-min))
  13695. (while (re-search-forward org-outline-regexp-bol nil t)
  13696. (org-set-tags nil t)
  13697. (end-of-line))
  13698. (message "All tags realigned to column %d" org-tags-column))
  13699. (let* ((current (org-get-tags-string))
  13700. (tags
  13701. (if just-align current
  13702. ;; Get a new set of tags from the user.
  13703. (save-excursion
  13704. (let* ((seen)
  13705. (table
  13706. (setq
  13707. org-last-tags-completion-table
  13708. ;; Uniquify tags in alists, yet preserve
  13709. ;; structure (i.e., keywords).
  13710. (delq nil
  13711. (mapcar
  13712. (lambda (pair)
  13713. (let ((head (car pair)))
  13714. (cond ((symbolp head) pair)
  13715. ((member head seen) nil)
  13716. (t (push head seen)
  13717. pair))))
  13718. (append
  13719. (or org-current-tag-alist
  13720. (org-get-buffer-tags))
  13721. (and
  13722. org-complete-tags-always-offer-all-agenda-tags
  13723. (org-global-tags-completion-table
  13724. (org-agenda-files))))))))
  13725. (current-tags (org-split-string current ":"))
  13726. (inherited-tags
  13727. (nreverse (nthcdr (length current-tags)
  13728. (nreverse (org-get-tags-at))))))
  13729. (replace-regexp-in-string
  13730. "\\([-+&]+\\|,\\)"
  13731. ":"
  13732. (if (or (eq t org-use-fast-tag-selection)
  13733. (and org-use-fast-tag-selection
  13734. (delq nil (mapcar #'cdr table))))
  13735. (org-fast-tag-selection
  13736. current-tags inherited-tags table
  13737. (and org-fast-tag-selection-include-todo
  13738. org-todo-key-alist))
  13739. (let ((org-add-colon-after-tag-completion
  13740. (< 1 (length table))))
  13741. (org-trim
  13742. (completing-read
  13743. "Tags: "
  13744. #'org-tags-completion-function
  13745. nil nil current 'org-tags-history))))))))))
  13746. (when org-tags-sort-function
  13747. (setq tags
  13748. (mapconcat
  13749. #'identity
  13750. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13751. org-tags-sort-function)
  13752. ":")))
  13753. (if (not (org-string-nw-p tags)) (setq tags "")
  13754. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  13755. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  13756. ;; Insert new tags at the correct column.
  13757. (unless (equal current tags)
  13758. (save-excursion
  13759. (beginning-of-line)
  13760. (looking-at org-complex-heading-regexp)
  13761. ;; Remove current tags, if any.
  13762. (when (match-end 5) (replace-match "" nil nil nil 5))
  13763. ;; Insert new tags, if any. Otherwise, remove trailing
  13764. ;; white spaces.
  13765. (end-of-line)
  13766. (if (not (equal tags ""))
  13767. (insert " " tags)
  13768. (skip-chars-backward " \t")
  13769. (delete-region (point) (line-end-position)))))
  13770. ;; Align tags, if any. Fix tags column if `org-indent-mode'
  13771. ;; is on.
  13772. (unless (equal tags "")
  13773. (let* ((level (save-excursion
  13774. (beginning-of-line)
  13775. (skip-chars-forward "\\*")))
  13776. (offset (if (bound-and-true-p org-indent-mode)
  13777. (* (1- org-indent-indentation-per-level)
  13778. (1- level))
  13779. 0))
  13780. (tags-column
  13781. (+ org-tags-column
  13782. (if (> org-tags-column 0) (- offset) offset))))
  13783. (org--align-tags-here tags-column))))
  13784. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13785. (defun org-change-tag-in-region (beg end tag off)
  13786. "Add or remove TAG for each entry in the region.
  13787. This works in the agenda, and also in an Org buffer."
  13788. (interactive
  13789. (list (region-beginning) (region-end)
  13790. (let ((org-last-tags-completion-table
  13791. (if (derived-mode-p 'org-mode)
  13792. (org-uniquify
  13793. (delq nil (append (org-get-buffer-tags)
  13794. (org-global-tags-completion-table))))
  13795. (org-global-tags-completion-table))))
  13796. (completing-read
  13797. "Tag: " 'org-tags-completion-function nil nil nil
  13798. 'org-tags-history))
  13799. (progn
  13800. (message "[s]et or [r]emove? ")
  13801. (equal (read-char-exclusive) ?r))))
  13802. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13803. (let ((agendap (equal major-mode 'org-agenda-mode))
  13804. l1 l2 m buf pos newhead (cnt 0))
  13805. (goto-char end)
  13806. (setq l2 (1- (org-current-line)))
  13807. (goto-char beg)
  13808. (setq l1 (org-current-line))
  13809. (cl-loop for l from l1 to l2 do
  13810. (org-goto-line l)
  13811. (setq m (get-text-property (point) 'org-hd-marker))
  13812. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13813. (and agendap m))
  13814. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13815. pos (if agendap m (point)))
  13816. (with-current-buffer buf
  13817. (save-excursion
  13818. (save-restriction
  13819. (goto-char pos)
  13820. (setq cnt (1+ cnt))
  13821. (org-toggle-tag tag (if off 'off 'on))
  13822. (setq newhead (org-get-heading)))))
  13823. (and agendap (org-agenda-change-all-lines newhead m))))
  13824. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13825. (defun org-tags-completion-function (string _predicate &optional flag)
  13826. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13827. (confirm (lambda (x) (stringp (car x)))))
  13828. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13829. (setq s1 (match-string 1 string)
  13830. s2 (match-string 2 string))
  13831. (setq s1 "" s2 string))
  13832. (cond
  13833. ((eq flag nil)
  13834. ;; try completion
  13835. (setq rtn (try-completion s2 ctable confirm))
  13836. (when (stringp rtn)
  13837. (setq rtn
  13838. (concat s1 s2 (substring rtn (length s2))
  13839. (if (and org-add-colon-after-tag-completion
  13840. (assoc rtn ctable))
  13841. ":" ""))))
  13842. rtn)
  13843. ((eq flag t)
  13844. ;; all-completions
  13845. (all-completions s2 ctable confirm))
  13846. ((eq flag 'lambda)
  13847. ;; exact match?
  13848. (assoc s2 ctable)))))
  13849. (defun org-fast-tag-insert (kwd tags face &optional end)
  13850. "Insert KDW, and the TAGS, the latter with face FACE.
  13851. Also insert END."
  13852. (insert (format "%-12s" (concat kwd ":"))
  13853. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13854. (or end "")))
  13855. (defun org-fast-tag-show-exit (flag)
  13856. (save-excursion
  13857. (org-goto-line 3)
  13858. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13859. (replace-match ""))
  13860. (when flag
  13861. (end-of-line 1)
  13862. (org-move-to-column (- (window-width) 19) t)
  13863. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13864. (defun org-set-current-tags-overlay (current prefix)
  13865. "Add an overlay to CURRENT tag with PREFIX."
  13866. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13867. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13868. (org-overlay-display org-tags-overlay (concat prefix s))))
  13869. (defvar org-last-tag-selection-key nil)
  13870. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13871. "Fast tag selection with single keys.
  13872. CURRENT is the current list of tags in the headline, INHERITED is the
  13873. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13874. possibly with grouping information. TODO-TABLE is a similar table with
  13875. TODO keywords, should these have keys assigned to them.
  13876. If the keys are nil, a-z are automatically assigned.
  13877. Returns the new tags string, or nil to not change the current settings."
  13878. (let* ((fulltable (append table todo-table))
  13879. (maxlen (apply 'max (mapcar
  13880. (lambda (x)
  13881. (if (stringp (car x)) (string-width (car x)) 0))
  13882. fulltable)))
  13883. (buf (current-buffer))
  13884. (expert (eq org-fast-tag-selection-single-key 'expert))
  13885. (buffer-tags nil)
  13886. (fwidth (+ maxlen 3 1 3))
  13887. (ncol (/ (- (window-width) 4) fwidth))
  13888. (i-face 'org-done)
  13889. (c-face 'org-todo)
  13890. tg cnt e c char c1 c2 ntable tbl rtn
  13891. ov-start ov-end ov-prefix
  13892. (exit-after-next org-fast-tag-selection-single-key)
  13893. (done-keywords org-done-keywords)
  13894. groups ingroup intaggroup)
  13895. (save-excursion
  13896. (beginning-of-line 1)
  13897. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13898. (setq ov-start (match-beginning 1)
  13899. ov-end (match-end 1)
  13900. ov-prefix "")
  13901. (setq ov-start (1- (point-at-eol))
  13902. ov-end (1+ ov-start))
  13903. (skip-chars-forward "^\n\r")
  13904. (setq ov-prefix
  13905. (concat
  13906. (buffer-substring (1- (point)) (point))
  13907. (if (> (current-column) org-tags-column)
  13908. " "
  13909. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13910. (move-overlay org-tags-overlay ov-start ov-end)
  13911. (save-window-excursion
  13912. (if expert
  13913. (set-buffer (get-buffer-create " *Org tags*"))
  13914. (delete-other-windows)
  13915. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13916. (org-switch-to-buffer-other-window " *Org tags*"))
  13917. (erase-buffer)
  13918. (setq-local org-done-keywords done-keywords)
  13919. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13920. (org-fast-tag-insert "Current" current c-face "\n\n")
  13921. (org-fast-tag-show-exit exit-after-next)
  13922. (org-set-current-tags-overlay current ov-prefix)
  13923. (setq tbl fulltable char ?a cnt 0)
  13924. (while (setq e (pop tbl))
  13925. (cond
  13926. ((eq (car e) :startgroup)
  13927. (push '() groups) (setq ingroup t)
  13928. (unless (zerop cnt)
  13929. (setq cnt 0)
  13930. (insert "\n"))
  13931. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13932. ((eq (car e) :endgroup)
  13933. (setq ingroup nil cnt 0)
  13934. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13935. ((eq (car e) :startgrouptag)
  13936. (setq intaggroup t)
  13937. (unless (zerop cnt)
  13938. (setq cnt 0)
  13939. (insert "\n"))
  13940. (insert "[ "))
  13941. ((eq (car e) :endgrouptag)
  13942. (setq intaggroup nil cnt 0)
  13943. (insert "]\n"))
  13944. ((equal e '(:newline))
  13945. (unless (zerop cnt)
  13946. (setq cnt 0)
  13947. (insert "\n")
  13948. (setq e (car tbl))
  13949. (while (equal (car tbl) '(:newline))
  13950. (insert "\n")
  13951. (setq tbl (cdr tbl)))))
  13952. ((equal e '(:grouptags)) (insert " : "))
  13953. (t
  13954. (setq tg (copy-sequence (car e)) c2 nil)
  13955. (if (cdr e)
  13956. (setq c (cdr e))
  13957. ;; automatically assign a character.
  13958. (setq c1 (string-to-char
  13959. (downcase (substring
  13960. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13961. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13962. (while (or (rassoc char ntable) (rassoc char table))
  13963. (setq char (1+ char)))
  13964. (setq c2 c1))
  13965. (setq c (or c2 char)))
  13966. (when ingroup (push tg (car groups)))
  13967. (setq tg (org-add-props tg nil 'face
  13968. (cond
  13969. ((not (assoc tg table))
  13970. (org-get-todo-face tg))
  13971. ((member tg current) c-face)
  13972. ((member tg inherited) i-face))))
  13973. (when (equal (caar tbl) :grouptags)
  13974. (org-add-props tg nil 'face 'org-tag-group))
  13975. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13976. (insert "[" c "] " tg (make-string
  13977. (- fwidth 4 (length tg)) ?\ ))
  13978. (push (cons tg c) ntable)
  13979. (when (= (cl-incf cnt) ncol)
  13980. (insert "\n")
  13981. (when (or ingroup intaggroup) (insert " "))
  13982. (setq cnt 0)))))
  13983. (setq ntable (nreverse ntable))
  13984. (insert "\n")
  13985. (goto-char (point-min))
  13986. (unless expert (org-fit-window-to-buffer))
  13987. (setq rtn
  13988. (catch 'exit
  13989. (while t
  13990. (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
  13991. (if (not groups) "no " "")
  13992. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13993. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13994. (setq org-last-tag-selection-key c)
  13995. (cond
  13996. ((= c ?\r) (throw 'exit t))
  13997. ((= c ?!)
  13998. (setq groups (not groups))
  13999. (goto-char (point-min))
  14000. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  14001. ((= c ?\C-c)
  14002. (if (not expert)
  14003. (org-fast-tag-show-exit
  14004. (setq exit-after-next (not exit-after-next)))
  14005. (setq expert nil)
  14006. (delete-other-windows)
  14007. (set-window-buffer (split-window-vertically) " *Org tags*")
  14008. (org-switch-to-buffer-other-window " *Org tags*")
  14009. (org-fit-window-to-buffer)))
  14010. ((or (= c ?\C-g)
  14011. (and (= c ?q) (not (rassoc c ntable))))
  14012. (delete-overlay org-tags-overlay)
  14013. (setq quit-flag t))
  14014. ((= c ?\ )
  14015. (setq current nil)
  14016. (when exit-after-next (setq exit-after-next 'now)))
  14017. ((= c ?\t)
  14018. (condition-case nil
  14019. (setq tg (completing-read
  14020. "Tag: "
  14021. (or buffer-tags
  14022. (with-current-buffer buf
  14023. (setq buffer-tags
  14024. (org-get-buffer-tags))))))
  14025. (quit (setq tg "")))
  14026. (when (string-match "\\S-" tg)
  14027. (cl-pushnew (list tg) buffer-tags :test #'equal)
  14028. (if (member tg current)
  14029. (setq current (delete tg current))
  14030. (push tg current)))
  14031. (when exit-after-next (setq exit-after-next 'now)))
  14032. ((setq e (rassoc c todo-table) tg (car e))
  14033. (with-current-buffer buf
  14034. (save-excursion (org-todo tg)))
  14035. (when exit-after-next (setq exit-after-next 'now)))
  14036. ((setq e (rassoc c ntable) tg (car e))
  14037. (if (member tg current)
  14038. (setq current (delete tg current))
  14039. (cl-loop for g in groups do
  14040. (when (member tg g)
  14041. (dolist (x g) (setq current (delete x current)))))
  14042. (push tg current))
  14043. (when exit-after-next (setq exit-after-next 'now))))
  14044. ;; Create a sorted list
  14045. (setq current
  14046. (sort current
  14047. (lambda (a b)
  14048. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  14049. (when (eq exit-after-next 'now) (throw 'exit t))
  14050. (goto-char (point-min))
  14051. (beginning-of-line 2)
  14052. (delete-region (point) (point-at-eol))
  14053. (org-fast-tag-insert "Current" current c-face)
  14054. (org-set-current-tags-overlay current ov-prefix)
  14055. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  14056. (setq tg (match-string 1))
  14057. (add-text-properties
  14058. (match-beginning 1) (match-end 1)
  14059. (list 'face
  14060. (cond
  14061. ((member tg current) c-face)
  14062. ((member tg inherited) i-face)
  14063. (t (get-text-property (match-beginning 1) 'face))))))
  14064. (goto-char (point-min)))))
  14065. (delete-overlay org-tags-overlay)
  14066. (if rtn
  14067. (mapconcat 'identity current ":")
  14068. nil))))
  14069. (defun org-get-tags-string ()
  14070. "Get the TAGS string in the current headline."
  14071. (unless (org-at-heading-p t)
  14072. (user-error "Not on a heading"))
  14073. (save-excursion
  14074. (beginning-of-line 1)
  14075. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  14076. (match-string-no-properties 1)
  14077. "")))
  14078. (defun org-get-tags ()
  14079. "Get the list of tags specified in the current headline."
  14080. (org-split-string (org-get-tags-string) ":"))
  14081. (defun org-get-buffer-tags ()
  14082. "Get a table of all tags used in the buffer, for completion."
  14083. (org-with-wide-buffer
  14084. (goto-char (point-min))
  14085. (let ((tag-re (concat org-outline-regexp-bol
  14086. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  14087. tags)
  14088. (while (re-search-forward tag-re nil t)
  14089. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  14090. (push tag tags)))
  14091. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  14092. ;;;; The mapping API
  14093. (defvar org-agenda-skip-comment-trees)
  14094. (defvar org-agenda-skip-function)
  14095. (defun org-map-entries (func &optional match scope &rest skip)
  14096. "Call FUNC at each headline selected by MATCH in SCOPE.
  14097. FUNC is a function or a lisp form. The function will be called without
  14098. arguments, with the cursor positioned at the beginning of the headline.
  14099. The return values of all calls to the function will be collected and
  14100. returned as a list.
  14101. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  14102. does not need to preserve point. After evaluation, the cursor will be
  14103. moved to the end of the line (presumably of the headline of the
  14104. processed entry) and search continues from there. Under some
  14105. circumstances, this may not produce the wanted results. For example,
  14106. if you have removed (e.g. archived) the current (sub)tree it could
  14107. mean that the next entry will be skipped entirely. In such cases, you
  14108. can specify the position from where search should continue by making
  14109. FUNC set the variable `org-map-continue-from' to the desired buffer
  14110. position.
  14111. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  14112. Only headlines that are matched by this query will be considered during
  14113. the iteration. When MATCH is nil or t, all headlines will be
  14114. visited by the iteration.
  14115. SCOPE determines the scope of this command. It can be any of:
  14116. nil The current buffer, respecting the restriction if any
  14117. tree The subtree started with the entry at point
  14118. region The entries within the active region, if any
  14119. region-start-level
  14120. The entries within the active region, but only those at
  14121. the same level than the first one.
  14122. file The current buffer, without restriction
  14123. file-with-archives
  14124. The current buffer, and any archives associated with it
  14125. agenda All agenda files
  14126. agenda-with-archives
  14127. All agenda files with any archive files associated with them
  14128. \(file1 file2 ...)
  14129. If this is a list, all files in the list will be scanned
  14130. The remaining args are treated as settings for the skipping facilities of
  14131. the scanner. The following items can be given here:
  14132. archive skip trees with the archive tag
  14133. comment skip trees with the COMMENT keyword
  14134. function or Emacs Lisp form:
  14135. will be used as value for `org-agenda-skip-function', so
  14136. whenever the function returns a position, FUNC will not be
  14137. called for that entry and search will continue from the
  14138. position returned
  14139. If your function needs to retrieve the tags including inherited tags
  14140. at the *current* entry, you can use the value of the variable
  14141. `org-scanner-tags' which will be much faster than getting the value
  14142. with `org-get-tags-at'. If your function gets properties with
  14143. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  14144. to t around the call to `org-entry-properties' to get the same speedup.
  14145. Note that if your function moves around to retrieve tags and properties at
  14146. a *different* entry, you cannot use these techniques."
  14147. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  14148. (not (org-region-active-p)))
  14149. (let* ((org-agenda-archives-mode nil) ; just to make sure
  14150. (org-agenda-skip-archived-trees (memq 'archive skip))
  14151. (org-agenda-skip-comment-trees (memq 'comment skip))
  14152. (org-agenda-skip-function
  14153. (car (org-delete-all '(comment archive) skip)))
  14154. (org-tags-match-list-sublevels t)
  14155. (start-level (eq scope 'region-start-level))
  14156. matcher res
  14157. org-todo-keywords-for-agenda
  14158. org-done-keywords-for-agenda
  14159. org-todo-keyword-alist-for-agenda
  14160. org-tag-alist-for-agenda
  14161. org--matcher-tags-todo-only)
  14162. (cond
  14163. ((eq match t) (setq matcher t))
  14164. ((eq match nil) (setq matcher t))
  14165. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  14166. (save-excursion
  14167. (save-restriction
  14168. (cond ((eq scope 'tree)
  14169. (org-back-to-heading t)
  14170. (org-narrow-to-subtree)
  14171. (setq scope nil))
  14172. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  14173. (org-region-active-p))
  14174. ;; If needed, set start-level to a string like "2"
  14175. (when start-level
  14176. (save-excursion
  14177. (goto-char (region-beginning))
  14178. (unless (org-at-heading-p) (outline-next-heading))
  14179. (setq start-level (org-current-level))))
  14180. (narrow-to-region (region-beginning)
  14181. (save-excursion
  14182. (goto-char (region-end))
  14183. (unless (and (bolp) (org-at-heading-p))
  14184. (outline-next-heading))
  14185. (point)))
  14186. (setq scope nil)))
  14187. (if (not scope)
  14188. (progn
  14189. (org-agenda-prepare-buffers
  14190. (and buffer-file-name (list buffer-file-name)))
  14191. (setq res
  14192. (org-scan-tags
  14193. func matcher org--matcher-tags-todo-only start-level)))
  14194. ;; Get the right scope
  14195. (cond
  14196. ((and scope (listp scope) (symbolp (car scope)))
  14197. (setq scope (eval scope)))
  14198. ((eq scope 'agenda)
  14199. (setq scope (org-agenda-files t)))
  14200. ((eq scope 'agenda-with-archives)
  14201. (setq scope (org-agenda-files t))
  14202. (setq scope (org-add-archive-files scope)))
  14203. ((eq scope 'file)
  14204. (setq scope (and buffer-file-name (list buffer-file-name))))
  14205. ((eq scope 'file-with-archives)
  14206. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  14207. (org-agenda-prepare-buffers scope)
  14208. (dolist (file scope)
  14209. (with-current-buffer (org-find-base-buffer-visiting file)
  14210. (org-with-wide-buffer
  14211. (goto-char (point-min))
  14212. (setq res
  14213. (append
  14214. res
  14215. (org-scan-tags
  14216. func matcher org--matcher-tags-todo-only)))))))))
  14217. res)))
  14218. ;;; Properties API
  14219. (defconst org-special-properties
  14220. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  14221. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  14222. "The special properties valid in Org mode.
  14223. These are properties that are not defined in the property drawer,
  14224. but in some other way.")
  14225. (defconst org-default-properties
  14226. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  14227. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  14228. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  14229. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  14230. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  14231. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  14232. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  14233. "Some properties that are used by Org mode for various purposes.
  14234. Being in this list makes sure that they are offered for completion.")
  14235. (defun org--valid-property-p (property)
  14236. "Non nil when string PROPERTY is a valid property name."
  14237. (not
  14238. (or (equal property "")
  14239. (string-match-p "\\s-" property))))
  14240. (defun org--update-property-plist (key val props)
  14241. "Associate KEY to VAL in alist PROPS.
  14242. Modifications are made by side-effect. Return new alist."
  14243. (let* ((appending (string= (substring key -1) "+"))
  14244. (key (if appending (substring key 0 -1) key))
  14245. (old (assoc-string key props t)))
  14246. (if (not old) (cons (cons key val) props)
  14247. (setcdr old (if appending (concat (cdr old) " " val) val))
  14248. props)))
  14249. (defun org-get-property-block (&optional beg force)
  14250. "Return the (beg . end) range of the body of the property drawer.
  14251. BEG is the beginning of the current subtree, or of the part
  14252. before the first headline. If it is not given, it will be found.
  14253. If the drawer does not exist, create it if FORCE is non-nil, or
  14254. return nil."
  14255. (org-with-wide-buffer
  14256. (when beg (goto-char beg))
  14257. (unless (org-before-first-heading-p)
  14258. (let ((beg (cond (beg)
  14259. ((or (not (featurep 'org-inlinetask))
  14260. (org-inlinetask-in-task-p))
  14261. (org-back-to-heading t))
  14262. (t (org-with-limited-levels (org-back-to-heading t))))))
  14263. (forward-line)
  14264. (when (looking-at-p org-planning-line-re) (forward-line))
  14265. (cond ((looking-at org-property-drawer-re)
  14266. (forward-line)
  14267. (cons (point) (progn (goto-char (match-end 0))
  14268. (line-beginning-position))))
  14269. (force
  14270. (goto-char beg)
  14271. (org-insert-property-drawer)
  14272. (let ((pos (save-excursion (search-forward ":END:")
  14273. (line-beginning-position))))
  14274. (cons pos pos))))))))
  14275. (defun org-at-property-p ()
  14276. "Non-nil when point is inside a property drawer.
  14277. See `org-property-re' for match data, if applicable."
  14278. (save-excursion
  14279. (beginning-of-line)
  14280. (and (looking-at org-property-re)
  14281. (let ((property-drawer (save-match-data (org-get-property-block))))
  14282. (and property-drawer
  14283. (>= (point) (car property-drawer))
  14284. (< (point) (cdr property-drawer)))))))
  14285. (defun org-property-action ()
  14286. "Do an action on properties."
  14287. (interactive)
  14288. (unless (org-at-property-p) (user-error "Not at a property"))
  14289. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  14290. (let ((c (read-char-exclusive)))
  14291. (cl-case c
  14292. (?s (call-interactively #'org-set-property))
  14293. (?d (call-interactively #'org-delete-property))
  14294. (?D (call-interactively #'org-delete-property-globally))
  14295. (?c (call-interactively #'org-compute-property-at-point))
  14296. (otherwise (user-error "No such property action %c" c)))))
  14297. (defun org-inc-effort ()
  14298. "Increment the value of the effort property in the current entry."
  14299. (interactive)
  14300. (org-set-effort nil t))
  14301. (defvar org-clock-effort) ; Defined in org-clock.el.
  14302. (defvar org-clock-current-task) ; Defined in org-clock.el.
  14303. (defun org-set-effort (&optional value increment)
  14304. "Set the effort property of the current entry.
  14305. With numerical prefix arg, use the nth allowed value, 0 stands for the
  14306. 10th allowed value.
  14307. When INCREMENT is non-nil, set the property to the next allowed value."
  14308. (interactive "P")
  14309. (when (equal value 0) (setq value 10))
  14310. (let* ((completion-ignore-case t)
  14311. (prop org-effort-property)
  14312. (cur (org-entry-get nil prop))
  14313. (allowed (org-property-get-allowed-values nil prop 'table))
  14314. (existing (mapcar 'list (org-property-values prop)))
  14315. (heading (nth 4 (org-heading-components)))
  14316. rpl
  14317. (val (cond
  14318. ((stringp value) value)
  14319. ((and allowed (integerp value))
  14320. (or (car (nth (1- value) allowed))
  14321. (car (org-last allowed))))
  14322. ((and allowed increment)
  14323. (or (cl-caadr (member (list cur) allowed))
  14324. (user-error "Allowed effort values are not set")))
  14325. (allowed
  14326. (message "Select 1-9,0, [RET%s]: %s"
  14327. (if cur (concat "=" cur) "")
  14328. (mapconcat 'car allowed " "))
  14329. (setq rpl (read-char-exclusive))
  14330. (if (equal rpl ?\r)
  14331. cur
  14332. (setq rpl (- rpl ?0))
  14333. (when (equal rpl 0) (setq rpl 10))
  14334. (if (and (> rpl 0) (<= rpl (length allowed)))
  14335. (car (nth (1- rpl) allowed))
  14336. (org-completing-read "Effort: " allowed nil))))
  14337. (t
  14338. (org-completing-read
  14339. (concat "Effort" (and cur (string-match "\\S-" cur)
  14340. (concat " [" cur "]"))
  14341. ": ")
  14342. existing nil nil "" nil cur)))))
  14343. (unless (equal (org-entry-get nil prop) val)
  14344. (org-entry-put nil prop val))
  14345. (org-refresh-property
  14346. '((effort . identity)
  14347. (effort-minutes . org-duration-string-to-minutes))
  14348. val)
  14349. (when (equal heading (bound-and-true-p org-clock-current-task))
  14350. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  14351. (org-clock-update-mode-line))
  14352. (message "%s is now %s" prop val)))
  14353. (defun org-entry-properties (&optional pom which)
  14354. "Get all properties of the current entry.
  14355. When POM is a buffer position, get all properties from the entry
  14356. there instead.
  14357. This includes the TODO keyword, the tags, time strings for
  14358. deadline, scheduled, and clocking, and any additional properties
  14359. defined in the entry.
  14360. If WHICH is nil or `all', get all properties. If WHICH is
  14361. `special' or `standard', only get that subclass. If WHICH is
  14362. a string, only get that property.
  14363. Return value is an alist. Keys are properties, as upcased
  14364. strings."
  14365. (org-with-point-at pom
  14366. (when (and (derived-mode-p 'org-mode)
  14367. (ignore-errors (org-back-to-heading t)))
  14368. (catch 'exit
  14369. (let* ((beg (point))
  14370. (specific (and (stringp which) (upcase which)))
  14371. (which (cond ((not specific) which)
  14372. ((member specific org-special-properties) 'special)
  14373. (t 'standard)))
  14374. props)
  14375. ;; Get the special properties, like TODO and TAGS.
  14376. (when (memq which '(nil all special))
  14377. (when (or (not specific) (string= specific "CLOCKSUM"))
  14378. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  14379. (when clocksum
  14380. (push (cons "CLOCKSUM"
  14381. (org-minutes-to-clocksum-string clocksum))
  14382. props)))
  14383. (when specific (throw 'exit props)))
  14384. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  14385. (let ((clocksumt (get-text-property (point)
  14386. :org-clock-minutes-today)))
  14387. (when clocksumt
  14388. (push (cons "CLOCKSUM_T"
  14389. (org-minutes-to-clocksum-string clocksumt))
  14390. props)))
  14391. (when specific (throw 'exit props)))
  14392. (when (or (not specific) (string= specific "ITEM"))
  14393. (when (looking-at org-complex-heading-regexp)
  14394. (push (cons "ITEM"
  14395. (let ((title (match-string-no-properties 4)))
  14396. (if (org-string-nw-p title)
  14397. (org-remove-tabs title)
  14398. "")))
  14399. props))
  14400. (when specific (throw 'exit props)))
  14401. (when (or (not specific) (string= specific "TODO"))
  14402. (let ((case-fold-search nil))
  14403. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  14404. (push (cons "TODO" (match-string-no-properties 2)) props)))
  14405. (when specific (throw 'exit props)))
  14406. (when (or (not specific) (string= specific "PRIORITY"))
  14407. (push (cons "PRIORITY"
  14408. (if (looking-at org-priority-regexp)
  14409. (match-string-no-properties 2)
  14410. (char-to-string org-default-priority)))
  14411. props)
  14412. (when specific (throw 'exit props)))
  14413. (when (or (not specific) (string= specific "FILE"))
  14414. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  14415. props)
  14416. (when specific (throw 'exit props)))
  14417. (when (or (not specific) (string= specific "TAGS"))
  14418. (let ((value (org-string-nw-p (org-get-tags-string))))
  14419. (when value (push (cons "TAGS" value) props)))
  14420. (when specific (throw 'exit props)))
  14421. (when (or (not specific) (string= specific "ALLTAGS"))
  14422. (let ((value (org-get-tags-at)))
  14423. (when value
  14424. (push (cons "ALLTAGS"
  14425. (format ":%s:" (mapconcat #'identity value ":")))
  14426. props)))
  14427. (when specific (throw 'exit props)))
  14428. (when (or (not specific) (string= specific "BLOCKED"))
  14429. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  14430. (when specific (throw 'exit props)))
  14431. (when (or (not specific)
  14432. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  14433. (forward-line)
  14434. (when (looking-at-p org-planning-line-re)
  14435. (end-of-line)
  14436. (let ((bol (line-beginning-position))
  14437. ;; Backward compatibility: time keywords used to
  14438. ;; be configurable (before 8.3). Make sure we
  14439. ;; get the correct keyword.
  14440. (key-assoc `(("CLOSED" . ,org-closed-string)
  14441. ("DEADLINE" . ,org-deadline-string)
  14442. ("SCHEDULED" . ,org-scheduled-string))))
  14443. (dolist (pair (if specific (list (assoc specific key-assoc))
  14444. key-assoc))
  14445. (save-excursion
  14446. (when (search-backward (cdr pair) bol t)
  14447. (goto-char (match-end 0))
  14448. (skip-chars-forward " \t")
  14449. (and (looking-at org-ts-regexp-both)
  14450. (push (cons (car pair)
  14451. (match-string-no-properties 0))
  14452. props)))))))
  14453. (when specific (throw 'exit props)))
  14454. (when (or (not specific)
  14455. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  14456. (let ((find-ts
  14457. (lambda (end ts)
  14458. ;; Fix next time-stamp before END. TS is the
  14459. ;; list of time-stamps found so far.
  14460. (let ((ts ts)
  14461. (regexp (cond
  14462. ((string= specific "TIMESTAMP")
  14463. org-ts-regexp)
  14464. ((string= specific "TIMESTAMP_IA")
  14465. org-ts-regexp-inactive)
  14466. ((assoc "TIMESTAMP_IA" ts)
  14467. org-ts-regexp)
  14468. ((assoc "TIMESTAMP" ts)
  14469. org-ts-regexp-inactive)
  14470. (t org-ts-regexp-both))))
  14471. (catch 'next
  14472. (while (re-search-forward regexp end t)
  14473. (backward-char)
  14474. (let ((object (org-element-context)))
  14475. ;; Accept to match timestamps in node
  14476. ;; properties, too.
  14477. (when (memq (org-element-type object)
  14478. '(node-property timestamp))
  14479. (let ((type
  14480. (org-element-property :type object)))
  14481. (cond
  14482. ((and (memq type '(active active-range))
  14483. (not (equal specific "TIMESTAMP_IA")))
  14484. (unless (assoc "TIMESTAMP" ts)
  14485. (push (cons "TIMESTAMP"
  14486. (org-element-property
  14487. :raw-value object))
  14488. ts)
  14489. (when specific (throw 'exit ts))))
  14490. ((and (memq type '(inactive inactive-range))
  14491. (not (string= specific "TIMESTAMP")))
  14492. (unless (assoc "TIMESTAMP_IA" ts)
  14493. (push (cons "TIMESTAMP_IA"
  14494. (org-element-property
  14495. :raw-value object))
  14496. ts)
  14497. (when specific (throw 'exit ts))))))
  14498. ;; Both timestamp types are found,
  14499. ;; move to next part.
  14500. (when (= (length ts) 2) (throw 'next ts)))))
  14501. ts)))))
  14502. (goto-char beg)
  14503. ;; First look for timestamps within headline.
  14504. (let ((ts (funcall find-ts (line-end-position) nil)))
  14505. (if (= (length ts) 2) (setq props (nconc ts props))
  14506. (forward-line)
  14507. ;; Then find timestamps in the section, skipping
  14508. ;; planning line.
  14509. (when (looking-at-p org-planning-line-re)
  14510. (forward-line))
  14511. (let ((end (save-excursion (outline-next-heading))))
  14512. (setq props (nconc (funcall find-ts end ts) props))))))))
  14513. ;; Get the standard properties, like :PROP:.
  14514. (when (memq which '(nil all standard))
  14515. ;; If we are looking after a specific property, delegate
  14516. ;; to `org-entry-get', which is faster. However, make an
  14517. ;; exception for "CATEGORY", since it can be also set
  14518. ;; through keywords (i.e. #+CATEGORY).
  14519. (if (and specific (not (equal specific "CATEGORY")))
  14520. (let ((value (org-entry-get beg specific nil t)))
  14521. (throw 'exit (and value (list (cons specific value)))))
  14522. (let ((range (org-get-property-block beg)))
  14523. (when range
  14524. (let ((end (cdr range)) seen-base)
  14525. (goto-char (car range))
  14526. ;; Unlike to `org--update-property-plist', we
  14527. ;; handle the case where base values is found
  14528. ;; after its extension. We also forbid standard
  14529. ;; properties to be named as special properties.
  14530. (while (re-search-forward org-property-re end t)
  14531. (let* ((key (upcase (match-string-no-properties 2)))
  14532. (extendp (string-match-p "\\+\\'" key))
  14533. (key-base (if extendp (substring key 0 -1) key))
  14534. (value (match-string-no-properties 3)))
  14535. (cond
  14536. ((member-ignore-case key-base org-special-properties))
  14537. (extendp
  14538. (setq props
  14539. (org--update-property-plist key value props)))
  14540. ((member key seen-base))
  14541. (t (push key seen-base)
  14542. (let ((p (assoc-string key props t)))
  14543. (if p (setcdr p (concat value " " (cdr p)))
  14544. (push (cons key value) props))))))))))))
  14545. (unless (assoc "CATEGORY" props)
  14546. (push (cons "CATEGORY" (org-get-category beg)) props)
  14547. (when (string= specific "CATEGORY") (throw 'exit props)))
  14548. ;; Return value.
  14549. props)))))
  14550. (defun org-property--local-values (property literal-nil)
  14551. "Return value for PROPERTY in current entry.
  14552. Value is a list whose car is the base value for PROPERTY and cdr
  14553. a list of accumulated values. Return nil if neither is found in
  14554. the entry. Also return nil when PROPERTY is set to \"nil\",
  14555. unless LITERAL-NIL is non-nil."
  14556. (let ((range (org-get-property-block)))
  14557. (when range
  14558. (goto-char (car range))
  14559. (let* ((case-fold-search t)
  14560. (end (cdr range))
  14561. (value
  14562. ;; Base value.
  14563. (save-excursion
  14564. (let ((v (and (re-search-forward
  14565. (org-re-property property nil t) end t)
  14566. (match-string-no-properties 3))))
  14567. (list (if literal-nil v (org-not-nil v)))))))
  14568. ;; Find additional values.
  14569. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14570. (while (re-search-forward property+ end t)
  14571. (push (match-string-no-properties 3) value)))
  14572. ;; Return final values.
  14573. (and (not (equal value '(nil))) (nreverse value))))))
  14574. (defun org-entry-get (pom property &optional inherit literal-nil)
  14575. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14576. If INHERIT is non-nil and the entry does not have the property,
  14577. then also check higher levels of the hierarchy. If INHERIT is
  14578. the symbol `selective', use inheritance only if the setting in
  14579. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14580. If the property is present but empty, the return value is the
  14581. empty string. If the property is not present at all, nil is
  14582. returned. In any other case, return the value as a string.
  14583. Search is case-insensitive.
  14584. If LITERAL-NIL is set, return the string value \"nil\" as
  14585. a string, do not interpret it as the list atom nil. This is used
  14586. for inheritance when a \"nil\" value can supersede a non-nil
  14587. value higher up the hierarchy."
  14588. (org-with-point-at pom
  14589. (cond
  14590. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14591. ;; We need a special property. Use `org-entry-properties' to
  14592. ;; retrieve it, but specify the wanted property.
  14593. (cdr (assoc-string property (org-entry-properties nil property))))
  14594. ((and inherit
  14595. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14596. (org-entry-get-with-inheritance property literal-nil))
  14597. (t
  14598. (let* ((local (org-property--local-values property literal-nil))
  14599. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14600. (if literal-nil value (org-not-nil value)))))))
  14601. (defun org-property-or-variable-value (var &optional inherit)
  14602. "Check if there is a property fixing the value of VAR.
  14603. If yes, return this value. If not, return the current value of the variable."
  14604. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14605. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14606. (read prop)
  14607. (symbol-value var))))
  14608. (defun org-entry-delete (pom property)
  14609. "Delete PROPERTY from entry at point-or-marker POM.
  14610. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14611. non-nil when a property was removed."
  14612. (unless (member property org-special-properties)
  14613. (org-with-point-at pom
  14614. (let ((range (org-get-property-block)))
  14615. (when range
  14616. (let* ((begin (car range))
  14617. (origin (cdr range))
  14618. (end (copy-marker origin))
  14619. (re (org-re-property
  14620. (concat (regexp-quote property) "\\+?") t t)))
  14621. (goto-char begin)
  14622. (while (re-search-forward re end t)
  14623. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14624. ;; If drawer is empty, remove it altogether.
  14625. (when (= begin end)
  14626. (delete-region (line-beginning-position 0)
  14627. (line-beginning-position 2)))
  14628. ;; Return non-nil if some property was removed.
  14629. (prog1 (/= end origin) (set-marker end nil))))))))
  14630. ;; Multi-values properties are properties that contain multiple values
  14631. ;; These values are assumed to be single words, separated by whitespace.
  14632. (defun org-entry-add-to-multivalued-property (pom property value)
  14633. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14634. (let* ((old (org-entry-get pom property))
  14635. (values (and old (org-split-string old "[ \t]"))))
  14636. (setq value (org-entry-protect-space value))
  14637. (unless (member value values)
  14638. (setq values (append values (list value)))
  14639. (org-entry-put pom property
  14640. (mapconcat 'identity values " ")))))
  14641. (defun org-entry-remove-from-multivalued-property (pom property value)
  14642. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14643. (let* ((old (org-entry-get pom property))
  14644. (values (and old (org-split-string old "[ \t]"))))
  14645. (setq value (org-entry-protect-space value))
  14646. (when (member value values)
  14647. (setq values (delete value values))
  14648. (org-entry-put pom property
  14649. (mapconcat 'identity values " ")))))
  14650. (defun org-entry-member-in-multivalued-property (pom property value)
  14651. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14652. (let* ((old (org-entry-get pom property))
  14653. (values (and old (org-split-string old "[ \t]"))))
  14654. (setq value (org-entry-protect-space value))
  14655. (member value values)))
  14656. (defun org-entry-get-multivalued-property (pom property)
  14657. "Return a list of values in a multivalued property."
  14658. (let* ((value (org-entry-get pom property))
  14659. (values (and value (org-split-string value "[ \t]"))))
  14660. (mapcar 'org-entry-restore-space values)))
  14661. (defun org-entry-put-multivalued-property (pom property &rest values)
  14662. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14663. VALUES should be a list of strings. Spaces will be protected."
  14664. (org-entry-put pom property
  14665. (mapconcat 'org-entry-protect-space values " "))
  14666. (let* ((value (org-entry-get pom property))
  14667. (values (and value (org-split-string value "[ \t]"))))
  14668. (mapcar 'org-entry-restore-space values)))
  14669. (defun org-entry-protect-space (s)
  14670. "Protect spaces and newline in string S."
  14671. (while (string-match " " s)
  14672. (setq s (replace-match "%20" t t s)))
  14673. (while (string-match "\n" s)
  14674. (setq s (replace-match "%0A" t t s)))
  14675. s)
  14676. (defun org-entry-restore-space (s)
  14677. "Restore spaces and newline in string S."
  14678. (while (string-match "%20" s)
  14679. (setq s (replace-match " " t t s)))
  14680. (while (string-match "%0A" s)
  14681. (setq s (replace-match "\n" t t s)))
  14682. s)
  14683. (defvar org-entry-property-inherited-from (make-marker)
  14684. "Marker pointing to the entry from where a property was inherited.
  14685. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14686. location of the entry where the inheritance search matched. If there was
  14687. no match, the marker will point nowhere.
  14688. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14689. is set.")
  14690. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14691. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14692. The search will stop at the first ancestor which has the property defined.
  14693. If the value found is \"nil\", return nil to show that the property
  14694. should be considered as undefined (this is the meaning of nil here).
  14695. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14696. (move-marker org-entry-property-inherited-from nil)
  14697. (org-with-wide-buffer
  14698. (let (value)
  14699. (catch 'exit
  14700. (while t
  14701. (let ((v (org-property--local-values property literal-nil)))
  14702. (when v
  14703. (setq value
  14704. (concat (mapconcat #'identity (delq nil v) " ")
  14705. (and value " ")
  14706. value)))
  14707. (cond
  14708. ((car v)
  14709. (org-back-to-heading t)
  14710. (move-marker org-entry-property-inherited-from (point))
  14711. (throw 'exit nil))
  14712. ((org-up-heading-safe))
  14713. (t
  14714. (let ((global
  14715. (cdr (or (assoc-string property org-file-properties t)
  14716. (assoc-string property org-global-properties t)
  14717. (assoc-string property org-global-properties-fixed t)))))
  14718. (cond ((not global))
  14719. (value (setq value (concat global " " value)))
  14720. (t (setq value global))))
  14721. (throw 'exit nil))))))
  14722. (if literal-nil value (org-not-nil value)))))
  14723. (defvar org-property-changed-functions nil
  14724. "Hook called when the value of a property has changed.
  14725. Each hook function should accept two arguments, the name of the property
  14726. and the new value.")
  14727. (defun org-entry-put (pom property value)
  14728. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14729. If the value is nil, it is converted to the empty string. If it
  14730. is not a string, an error is raised. Also raise an error on
  14731. invalid property names.
  14732. PROPERTY can be any regular property (see
  14733. `org-special-properties'). It can also be \"TODO\",
  14734. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14735. For the last two properties, VALUE may have any of the special
  14736. values \"earlier\" and \"later\". The function then increases or
  14737. decreases scheduled or deadline date by one day."
  14738. (cond ((null value) (setq value ""))
  14739. ((not (stringp value)) (error "Properties values should be strings"))
  14740. ((not (org--valid-property-p property))
  14741. (user-error "Invalid property name: \"%s\"" property)))
  14742. (org-with-point-at pom
  14743. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14744. (org-back-to-heading t)
  14745. (org-with-limited-levels (org-back-to-heading t)))
  14746. (let ((beg (point)))
  14747. (cond
  14748. ((equal property "TODO")
  14749. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14750. ((not (member value org-todo-keywords-1))
  14751. (user-error "\"%s\" is not a valid TODO state" value)))
  14752. (org-todo value)
  14753. (org-set-tags nil 'align))
  14754. ((equal property "PRIORITY")
  14755. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14756. (org-set-tags nil 'align))
  14757. ((equal property "SCHEDULED")
  14758. (forward-line)
  14759. (if (and (looking-at-p org-planning-line-re)
  14760. (re-search-forward
  14761. org-scheduled-time-regexp (line-end-position) t))
  14762. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14763. ((string= value "later") (org-timestamp-change 1 'day))
  14764. ((string= value "") (org-schedule '(4)))
  14765. (t (org-schedule nil value)))
  14766. (if (member value '("earlier" "later" ""))
  14767. (call-interactively #'org-schedule)
  14768. (org-schedule nil value))))
  14769. ((equal property "DEADLINE")
  14770. (forward-line)
  14771. (if (and (looking-at-p org-planning-line-re)
  14772. (re-search-forward
  14773. org-deadline-time-regexp (line-end-position) t))
  14774. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14775. ((string= value "later") (org-timestamp-change 1 'day))
  14776. ((string= value "") (org-deadline '(4)))
  14777. (t (org-deadline nil value)))
  14778. (if (member value '("earlier" "later" ""))
  14779. (call-interactively #'org-deadline)
  14780. (org-deadline nil value))))
  14781. ((member property org-special-properties)
  14782. (error "The %s property cannot be set with `org-entry-put'" property))
  14783. (t
  14784. (let* ((range (org-get-property-block beg 'force))
  14785. (end (cdr range))
  14786. (case-fold-search t))
  14787. (goto-char (car range))
  14788. (if (re-search-forward (org-re-property property nil t) end t)
  14789. (progn (delete-region (match-beginning 0) (match-end 0))
  14790. (goto-char (match-beginning 0)))
  14791. (goto-char end)
  14792. (insert "\n")
  14793. (backward-char))
  14794. (insert ":" property ":")
  14795. (when value (insert " " value))
  14796. (org-indent-line)))))
  14797. (run-hook-with-args 'org-property-changed-functions property value)))
  14798. (defun org-buffer-property-keys
  14799. (&optional specials defaults columns ignore-malformed)
  14800. "Get all property keys in the current buffer.
  14801. When SPECIALS is non-nil, also list the special properties that
  14802. reflect things like tags and TODO state.
  14803. When DEFAULTS is non-nil, also include properties that has
  14804. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14805. DESCRIPTION, LOCATION, and LOGGING and others.
  14806. When COLUMNS in non-nil, also include property names given in
  14807. COLUMN formats in the current buffer.
  14808. When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
  14809. automatically performed, such drawers will be silently ignored."
  14810. (let ((case-fold-search t)
  14811. (props (append
  14812. (and specials org-special-properties)
  14813. (and defaults (cons org-effort-property org-default-properties))
  14814. nil)))
  14815. (org-with-wide-buffer
  14816. (goto-char (point-min))
  14817. (while (re-search-forward org-property-start-re nil t)
  14818. (let ((range (org-get-property-block)))
  14819. (catch 'skip
  14820. (unless range
  14821. (when (and (not ignore-malformed)
  14822. (not (org-before-first-heading-p))
  14823. (y-or-n-p (format "Malformed drawer at %d, repair?"
  14824. (line-beginning-position))))
  14825. (org-get-property-block nil t))
  14826. (throw 'skip nil))
  14827. (goto-char (car range))
  14828. (let ((begin (car range))
  14829. (end (cdr range)))
  14830. ;; Make sure that found property block is not located
  14831. ;; before current point, as it would generate an infloop.
  14832. ;; It can happen, for example, in the following
  14833. ;; situation:
  14834. ;;
  14835. ;; * Headline
  14836. ;; :PROPERTIES:
  14837. ;; ...
  14838. ;; :END:
  14839. ;; *************** Inlinetask
  14840. ;; #+BEGIN_EXAMPLE
  14841. ;; :PROPERTIES:
  14842. ;; #+END_EXAMPLE
  14843. ;;
  14844. (if (< begin (point)) (throw 'skip nil) (goto-char begin))
  14845. (while (< (point) end)
  14846. (let ((p (progn (looking-at org-property-re)
  14847. (match-string-no-properties 2))))
  14848. ;; Only add true property name, not extension symbol.
  14849. (push (if (not (string-match-p "\\+\\'" p)) p
  14850. (substring p 0 -1))
  14851. props))
  14852. (forward-line))))
  14853. (outline-next-heading)))
  14854. (when columns
  14855. (goto-char (point-min))
  14856. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14857. (let ((element (org-element-at-point)))
  14858. (when (memq (org-element-type element) '(keyword node-property))
  14859. (let ((value (org-element-property :value element))
  14860. (start 0))
  14861. (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
  14862. (setq start (match-end 0))
  14863. (let ((p (match-string-no-properties 1 value)))
  14864. (unless (member-ignore-case p org-special-properties)
  14865. (push p props))))))))))
  14866. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14867. (defun org-property-values (key)
  14868. "List all non-nil values of property KEY in current buffer."
  14869. (org-with-wide-buffer
  14870. (goto-char (point-min))
  14871. (let ((case-fold-search t)
  14872. (re (org-re-property key))
  14873. values)
  14874. (while (re-search-forward re nil t)
  14875. (push (org-entry-get (point) key) values))
  14876. (delete-dups values))))
  14877. (defun org-insert-property-drawer ()
  14878. "Insert a property drawer into the current entry."
  14879. (org-with-wide-buffer
  14880. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14881. (org-back-to-heading t)
  14882. (org-with-limited-levels (org-back-to-heading t)))
  14883. (forward-line)
  14884. (when (looking-at-p org-planning-line-re) (forward-line))
  14885. (unless (looking-at-p org-property-drawer-re)
  14886. ;; Make sure we start editing a line from current entry, not from
  14887. ;; next one. It prevents extending text properties or overlays
  14888. ;; belonging to the latter.
  14889. (when (bolp) (backward-char))
  14890. (let ((begin (1+ (point)))
  14891. (inhibit-read-only t))
  14892. (insert "\n:PROPERTIES:\n:END:")
  14893. (when (eobp) (insert "\n"))
  14894. (org-indent-region begin (point))))))
  14895. (defun org-insert-drawer (&optional arg drawer)
  14896. "Insert a drawer at point.
  14897. When optional argument ARG is non-nil, insert a property drawer.
  14898. Optional argument DRAWER, when non-nil, is a string representing
  14899. drawer's name. Otherwise, the user is prompted for a name.
  14900. If a region is active, insert the drawer around that region
  14901. instead.
  14902. Point is left between drawer's boundaries."
  14903. (interactive "P")
  14904. (let* ((drawer (if arg "PROPERTIES"
  14905. (or drawer (read-from-minibuffer "Drawer: ")))))
  14906. (cond
  14907. ;; With C-u, fall back on `org-insert-property-drawer'
  14908. (arg (org-insert-property-drawer))
  14909. ;; Check validity of suggested drawer's name.
  14910. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14911. (user-error "Invalid drawer name"))
  14912. ;; With an active region, insert a drawer at point.
  14913. ((not (org-region-active-p))
  14914. (progn
  14915. (unless (bolp) (insert "\n"))
  14916. (insert (format ":%s:\n\n:END:\n" drawer))
  14917. (forward-line -2)))
  14918. ;; Otherwise, insert the drawer at point
  14919. (t
  14920. (let ((rbeg (region-beginning))
  14921. (rend (copy-marker (region-end))))
  14922. (unwind-protect
  14923. (progn
  14924. (goto-char rbeg)
  14925. (beginning-of-line)
  14926. (when (save-excursion
  14927. (re-search-forward org-outline-regexp-bol rend t))
  14928. (user-error "Drawers cannot contain headlines"))
  14929. ;; Position point at the beginning of the first
  14930. ;; non-blank line in region. Insert drawer's opening
  14931. ;; there, then indent it.
  14932. (org-skip-whitespace)
  14933. (beginning-of-line)
  14934. (insert ":" drawer ":\n")
  14935. (forward-line -1)
  14936. (indent-for-tab-command)
  14937. ;; Move point to the beginning of the first blank line
  14938. ;; after the last non-blank line in region. Insert
  14939. ;; drawer's closing, then indent it.
  14940. (goto-char rend)
  14941. (skip-chars-backward " \r\t\n")
  14942. (insert "\n:END:")
  14943. (deactivate-mark t)
  14944. (indent-for-tab-command)
  14945. (unless (eolp) (insert "\n")))
  14946. ;; Clear marker, whatever the outcome of insertion is.
  14947. (set-marker rend nil)))))))
  14948. (defvar org-property-set-functions-alist nil
  14949. "Property set function alist.
  14950. Each entry should have the following format:
  14951. (PROPERTY . READ-FUNCTION)
  14952. The read function will be called with the same argument as
  14953. `org-completing-read'.")
  14954. (defun org-set-property-function (property)
  14955. "Get the function that should be used to set PROPERTY.
  14956. This is computed according to `org-property-set-functions-alist'."
  14957. (or (cdr (assoc property org-property-set-functions-alist))
  14958. 'org-completing-read))
  14959. (defun org-read-property-value (property)
  14960. "Read PROPERTY value from user."
  14961. (let* ((completion-ignore-case t)
  14962. (allowed (org-property-get-allowed-values nil property 'table))
  14963. (cur (org-entry-get nil property))
  14964. (prompt (concat property " value"
  14965. (if (and cur (string-match "\\S-" cur))
  14966. (concat " [" cur "]") "") ": "))
  14967. (set-function (org-set-property-function property))
  14968. (val (if allowed
  14969. (funcall set-function prompt allowed nil
  14970. (not (get-text-property 0 'org-unrestricted
  14971. (caar allowed))))
  14972. (funcall set-function prompt
  14973. (mapcar 'list (org-property-values property))
  14974. nil nil "" nil cur))))
  14975. (org-trim val)))
  14976. (defvar org-last-set-property nil)
  14977. (defvar org-last-set-property-value nil)
  14978. (defun org-read-property-name ()
  14979. "Read a property name."
  14980. (let ((completion-ignore-case t)
  14981. (default-prop (or (and (org-at-property-p)
  14982. (match-string-no-properties 2))
  14983. org-last-set-property)))
  14984. (org-completing-read
  14985. (concat "Property"
  14986. (if default-prop (concat " [" default-prop "]") "")
  14987. ": ")
  14988. (mapcar #'list (org-buffer-property-keys nil t t))
  14989. nil nil nil nil default-prop)))
  14990. (defun org-set-property-and-value (use-last)
  14991. "Allow to set [PROPERTY]: [value] direction from prompt.
  14992. When use-default, don't even ask, just use the last
  14993. \"[PROPERTY]: [value]\" string from the history."
  14994. (interactive "P")
  14995. (let* ((completion-ignore-case t)
  14996. (pv (or (and use-last org-last-set-property-value)
  14997. (org-completing-read
  14998. "Enter a \"[Property]: [value]\" pair: "
  14999. nil nil nil nil nil
  15000. org-last-set-property-value)))
  15001. prop val)
  15002. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  15003. (setq prop (match-string 1 pv)
  15004. val (match-string 2 pv))
  15005. (org-set-property prop val))))
  15006. (defun org-set-property (property value)
  15007. "In the current entry, set PROPERTY to VALUE.
  15008. When called interactively, this will prompt for a property name, offering
  15009. completion on existing and default properties. And then it will prompt
  15010. for a value, offering completion either on allowed values (via an inherited
  15011. xxx_ALL property) or on existing values in other instances of this property
  15012. in the current file.
  15013. Throw an error when trying to set a property with an invalid name."
  15014. (interactive (list nil nil))
  15015. (let ((property (or property (org-read-property-name))))
  15016. ;; `org-entry-put' also makes the following check, but this one
  15017. ;; avoids polluting `org-last-set-property' and
  15018. ;; `org-last-set-property-value' needlessly.
  15019. (unless (org--valid-property-p property)
  15020. (user-error "Invalid property name: \"%s\"" property))
  15021. (let ((value (or value (org-read-property-value property)))
  15022. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  15023. (setq org-last-set-property property)
  15024. (setq org-last-set-property-value (concat property ": " value))
  15025. ;; Possibly postprocess the inserted value:
  15026. (when fn (setq value (funcall fn value)))
  15027. (unless (equal (org-entry-get nil property) value)
  15028. (org-entry-put nil property value)))))
  15029. (defun org-find-property (property &optional value)
  15030. "Find first entry in buffer that sets PROPERTY.
  15031. When optional argument VALUE is non-nil, only consider an entry
  15032. if it contains PROPERTY set to this value. If PROPERTY should be
  15033. explicitly set to nil, use string \"nil\" for VALUE.
  15034. Return position where the entry begins, or nil if there is no
  15035. such entry. If narrowing is in effect, only search the visible
  15036. part of the buffer."
  15037. (save-excursion
  15038. (goto-char (point-min))
  15039. (let ((case-fold-search t)
  15040. (re (org-re-property property nil (not value) value)))
  15041. (catch 'exit
  15042. (while (re-search-forward re nil t)
  15043. (when (if value (org-at-property-p)
  15044. (org-entry-get (point) property nil t))
  15045. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  15046. (defun org-delete-property (property)
  15047. "In the current entry, delete PROPERTY."
  15048. (interactive
  15049. (let* ((completion-ignore-case t)
  15050. (cat (org-entry-get (point) "CATEGORY"))
  15051. (props0 (org-entry-properties nil 'standard))
  15052. (props (if cat props0
  15053. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  15054. (prop (if (< 1 (length props))
  15055. (completing-read "Property: " props nil t)
  15056. (caar props))))
  15057. (list prop)))
  15058. (if (not property)
  15059. (message "No property to delete in this entry")
  15060. (org-entry-delete nil property)
  15061. (message "Property \"%s\" deleted" property)))
  15062. (defun org-delete-property-globally (property)
  15063. "Remove PROPERTY globally, from all entries.
  15064. This function ignores narrowing, if any."
  15065. (interactive
  15066. (let* ((completion-ignore-case t)
  15067. (prop (completing-read
  15068. "Globally remove property: "
  15069. (mapcar #'list (org-buffer-property-keys)))))
  15070. (list prop)))
  15071. (org-with-wide-buffer
  15072. (goto-char (point-min))
  15073. (let ((count 0)
  15074. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  15075. (while (re-search-forward re nil t)
  15076. (when (org-entry-delete (point) property) (cl-incf count)))
  15077. (message "Property \"%s\" removed from %d entries" property count))))
  15078. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  15079. (defun org-compute-property-at-point ()
  15080. "Compute the property at point.
  15081. This looks for an enclosing column format, extracts the operator and
  15082. then applies it to the property in the column format's scope."
  15083. (interactive)
  15084. (unless (org-at-property-p)
  15085. (user-error "Not at a property"))
  15086. (let ((prop (match-string-no-properties 2)))
  15087. (org-columns-get-format-and-top-level)
  15088. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  15089. (user-error "No operator defined for property %s" prop))
  15090. (org-columns-compute prop)))
  15091. (defvar org-property-allowed-value-functions nil
  15092. "Hook for functions supplying allowed values for a specific property.
  15093. The functions must take a single argument, the name of the property, and
  15094. return a flat list of allowed values. If \":ETC\" is one of
  15095. the values, this means that these values are intended as defaults for
  15096. completion, but that other values should be allowed too.
  15097. The functions must return nil if they are not responsible for this
  15098. property.")
  15099. (defun org-property-get-allowed-values (pom property &optional table)
  15100. "Get allowed values for the property PROPERTY.
  15101. When TABLE is non-nil, return an alist that can directly be used for
  15102. completion."
  15103. (let (vals)
  15104. (cond
  15105. ((equal property "TODO")
  15106. (setq vals (org-with-point-at pom
  15107. (append org-todo-keywords-1 '("")))))
  15108. ((equal property "PRIORITY")
  15109. (let ((n org-lowest-priority))
  15110. (while (>= n org-highest-priority)
  15111. (push (char-to-string n) vals)
  15112. (setq n (1- n)))))
  15113. ((equal property "CATEGORY"))
  15114. ((member property org-special-properties))
  15115. ((setq vals (run-hook-with-args-until-success
  15116. 'org-property-allowed-value-functions property)))
  15117. (t
  15118. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  15119. (when (and vals (string-match "\\S-" vals))
  15120. (setq vals (car (read-from-string (concat "(" vals ")"))))
  15121. (setq vals (mapcar (lambda (x)
  15122. (cond ((stringp x) x)
  15123. ((numberp x) (number-to-string x))
  15124. ((symbolp x) (symbol-name x))
  15125. (t "???")))
  15126. vals)))))
  15127. (when (member ":ETC" vals)
  15128. (setq vals (remove ":ETC" vals))
  15129. (org-add-props (car vals) '(org-unrestricted t)))
  15130. (if table (mapcar 'list vals) vals)))
  15131. (defun org-property-previous-allowed-value (&optional _previous)
  15132. "Switch to the next allowed value for this property."
  15133. (interactive)
  15134. (org-property-next-allowed-value t))
  15135. (defun org-property-next-allowed-value (&optional previous)
  15136. "Switch to the next allowed value for this property."
  15137. (interactive)
  15138. (unless (org-at-property-p)
  15139. (user-error "Not at a property"))
  15140. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  15141. (key (match-string 2))
  15142. (value (match-string 3))
  15143. (allowed (or (org-property-get-allowed-values (point) key)
  15144. (and (member value '("[ ]" "[-]" "[X]"))
  15145. '("[ ]" "[X]"))))
  15146. (heading (save-match-data (nth 4 (org-heading-components))))
  15147. nval)
  15148. (unless allowed
  15149. (user-error "Allowed values for this property have not been defined"))
  15150. (when previous (setq allowed (reverse allowed)))
  15151. (when (member value allowed)
  15152. (setq nval (car (cdr (member value allowed)))))
  15153. (setq nval (or nval (car allowed)))
  15154. (when (equal nval value)
  15155. (user-error "Only one allowed value for this property"))
  15156. (org-at-property-p)
  15157. (replace-match (concat " :" key ": " nval) t t)
  15158. (org-indent-line)
  15159. (beginning-of-line 1)
  15160. (skip-chars-forward " \t")
  15161. (when (equal prop org-effort-property)
  15162. (org-refresh-property
  15163. '((effort . identity)
  15164. (effort-minutes . org-duration-string-to-minutes))
  15165. nval)
  15166. (when (string= org-clock-current-task heading)
  15167. (setq org-clock-effort nval)
  15168. (org-clock-update-mode-line)))
  15169. (run-hook-with-args 'org-property-changed-functions key nval)))
  15170. (defun org-find-olp (path &optional this-buffer)
  15171. "Return a marker pointing to the entry at outline path OLP.
  15172. If anything goes wrong, throw an error.
  15173. You can wrap this call to catch the error like this:
  15174. \(condition-case msg
  15175. \(org-mobile-locate-entry (match-string 4))
  15176. \(error (nth 1 msg)))
  15177. The return value will then be either a string with the error message,
  15178. or a marker if everything is OK.
  15179. If THIS-BUFFER is set, the outline path does not contain a file,
  15180. only headings."
  15181. (let* ((file (if this-buffer buffer-file-name (pop path)))
  15182. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  15183. (level 1)
  15184. (lmin 1)
  15185. (lmax 1)
  15186. end found flevel)
  15187. (unless buffer (error "File not found :%s" file))
  15188. (with-current-buffer buffer
  15189. (org-with-wide-buffer
  15190. (goto-char (point-min))
  15191. (dolist (heading path)
  15192. (let ((re (format org-complex-heading-regexp-format
  15193. (regexp-quote heading)))
  15194. (cnt 0))
  15195. (while (re-search-forward re end t)
  15196. (setq level (- (match-end 1) (match-beginning 1)))
  15197. (when (and (>= level lmin) (<= level lmax))
  15198. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  15199. (when (= cnt 0)
  15200. (error "Heading not found on level %d: %s" lmax heading))
  15201. (when (> cnt 1)
  15202. (error "Heading not unique on level %d: %s" lmax heading))
  15203. (goto-char found)
  15204. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  15205. (setq end (save-excursion (org-end-of-subtree t t)))))
  15206. (when (org-at-heading-p)
  15207. (point-marker))))))
  15208. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  15209. "Find node HEADING in BUFFER.
  15210. Return a marker to the heading if it was found, or nil if not.
  15211. If POS-ONLY is set, return just the position instead of a marker.
  15212. The heading text must match exact, but it may have a TODO keyword,
  15213. a priority cookie and tags in the standard locations."
  15214. (with-current-buffer (or buffer (current-buffer))
  15215. (org-with-wide-buffer
  15216. (goto-char (point-min))
  15217. (let (case-fold-search)
  15218. (when (re-search-forward
  15219. (format org-complex-heading-regexp-format
  15220. (regexp-quote heading)) nil t)
  15221. (if pos-only
  15222. (match-beginning 0)
  15223. (move-marker (make-marker) (match-beginning 0))))))))
  15224. (defun org-find-exact-heading-in-directory (heading &optional dir)
  15225. "Find Org node headline HEADING in all .org files in directory DIR.
  15226. When the target headline is found, return a marker to this location."
  15227. (let ((files (directory-files (or dir default-directory)
  15228. t "\\`[^.#].*\\.org\\'"))
  15229. visiting m buffer)
  15230. (catch 'found
  15231. (dolist (file files)
  15232. (message "trying %s" file)
  15233. (setq visiting (org-find-base-buffer-visiting file))
  15234. (setq buffer (or visiting (find-file-noselect file)))
  15235. (setq m (org-find-exact-headline-in-buffer
  15236. heading buffer))
  15237. (when (and (not m) (not visiting)) (kill-buffer buffer))
  15238. (and m (throw 'found m))))))
  15239. (defun org-find-entry-with-id (ident)
  15240. "Locate the entry that contains the ID property with exact value IDENT.
  15241. IDENT can be a string, a symbol or a number, this function will search for
  15242. the string representation of it.
  15243. Return the position where this entry starts, or nil if there is no such entry."
  15244. (interactive "sID: ")
  15245. (let ((id (cond
  15246. ((stringp ident) ident)
  15247. ((symbolp ident) (symbol-name ident))
  15248. ((numberp ident) (number-to-string ident))
  15249. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  15250. (org-with-wide-buffer (org-find-property "ID" id))))
  15251. ;;;; Timestamps
  15252. (defvar org-last-changed-timestamp nil)
  15253. (defvar org-last-inserted-timestamp nil
  15254. "The last time stamp inserted with `org-insert-time-stamp'.")
  15255. (defvar org-ts-what) ; dynamically scoped parameter
  15256. (defun org-time-stamp (arg &optional inactive)
  15257. "Prompt for a date/time and insert a time stamp.
  15258. If the user specifies a time like HH:MM or if this command is
  15259. called with at least one prefix argument, the time stamp contains
  15260. the date and the time. Otherwise, only the date is included.
  15261. All parts of a date not specified by the user are filled in from
  15262. the timestamp at point, if any, or the current date/time
  15263. otherwise.
  15264. If there is already a timestamp at the cursor, it is replaced.
  15265. With two universal prefix arguments, insert an active timestamp
  15266. with the current time without prompting the user.
  15267. When called from lisp, the timestamp is inactive if INACTIVE is
  15268. non-nil."
  15269. (interactive "P")
  15270. (let* ((ts (cond
  15271. ((org-at-date-range-p t)
  15272. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  15273. ((org-at-timestamp-p t) (match-string 0))))
  15274. ;; Default time is either the timestamp at point or today.
  15275. ;; When entering a range, only the range start is considered.
  15276. (default-time (if (not ts) (current-time)
  15277. (apply #'encode-time (org-parse-time-string ts))))
  15278. (default-input (and ts (org-get-compact-tod ts)))
  15279. (repeater (and ts
  15280. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  15281. (match-string 0 ts)))
  15282. org-time-was-given
  15283. org-end-time-was-given
  15284. (time
  15285. (and (if (equal arg '(16)) (current-time)
  15286. ;; Preserve `this-command' and `last-command'.
  15287. (let ((this-command this-command)
  15288. (last-command last-command))
  15289. (org-read-date
  15290. arg 'totime nil nil default-time default-input
  15291. inactive))))))
  15292. (cond
  15293. ((and ts
  15294. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  15295. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  15296. (insert "--")
  15297. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  15298. (ts
  15299. ;; Make sure we're on a timestamp. When in the middle of a date
  15300. ;; range, move arbitrarily to range end.
  15301. (unless (org-at-timestamp-p t)
  15302. (skip-chars-forward "-")
  15303. (org-at-timestamp-p t))
  15304. (replace-match "")
  15305. (setq org-last-changed-timestamp
  15306. (org-insert-time-stamp
  15307. time (or org-time-was-given arg)
  15308. inactive nil nil (list org-end-time-was-given)))
  15309. (when repeater
  15310. (backward-char)
  15311. (insert " " repeater)
  15312. (setq org-last-changed-timestamp
  15313. (concat (substring org-last-inserted-timestamp 0 -1)
  15314. " " repeater ">")))
  15315. (message "Timestamp updated"))
  15316. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  15317. (t (org-insert-time-stamp
  15318. time (or org-time-was-given arg) inactive nil nil
  15319. (list org-end-time-was-given))))))
  15320. ;; FIXME: can we use this for something else, like computing time differences?
  15321. (defun org-get-compact-tod (s)
  15322. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  15323. (let* ((t1 (match-string 1 s))
  15324. (h1 (string-to-number (match-string 2 s)))
  15325. (m1 (string-to-number (match-string 3 s)))
  15326. (t2 (and (match-end 4) (match-string 5 s)))
  15327. (h2 (and t2 (string-to-number (match-string 6 s))))
  15328. (m2 (and t2 (string-to-number (match-string 7 s))))
  15329. dh dm)
  15330. (if (not t2)
  15331. t1
  15332. (setq dh (- h2 h1) dm (- m2 m1))
  15333. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  15334. (concat t1 "+" (number-to-string dh)
  15335. (and (/= 0 dm) (format ":%02d" dm)))))))
  15336. (defun org-time-stamp-inactive (&optional arg)
  15337. "Insert an inactive time stamp.
  15338. An inactive time stamp is enclosed in square brackets instead of angle
  15339. brackets. It is inactive in the sense that it does not trigger agenda entries,
  15340. does not link to the calendar and cannot be changed with the S-cursor keys.
  15341. So these are more for recording a certain time/date."
  15342. (interactive "P")
  15343. (org-time-stamp arg 'inactive))
  15344. (defvar org-date-ovl (make-overlay 1 1))
  15345. (overlay-put org-date-ovl 'face 'org-date-selected)
  15346. (delete-overlay org-date-ovl)
  15347. (defvar org-ans1) ; dynamically scoped parameter
  15348. (defvar org-ans2) ; dynamically scoped parameter
  15349. (defvar org-plain-time-of-day-regexp) ; defined below
  15350. (defvar org-overriding-default-time nil) ; dynamically scoped
  15351. (defvar org-read-date-overlay nil)
  15352. (defvar org-dcst nil) ; dynamically scoped
  15353. (defvar org-read-date-history nil)
  15354. (defvar org-read-date-final-answer nil)
  15355. (defvar org-read-date-analyze-futurep nil)
  15356. (defvar org-read-date-analyze-forced-year nil)
  15357. (defvar org-read-date-inactive)
  15358. (defvar org-read-date-minibuffer-local-map
  15359. (let* ((map (make-sparse-keymap)))
  15360. (set-keymap-parent map minibuffer-local-map)
  15361. (org-defkey map (kbd ".")
  15362. (lambda () (interactive)
  15363. ;; Are we at the beginning of the prompt?
  15364. (if (looking-back "^[^:]+: "
  15365. (let ((inhibit-field-text-motion t))
  15366. (line-beginning-position)))
  15367. (org-eval-in-calendar '(calendar-goto-today))
  15368. (insert "."))))
  15369. (org-defkey map (kbd "C-.")
  15370. (lambda () (interactive)
  15371. (org-eval-in-calendar '(calendar-goto-today))))
  15372. (org-defkey map [(meta shift left)]
  15373. (lambda () (interactive)
  15374. (org-eval-in-calendar '(calendar-backward-month 1))))
  15375. (org-defkey map [(meta shift right)]
  15376. (lambda () (interactive)
  15377. (org-eval-in-calendar '(calendar-forward-month 1))))
  15378. (org-defkey map [(meta shift up)]
  15379. (lambda () (interactive)
  15380. (org-eval-in-calendar '(calendar-backward-year 1))))
  15381. (org-defkey map [(meta shift down)]
  15382. (lambda () (interactive)
  15383. (org-eval-in-calendar '(calendar-forward-year 1))))
  15384. (org-defkey map [?\e (shift left)]
  15385. (lambda () (interactive)
  15386. (org-eval-in-calendar '(calendar-backward-month 1))))
  15387. (org-defkey map [?\e (shift right)]
  15388. (lambda () (interactive)
  15389. (org-eval-in-calendar '(calendar-forward-month 1))))
  15390. (org-defkey map [?\e (shift up)]
  15391. (lambda () (interactive)
  15392. (org-eval-in-calendar '(calendar-backward-year 1))))
  15393. (org-defkey map [?\e (shift down)]
  15394. (lambda () (interactive)
  15395. (org-eval-in-calendar '(calendar-forward-year 1))))
  15396. (org-defkey map [(shift up)]
  15397. (lambda () (interactive)
  15398. (org-eval-in-calendar '(calendar-backward-week 1))))
  15399. (org-defkey map [(shift down)]
  15400. (lambda () (interactive)
  15401. (org-eval-in-calendar '(calendar-forward-week 1))))
  15402. (org-defkey map [(shift left)]
  15403. (lambda () (interactive)
  15404. (org-eval-in-calendar '(calendar-backward-day 1))))
  15405. (org-defkey map [(shift right)]
  15406. (lambda () (interactive)
  15407. (org-eval-in-calendar '(calendar-forward-day 1))))
  15408. (org-defkey map "!"
  15409. (lambda () (interactive)
  15410. (org-eval-in-calendar '(diary-view-entries))
  15411. (message "")))
  15412. (org-defkey map ">"
  15413. (lambda () (interactive)
  15414. (org-eval-in-calendar '(calendar-scroll-left 1))))
  15415. (org-defkey map "<"
  15416. (lambda () (interactive)
  15417. (org-eval-in-calendar '(calendar-scroll-right 1))))
  15418. (org-defkey map "\C-v"
  15419. (lambda () (interactive)
  15420. (org-eval-in-calendar
  15421. '(calendar-scroll-left-three-months 1))))
  15422. (org-defkey map "\M-v"
  15423. (lambda () (interactive)
  15424. (org-eval-in-calendar
  15425. '(calendar-scroll-right-three-months 1))))
  15426. map)
  15427. "Keymap for minibuffer commands when using `org-read-date'.")
  15428. (defvar org-def)
  15429. (defvar org-defdecode)
  15430. (defvar org-with-time)
  15431. (defvar calendar-setup) ; Dynamically scoped.
  15432. (defun org-read-date (&optional with-time to-time from-string prompt
  15433. default-time default-input inactive)
  15434. "Read a date, possibly a time, and make things smooth for the user.
  15435. The prompt will suggest to enter an ISO date, but you can also enter anything
  15436. which will at least partially be understood by `parse-time-string'.
  15437. Unrecognized parts of the date will default to the current day, month, year,
  15438. hour and minute. If this command is called to replace a timestamp at point,
  15439. or to enter the second timestamp of a range, the default time is taken
  15440. from the existing stamp. Furthermore, the command prefers the future,
  15441. so if you are giving a date where the year is not given, and the day-month
  15442. combination is already past in the current year, it will assume you
  15443. mean next year. For details, see the manual. A few examples:
  15444. 3-2-5 --> 2003-02-05
  15445. feb 15 --> currentyear-02-15
  15446. 2/15 --> currentyear-02-15
  15447. sep 12 9 --> 2009-09-12
  15448. 12:45 --> today 12:45
  15449. 22 sept 0:34 --> currentyear-09-22 0:34
  15450. 12 --> currentyear-currentmonth-12
  15451. Fri --> nearest Friday after today
  15452. -Tue --> last Tuesday
  15453. etc.
  15454. Furthermore you can specify a relative date by giving, as the *first* thing
  15455. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  15456. change in days weeks, months, years.
  15457. With a single plus or minus, the date is relative to today. With a double
  15458. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  15459. +4d --> four days from today
  15460. +4 --> same as above
  15461. +2w --> two weeks from today
  15462. ++5 --> five days from default date
  15463. The function understands only English month and weekday abbreviations.
  15464. While prompting, a calendar is popped up - you can also select the
  15465. date with the mouse (button 1). The calendar shows a period of three
  15466. months. To scroll it to other months, use the keys `>' and `<'.
  15467. If you don't like the calendar, turn it off with
  15468. (setq org-read-date-popup-calendar nil)
  15469. With optional argument TO-TIME, the date will immediately be converted
  15470. to an internal time.
  15471. With an optional argument WITH-TIME, the prompt will suggest to
  15472. also insert a time. Note that when WITH-TIME is not set, you can
  15473. still enter a time, and this function will inform the calling routine
  15474. about this change. The calling routine may then choose to change the
  15475. format used to insert the time stamp into the buffer to include the time.
  15476. With optional argument FROM-STRING, read from this string instead from
  15477. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  15478. the time/date that is used for everything that is not specified by the
  15479. user."
  15480. (require 'parse-time)
  15481. (let* ((org-with-time with-time)
  15482. (org-time-stamp-rounding-minutes
  15483. (if (equal org-with-time '(16))
  15484. '(0 0)
  15485. org-time-stamp-rounding-minutes))
  15486. (org-dcst org-display-custom-times)
  15487. (ct (org-current-time))
  15488. (org-def (or org-overriding-default-time default-time ct))
  15489. (org-defdecode (decode-time org-def))
  15490. (cur-frame (selected-frame))
  15491. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15492. (calendar-setup
  15493. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  15494. (calendar-move-hook nil)
  15495. (calendar-view-diary-initially-flag nil)
  15496. (calendar-view-holidays-initially-flag nil)
  15497. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15498. ;; Rationalize `org-def' and `org-defdecode', if required.
  15499. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15500. (setf (nth 2 org-defdecode) -1)
  15501. (setf (nth 1 org-defdecode) 59)
  15502. (setq org-def (apply #'encode-time org-defdecode))
  15503. (setq org-defdecode (decode-time org-def)))
  15504. (let* ((timestr (format-time-string
  15505. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15506. org-def))
  15507. (prompt (concat (if prompt (concat prompt " ") "")
  15508. (format "Date+time [%s]: " timestr))))
  15509. (cond
  15510. (from-string (setq ans from-string))
  15511. (org-read-date-popup-calendar
  15512. (save-excursion
  15513. (save-window-excursion
  15514. (calendar)
  15515. (when (eq calendar-setup 'calendar-only)
  15516. (setq cal-frame
  15517. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15518. (select-frame cal-frame))
  15519. (org-eval-in-calendar '(setq cursor-type nil) t)
  15520. (unwind-protect
  15521. (progn
  15522. (calendar-forward-day (- (time-to-days org-def)
  15523. (calendar-absolute-from-gregorian
  15524. (calendar-current-date))))
  15525. (org-eval-in-calendar nil t)
  15526. (let* ((old-map (current-local-map))
  15527. (map (copy-keymap calendar-mode-map))
  15528. (minibuffer-local-map
  15529. (copy-keymap org-read-date-minibuffer-local-map)))
  15530. (org-defkey map (kbd "RET") 'org-calendar-select)
  15531. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15532. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15533. (unwind-protect
  15534. (progn
  15535. (use-local-map map)
  15536. (setq org-read-date-inactive inactive)
  15537. (add-hook 'post-command-hook 'org-read-date-display)
  15538. (setq org-ans0
  15539. (read-string prompt
  15540. default-input
  15541. 'org-read-date-history
  15542. nil))
  15543. ;; org-ans0: from prompt
  15544. ;; org-ans1: from mouse click
  15545. ;; org-ans2: from calendar motion
  15546. (setq ans
  15547. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15548. (remove-hook 'post-command-hook 'org-read-date-display)
  15549. (use-local-map old-map)
  15550. (when org-read-date-overlay
  15551. (delete-overlay org-read-date-overlay)
  15552. (setq org-read-date-overlay nil)))))
  15553. (bury-buffer "*Calendar*")
  15554. (when cal-frame
  15555. (delete-frame cal-frame)
  15556. (select-frame-set-input-focus cur-frame))))))
  15557. (t ; Naked prompt only
  15558. (unwind-protect
  15559. (setq ans (read-string prompt default-input
  15560. 'org-read-date-history timestr))
  15561. (when org-read-date-overlay
  15562. (delete-overlay org-read-date-overlay)
  15563. (setq org-read-date-overlay nil))))))
  15564. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15565. (when org-read-date-analyze-forced-year
  15566. (message "Year was forced into %s"
  15567. (if org-read-date-force-compatible-dates
  15568. "compatible range (1970-2037)"
  15569. "range representable on this machine"))
  15570. (ding))
  15571. ;; One round trip to get rid of 34th of August and stuff like that....
  15572. (setq final (decode-time (apply 'encode-time final)))
  15573. (setq org-read-date-final-answer ans)
  15574. (if to-time
  15575. (apply 'encode-time final)
  15576. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15577. (format "%04d-%02d-%02d %02d:%02d"
  15578. (nth 5 final) (nth 4 final) (nth 3 final)
  15579. (nth 2 final) (nth 1 final))
  15580. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15581. (defun org-read-date-display ()
  15582. "Display the current date prompt interpretation in the minibuffer."
  15583. (when org-read-date-display-live
  15584. (when org-read-date-overlay
  15585. (delete-overlay org-read-date-overlay))
  15586. (when (minibufferp (current-buffer))
  15587. (save-excursion
  15588. (end-of-line 1)
  15589. (while (not (equal (buffer-substring
  15590. (max (point-min) (- (point) 4)) (point))
  15591. " "))
  15592. (insert " ")))
  15593. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15594. " " (or org-ans1 org-ans2)))
  15595. (org-end-time-was-given nil)
  15596. (f (org-read-date-analyze ans org-def org-defdecode))
  15597. (fmts (if org-dcst
  15598. org-time-stamp-custom-formats
  15599. org-time-stamp-formats))
  15600. (fmt (if (or org-with-time
  15601. (and (boundp 'org-time-was-given) org-time-was-given))
  15602. (cdr fmts)
  15603. (car fmts)))
  15604. (txt (format-time-string fmt (apply 'encode-time f)))
  15605. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15606. (txt (concat "=> " txt)))
  15607. (when (and org-end-time-was-given
  15608. (string-match org-plain-time-of-day-regexp txt))
  15609. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15610. org-end-time-was-given
  15611. (substring txt (match-end 0)))))
  15612. (when org-read-date-analyze-futurep
  15613. (setq txt (concat txt " (=>F)")))
  15614. (setq org-read-date-overlay
  15615. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15616. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15617. (defun org-read-date-analyze (ans def defdecode)
  15618. "Analyze the combined answer of the date prompt."
  15619. ;; FIXME: cleanup and comment
  15620. ;; Pass `current-time' result to `decode-time' (instead of calling
  15621. ;; without arguments) so that only `current-time' has to be
  15622. ;; overriden in tests.
  15623. (let ((org-def def)
  15624. (org-defdecode defdecode)
  15625. (nowdecode (decode-time (current-time)))
  15626. delta deltan deltaw deltadef year month day
  15627. hour minute second wday pm h2 m2 tl wday1
  15628. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15629. (setq org-read-date-analyze-futurep nil
  15630. org-read-date-analyze-forced-year nil)
  15631. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15632. (setq ans "+0"))
  15633. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15634. (setq ans (replace-match "" t t ans)
  15635. deltan (car delta)
  15636. deltaw (nth 1 delta)
  15637. deltadef (nth 2 delta)))
  15638. ;; Check if there is an iso week date in there. If yes, store the
  15639. ;; info and postpone interpreting it until the rest of the parsing
  15640. ;; is done.
  15641. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15642. (setq iso-year (when (match-end 1)
  15643. (org-small-year-to-year
  15644. (string-to-number (match-string 1 ans))))
  15645. iso-weekday (when (match-end 3)
  15646. (string-to-number (match-string 3 ans)))
  15647. iso-week (string-to-number (match-string 2 ans)))
  15648. (setq ans (replace-match "" t t ans)))
  15649. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15650. (when (string-match
  15651. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15652. (setq year (if (match-end 2)
  15653. (string-to-number (match-string 2 ans))
  15654. (progn (setq kill-year t)
  15655. (string-to-number (format-time-string "%Y"))))
  15656. month (string-to-number (match-string 3 ans))
  15657. day (string-to-number (match-string 4 ans)))
  15658. (setq year (org-small-year-to-year year))
  15659. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15660. t nil ans)))
  15661. ;; Help matching dotted european dates
  15662. (when (string-match
  15663. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15664. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15665. (setq kill-year t)
  15666. (string-to-number (format-time-string "%Y")))
  15667. day (string-to-number (match-string 1 ans))
  15668. month (string-to-number (match-string 2 ans))
  15669. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15670. t nil ans)))
  15671. ;; Help matching american dates, like 5/30 or 5/30/7
  15672. (when (string-match
  15673. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15674. (setq year (if (match-end 4)
  15675. (string-to-number (match-string 4 ans))
  15676. (progn (setq kill-year t)
  15677. (string-to-number (format-time-string "%Y"))))
  15678. month (string-to-number (match-string 1 ans))
  15679. day (string-to-number (match-string 2 ans)))
  15680. (setq year (org-small-year-to-year year))
  15681. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15682. t nil ans)))
  15683. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15684. ;; If there is a time with am/pm, and *no* time without it, we convert
  15685. ;; so that matching will be successful.
  15686. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  15687. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15688. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15689. (setq hour (string-to-number (match-string 1 ans))
  15690. minute (if (match-end 3)
  15691. (string-to-number (match-string 3 ans))
  15692. 0)
  15693. pm (equal ?p
  15694. (string-to-char (downcase (match-string 4 ans)))))
  15695. (if (and (= hour 12) (not pm))
  15696. (setq hour 0)
  15697. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15698. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15699. t t ans))))
  15700. ;; Check if a time range is given as a duration
  15701. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15702. (setq hour (string-to-number (match-string 1 ans))
  15703. h2 (+ hour (string-to-number (match-string 3 ans)))
  15704. minute (string-to-number (match-string 2 ans))
  15705. m2 (+ minute (if (match-end 5) (string-to-number
  15706. (match-string 5 ans))0)))
  15707. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15708. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15709. t t ans)))
  15710. ;; Check if there is a time range
  15711. (when (boundp 'org-end-time-was-given)
  15712. (setq org-time-was-given nil)
  15713. (when (and (string-match org-plain-time-of-day-regexp ans)
  15714. (match-end 8))
  15715. (setq org-end-time-was-given (match-string 8 ans))
  15716. (setq ans (concat (substring ans 0 (match-beginning 7))
  15717. (substring ans (match-end 7))))))
  15718. (setq tl (parse-time-string ans)
  15719. day (or (nth 3 tl) (nth 3 org-defdecode))
  15720. month
  15721. (cond ((nth 4 tl))
  15722. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15723. ;; Day was specified. Make sure DAY+MONTH
  15724. ;; combination happens in the future.
  15725. ((nth 3 tl)
  15726. (setq futurep t)
  15727. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15728. (nth 4 nowdecode)))
  15729. (t (nth 4 org-defdecode)))
  15730. year
  15731. (cond ((and (not kill-year) (nth 5 tl)))
  15732. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15733. ;; Month was guessed in the future and is at least
  15734. ;; equal to NOWDECODE's. Fix year accordingly.
  15735. (futurep
  15736. (if (or (> month (nth 4 nowdecode))
  15737. (>= day (nth 3 nowdecode)))
  15738. (nth 5 nowdecode)
  15739. (1+ (nth 5 nowdecode))))
  15740. ;; Month was specified. Make sure MONTH+YEAR
  15741. ;; combination happens in the future.
  15742. ((nth 4 tl)
  15743. (setq futurep t)
  15744. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15745. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15746. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15747. (t (nth 5 nowdecode))))
  15748. (t (nth 5 org-defdecode)))
  15749. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15750. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15751. second (or (nth 0 tl) 0)
  15752. wday (nth 6 tl))
  15753. (when (and (eq org-read-date-prefer-future 'time)
  15754. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15755. (equal day (nth 3 nowdecode))
  15756. (equal month (nth 4 nowdecode))
  15757. (equal year (nth 5 nowdecode))
  15758. (nth 2 tl)
  15759. (or (< (nth 2 tl) (nth 2 nowdecode))
  15760. (and (= (nth 2 tl) (nth 2 nowdecode))
  15761. (nth 1 tl)
  15762. (< (nth 1 tl) (nth 1 nowdecode)))))
  15763. (setq day (1+ day)
  15764. futurep t))
  15765. ;; Special date definitions below
  15766. (cond
  15767. (iso-week
  15768. ;; There was an iso week
  15769. (require 'cal-iso)
  15770. (setq futurep nil)
  15771. (setq year (or iso-year year)
  15772. day (or iso-weekday wday 1)
  15773. wday nil ; to make sure that the trigger below does not match
  15774. iso-date (calendar-gregorian-from-absolute
  15775. (calendar-iso-to-absolute
  15776. (list iso-week day year))))
  15777. ; FIXME: Should we also push ISO weeks into the future?
  15778. ; (when (and org-read-date-prefer-future
  15779. ; (not iso-year)
  15780. ; (< (calendar-absolute-from-gregorian iso-date)
  15781. ; (time-to-days (current-time))))
  15782. ; (setq year (1+ year)
  15783. ; iso-date (calendar-gregorian-from-absolute
  15784. ; (calendar-iso-to-absolute
  15785. ; (list iso-week day year)))))
  15786. (setq month (car iso-date)
  15787. year (nth 2 iso-date)
  15788. day (nth 1 iso-date)))
  15789. (deltan
  15790. (setq futurep nil)
  15791. (unless deltadef
  15792. ;; Pass `current-time' result to `decode-time' (instead of
  15793. ;; calling without arguments) so that only `current-time' has
  15794. ;; to be overriden in tests.
  15795. (let ((now (decode-time (current-time))))
  15796. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15797. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15798. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15799. ((equal deltaw "m") (setq month (+ month deltan)))
  15800. ((equal deltaw "y") (setq year (+ year deltan)))))
  15801. ((and wday (not (nth 3 tl)))
  15802. ;; Weekday was given, but no day, so pick that day in the week
  15803. ;; on or after the derived date.
  15804. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15805. (unless (equal wday wday1)
  15806. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15807. (when (and (boundp 'org-time-was-given)
  15808. (nth 2 tl))
  15809. (setq org-time-was-given t))
  15810. (when (< year 100) (setq year (+ 2000 year)))
  15811. ;; Check of the date is representable
  15812. (if org-read-date-force-compatible-dates
  15813. (progn
  15814. (when (< year 1970)
  15815. (setq year 1970 org-read-date-analyze-forced-year t))
  15816. (when (> year 2037)
  15817. (setq year 2037 org-read-date-analyze-forced-year t)))
  15818. (condition-case nil
  15819. (ignore (encode-time second minute hour day month year))
  15820. (error
  15821. (setq year (nth 5 org-defdecode))
  15822. (setq org-read-date-analyze-forced-year t))))
  15823. (setq org-read-date-analyze-futurep futurep)
  15824. (list second minute hour day month year)))
  15825. (defvar parse-time-weekdays)
  15826. (defun org-read-date-get-relative (s today default)
  15827. "Check string S for special relative date string.
  15828. TODAY and DEFAULT are internal times, for today and for a default.
  15829. Return shift list (N what def-flag)
  15830. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15831. N is the number of WHATs to shift.
  15832. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15833. the DEFAULT date rather than TODAY."
  15834. (require 'parse-time)
  15835. (when (and
  15836. (string-match
  15837. (concat
  15838. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15839. "\\([0-9]+\\)?"
  15840. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15841. "\\([ \t]\\|$\\)") s)
  15842. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15843. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15844. (string-to-char (substring (match-string 1 s) -1))
  15845. ?+))
  15846. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15847. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15848. (what (if (match-end 3) (match-string 3 s) "d"))
  15849. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15850. (date (if rel default today))
  15851. (wday (nth 6 (decode-time date)))
  15852. delta)
  15853. (if wday1
  15854. (progn
  15855. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15856. (when (= delta 0) (setq delta 7))
  15857. (when (= dir ?-)
  15858. (setq delta (- delta 7))
  15859. (when (= delta 0) (setq delta -7)))
  15860. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15861. (list delta "d" rel))
  15862. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15863. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15864. "Turn a user-specified date into the internal representation.
  15865. The internal representation needed by the calendar is (month day year).
  15866. This is a wrapper to handle the brain-dead convention in calendar that
  15867. user function argument order change dependent on argument order."
  15868. (pcase calendar-date-style
  15869. (`american (list arg1 arg2 arg3))
  15870. (`european (list arg2 arg1 arg3))
  15871. (`iso (list arg2 arg3 arg1))))
  15872. (defun org-eval-in-calendar (form &optional keepdate)
  15873. "Eval FORM in the calendar window and return to current window.
  15874. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15875. (let ((sf (selected-frame))
  15876. (sw (selected-window)))
  15877. (select-window (get-buffer-window "*Calendar*" t))
  15878. (eval form)
  15879. (when (and (not keepdate) (calendar-cursor-to-date))
  15880. (let* ((date (calendar-cursor-to-date))
  15881. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15882. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15883. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15884. (select-window sw)
  15885. (select-frame-set-input-focus sf)))
  15886. (defun org-calendar-select ()
  15887. "Return to `org-read-date' with the date currently selected.
  15888. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15889. (interactive)
  15890. (when (calendar-cursor-to-date)
  15891. (let* ((date (calendar-cursor-to-date))
  15892. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15893. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15894. (when (active-minibuffer-window) (exit-minibuffer))))
  15895. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15896. "Insert a date stamp for the date given by the internal TIME.
  15897. See `format-time-string' for the format of TIME.
  15898. WITH-HM means use the stamp format that includes the time of the day.
  15899. INACTIVE means use square brackets instead of angular ones, so that the
  15900. stamp will not contribute to the agenda.
  15901. PRE and POST are optional strings to be inserted before and after the
  15902. stamp.
  15903. The command returns the inserted time stamp."
  15904. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15905. stamp)
  15906. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15907. (insert-before-markers (or pre ""))
  15908. (when (listp extra)
  15909. (setq extra (car extra))
  15910. (if (and (stringp extra)
  15911. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15912. (setq extra (format "-%02d:%02d"
  15913. (string-to-number (match-string 1 extra))
  15914. (string-to-number (match-string 2 extra))))
  15915. (setq extra nil)))
  15916. (when extra
  15917. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15918. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15919. (insert-before-markers (or post ""))
  15920. (setq org-last-inserted-timestamp stamp)))
  15921. (defun org-toggle-time-stamp-overlays ()
  15922. "Toggle the use of custom time stamp formats."
  15923. (interactive)
  15924. (setq org-display-custom-times (not org-display-custom-times))
  15925. (unless org-display-custom-times
  15926. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15927. (while (setq p (next-single-property-change p 'display))
  15928. (when (and (get-text-property p 'display)
  15929. (eq (get-text-property p 'face) 'org-date))
  15930. (remove-text-properties
  15931. p (setq p (next-single-property-change p 'display))
  15932. '(display t))))
  15933. (set-buffer-modified-p bmp)))
  15934. (org-restart-font-lock)
  15935. (setq org-table-may-need-update t)
  15936. (if org-display-custom-times
  15937. (message "Time stamps are overlaid with custom format")
  15938. (message "Time stamp overlays removed")))
  15939. (defun org-display-custom-time (beg end)
  15940. "Overlay modified time stamp format over timestamp between BEG and END."
  15941. (let* ((ts (buffer-substring beg end))
  15942. t1 w1 with-hm tf time str w2 (off 0))
  15943. (save-match-data
  15944. (setq t1 (org-parse-time-string ts t))
  15945. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15946. (setq off (- (match-end 0) (match-beginning 0)))))
  15947. (setq end (- end off))
  15948. (setq w1 (- end beg)
  15949. with-hm (and (nth 1 t1) (nth 2 t1))
  15950. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15951. time (org-fix-decoded-time t1)
  15952. str (org-add-props
  15953. (format-time-string
  15954. (substring tf 1 -1) (apply 'encode-time time))
  15955. nil 'mouse-face 'highlight)
  15956. w2 (length str))
  15957. (unless (= w2 w1)
  15958. (add-text-properties (1+ beg) (+ 2 beg)
  15959. (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
  15960. (put-text-property beg end 'display str)))
  15961. (defun org-fix-decoded-time (time)
  15962. "Set 0 instead of nil for the first 6 elements of time.
  15963. Don't touch the rest."
  15964. (let ((n 0))
  15965. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15966. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15967. "Difference between TIMESTAMP-STRING and now in days.
  15968. If SECONDS is non-nil, return the difference in seconds."
  15969. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15970. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15971. (funcall fdiff (current-time)))))
  15972. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15973. "Is the time in TIMESTAMP-STRING close to the current date?"
  15974. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15975. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15976. (not (org-entry-is-done-p))))
  15977. (defun org-get-wdays (ts &optional delay zero-delay)
  15978. "Get the deadline lead time appropriate for timestring TS.
  15979. When DELAY is non-nil, get the delay time for scheduled items
  15980. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15981. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15982. don't try to find the delay cookie in the scheduled timestamp."
  15983. (let ((tv (if delay org-scheduled-delay-days
  15984. org-deadline-warning-days)))
  15985. (cond
  15986. ((or (and delay (< tv 0))
  15987. (and delay zero-delay (<= tv 0))
  15988. (and (not delay) (<= tv 0)))
  15989. ;; Enforce this value no matter what
  15990. (- tv))
  15991. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15992. ;; lead time is specified.
  15993. (floor (* (string-to-number (match-string 1 ts))
  15994. (cdr (assoc (match-string 2 ts)
  15995. '(("d" . 1) ("w" . 7)
  15996. ("m" . 30.4) ("y" . 365.25)
  15997. ("h" . 0.041667)))))))
  15998. ;; go for the default.
  15999. (t tv))))
  16000. (defun org-calendar-select-mouse (ev)
  16001. "Return to `org-read-date' with the date currently selected.
  16002. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  16003. (interactive "e")
  16004. (mouse-set-point ev)
  16005. (when (calendar-cursor-to-date)
  16006. (let* ((date (calendar-cursor-to-date))
  16007. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  16008. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  16009. (when (active-minibuffer-window) (exit-minibuffer))))
  16010. (defun org-check-deadlines (ndays)
  16011. "Check if there are any deadlines due or past due.
  16012. A deadline is considered due if it happens within `org-deadline-warning-days'
  16013. days from today's date. If the deadline appears in an entry marked DONE,
  16014. it is not shown. A numeric prefix argument NDAYS can be used to test that
  16015. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  16016. are shown."
  16017. (interactive "P")
  16018. (let* ((org-warn-days
  16019. (cond
  16020. ((equal ndays '(4)) 100000)
  16021. (ndays (prefix-numeric-value ndays))
  16022. (t (abs org-deadline-warning-days))))
  16023. (case-fold-search nil)
  16024. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  16025. (callback
  16026. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  16027. (message "%d deadlines past-due or due within %d days"
  16028. (org-occur regexp nil callback)
  16029. org-warn-days)))
  16030. (defsubst org-re-timestamp (type)
  16031. "Return a regexp for timestamp TYPE.
  16032. Allowed values for TYPE are:
  16033. all: all timestamps
  16034. active: only active timestamps (<...>)
  16035. inactive: only inactive timestamps ([...])
  16036. scheduled: only scheduled timestamps
  16037. deadline: only deadline timestamps
  16038. closed: only closed time-stamps
  16039. When TYPE is nil, fall back on returning a regexp that matches
  16040. both scheduled and deadline timestamps."
  16041. (cl-case type
  16042. (all org-ts-regexp-both)
  16043. (active org-ts-regexp)
  16044. (inactive org-ts-regexp-inactive)
  16045. (scheduled org-scheduled-time-regexp)
  16046. (deadline org-deadline-time-regexp)
  16047. (closed org-closed-time-regexp)
  16048. (otherwise
  16049. (concat "\\<"
  16050. (regexp-opt (list org-deadline-string org-scheduled-string))
  16051. " *<\\([^>]+\\)>"))))
  16052. (defun org-check-before-date (d)
  16053. "Check if there are deadlines or scheduled entries before date D."
  16054. (interactive (list (org-read-date)))
  16055. (let* ((case-fold-search nil)
  16056. (regexp (org-re-timestamp org-ts-type))
  16057. (ts-type org-ts-type)
  16058. (callback
  16059. (lambda ()
  16060. (let ((match (match-string 1)))
  16061. (and (if (memq ts-type '(active inactive all))
  16062. (eq (org-element-type (save-excursion
  16063. (backward-char)
  16064. (org-element-context)))
  16065. 'timestamp)
  16066. (org-at-planning-p))
  16067. (time-less-p
  16068. (org-time-string-to-time match)
  16069. (org-time-string-to-time d)))))))
  16070. (message "%d entries before %s"
  16071. (org-occur regexp nil callback)
  16072. d)))
  16073. (defun org-check-after-date (d)
  16074. "Check if there are deadlines or scheduled entries after date D."
  16075. (interactive (list (org-read-date)))
  16076. (let* ((case-fold-search nil)
  16077. (regexp (org-re-timestamp org-ts-type))
  16078. (ts-type org-ts-type)
  16079. (callback
  16080. (lambda ()
  16081. (let ((match (match-string 1)))
  16082. (and (if (memq ts-type '(active inactive all))
  16083. (eq (org-element-type (save-excursion
  16084. (backward-char)
  16085. (org-element-context)))
  16086. 'timestamp)
  16087. (org-at-planning-p))
  16088. (not (time-less-p
  16089. (org-time-string-to-time match)
  16090. (org-time-string-to-time d))))))))
  16091. (message "%d entries after %s"
  16092. (org-occur regexp nil callback)
  16093. d)))
  16094. (defun org-check-dates-range (start-date end-date)
  16095. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  16096. (interactive (list (org-read-date nil nil nil "Range starts")
  16097. (org-read-date nil nil nil "Range end")))
  16098. (let ((case-fold-search nil)
  16099. (regexp (org-re-timestamp org-ts-type))
  16100. (callback
  16101. (let ((type org-ts-type))
  16102. (lambda ()
  16103. (let ((match (match-string 1)))
  16104. (and
  16105. (if (memq type '(active inactive all))
  16106. (eq (org-element-type (save-excursion
  16107. (backward-char)
  16108. (org-element-context)))
  16109. 'timestamp)
  16110. (org-at-planning-p))
  16111. (not (time-less-p
  16112. (org-time-string-to-time match)
  16113. (org-time-string-to-time start-date)))
  16114. (time-less-p
  16115. (org-time-string-to-time match)
  16116. (org-time-string-to-time end-date))))))))
  16117. (message "%d entries between %s and %s"
  16118. (org-occur regexp nil callback) start-date end-date)))
  16119. (defun org-evaluate-time-range (&optional to-buffer)
  16120. "Evaluate a time range by computing the difference between start and end.
  16121. Normally the result is just printed in the echo area, but with prefix arg
  16122. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  16123. If the time range is actually in a table, the result is inserted into the
  16124. next column.
  16125. For time difference computation, a year is assumed to be exactly 365
  16126. days in order to avoid rounding problems."
  16127. (interactive "P")
  16128. (or
  16129. (org-clock-update-time-maybe)
  16130. (save-excursion
  16131. (unless (org-at-date-range-p t)
  16132. (goto-char (point-at-bol))
  16133. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  16134. (unless (org-at-date-range-p t)
  16135. (user-error "Not at a time-stamp range, and none found in current line")))
  16136. (let* ((ts1 (match-string 1))
  16137. (ts2 (match-string 2))
  16138. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  16139. (match-end (match-end 0))
  16140. (time1 (org-time-string-to-time ts1))
  16141. (time2 (org-time-string-to-time ts2))
  16142. (t1 (float-time time1))
  16143. (t2 (float-time time2))
  16144. (diff (abs (- t2 t1)))
  16145. (negative (< (- t2 t1) 0))
  16146. ;; (ys (floor (* 365 24 60 60)))
  16147. (ds (* 24 60 60))
  16148. (hs (* 60 60))
  16149. (fy "%dy %dd %02d:%02d")
  16150. (fy1 "%dy %dd")
  16151. (fd "%dd %02d:%02d")
  16152. (fd1 "%dd")
  16153. (fh "%02d:%02d")
  16154. y d h m align)
  16155. (if havetime
  16156. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16157. y 0
  16158. d (floor (/ diff ds)) diff (mod diff ds)
  16159. h (floor (/ diff hs)) diff (mod diff hs)
  16160. m (floor (/ diff 60)))
  16161. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16162. y 0
  16163. d (floor (+ (/ diff ds) 0.5))
  16164. h 0 m 0))
  16165. (if (not to-buffer)
  16166. (message "%s" (org-make-tdiff-string y d h m))
  16167. (if (org-at-table-p)
  16168. (progn
  16169. (goto-char match-end)
  16170. (setq align t)
  16171. (and (looking-at " *|") (goto-char (match-end 0))))
  16172. (goto-char match-end))
  16173. (when (looking-at
  16174. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  16175. (replace-match ""))
  16176. (when negative (insert " -"))
  16177. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  16178. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  16179. (insert " " (format fh h m))))
  16180. (when align (org-table-align))
  16181. (message "Time difference inserted")))))
  16182. (defun org-make-tdiff-string (y d h m)
  16183. (let ((fmt "")
  16184. (l nil))
  16185. (when (> y 0)
  16186. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  16187. (push y l))
  16188. (when (> d 0)
  16189. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  16190. (push d l))
  16191. (when (> h 0)
  16192. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  16193. (push h l))
  16194. (when (> m 0)
  16195. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  16196. (push m l))
  16197. (apply 'format fmt (nreverse l))))
  16198. (defun org-time-string-to-time (s &optional buffer pos)
  16199. "Convert a timestamp string into internal time."
  16200. (condition-case errdata
  16201. (apply 'encode-time (org-parse-time-string s))
  16202. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16203. s (if (not (and buffer pos))
  16204. ""
  16205. (format-message " at %d in buffer `%s'" pos buffer))
  16206. (cdr errdata)))))
  16207. (defun org-time-string-to-seconds (s)
  16208. "Convert a timestamp string to a number of seconds."
  16209. (float-time (org-time-string-to-time s)))
  16210. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  16211. (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
  16212. "Convert time stamp S to an absolute day number.
  16213. If DAYNR in non-nil, and there is a specifier for a cyclic time
  16214. stamp, get the closest date to DAYNR. If PREFER is
  16215. `past' (respectively `future') return a date past (respectively
  16216. after) or equal to DAYNR.
  16217. POS is the location of time stamp S, as a buffer position in
  16218. BUFFER.
  16219. Diary sexp timestamps are matched against DAYNR, when non-nil.
  16220. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  16221. signalled."
  16222. (cond
  16223. ((string-match "\\`%%\\((.*)\\)" s)
  16224. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  16225. ;; only able to match individual dates. If it fails, raise an
  16226. ;; error.
  16227. (if (and daynr
  16228. (org-diary-sexp-entry
  16229. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  16230. daynr
  16231. (signal 'org-diary-sexp-no-match (list s))))
  16232. ((and daynr show-all) (org-closest-date s daynr prefer))
  16233. (t (time-to-days
  16234. (condition-case errdata
  16235. (apply #'encode-time (org-parse-time-string s))
  16236. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16237. s
  16238. (if (not (and buffer pos)) ""
  16239. (format-message " at %d in buffer `%s'" pos buffer))
  16240. (cdr errdata))))))))
  16241. (defun org-days-to-iso-week (days)
  16242. "Return the iso week number."
  16243. (require 'cal-iso)
  16244. (car (calendar-iso-from-absolute days)))
  16245. (defun org-small-year-to-year (year)
  16246. "Convert 2-digit years into 4-digit years.
  16247. YEAR is expanded into one of the 30 next years, if possible, or
  16248. into a past one. Any year larger than 99 is returned unchanged."
  16249. (if (>= year 100) year
  16250. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  16251. (century (/ current 100))
  16252. (offset (- year (% current 100))))
  16253. (cond ((> offset 30) (+ (* (1- century) 100) year))
  16254. ((> offset -70) (+ (* century 100) year))
  16255. (t (+ (* (1+ century) 100) year))))))
  16256. (defun org-time-from-absolute (d)
  16257. "Return the time corresponding to date D.
  16258. D may be an absolute day number, or a calendar-type list (month day year)."
  16259. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  16260. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  16261. (defvar org-agenda-current-date)
  16262. (defun org-calendar-holiday ()
  16263. "List of holidays, for Diary display in Org mode."
  16264. (require 'holidays)
  16265. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  16266. (and hl (mapconcat #'identity hl "; "))))
  16267. (defun org-diary-sexp-entry (sexp entry d)
  16268. "Process a SEXP diary ENTRY for date D."
  16269. (require 'diary-lib)
  16270. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  16271. ;; dynamically.
  16272. (let* ((sexp `(let ((entry ,entry)
  16273. (date ',d))
  16274. ,(car (read-from-string sexp))))
  16275. (result (if calendar-debug-sexp (eval sexp)
  16276. (condition-case nil
  16277. (eval sexp)
  16278. (error
  16279. (beep)
  16280. (message "Bad sexp at line %d in %s: %s"
  16281. (org-current-line)
  16282. (buffer-file-name) sexp)
  16283. (sleep-for 2))))))
  16284. (cond ((stringp result) (split-string result "; "))
  16285. ((and (consp result)
  16286. (not (consp (cdr result)))
  16287. (stringp (cdr result))) (cdr result))
  16288. ((and (consp result)
  16289. (stringp (car result))) result)
  16290. (result entry))))
  16291. (defun org-diary-to-ical-string (frombuf)
  16292. "Get iCalendar entries from diary entries in buffer FROMBUF.
  16293. This uses the icalendar.el library."
  16294. (let* ((tmpdir temporary-file-directory)
  16295. (tmpfile (make-temp-name
  16296. (expand-file-name "orgics" tmpdir)))
  16297. buf rtn b e)
  16298. (with-current-buffer frombuf
  16299. (icalendar-export-region (point-min) (point-max) tmpfile)
  16300. (setq buf (find-buffer-visiting tmpfile))
  16301. (set-buffer buf)
  16302. (goto-char (point-min))
  16303. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  16304. (setq b (match-beginning 0)))
  16305. (goto-char (point-max))
  16306. (when (re-search-backward "^END:VEVENT" nil t)
  16307. (setq e (match-end 0)))
  16308. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  16309. (kill-buffer buf)
  16310. (delete-file tmpfile)
  16311. rtn))
  16312. (defun org-closest-date (start current prefer)
  16313. "Return closest date to CURRENT starting from START.
  16314. CURRENT and START are both time stamps.
  16315. When PREFER is `past', return a date that is either CURRENT or
  16316. past. When PREFER is `future', return a date that is either
  16317. CURRENT or future.
  16318. Only time stamps with a repeater are modified. Any other time
  16319. stamp stay unchanged. In any case, return value is an absolute
  16320. day number."
  16321. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  16322. ;; No repeater. Do not shift time stamp.
  16323. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16324. (let ((value (string-to-number (match-string 1 start)))
  16325. (type (match-string 2 start)))
  16326. (if (= 0 value)
  16327. ;; Repeater with a 0-value is considered as void.
  16328. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16329. (let* ((base (org-date-to-gregorian start))
  16330. (target (org-date-to-gregorian current))
  16331. (sday (calendar-absolute-from-gregorian base))
  16332. (cday (calendar-absolute-from-gregorian target))
  16333. n1 n2)
  16334. ;; If START is already past CURRENT, just return START.
  16335. (if (<= cday sday) sday
  16336. ;; Compute closest date before (N1) and closest date past
  16337. ;; (N2) CURRENT.
  16338. (pcase type
  16339. ("h"
  16340. (let ((missing-hours
  16341. (mod (+ (- (* 24 (- cday sday))
  16342. (nth 2 (org-parse-time-string start)))
  16343. org-extend-today-until)
  16344. value)))
  16345. (setf n1 (if (= missing-hours 0) cday
  16346. (- cday (1+ (/ missing-hours 24)))))
  16347. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  16348. ((or "d" "w")
  16349. (let ((value (if (equal type "w") (* 7 value) value)))
  16350. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  16351. (setf n2 (+ n1 value))))
  16352. ("m"
  16353. (let* ((add-months
  16354. (lambda (d n)
  16355. ;; Add N months to gregorian date D, i.e.,
  16356. ;; a list (MONTH DAY YEAR). Return a valid
  16357. ;; gregorian date.
  16358. (let ((m (+ (nth 0 d) n)))
  16359. (list (mod m 12)
  16360. (nth 1 d)
  16361. (+ (/ m 12) (nth 2 d))))))
  16362. (months ; Complete months to TARGET.
  16363. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  16364. (- (nth 0 target) (nth 0 base))
  16365. ;; If START's day is greater than
  16366. ;; TARGET's, remove incomplete month.
  16367. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  16368. value)
  16369. value))
  16370. (before (funcall add-months base months)))
  16371. (setf n1 (calendar-absolute-from-gregorian before))
  16372. (setf n2
  16373. (calendar-absolute-from-gregorian
  16374. (funcall add-months before value)))))
  16375. (_
  16376. (let* ((d (nth 1 base))
  16377. (m (nth 0 base))
  16378. (y (nth 2 base))
  16379. (years ; Complete years to TARGET.
  16380. (* (/ (- (nth 2 target)
  16381. y
  16382. ;; If START's month and day are
  16383. ;; greater than TARGET's, remove
  16384. ;; incomplete year.
  16385. (if (or (> (nth 0 target) m)
  16386. (and (= (nth 0 target) m)
  16387. (> (nth 1 target) d)))
  16388. 0
  16389. 1))
  16390. value)
  16391. value))
  16392. (before (list m d (+ y years))))
  16393. (setf n1 (calendar-absolute-from-gregorian before))
  16394. (setf n2 (calendar-absolute-from-gregorian
  16395. (list m d (+ (nth 2 before) value)))))))
  16396. ;; Handle PREFER parameter, if any.
  16397. (cond
  16398. ((eq prefer 'past) (if (= cday n2) n2 n1))
  16399. ((eq prefer 'future) (if (= cday n1) n1 n2))
  16400. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  16401. (defun org-date-to-gregorian (d)
  16402. "Turn any specification of date D into a Gregorian date for the calendar."
  16403. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  16404. ((and (listp d) (= (length d) 3)) d)
  16405. ((stringp d)
  16406. (let ((d (org-parse-time-string d)))
  16407. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  16408. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  16409. (defun org-parse-time-string (s &optional nodefault)
  16410. "Parse the standard Org time string.
  16411. This should be a lot faster than the normal `parse-time-string'.
  16412. If time is not given, defaults to 0:00. However, with optional NODEFAULT,
  16413. hour and minute fields will be nil if not given."
  16414. (cond ((string-match org-ts-regexp0 s)
  16415. (list 0
  16416. (when (or (match-beginning 8) (not nodefault))
  16417. (string-to-number (or (match-string 8 s) "0")))
  16418. (when (or (match-beginning 7) (not nodefault))
  16419. (string-to-number (or (match-string 7 s) "0")))
  16420. (string-to-number (match-string 4 s))
  16421. (string-to-number (match-string 3 s))
  16422. (string-to-number (match-string 2 s))
  16423. nil nil nil))
  16424. ((string-match "^<[^>]+>$" s)
  16425. (decode-time (seconds-to-time (org-matcher-time s))))
  16426. (t (error "Not a standard Org time string: %s" s))))
  16427. (defun org-timestamp-up (&optional arg)
  16428. "Increase the date item at the cursor by one.
  16429. If the cursor is on the year, change the year. If it is on the month,
  16430. the day or the time, change that.
  16431. With prefix ARG, change by that many units."
  16432. (interactive "p")
  16433. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  16434. (defun org-timestamp-down (&optional arg)
  16435. "Decrease the date item at the cursor by one.
  16436. If the cursor is on the year, change the year. If it is on the month,
  16437. the day or the time, change that.
  16438. With prefix ARG, change by that many units."
  16439. (interactive "p")
  16440. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  16441. (defun org-timestamp-up-day (&optional arg)
  16442. "Increase the date in the time stamp by one day.
  16443. With prefix ARG, change that many days."
  16444. (interactive "p")
  16445. (if (and (not (org-at-timestamp-p t))
  16446. (org-at-heading-p))
  16447. (org-todo 'up)
  16448. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  16449. (defun org-timestamp-down-day (&optional arg)
  16450. "Decrease the date in the time stamp by one day.
  16451. With prefix ARG, change that many days."
  16452. (interactive "p")
  16453. (if (and (not (org-at-timestamp-p t))
  16454. (org-at-heading-p))
  16455. (org-todo 'down)
  16456. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  16457. (defun org-at-timestamp-p (&optional inactive-ok)
  16458. "Non-nil if point is inside a timestamp.
  16459. When optional argument INACTIVE-OK is non-nil, also consider
  16460. inactive timestamps.
  16461. When this function returns a non-nil value, match data is set
  16462. according to `org-ts-regexp3' or `org-ts-regexp2', depending on
  16463. INACTIVE-OK."
  16464. (interactive)
  16465. (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
  16466. (pos (point))
  16467. (ans (or (looking-at tsr)
  16468. (save-excursion
  16469. (skip-chars-backward "^[<\n\r\t")
  16470. (when (> (point) (point-min)) (backward-char 1))
  16471. (and (looking-at tsr)
  16472. (> (- (match-end 0) pos) -1))))))
  16473. (and ans
  16474. (boundp 'org-ts-what)
  16475. (setq org-ts-what
  16476. (cond
  16477. ((= pos (match-beginning 0)) 'bracket)
  16478. ;; Point is considered to be "on the bracket" whether
  16479. ;; it's really on it or right after it.
  16480. ((= pos (1- (match-end 0))) 'bracket)
  16481. ((= pos (match-end 0)) 'after)
  16482. ((org-pos-in-match-range pos 2) 'year)
  16483. ((org-pos-in-match-range pos 3) 'month)
  16484. ((org-pos-in-match-range pos 7) 'hour)
  16485. ((org-pos-in-match-range pos 8) 'minute)
  16486. ((or (org-pos-in-match-range pos 4)
  16487. (org-pos-in-match-range pos 5)) 'day)
  16488. ((and (> pos (or (match-end 8) (match-end 5)))
  16489. (< pos (match-end 0)))
  16490. (- pos (or (match-end 8) (match-end 5))))
  16491. (t 'day))))
  16492. ans))
  16493. (defun org-toggle-timestamp-type ()
  16494. "Toggle the type (<active> or [inactive]) of a time stamp."
  16495. (interactive)
  16496. (when (org-at-timestamp-p t)
  16497. (let ((beg (match-beginning 0)) (end (match-end 0))
  16498. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16499. (save-excursion
  16500. (goto-char beg)
  16501. (while (re-search-forward "[][<>]" end t)
  16502. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16503. t t)))
  16504. (message "Timestamp is now %sactive"
  16505. (if (equal (char-after beg) ?<) "" "in")))))
  16506. (defun org-at-clock-log-p nil
  16507. "Is the cursor on the clock log line?"
  16508. (save-excursion
  16509. (move-beginning-of-line 1)
  16510. (looking-at org-clock-line-re)))
  16511. (defvar org-clock-history) ; defined in org-clock.el
  16512. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16513. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16514. "Change the date in the time stamp at point.
  16515. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16516. `year', `minute', `second'. If WHAT is not given, the cursor position
  16517. in the timestamp determines what will be changed.
  16518. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16519. (let ((origin (point)) origin-cat
  16520. with-hm inactive
  16521. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16522. org-ts-what
  16523. extra rem
  16524. ts time time0 fixnext clrgx)
  16525. (unless (org-at-timestamp-p t)
  16526. (user-error "Not at a timestamp"))
  16527. (if (and (not what) (eq org-ts-what 'bracket))
  16528. (org-toggle-timestamp-type)
  16529. ;; Point isn't on brackets. Remember the part of the time-stamp
  16530. ;; the point was in. Indeed, size of time-stamps may change,
  16531. ;; but point must be kept in the same category nonetheless.
  16532. (setq origin-cat org-ts-what)
  16533. (when (and (not what) (not (eq org-ts-what 'day))
  16534. org-display-custom-times
  16535. (get-text-property (point) 'display)
  16536. (not (get-text-property (1- (point)) 'display)))
  16537. (setq org-ts-what 'day))
  16538. (setq org-ts-what (or what org-ts-what)
  16539. inactive (= (char-after (match-beginning 0)) ?\[)
  16540. ts (match-string 0))
  16541. (replace-match "")
  16542. (when (string-match
  16543. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16544. ts)
  16545. (setq extra (match-string 1 ts))
  16546. (when suppress-tmp-delay
  16547. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16548. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16549. (setq with-hm t))
  16550. (setq time0 (org-parse-time-string ts))
  16551. (when (and updown
  16552. (eq org-ts-what 'minute)
  16553. (not current-prefix-arg))
  16554. ;; This looks like s-up and s-down. Change by one rounding step.
  16555. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16556. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16557. (setcar (cdr time0) (+ (nth 1 time0)
  16558. (if (> n 0) (- rem) (- dm rem))))))
  16559. (setq time
  16560. (apply #'encode-time
  16561. (or (car time0) 0)
  16562. (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
  16563. (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
  16564. (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
  16565. (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
  16566. (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
  16567. (nthcdr 6 time0)))
  16568. (when (and (member org-ts-what '(hour minute))
  16569. extra
  16570. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16571. (setq extra (org-modify-ts-extra
  16572. extra
  16573. (if (eq org-ts-what 'hour) 2 5)
  16574. n dm)))
  16575. (when (integerp org-ts-what)
  16576. (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
  16577. (when (eq what 'calendar)
  16578. (let ((cal-date (org-get-date-from-calendar)))
  16579. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16580. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16581. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16582. (setcar time0 (or (car time0) 0))
  16583. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16584. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16585. (setq time (apply 'encode-time time0))))
  16586. ;; Insert the new time-stamp, and ensure point stays in the same
  16587. ;; category as before (i.e. not after the last position in that
  16588. ;; category).
  16589. (let ((pos (point)))
  16590. ;; Stay before inserted string. `save-excursion' is of no use.
  16591. (setq org-last-changed-timestamp
  16592. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16593. (goto-char pos))
  16594. (save-match-data
  16595. (looking-at org-ts-regexp3)
  16596. (goto-char (cond
  16597. ;; `day' category ends before `hour' if any, or at
  16598. ;; the end of the day name.
  16599. ((eq origin-cat 'day)
  16600. (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16601. ((eq origin-cat 'hour) (min (match-end 7) origin))
  16602. ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
  16603. ((integerp origin-cat) (min (1- (match-end 0)) origin))
  16604. ;; `year' and `month' have both fixed size: point
  16605. ;; couldn't have moved into another part.
  16606. (t origin))))
  16607. ;; Update clock if on a CLOCK line.
  16608. (org-clock-update-time-maybe)
  16609. ;; Maybe adjust the closest clock in `org-clock-history'
  16610. (when org-clock-adjust-closest
  16611. (if (not (and (org-at-clock-log-p)
  16612. (< 1 (length (delq nil (mapcar 'marker-position
  16613. org-clock-history))))))
  16614. (message "No clock to adjust")
  16615. (cond ((save-excursion ; fix previous clock?
  16616. (re-search-backward org-ts-regexp0 nil t)
  16617. (looking-back (concat org-clock-string " \\[")
  16618. (line-beginning-position)))
  16619. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16620. ((save-excursion ; fix next clock?
  16621. (re-search-backward org-ts-regexp0 nil t)
  16622. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16623. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16624. (save-window-excursion
  16625. ;; Find closest clock to point, adjust the previous/next one in history
  16626. (let* ((p (save-excursion (org-back-to-heading t)))
  16627. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16628. (clfixnth
  16629. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16630. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16631. (if (not clfixpos)
  16632. (message "No clock to adjust")
  16633. (save-excursion
  16634. (org-goto-marker-or-bmk clfixpos)
  16635. (org-show-subtree)
  16636. (when (re-search-forward clrgx nil t)
  16637. (goto-char (match-beginning 1))
  16638. (let (org-clock-adjust-closest)
  16639. (org-timestamp-change n org-ts-what updown))
  16640. (message "Clock adjusted in %s for heading: %s"
  16641. (file-name-nondirectory (buffer-file-name))
  16642. (org-get-heading t t)))))))))
  16643. ;; Try to recenter the calendar window, if any.
  16644. (when (and org-calendar-follow-timestamp-change
  16645. (get-buffer-window "*Calendar*" t)
  16646. (memq org-ts-what '(day month year)))
  16647. (org-recenter-calendar (time-to-days time))))))
  16648. (defun org-modify-ts-extra (s pos n dm)
  16649. "Change the different parts of the lead-time and repeat fields in timestamp."
  16650. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16651. ng h m new rem)
  16652. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16653. (cond
  16654. ((or (org-pos-in-match-range pos 2)
  16655. (org-pos-in-match-range pos 3))
  16656. (setq m (string-to-number (match-string 3 s))
  16657. h (string-to-number (match-string 2 s)))
  16658. (if (org-pos-in-match-range pos 2)
  16659. (setq h (+ h n))
  16660. (setq n (* dm (with-no-warnings (signum n))))
  16661. (unless (= 0 (setq rem (% m dm)))
  16662. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16663. (setq m (+ m n)))
  16664. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16665. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16666. (setq h (mod h 24))
  16667. (setq ng 1 new (format "-%02d:%02d" h m)))
  16668. ((org-pos-in-match-range pos 6)
  16669. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16670. ((org-pos-in-match-range pos 5)
  16671. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16672. ((org-pos-in-match-range pos 9)
  16673. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16674. ((org-pos-in-match-range pos 8)
  16675. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16676. (when ng
  16677. (setq s (concat
  16678. (substring s 0 (match-beginning ng))
  16679. new
  16680. (substring s (match-end ng))))))
  16681. s))
  16682. (defun org-recenter-calendar (d)
  16683. "If the calendar is visible, recenter it to date D."
  16684. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16685. (when cwin
  16686. (let ((calendar-move-hook nil))
  16687. (with-selected-window cwin
  16688. (calendar-goto-date
  16689. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16690. (defun org-goto-calendar (&optional arg)
  16691. "Go to the Emacs calendar at the current date.
  16692. If there is a time stamp in the current line, go to that date.
  16693. A prefix ARG can be used to force the current date."
  16694. (interactive "P")
  16695. (let ((tsr org-ts-regexp) diff
  16696. (calendar-move-hook nil)
  16697. (calendar-view-holidays-initially-flag nil)
  16698. (calendar-view-diary-initially-flag nil))
  16699. (when (or (org-at-timestamp-p)
  16700. (save-excursion
  16701. (beginning-of-line 1)
  16702. (looking-at (concat ".*" tsr))))
  16703. (let ((d1 (time-to-days (current-time)))
  16704. (d2 (time-to-days
  16705. (org-time-string-to-time (match-string 1)))))
  16706. (setq diff (- d2 d1))))
  16707. (calendar)
  16708. (calendar-goto-today)
  16709. (when (and diff (not arg)) (calendar-forward-day diff))))
  16710. (defun org-get-date-from-calendar ()
  16711. "Return a list (month day year) of date at point in calendar."
  16712. (with-current-buffer "*Calendar*"
  16713. (save-match-data
  16714. (calendar-cursor-to-date))))
  16715. (defun org-date-from-calendar ()
  16716. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16717. If there is already a time stamp at the cursor position, update it."
  16718. (interactive)
  16719. (if (org-at-timestamp-p t)
  16720. (org-timestamp-change 0 'calendar)
  16721. (let ((cal-date (org-get-date-from-calendar)))
  16722. (org-insert-time-stamp
  16723. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16724. (defcustom org-effort-durations
  16725. `(("min" . 1)
  16726. ("h" . 60)
  16727. ("d" . ,(* 60 8))
  16728. ("w" . ,(* 60 8 5))
  16729. ("m" . ,(* 60 8 5 4))
  16730. ("y" . ,(* 60 8 5 40)))
  16731. "Conversion factor to minutes for an effort modifier.
  16732. Each entry has the form (MODIFIER . MINUTES).
  16733. In an effort string, a number followed by MODIFIER is multiplied
  16734. by the specified number of MINUTES to obtain an effort in
  16735. minutes.
  16736. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16737. effort string \"2hours\" is equivalent to 120 minutes."
  16738. :group 'org-agenda
  16739. :version "25.2"
  16740. :package-version '(Org . "8.3")
  16741. :type '(alist :key-type (string :tag "Modifier")
  16742. :value-type (number :tag "Minutes")))
  16743. (defun org-minutes-to-clocksum-string (m)
  16744. "Format number of minutes as a clocksum string.
  16745. The format is determined by `org-time-clocksum-format',
  16746. `org-time-clocksum-use-fractional' and
  16747. `org-time-clocksum-fractional-format' and
  16748. `org-time-clocksum-use-effort-durations'."
  16749. (let ((clocksum "")
  16750. (m (round m)) ; Don't allow fractions of minutes
  16751. h d w mo y fmt n)
  16752. (setq h (if org-time-clocksum-use-effort-durations
  16753. (cdr (assoc "h" org-effort-durations)) 60)
  16754. d (if org-time-clocksum-use-effort-durations
  16755. (/ (cdr (assoc "d" org-effort-durations)) h) 24)
  16756. w (if org-time-clocksum-use-effort-durations
  16757. (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
  16758. mo (if org-time-clocksum-use-effort-durations
  16759. (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
  16760. y (if org-time-clocksum-use-effort-durations
  16761. (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
  16762. ;; fractional format
  16763. (if org-time-clocksum-use-fractional
  16764. (cond
  16765. ;; single format string
  16766. ((stringp org-time-clocksum-fractional-format)
  16767. (format org-time-clocksum-fractional-format (/ m (float h))))
  16768. ;; choice of fractional formats for different time units
  16769. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16770. (> (/ (truncate m) (* y d h)) 0))
  16771. (format fmt (/ m (* y d (float h)))))
  16772. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16773. (> (/ (truncate m) (* mo d h)) 0))
  16774. (format fmt (/ m (* mo d (float h)))))
  16775. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16776. (> (/ (truncate m) (* w d h)) 0))
  16777. (format fmt (/ m (* w d (float h)))))
  16778. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16779. (> (/ (truncate m) (* d h)) 0))
  16780. (format fmt (/ m (* d (float h)))))
  16781. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16782. (> (/ (truncate m) h) 0))
  16783. (format fmt (/ m (float h))))
  16784. ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
  16785. (format fmt m))
  16786. ;; fall back to smallest time unit with a format
  16787. ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16788. (format fmt (/ m (float h))))
  16789. ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16790. (format fmt (/ m (* d (float h)))))
  16791. ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16792. (format fmt (/ m (* w d (float h)))))
  16793. ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16794. (format fmt (/ m (* mo d (float h)))))
  16795. ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16796. (format fmt (/ m (* y d (float h))))))
  16797. ;; standard (non-fractional) format, with single format string
  16798. (if (stringp org-time-clocksum-format)
  16799. (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
  16800. ;; separate formats components
  16801. (and (setq fmt (plist-get org-time-clocksum-format :years))
  16802. (or (> (setq n (/ (truncate m) (* y d h))) 0)
  16803. (plist-get org-time-clocksum-format :require-years))
  16804. (setq clocksum (concat clocksum (format fmt n))
  16805. m (- m (* n y d h))))
  16806. (and (setq fmt (plist-get org-time-clocksum-format :months))
  16807. (or (> (setq n (/ (truncate m) (* mo d h))) 0)
  16808. (plist-get org-time-clocksum-format :require-months))
  16809. (setq clocksum (concat clocksum (format fmt n))
  16810. m (- m (* n mo d h))))
  16811. (and (setq fmt (plist-get org-time-clocksum-format :weeks))
  16812. (or (> (setq n (/ (truncate m) (* w d h))) 0)
  16813. (plist-get org-time-clocksum-format :require-weeks))
  16814. (setq clocksum (concat clocksum (format fmt n))
  16815. m (- m (* n w d h))))
  16816. (and (setq fmt (plist-get org-time-clocksum-format :days))
  16817. (or (> (setq n (/ (truncate m) (* d h))) 0)
  16818. (plist-get org-time-clocksum-format :require-days))
  16819. (setq clocksum (concat clocksum (format fmt n))
  16820. m (- m (* n d h))))
  16821. (and (setq fmt (plist-get org-time-clocksum-format :hours))
  16822. (or (> (setq n (/ (truncate m) h)) 0)
  16823. (plist-get org-time-clocksum-format :require-hours))
  16824. (setq clocksum (concat clocksum (format fmt n))
  16825. m (- m (* n h))))
  16826. (and (setq fmt (plist-get org-time-clocksum-format :minutes))
  16827. (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
  16828. (setq clocksum (concat clocksum (format fmt m))))
  16829. ;; return formatted time duration
  16830. clocksum))))
  16831. (defun org-hours-to-clocksum-string (n)
  16832. (org-minutes-to-clocksum-string (* n 60)))
  16833. (defun org-hh:mm-string-to-minutes (s)
  16834. "Convert a string H:MM to a number of minutes.
  16835. If the string is just a number, interpret it as minutes.
  16836. In fact, the first hh:mm or number in the string will be taken,
  16837. there can be extra stuff in the string.
  16838. If no number is found, the return value is 0."
  16839. (cond
  16840. ((integerp s) s)
  16841. ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
  16842. (+ (* (string-to-number (match-string 1 s)) 60)
  16843. (string-to-number (match-string 2 s))))
  16844. ((string-match "\\([0-9]+\\)" s)
  16845. (string-to-number (match-string 1 s)))
  16846. (t 0)))
  16847. (defcustom org-image-actual-width t
  16848. "Should we use the actual width of images when inlining them?
  16849. When set to t, always use the image width.
  16850. When set to a number, use imagemagick (when available) to set
  16851. the image's width to this value.
  16852. When set to a number in a list, try to get the width from any
  16853. #+ATTR.* keyword if it matches a width specification like
  16854. #+ATTR_HTML: :width 300px
  16855. and fall back on that number if none is found.
  16856. When set to nil, try to get the width from an #+ATTR.* keyword
  16857. and fall back on the original width if none is found.
  16858. This requires Emacs >= 24.1, build with imagemagick support."
  16859. :group 'org-appearance
  16860. :version "24.4"
  16861. :package-version '(Org . "8.0")
  16862. :type '(choice
  16863. (const :tag "Use the image width" t)
  16864. (integer :tag "Use a number of pixels")
  16865. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16866. (const :tag "Use #+ATTR* or don't resize" nil)))
  16867. (defcustom org-agenda-inhibit-startup nil
  16868. "Inhibit startup when preparing agenda buffers.
  16869. When this variable is t, the initialization of the Org agenda
  16870. buffers is inhibited: e.g. the visibility state is not set, the
  16871. tables are not re-aligned, etc."
  16872. :type 'boolean
  16873. :version "24.3"
  16874. :group 'org-agenda)
  16875. (defcustom org-agenda-ignore-properties nil
  16876. "Avoid updating text properties when building the agenda.
  16877. Properties are used to prepare buffers for effort estimates,
  16878. appointments, statistics and subtree-local categories.
  16879. If you don't use these in the agenda, you can add them to this
  16880. list and agenda building will be a bit faster.
  16881. The value is a list, with zero or more of the symbols `effort', `appt',
  16882. `stats' or `category'."
  16883. :type '(set :greedy t
  16884. (const effort)
  16885. (const appt)
  16886. (const stats)
  16887. (const category))
  16888. :version "25.2"
  16889. :package-version '(Org . "8.3")
  16890. :group 'org-agenda)
  16891. (defun org-duration-string-to-minutes (s &optional output-to-string)
  16892. "Convert a duration string S to minutes.
  16893. A bare number is interpreted as minutes, modifiers can be set by
  16894. customizing `org-effort-durations' (which see).
  16895. Entries containing a colon are interpreted as H:MM by
  16896. `org-hh:mm-string-to-minutes'."
  16897. (let ((result 0)
  16898. (re (concat "\\([0-9.]+\\) *\\("
  16899. (regexp-opt (mapcar 'car org-effort-durations))
  16900. "\\)")))
  16901. (while (string-match re s)
  16902. (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
  16903. (string-to-number (match-string 1 s))))
  16904. (setq s (replace-match "" nil t s)))
  16905. (setq result (floor result))
  16906. (cl-incf result (org-hh:mm-string-to-minutes s))
  16907. (if output-to-string (number-to-string result) result)))
  16908. ;;;; Files
  16909. (defun org-save-all-org-buffers ()
  16910. "Save all Org buffers without user confirmation."
  16911. (interactive)
  16912. (message "Saving all Org buffers...")
  16913. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16914. (when (featurep 'org-id) (org-id-locations-save))
  16915. (message "Saving all Org buffers... done"))
  16916. (defun org-revert-all-org-buffers ()
  16917. "Revert all Org buffers.
  16918. Prompt for confirmation when there are unsaved changes.
  16919. Be sure you know what you are doing before letting this function
  16920. overwrite your changes.
  16921. This function is useful in a setup where one tracks org files
  16922. with a version control system, to revert on one machine after pulling
  16923. changes from another. I believe the procedure must be like this:
  16924. 1. M-x org-save-all-org-buffers
  16925. 2. Pull changes from the other machine, resolve conflicts
  16926. 3. M-x org-revert-all-org-buffers"
  16927. (interactive)
  16928. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16929. (user-error "Abort"))
  16930. (save-excursion
  16931. (save-window-excursion
  16932. (dolist (b (buffer-list))
  16933. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16934. (with-current-buffer b buffer-file-name))
  16935. (pop-to-buffer-same-window b)
  16936. (revert-buffer t 'no-confirm)))
  16937. (when (and (featurep 'org-id) org-id-track-globally)
  16938. (org-id-locations-load)))))
  16939. ;;;; Agenda files
  16940. ;;;###autoload
  16941. (defun org-switchb (&optional arg)
  16942. "Switch between Org buffers.
  16943. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16944. With `\\[universal-argument] \\[universal-argument]' \
  16945. prefix, restrict available buffers to agenda files."
  16946. (interactive "P")
  16947. (let ((blist (org-buffer-list
  16948. (cond ((equal arg '(4)) 'files)
  16949. ((equal arg '(16)) 'agenda)))))
  16950. (pop-to-buffer-same-window
  16951. (completing-read "Org buffer: "
  16952. (mapcar #'list (mapcar #'buffer-name blist))
  16953. nil t))))
  16954. (defun org-buffer-list (&optional predicate exclude-tmp)
  16955. "Return a list of Org buffers.
  16956. PREDICATE can be `export', `files' or `agenda'.
  16957. export restrict the list to Export buffers.
  16958. files restrict the list to buffers visiting Org files.
  16959. agenda restrict the list to buffers visiting agenda files.
  16960. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16961. (let* ((bfn nil)
  16962. (agenda-files (and (eq predicate 'agenda)
  16963. (mapcar 'file-truename (org-agenda-files t))))
  16964. (filter
  16965. (cond
  16966. ((eq predicate 'files)
  16967. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16968. ((eq predicate 'export)
  16969. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16970. ((eq predicate 'agenda)
  16971. (lambda (b)
  16972. (with-current-buffer b
  16973. (and (derived-mode-p 'org-mode)
  16974. (setq bfn (buffer-file-name b))
  16975. (member (file-truename bfn) agenda-files)))))
  16976. (t (lambda (b) (with-current-buffer b
  16977. (or (derived-mode-p 'org-mode)
  16978. (string-match "\\*Org .*Export"
  16979. (buffer-name b)))))))))
  16980. (delq nil
  16981. (mapcar
  16982. (lambda(b)
  16983. (if (and (funcall filter b)
  16984. (or (not exclude-tmp)
  16985. (not (string-match "tmp" (buffer-name b)))))
  16986. b
  16987. nil))
  16988. (buffer-list)))))
  16989. (defun org-agenda-files (&optional unrestricted archives)
  16990. "Get the list of agenda files.
  16991. Optional UNRESTRICTED means return the full list even if a restriction
  16992. is currently in place.
  16993. When ARCHIVES is t, include all archive files that are really being
  16994. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16995. `org-agenda-archives-mode' is t."
  16996. (let ((files
  16997. (cond
  16998. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16999. ((stringp org-agenda-files) (org-read-agenda-file-list))
  17000. ((listp org-agenda-files) org-agenda-files)
  17001. (t (error "Invalid value of `org-agenda-files'")))))
  17002. (setq files (apply 'append
  17003. (mapcar (lambda (f)
  17004. (if (file-directory-p f)
  17005. (directory-files
  17006. f t org-agenda-file-regexp)
  17007. (list f)))
  17008. files)))
  17009. (when org-agenda-skip-unavailable-files
  17010. (setq files (delq nil
  17011. (mapcar (function
  17012. (lambda (file)
  17013. (and (file-readable-p file) file)))
  17014. files))))
  17015. (when (or (eq archives t)
  17016. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  17017. (setq files (org-add-archive-files files)))
  17018. files))
  17019. (defun org-agenda-file-p (&optional file)
  17020. "Return non-nil, if FILE is an agenda file.
  17021. If FILE is omitted, use the file associated with the current
  17022. buffer."
  17023. (let ((fname (or file (buffer-file-name))))
  17024. (and fname
  17025. (member (file-truename fname)
  17026. (mapcar #'file-truename (org-agenda-files t))))))
  17027. (defun org-edit-agenda-file-list ()
  17028. "Edit the list of agenda files.
  17029. Depending on setup, this either uses customize to edit the variable
  17030. `org-agenda-files', or it visits the file that is holding the list. In the
  17031. latter case, the buffer is set up in a way that saving it automatically kills
  17032. the buffer and restores the previous window configuration."
  17033. (interactive)
  17034. (if (stringp org-agenda-files)
  17035. (let ((cw (current-window-configuration)))
  17036. (find-file org-agenda-files)
  17037. (setq-local org-window-configuration cw)
  17038. (add-hook 'after-save-hook
  17039. (lambda ()
  17040. (set-window-configuration
  17041. (prog1 org-window-configuration
  17042. (kill-buffer (current-buffer))))
  17043. (org-install-agenda-files-menu)
  17044. (message "New agenda file list installed"))
  17045. nil 'local)
  17046. (message "%s" (substitute-command-keys
  17047. "Edit list and finish with \\[save-buffer]")))
  17048. (customize-variable 'org-agenda-files)))
  17049. (defun org-store-new-agenda-file-list (list)
  17050. "Set new value for the agenda file list and save it correctly."
  17051. (if (stringp org-agenda-files)
  17052. (let ((fe (org-read-agenda-file-list t)) b u)
  17053. (while (setq b (find-buffer-visiting org-agenda-files))
  17054. (kill-buffer b))
  17055. (with-temp-file org-agenda-files
  17056. (insert
  17057. (mapconcat
  17058. (lambda (f) ;; Keep un-expanded entries.
  17059. (if (setq u (assoc f fe))
  17060. (cdr u)
  17061. f))
  17062. list "\n")
  17063. "\n")))
  17064. (let ((org-mode-hook nil) (org-inhibit-startup t)
  17065. (org-insert-mode-line-in-empty-file nil))
  17066. (setq org-agenda-files list)
  17067. (customize-save-variable 'org-agenda-files org-agenda-files))))
  17068. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  17069. "Read the list of agenda files from a file.
  17070. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  17071. filenames, used by `org-store-new-agenda-file-list' to write back
  17072. un-expanded file names."
  17073. (when (file-directory-p org-agenda-files)
  17074. (error "`org-agenda-files' cannot be a single directory"))
  17075. (when (stringp org-agenda-files)
  17076. (with-temp-buffer
  17077. (insert-file-contents org-agenda-files)
  17078. (mapcar
  17079. (lambda (f)
  17080. (let ((e (expand-file-name (substitute-in-file-name f)
  17081. org-directory)))
  17082. (if pair-with-expansion
  17083. (cons e f)
  17084. e)))
  17085. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  17086. ;;;###autoload
  17087. (defun org-cycle-agenda-files ()
  17088. "Cycle through the files in `org-agenda-files'.
  17089. If the current buffer visits an agenda file, find the next one in the list.
  17090. If the current buffer does not, find the first agenda file."
  17091. (interactive)
  17092. (let* ((fs (or (org-agenda-files t)
  17093. (user-error "No agenda files")))
  17094. (files (copy-sequence fs))
  17095. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  17096. file)
  17097. (when tcf
  17098. (while (and (setq file (pop files))
  17099. (not (equal (file-truename file) tcf)))))
  17100. (find-file (car (or files fs)))
  17101. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  17102. (defun org-agenda-file-to-front (&optional to-end)
  17103. "Move/add the current file to the top of the agenda file list.
  17104. If the file is not present in the list, it is added to the front. If it is
  17105. present, it is moved there. With optional argument TO-END, add/move to the
  17106. end of the list."
  17107. (interactive "P")
  17108. (let ((org-agenda-skip-unavailable-files nil)
  17109. (file-alist (mapcar (lambda (x)
  17110. (cons (file-truename x) x))
  17111. (org-agenda-files t)))
  17112. (ctf (file-truename
  17113. (or buffer-file-name
  17114. (user-error "Please save the current buffer to a file"))))
  17115. x had)
  17116. (setq x (assoc ctf file-alist) had x)
  17117. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  17118. (if to-end
  17119. (setq file-alist (append (delq x file-alist) (list x)))
  17120. (setq file-alist (cons x (delq x file-alist))))
  17121. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  17122. (org-install-agenda-files-menu)
  17123. (message "File %s to %s of agenda file list"
  17124. (if had "moved" "added") (if to-end "end" "front"))))
  17125. (defun org-remove-file (&optional file)
  17126. "Remove current file from the list of files in variable `org-agenda-files'.
  17127. These are the files which are being checked for agenda entries.
  17128. Optional argument FILE means use this file instead of the current."
  17129. (interactive)
  17130. (let* ((org-agenda-skip-unavailable-files nil)
  17131. (file (or file buffer-file-name
  17132. (user-error "Current buffer does not visit a file")))
  17133. (true-file (file-truename file))
  17134. (afile (abbreviate-file-name file))
  17135. (files (delq nil (mapcar
  17136. (lambda (x)
  17137. (unless (equal true-file
  17138. (file-truename x))
  17139. x))
  17140. (org-agenda-files t)))))
  17141. (if (not (= (length files) (length (org-agenda-files t))))
  17142. (progn
  17143. (org-store-new-agenda-file-list files)
  17144. (org-install-agenda-files-menu)
  17145. (message "Removed from Org Agenda list: %s" afile))
  17146. (message "File was not in list: %s (not removed)" afile))))
  17147. (defun org-file-menu-entry (file)
  17148. (vector file (list 'find-file file) t))
  17149. (defun org-check-agenda-file (file)
  17150. "Make sure FILE exists. If not, ask user what to do."
  17151. (unless (file-exists-p file)
  17152. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  17153. (abbreviate-file-name file))
  17154. (let ((r (downcase (read-char-exclusive))))
  17155. (cond
  17156. ((equal r ?r)
  17157. (org-remove-file file)
  17158. (throw 'nextfile t))
  17159. (t (user-error "Abort"))))))
  17160. (defun org-get-agenda-file-buffer (file)
  17161. "Get an agenda buffer visiting FILE.
  17162. If the buffer needs to be created, add it to the list of buffers
  17163. which might be released later."
  17164. (let ((buf (org-find-base-buffer-visiting file)))
  17165. (if buf
  17166. buf ; just return it
  17167. ;; Make a new buffer and remember it
  17168. (setq buf (find-file-noselect file))
  17169. (when buf (push buf org-agenda-new-buffers))
  17170. buf)))
  17171. (defun org-release-buffers (blist)
  17172. "Release all buffers in list, asking the user for confirmation when needed.
  17173. When a buffer is unmodified, it is just killed. When modified, it is saved
  17174. \(if the user agrees) and then killed."
  17175. (let (file)
  17176. (dolist (buf blist)
  17177. (setq file (buffer-file-name buf))
  17178. (when (and (buffer-modified-p buf)
  17179. file
  17180. (y-or-n-p (format "Save file %s? " file)))
  17181. (with-current-buffer buf (save-buffer)))
  17182. (kill-buffer buf))))
  17183. (defun org-agenda-prepare-buffers (files)
  17184. "Create buffers for all agenda files, protect archived trees and comments."
  17185. (interactive)
  17186. (let ((pa '(:org-archived t))
  17187. (pc '(:org-comment t))
  17188. (pall '(:org-archived t :org-comment t))
  17189. (inhibit-read-only t)
  17190. (org-inhibit-startup org-agenda-inhibit-startup)
  17191. (rea (concat ":" org-archive-tag ":"))
  17192. re pos)
  17193. (setq org-tag-alist-for-agenda nil
  17194. org-tag-groups-alist-for-agenda nil)
  17195. (save-excursion
  17196. (save-restriction
  17197. (dolist (file files)
  17198. (catch 'nextfile
  17199. (if (bufferp file)
  17200. (set-buffer file)
  17201. (org-check-agenda-file file)
  17202. (set-buffer (org-get-agenda-file-buffer file)))
  17203. (widen)
  17204. (org-set-regexps-and-options 'tags-only)
  17205. (setq pos (point))
  17206. (or (memq 'category org-agenda-ignore-properties)
  17207. (org-refresh-category-properties))
  17208. (or (memq 'stats org-agenda-ignore-properties)
  17209. (org-refresh-stats-properties))
  17210. (or (memq 'effort org-agenda-ignore-properties)
  17211. (org-refresh-effort-properties))
  17212. (or (memq 'appt org-agenda-ignore-properties)
  17213. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  17214. (setq org-todo-keywords-for-agenda
  17215. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  17216. (setq org-done-keywords-for-agenda
  17217. (append org-done-keywords-for-agenda org-done-keywords))
  17218. (setq org-todo-keyword-alist-for-agenda
  17219. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  17220. (setq org-tag-alist-for-agenda
  17221. (org-uniquify
  17222. (append org-tag-alist-for-agenda
  17223. org-current-tag-alist)))
  17224. ;; Merge current file's tag groups into global
  17225. ;; `org-tag-groups-alist-for-agenda'.
  17226. (when org-group-tags
  17227. (dolist (alist org-tag-groups-alist)
  17228. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  17229. (if old
  17230. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  17231. (push alist org-tag-groups-alist-for-agenda)))))
  17232. (org-with-silent-modifications
  17233. (save-excursion
  17234. (remove-text-properties (point-min) (point-max) pall)
  17235. (when org-agenda-skip-archived-trees
  17236. (goto-char (point-min))
  17237. (while (re-search-forward rea nil t)
  17238. (when (org-at-heading-p t)
  17239. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  17240. (goto-char (point-min))
  17241. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  17242. (while (re-search-forward re nil t)
  17243. (when (save-match-data (org-in-commented-heading-p t))
  17244. (add-text-properties
  17245. (match-beginning 0) (org-end-of-subtree t) pc)))))
  17246. (goto-char pos)))))
  17247. (setq org-todo-keywords-for-agenda
  17248. (org-uniquify org-todo-keywords-for-agenda))
  17249. (setq org-todo-keyword-alist-for-agenda
  17250. (org-uniquify org-todo-keyword-alist-for-agenda))))
  17251. ;;;; CDLaTeX minor mode
  17252. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  17253. "Keymap for the minor `org-cdlatex-mode'.")
  17254. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  17255. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  17256. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  17257. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  17258. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  17259. (defvar org-cdlatex-texmathp-advice-is-done nil
  17260. "Flag remembering if we have applied the advice to texmathp already.")
  17261. (define-minor-mode org-cdlatex-mode
  17262. "Toggle the minor `org-cdlatex-mode'.
  17263. This mode supports entering LaTeX environment and math in LaTeX fragments
  17264. in Org mode.
  17265. \\{org-cdlatex-mode-map}"
  17266. nil " OCDL" nil
  17267. (when org-cdlatex-mode
  17268. (require 'cdlatex)
  17269. (run-hooks 'cdlatex-mode-hook)
  17270. (cdlatex-compute-tables))
  17271. (unless org-cdlatex-texmathp-advice-is-done
  17272. (setq org-cdlatex-texmathp-advice-is-done t)
  17273. (defadvice texmathp (around org-math-always-on activate)
  17274. "Always return t in Org buffers.
  17275. This is because we want to insert math symbols without dollars even outside
  17276. the LaTeX math segments. If Org mode thinks that point is actually inside
  17277. an embedded LaTeX fragment, let `texmathp' do its job.
  17278. `\\[org-cdlatex-mode-map]'"
  17279. (interactive)
  17280. (let (p)
  17281. (cond
  17282. ((not (derived-mode-p 'org-mode)) ad-do-it)
  17283. ((eq this-command 'cdlatex-math-symbol)
  17284. (setq ad-return-value t
  17285. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  17286. (t
  17287. (let ((p (org-inside-LaTeX-fragment-p)))
  17288. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  17289. (setq ad-return-value t
  17290. texmathp-why '("Org mode embedded math" . 0))
  17291. (when p ad-do-it)))))))))
  17292. (defun turn-on-org-cdlatex ()
  17293. "Unconditionally turn on `org-cdlatex-mode'."
  17294. (org-cdlatex-mode 1))
  17295. (defun org-try-cdlatex-tab ()
  17296. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  17297. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  17298. - inside a LaTeX fragment, or
  17299. - after the first word in a line, where an abbreviation expansion could
  17300. insert a LaTeX environment."
  17301. (when org-cdlatex-mode
  17302. (cond
  17303. ;; Before any word on the line: No expansion possible.
  17304. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  17305. ;; Just after first word on the line: Expand it. Make sure it
  17306. ;; cannot happen on headlines, though.
  17307. ((save-excursion
  17308. (skip-chars-backward "a-zA-Z0-9*")
  17309. (skip-chars-backward " \t")
  17310. (and (bolp) (not (org-at-heading-p))))
  17311. (cdlatex-tab) t)
  17312. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  17313. (defun org-cdlatex-underscore-caret (&optional _arg)
  17314. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  17315. Revert to the normal definition outside of these fragments."
  17316. (interactive "P")
  17317. (if (org-inside-LaTeX-fragment-p)
  17318. (call-interactively 'cdlatex-sub-superscript)
  17319. (let (org-cdlatex-mode)
  17320. (call-interactively (key-binding (vector last-input-event))))))
  17321. (defun org-cdlatex-math-modify (&optional _arg)
  17322. "Execute `cdlatex-math-modify' in LaTeX fragments.
  17323. Revert to the normal definition outside of these fragments."
  17324. (interactive "P")
  17325. (if (org-inside-LaTeX-fragment-p)
  17326. (call-interactively 'cdlatex-math-modify)
  17327. (let (org-cdlatex-mode)
  17328. (call-interactively (key-binding (vector last-input-event))))))
  17329. (defun org-cdlatex-environment-indent (&optional environment item)
  17330. "Execute `cdlatex-environment' and indent the inserted environment.
  17331. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  17332. The inserted environment is indented to current indentation
  17333. unless point is at the beginning of the line, in which the
  17334. environment remains unintended."
  17335. (interactive)
  17336. ;; cdlatex-environment always return nil. Therefore, capture output
  17337. ;; first and determine if an environment was selected.
  17338. (let* ((beg (point-marker))
  17339. (end (copy-marker (point) t))
  17340. (inserted (progn
  17341. (ignore-errors (cdlatex-environment environment item))
  17342. (< beg end)))
  17343. ;; Figure out how many lines to move forward after the
  17344. ;; environment has been inserted.
  17345. (lines (when inserted
  17346. (save-excursion
  17347. (- (cl-loop while (< beg (point))
  17348. with x = 0
  17349. do (forward-line -1)
  17350. (cl-incf x)
  17351. finally return x)
  17352. (if (progn (goto-char beg)
  17353. (and (progn (skip-chars-forward " \t") (eolp))
  17354. (progn (skip-chars-backward " \t") (bolp))))
  17355. 1 0)))))
  17356. (env (org-trim (delete-and-extract-region beg end))))
  17357. (when inserted
  17358. ;; Get indentation of next line unless at column 0.
  17359. (let ((ind (if (bolp) 0
  17360. (save-excursion
  17361. (org-return-indent)
  17362. (prog1 (org-get-indentation)
  17363. (when (progn (skip-chars-forward " \t") (eolp))
  17364. (delete-region beg (point)))))))
  17365. (bol (progn (skip-chars-backward " \t") (bolp))))
  17366. ;; Insert a newline before environment unless at column zero
  17367. ;; to "escape" the current line. Insert a newline if
  17368. ;; something is one the same line as \end{ENVIRONMENT}.
  17369. (insert
  17370. (concat (unless bol "\n") env
  17371. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  17372. (unless (zerop ind)
  17373. (save-excursion
  17374. (goto-char beg)
  17375. (while (< (point) end)
  17376. (unless (eolp) (indent-line-to ind))
  17377. (forward-line))))
  17378. (goto-char beg)
  17379. (forward-line lines)
  17380. (indent-line-to ind)))
  17381. (set-marker beg nil)
  17382. (set-marker end nil)))
  17383. ;;;; LaTeX fragments
  17384. (defun org-inside-LaTeX-fragment-p ()
  17385. "Test if point is inside a LaTeX fragment.
  17386. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  17387. sequence appearing also before point.
  17388. Even though the matchers for math are configurable, this function assumes
  17389. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  17390. delimiters are skipped when they have been removed by customization.
  17391. The return value is nil, or a cons cell with the delimiter and the
  17392. position of this delimiter.
  17393. This function does a reasonably good job, but can locally be fooled by
  17394. for example currency specifications. For example it will assume being in
  17395. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  17396. fragments that are properly closed, but during editing, we have to live
  17397. with the uncertainty caused by missing closing delimiters. This function
  17398. looks only before point, not after."
  17399. (catch 'exit
  17400. (let ((pos (point))
  17401. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  17402. (lim (progn
  17403. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
  17404. (point)))
  17405. dd-on str (start 0) m re)
  17406. (goto-char pos)
  17407. (when dodollar
  17408. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  17409. re (nth 1 (assoc "$" org-latex-regexps)))
  17410. (while (string-match re str start)
  17411. (cond
  17412. ((= (match-end 0) (length str))
  17413. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  17414. ((= (match-end 0) (- (length str) 5))
  17415. (throw 'exit nil))
  17416. (t (setq start (match-end 0))))))
  17417. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  17418. (goto-char pos)
  17419. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  17420. (and (match-beginning 2) (throw 'exit nil))
  17421. ;; count $$
  17422. (while (re-search-backward "\\$\\$" lim t)
  17423. (setq dd-on (not dd-on)))
  17424. (goto-char pos)
  17425. (when dd-on (cons "$$" m))))))
  17426. (defun org-inside-latex-macro-p ()
  17427. "Is point inside a LaTeX macro or its arguments?"
  17428. (save-match-data
  17429. (org-in-regexp
  17430. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  17431. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  17432. "Build an overlay between BEG and END using IMAGE file.
  17433. Argument IMAGETYPE is the extension of the displayed image,
  17434. as a string. It defaults to \"png\"."
  17435. (let ((ov (make-overlay beg end))
  17436. (imagetype (or (intern imagetype) 'png)))
  17437. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  17438. (overlay-put ov 'evaporate t)
  17439. (overlay-put ov
  17440. 'modification-hooks
  17441. (list (lambda (o _flag _beg _end &optional _l)
  17442. (delete-overlay o))))
  17443. (overlay-put ov
  17444. 'display
  17445. (list 'image :type imagetype :file image :ascent 'center))))
  17446. (defun org--list-latex-overlays (&optional beg end)
  17447. "List all Org LaTeX overlays in current buffer.
  17448. Limit to overlays between BEG and END when those are provided."
  17449. (cl-remove-if-not
  17450. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  17451. (overlays-in (or beg (point-min)) (or end (point-max)))))
  17452. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  17453. "Remove all overlays with LaTeX fragment images in current buffer.
  17454. When optional arguments BEG and END are non-nil, remove all
  17455. overlays between them instead. Return a non-nil value when some
  17456. overlays were removed, nil otherwise."
  17457. (let ((overlays (org--list-latex-overlays beg end)))
  17458. (mapc #'delete-overlay overlays)
  17459. overlays))
  17460. (defun org-toggle-latex-fragment (&optional arg)
  17461. "Preview the LaTeX fragment at point, or all locally or globally.
  17462. If the cursor is on a LaTeX fragment, create the image and overlay
  17463. it over the source code, if there is none. Remove it otherwise.
  17464. If there is no fragment at point, display all fragments in the
  17465. current section.
  17466. With prefix ARG, preview or clear image for all fragments in the
  17467. current subtree or in the whole buffer when used before the first
  17468. headline. With a prefix ARG `\\[universal-argument] \
  17469. \\[universal-argument]' preview or clear images
  17470. for all fragments in the buffer."
  17471. (interactive "P")
  17472. (when (display-graphic-p)
  17473. (catch 'exit
  17474. (save-excursion
  17475. (let (beg end msg)
  17476. (cond
  17477. ((or (equal arg '(16))
  17478. (and (equal arg '(4))
  17479. (org-with-limited-levels (org-before-first-heading-p))))
  17480. (if (org-remove-latex-fragment-image-overlays)
  17481. (progn (message "LaTeX fragments images removed from buffer")
  17482. (throw 'exit nil))
  17483. (setq msg "Creating images for buffer...")))
  17484. ((equal arg '(4))
  17485. (org-with-limited-levels (org-back-to-heading t))
  17486. (setq beg (point))
  17487. (setq end (progn (org-end-of-subtree t) (point)))
  17488. (if (org-remove-latex-fragment-image-overlays beg end)
  17489. (progn
  17490. (message "LaTeX fragment images removed from subtree")
  17491. (throw 'exit nil))
  17492. (setq msg "Creating images for subtree...")))
  17493. ((let ((datum (org-element-context)))
  17494. (when (memq (org-element-type datum)
  17495. '(latex-environment latex-fragment))
  17496. (setq beg (org-element-property :begin datum))
  17497. (setq end (org-element-property :end datum))
  17498. (if (org-remove-latex-fragment-image-overlays beg end)
  17499. (progn (message "LaTeX fragment image removed")
  17500. (throw 'exit nil))
  17501. (setq msg "Creating image...")))))
  17502. (t
  17503. (org-with-limited-levels
  17504. (setq beg (if (org-at-heading-p) (line-beginning-position)
  17505. (outline-previous-heading)
  17506. (point)))
  17507. (setq end (progn (outline-next-heading) (point)))
  17508. (if (org-remove-latex-fragment-image-overlays beg end)
  17509. (progn
  17510. (message "LaTeX fragment images removed from section")
  17511. (throw 'exit nil))
  17512. (setq msg "Creating images for section...")))))
  17513. (let ((file (buffer-file-name (buffer-base-buffer))))
  17514. (org-format-latex
  17515. (concat org-preview-latex-image-directory "org-ltximg")
  17516. beg end
  17517. ;; Emacs cannot overlay images from remote hosts. Create
  17518. ;; it in `temporary-file-directory' instead.
  17519. (if (or (not file) (file-remote-p file))
  17520. temporary-file-directory
  17521. default-directory)
  17522. 'overlays msg 'forbuffer org-preview-latex-default-process))
  17523. (message (concat msg "done")))))))
  17524. (defun org-format-latex
  17525. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  17526. "Replace LaTeX fragments with links to an image.
  17527. The function takes care of creating the replacement image.
  17528. Only consider fragments between BEG and END when those are
  17529. provided.
  17530. When optional argument OVERLAYS is non-nil, display the image on
  17531. top of the fragment instead of replacing it.
  17532. PROCESSING-TYPE is the conversion method to use, as a symbol.
  17533. Some of the options can be changed using the variable
  17534. `org-format-latex-options', which see."
  17535. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  17536. (unless (eq processing-type 'verbatim)
  17537. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  17538. (cnt 0)
  17539. checkdir-flag)
  17540. (goto-char (or beg (point-min)))
  17541. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  17542. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  17543. (overlay-recenter (or end (point-max))))
  17544. (while (re-search-forward math-regexp end t)
  17545. (unless (and overlays
  17546. (eq (get-char-property (point) 'org-overlay-type)
  17547. 'org-latex-overlay))
  17548. (let* ((context (org-element-context))
  17549. (type (org-element-type context)))
  17550. (when (memq type '(latex-environment latex-fragment))
  17551. (let ((block-type (eq type 'latex-environment))
  17552. (value (org-element-property :value context))
  17553. (beg (org-element-property :begin context))
  17554. (end (save-excursion
  17555. (goto-char (org-element-property :end context))
  17556. (skip-chars-backward " \r\t\n")
  17557. (point))))
  17558. (cond
  17559. ((eq processing-type 'mathjax)
  17560. ;; Prepare for MathJax processing.
  17561. (if (not (string-match "\\`\\$\\$?" value))
  17562. (goto-char end)
  17563. (delete-region beg end)
  17564. (if (string= (match-string 0 value) "$$")
  17565. (insert "\\[" (substring value 2 -2) "\\]")
  17566. (insert "\\(" (substring value 1 -1) "\\)"))))
  17567. ((assq processing-type org-preview-latex-process-alist)
  17568. ;; Process to an image.
  17569. (cl-incf cnt)
  17570. (goto-char beg)
  17571. (let* ((processing-info
  17572. (cdr (assq processing-type org-preview-latex-process-alist)))
  17573. (face (face-at-point))
  17574. ;; Get the colors from the face at point.
  17575. (fg
  17576. (let ((color (plist-get org-format-latex-options
  17577. :foreground)))
  17578. (if (and forbuffer (eq color 'auto))
  17579. (face-attribute face :foreground nil 'default)
  17580. color)))
  17581. (bg
  17582. (let ((color (plist-get org-format-latex-options
  17583. :background)))
  17584. (if (and forbuffer (eq color 'auto))
  17585. (face-attribute face :background nil 'default)
  17586. color)))
  17587. (hash (sha1 (prin1-to-string
  17588. (list org-format-latex-header
  17589. org-latex-default-packages-alist
  17590. org-latex-packages-alist
  17591. org-format-latex-options
  17592. forbuffer value fg bg))))
  17593. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  17594. (absprefix (expand-file-name prefix dir))
  17595. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  17596. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  17597. (sep (and block-type "\n\n"))
  17598. (link (concat sep "[[file:" linkfile "]]" sep))
  17599. (options
  17600. (org-combine-plists
  17601. org-format-latex-options
  17602. `(:foreground ,fg :background ,bg))))
  17603. (when msg (message msg cnt))
  17604. (unless checkdir-flag ; Ensure the directory exists.
  17605. (setq checkdir-flag t)
  17606. (let ((todir (file-name-directory absprefix)))
  17607. (unless (file-directory-p todir)
  17608. (make-directory todir t))))
  17609. (unless (file-exists-p movefile)
  17610. (org-create-formula-image
  17611. value movefile options forbuffer processing-type))
  17612. (if overlays
  17613. (progn
  17614. (dolist (o (overlays-in beg end))
  17615. (when (eq (overlay-get o 'org-overlay-type)
  17616. 'org-latex-overlay)
  17617. (delete-overlay o)))
  17618. (org--format-latex-make-overlay beg end movefile imagetype)
  17619. (goto-char end))
  17620. (delete-region beg end)
  17621. (insert
  17622. (org-add-props link
  17623. (list 'org-latex-src
  17624. (replace-regexp-in-string "\"" "" value)
  17625. 'org-latex-src-embed-type
  17626. (if block-type 'paragraph 'character)))))))
  17627. ((eq processing-type 'mathml)
  17628. ;; Process to MathML.
  17629. (unless (org-format-latex-mathml-available-p)
  17630. (user-error "LaTeX to MathML converter not configured"))
  17631. (cl-incf cnt)
  17632. (when msg (message msg cnt))
  17633. (goto-char beg)
  17634. (delete-region beg end)
  17635. (insert (org-format-latex-as-mathml
  17636. value block-type prefix dir)))
  17637. (t
  17638. (error "Unknown conversion process %s for LaTeX fragments"
  17639. processing-type)))))))))))
  17640. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17641. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17642. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17643. sucessful, return the portion between \"<math...> </math>\"
  17644. elements otherwise return nil. When MATHML-FILE is specified,
  17645. write the results in to that file. When invoked as an
  17646. interactive command, prompt for LATEX-FRAG, with initial value
  17647. set to the current active region and echo the results for user
  17648. inspection."
  17649. (interactive (list (let ((frag (when (org-region-active-p)
  17650. (buffer-substring-no-properties
  17651. (region-beginning) (region-end)))))
  17652. (read-string "LaTeX Fragment: " frag nil frag))))
  17653. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17654. (let* ((tmp-in-file
  17655. (let ((file (file-relative-name
  17656. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17657. (write-region latex-frag nil file)
  17658. file))
  17659. (tmp-out-file (file-relative-name
  17660. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17661. (cmd (format-spec
  17662. org-latex-to-mathml-convert-command
  17663. `((?j . ,(and org-latex-to-mathml-jar-file
  17664. (shell-quote-argument
  17665. (expand-file-name
  17666. org-latex-to-mathml-jar-file))))
  17667. (?I . ,(shell-quote-argument tmp-in-file))
  17668. (?i . ,latex-frag)
  17669. (?o . ,(shell-quote-argument tmp-out-file)))))
  17670. mathml shell-command-output)
  17671. (when (called-interactively-p 'any)
  17672. (unless (org-format-latex-mathml-available-p)
  17673. (user-error "LaTeX to MathML converter not configured")))
  17674. (message "Running %s" cmd)
  17675. (setq shell-command-output (shell-command-to-string cmd))
  17676. (setq mathml
  17677. (when (file-readable-p tmp-out-file)
  17678. (with-current-buffer (find-file-noselect tmp-out-file t)
  17679. (goto-char (point-min))
  17680. (when (re-search-forward
  17681. (concat
  17682. (regexp-quote
  17683. "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
  17684. "[^>]*?>"
  17685. "\\(.\\|\n\\)*"
  17686. "</math>")
  17687. nil t)
  17688. (prog1 (match-string 0) (kill-buffer))))))
  17689. (cond
  17690. (mathml
  17691. (setq mathml
  17692. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17693. (when mathml-file
  17694. (write-region mathml nil mathml-file))
  17695. (when (called-interactively-p 'any)
  17696. (message mathml)))
  17697. ((message "LaTeX to MathML conversion failed")
  17698. (message shell-command-output)))
  17699. (delete-file tmp-in-file)
  17700. (when (file-exists-p tmp-out-file)
  17701. (delete-file tmp-out-file))
  17702. mathml))
  17703. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17704. prefix &optional dir)
  17705. "Use `org-create-math-formula' but check local cache first."
  17706. (let* ((absprefix (expand-file-name prefix dir))
  17707. (print-length nil) (print-level nil)
  17708. (formula-id (concat
  17709. "formula-"
  17710. (sha1
  17711. (prin1-to-string
  17712. (list latex-frag
  17713. org-latex-to-mathml-convert-command)))))
  17714. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17715. (formula-cache-dir (file-name-directory formula-cache)))
  17716. (unless (file-directory-p formula-cache-dir)
  17717. (make-directory formula-cache-dir t))
  17718. (unless (file-exists-p formula-cache)
  17719. (org-create-math-formula latex-frag formula-cache))
  17720. (if (file-exists-p formula-cache)
  17721. ;; Successful conversion. Return the link to MathML file.
  17722. (org-add-props
  17723. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17724. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17725. 'org-latex-src-embed-type (if latex-frag-type
  17726. 'paragraph 'character)))
  17727. ;; Failed conversion. Return the LaTeX fragment verbatim
  17728. latex-frag)))
  17729. (declare-function org-export-get-backend "ox" (name))
  17730. (declare-function org-export--get-global-options "ox" (&optional backend))
  17731. (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
  17732. (declare-function org-latex-guess-inputenc "ox-latex" (header))
  17733. (declare-function org-latex-guess-babel-language "ox-latex" (header info))
  17734. (defun org-create-formula--latex-header ()
  17735. "Return LaTeX header appropriate for previewing a LaTeX snippet."
  17736. (let ((info (org-combine-plists (org-export--get-global-options
  17737. (org-export-get-backend 'latex))
  17738. (org-export--get-inbuffer-options
  17739. (org-export-get-backend 'latex)))))
  17740. (org-latex-guess-babel-language
  17741. (org-latex-guess-inputenc
  17742. (org-splice-latex-header
  17743. org-format-latex-header
  17744. org-latex-default-packages-alist
  17745. org-latex-packages-alist t
  17746. (plist-get info :latex-header)))
  17747. info)))
  17748. (defun org--get-display-dpi ()
  17749. "Get the DPI of the display.
  17750. Assumes that the display has the same pixel width in the
  17751. horizontal and vertical directions."
  17752. (if (display-graphic-p)
  17753. (round (/ (display-pixel-height)
  17754. (/ (display-mm-height) 25.4)))
  17755. (error "Attempt to calculate the dpi of a non-graphic display")))
  17756. (defun org-create-formula-image
  17757. (string tofile options buffer &optional processing-type)
  17758. "Create an image from LaTeX source using external processes.
  17759. The LaTeX STRING is saved to a temporary LaTeX file, then
  17760. converted to an image file by process PROCESSING-TYPE defined in
  17761. `org-preview-latex-process-alist'. A nil value defaults to
  17762. `org-preview-latex-default-process'.
  17763. The generated image file is eventually moved to TOFILE.
  17764. The OPTIONS argument controls the size, foreground color and
  17765. background color of the generated image.
  17766. When BUFFER non-nil, this function is used for LaTeX previewing.
  17767. Otherwise, it is used to deal with LaTeX snippets showed in
  17768. a HTML file."
  17769. (let* ((processing-type (or processing-type
  17770. org-preview-latex-default-process))
  17771. (processing-info
  17772. (cdr (assq processing-type org-preview-latex-process-alist)))
  17773. (programs (plist-get processing-info :programs))
  17774. (error-message (or (plist-get processing-info :message) ""))
  17775. (use-xcolor (plist-get processing-info :use-xcolor))
  17776. (image-input-type (plist-get processing-info :image-input-type))
  17777. (image-output-type (plist-get processing-info :image-output-type))
  17778. (post-clean (or (plist-get processing-info :post-clean)
  17779. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  17780. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  17781. (latex-header (or (plist-get processing-info :latex-header)
  17782. (org-create-formula--latex-header)))
  17783. (latex-compiler (plist-get processing-info :latex-compiler))
  17784. (image-converter (plist-get processing-info :image-converter))
  17785. (tmpdir temporary-file-directory)
  17786. (texfilebase (make-temp-name
  17787. (expand-file-name "orgtex" tmpdir)))
  17788. (texfile (concat texfilebase ".tex"))
  17789. (font-height (face-attribute 'default :height nil))
  17790. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  17791. '(1.0 . 1.0)))
  17792. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  17793. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  17794. (dpi (* scale (floor (if buffer font-height 140.0))))
  17795. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17796. "Black"))
  17797. (bg (or (plist-get options (if buffer :background :html-background))
  17798. "Transparent"))
  17799. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  17800. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  17801. (dolist (program programs)
  17802. (org-check-external-command program error-message))
  17803. (if use-xcolor
  17804. (progn (if (eq fg 'default)
  17805. (setq fg (org-latex-color :foreground))
  17806. (setq fg (org-latex-color-format fg)))
  17807. (if (eq bg 'default)
  17808. (setq bg (org-latex-color :background))
  17809. (setq bg (org-latex-color-format
  17810. (if (string= bg "Transparent") "white" bg))))
  17811. (with-temp-file texfile
  17812. (insert latex-header)
  17813. (insert "\n\\begin{document}\n"
  17814. "\\definecolor{fg}{rgb}{" fg "}\n"
  17815. "\\definecolor{bg}{rgb}{" bg "}\n"
  17816. "\n\\pagecolor{bg}\n"
  17817. "\n{\\color{fg}\n"
  17818. string
  17819. "\n}\n"
  17820. "\n\\end{document}\n")))
  17821. (if (eq fg 'default)
  17822. (setq fg (org-dvipng-color :foreground))
  17823. (unless (string= fg "Transparent")
  17824. (setq fg (org-dvipng-color-format fg))))
  17825. (if (eq bg 'default)
  17826. (setq bg (org-dvipng-color :background))
  17827. (unless (string= bg "Transparent")
  17828. (setq bg (org-dvipng-color-format bg))))
  17829. (with-temp-file texfile
  17830. (insert latex-header)
  17831. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17832. (let* ((err-msg (format "Please adjust '%s' part of \
  17833. `org-preview-latex-process-alist'."
  17834. processing-type))
  17835. (image-input-file
  17836. (org-compile-file
  17837. texfile latex-compiler image-input-type err-msg log-buf))
  17838. (image-output-file
  17839. (org-compile-file
  17840. image-input-file image-converter image-output-type err-msg log-buf
  17841. `((?F . ,(shell-quote-argument fg))
  17842. (?B . ,(shell-quote-argument bg))
  17843. (?D . ,(shell-quote-argument (format "%s" dpi)))
  17844. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  17845. (copy-file image-output-file tofile 'replace)
  17846. (dolist (e post-clean)
  17847. (when (file-exists-p (concat texfilebase e))
  17848. (delete-file (concat texfilebase e))))
  17849. image-output-file)))
  17850. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17851. "Fill a LaTeX header template TPL.
  17852. In the template, the following place holders will be recognized:
  17853. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17854. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17855. [PACKAGES] \\usepackage statements for PKG
  17856. [NO-PACKAGES] do not include PKG
  17857. [EXTRA] the string EXTRA
  17858. [NO-EXTRA] do not include EXTRA
  17859. For backward compatibility, if both the positive and the negative place
  17860. holder is missing, the positive one (without the \"NO-\") will be
  17861. assumed to be present at the end of the template.
  17862. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17863. EXTRA is a string.
  17864. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17865. (let (rpl (end ""))
  17866. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17867. (setq rpl (if (or (match-end 1) (not def-pkg))
  17868. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17869. tpl (replace-match rpl t t tpl))
  17870. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17871. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17872. (setq rpl (if (or (match-end 1) (not pkg))
  17873. "" (org-latex-packages-to-string pkg snippets-p t))
  17874. tpl (replace-match rpl t t tpl))
  17875. (when pkg (setq end
  17876. (concat end "\n"
  17877. (org-latex-packages-to-string pkg snippets-p)))))
  17878. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17879. (setq rpl (if (or (match-end 1) (not extra))
  17880. "" (concat extra "\n"))
  17881. tpl (replace-match rpl t t tpl))
  17882. (when (and extra (string-match "\\S-" extra))
  17883. (setq end (concat end "\n" extra))))
  17884. (if (string-match "\\S-" end)
  17885. (concat tpl "\n" end)
  17886. tpl)))
  17887. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17888. "Turn an alist of packages into a string with the \\usepackage macros."
  17889. (setq pkg (mapconcat (lambda(p)
  17890. (cond
  17891. ((stringp p) p)
  17892. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17893. (format "%% Package %s omitted" (cadr p)))
  17894. ((equal "" (car p))
  17895. (format "\\usepackage{%s}" (cadr p)))
  17896. (t
  17897. (format "\\usepackage[%s]{%s}"
  17898. (car p) (cadr p)))))
  17899. pkg
  17900. "\n"))
  17901. (if newline (concat pkg "\n") pkg))
  17902. (defun org-dvipng-color (attr)
  17903. "Return a RGB color specification for dvipng."
  17904. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17905. (defun org-dvipng-color-format (color-name)
  17906. "Convert COLOR-NAME to a RGB color value for dvipng."
  17907. (apply #'format "rgb %s %s %s"
  17908. (mapcar 'org-normalize-color
  17909. (color-values color-name))))
  17910. (defun org-latex-color (attr)
  17911. "Return a RGB color for the LaTeX color package."
  17912. (org-latex-color-format (face-attribute 'default attr nil)))
  17913. (defun org-latex-color-format (color-name)
  17914. "Convert COLOR-NAME to a RGB color value."
  17915. (apply #'format "%s,%s,%s"
  17916. (mapcar 'org-normalize-color
  17917. (color-values color-name))))
  17918. (defun org-normalize-color (value)
  17919. "Return string to be used as color value for an RGB component."
  17920. (format "%g" (/ value 65535.0)))
  17921. ;; Image display
  17922. (defvar-local org-inline-image-overlays nil)
  17923. (defun org-toggle-inline-images (&optional include-linked)
  17924. "Toggle the display of inline images.
  17925. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17926. (interactive "P")
  17927. (if org-inline-image-overlays
  17928. (progn
  17929. (org-remove-inline-images)
  17930. (when (called-interactively-p 'interactive)
  17931. (message "Inline image display turned off")))
  17932. (org-display-inline-images include-linked)
  17933. (when (called-interactively-p 'interactive)
  17934. (message (if org-inline-image-overlays
  17935. (format "%d images displayed inline"
  17936. (length org-inline-image-overlays))
  17937. "No images to display inline")))))
  17938. (defun org-redisplay-inline-images ()
  17939. "Refresh the display of inline images."
  17940. (interactive)
  17941. (if (not org-inline-image-overlays)
  17942. (org-toggle-inline-images)
  17943. (org-toggle-inline-images)
  17944. (org-toggle-inline-images)))
  17945. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17946. "Display inline images.
  17947. An inline image is a link which follows either of these
  17948. conventions:
  17949. 1. Its path is a file with an extension matching return value
  17950. from `image-file-name-regexp' and it has no contents.
  17951. 2. Its description consists in a single link of the previous
  17952. type.
  17953. When optional argument INCLUDE-LINKED is non-nil, also links with
  17954. a text description part will be inlined. This can be nice for
  17955. a quick look at those images, but it does not reflect what
  17956. exported files will look like.
  17957. When optional argument REFRESH is non-nil, refresh existing
  17958. images between BEG and END. This will create new image displays
  17959. only if necessary. BEG and END default to the buffer
  17960. boundaries."
  17961. (interactive "P")
  17962. (when (display-graphic-p)
  17963. (unless refresh
  17964. (org-remove-inline-images)
  17965. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17966. (org-with-wide-buffer
  17967. (goto-char (or beg (point-min)))
  17968. (let ((case-fold-search t)
  17969. (file-extension-re (image-file-name-regexp)))
  17970. (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
  17971. (let ((link (save-match-data (org-element-context))))
  17972. ;; Check if we're at an inline image.
  17973. (when (and (equal (org-element-property :type link) "file")
  17974. (or include-linked
  17975. (not (org-element-property :contents-begin link)))
  17976. (let ((parent (org-element-property :parent link)))
  17977. (or (not (eq (org-element-type parent) 'link))
  17978. (not (cdr (org-element-contents parent)))))
  17979. (string-match-p file-extension-re
  17980. (org-element-property :path link)))
  17981. (let ((file (expand-file-name
  17982. (org-link-unescape
  17983. (org-element-property :path link)))))
  17984. (when (file-exists-p file)
  17985. (let ((width
  17986. ;; Apply `org-image-actual-width' specifications.
  17987. (cond
  17988. ((not (image-type-available-p 'imagemagick)) nil)
  17989. ((eq org-image-actual-width t) nil)
  17990. ((listp org-image-actual-width)
  17991. (or
  17992. ;; First try to find a width among
  17993. ;; attributes associated to the paragraph
  17994. ;; containing link.
  17995. (let ((paragraph
  17996. (let ((e link))
  17997. (while (and (setq e (org-element-property
  17998. :parent e))
  17999. (not (eq (org-element-type e)
  18000. 'paragraph))))
  18001. e)))
  18002. (when paragraph
  18003. (save-excursion
  18004. (goto-char (org-element-property :begin paragraph))
  18005. (when
  18006. (re-search-forward
  18007. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  18008. (org-element-property
  18009. :post-affiliated paragraph)
  18010. t)
  18011. (string-to-number (match-string 1))))))
  18012. ;; Otherwise, fall-back to provided number.
  18013. (car org-image-actual-width)))
  18014. ((numberp org-image-actual-width)
  18015. org-image-actual-width)))
  18016. (old (get-char-property-and-overlay
  18017. (org-element-property :begin link)
  18018. 'org-image-overlay)))
  18019. (if (and (car-safe old) refresh)
  18020. (image-refresh (overlay-get (cdr old) 'display))
  18021. (let ((image (create-image file
  18022. (and width 'imagemagick)
  18023. nil
  18024. :width width)))
  18025. (when image
  18026. (let* ((link
  18027. ;; If inline image is the description
  18028. ;; of another link, be sure to
  18029. ;; consider the latter as the one to
  18030. ;; apply the overlay on.
  18031. (let ((parent
  18032. (org-element-property :parent link)))
  18033. (if (eq (org-element-type parent) 'link)
  18034. parent
  18035. link)))
  18036. (ov (make-overlay
  18037. (org-element-property :begin link)
  18038. (progn
  18039. (goto-char
  18040. (org-element-property :end link))
  18041. (skip-chars-backward " \t")
  18042. (point)))))
  18043. (overlay-put ov 'display image)
  18044. (overlay-put ov 'face 'default)
  18045. (overlay-put ov 'org-image-overlay t)
  18046. (overlay-put
  18047. ov 'modification-hooks
  18048. (list 'org-display-inline-remove-overlay))
  18049. (push ov org-inline-image-overlays)))))))))))))))
  18050. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  18051. "Remove inline-display overlay if a corresponding region is modified."
  18052. (let ((inhibit-modification-hooks t))
  18053. (when (and ov after)
  18054. (delete ov org-inline-image-overlays)
  18055. (delete-overlay ov))))
  18056. (defun org-remove-inline-images ()
  18057. "Remove inline display of images."
  18058. (interactive)
  18059. (mapc #'delete-overlay org-inline-image-overlays)
  18060. (setq org-inline-image-overlays nil))
  18061. ;;;; Key bindings
  18062. ;; Outline functions from `outline-mode-prefix-map'
  18063. ;; that can be remapped in Org:
  18064. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  18065. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  18066. (define-key org-mode-map [remap outline-forward-same-level]
  18067. 'org-forward-heading-same-level)
  18068. (define-key org-mode-map [remap outline-backward-same-level]
  18069. 'org-backward-heading-same-level)
  18070. (define-key org-mode-map [remap outline-show-branches]
  18071. 'org-kill-note-or-show-branches)
  18072. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  18073. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  18074. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  18075. (define-key org-mode-map [remap outline-next-visible-heading]
  18076. 'org-next-visible-heading)
  18077. (define-key org-mode-map [remap outline-previous-visible-heading]
  18078. 'org-previous-visible-heading)
  18079. (define-key org-mode-map [remap show-children] 'org-show-children)
  18080. ;; Outline functions from `outline-mode-prefix-map' that can not
  18081. ;; be remapped in Org:
  18082. ;; - the column "key binding" shows whether the Outline function is still
  18083. ;; available in Org mode on the same key that it has been bound to in
  18084. ;; Outline mode:
  18085. ;; - "overridden": key used for a different functionality in Org mode
  18086. ;; - else: key still bound to the same Outline function in Org mode
  18087. ;; | Outline function | key binding | Org replacement |
  18088. ;; |------------------------------------+-------------+--------------------------|
  18089. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  18090. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  18091. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  18092. ;; | `show-entry' | overridden | no replacement |
  18093. ;; | `show-branches' | `C-c C-k' | still same function |
  18094. ;; | `show-subtree' | overridden | visibility cycling |
  18095. ;; | `show-all' | overridden | no replacement |
  18096. ;; | `hide-subtree' | overridden | visibility cycling |
  18097. ;; | `hide-body' | overridden | no replacement |
  18098. ;; | `hide-entry' | overridden | visibility cycling |
  18099. ;; | `hide-leaves' | overridden | no replacement |
  18100. ;; | `hide-sublevels' | overridden | no replacement |
  18101. ;; | `hide-other' | overridden | no replacement |
  18102. ;; Make `C-c C-x' a prefix key
  18103. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  18104. ;; TAB key with modifiers
  18105. (org-defkey org-mode-map "\C-i" 'org-cycle)
  18106. (org-defkey org-mode-map [(tab)] 'org-cycle)
  18107. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  18108. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  18109. ;; The following line is necessary under Suse GNU/Linux
  18110. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  18111. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  18112. (define-key org-mode-map [backtab] 'org-shifttab)
  18113. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  18114. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  18115. (org-defkey org-mode-map [(meta return)] 'org-meta-return)
  18116. ;; Cursor keys with modifiers
  18117. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  18118. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  18119. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  18120. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  18121. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  18122. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  18123. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  18124. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  18125. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  18126. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  18127. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  18128. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  18129. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  18130. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  18131. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  18132. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  18133. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  18134. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  18135. ;; Babel keys
  18136. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  18137. (dolist (pair org-babel-key-bindings)
  18138. (define-key org-babel-map (car pair) (cdr pair)))
  18139. ;;; Extra keys for tty access.
  18140. ;; We only set them when really needed because otherwise the
  18141. ;; menus don't show the simple keys
  18142. (when (or org-use-extra-keys (not window-system))
  18143. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  18144. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  18145. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  18146. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  18147. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  18148. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  18149. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  18150. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  18151. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  18152. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  18153. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  18154. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  18155. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  18156. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  18157. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  18158. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  18159. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  18160. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  18161. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  18162. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  18163. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  18164. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  18165. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  18166. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  18167. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  18168. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  18169. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  18170. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  18171. ;; All the other keys
  18172. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  18173. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  18174. (if (boundp 'narrow-map)
  18175. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  18176. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  18177. (if (boundp 'narrow-map)
  18178. (org-defkey narrow-map "b" 'org-narrow-to-block)
  18179. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  18180. (if (boundp 'narrow-map)
  18181. (org-defkey narrow-map "e" 'org-narrow-to-element)
  18182. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  18183. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  18184. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  18185. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  18186. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  18187. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  18188. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  18189. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  18190. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  18191. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  18192. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  18193. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  18194. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  18195. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  18196. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  18197. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  18198. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  18199. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  18200. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  18201. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  18202. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  18203. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  18204. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  18205. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  18206. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  18207. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  18208. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  18209. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  18210. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  18211. (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
  18212. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  18213. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  18214. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  18215. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  18216. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  18217. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  18218. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  18219. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  18220. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  18221. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  18222. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  18223. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  18224. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  18225. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  18226. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  18227. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  18228. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  18229. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  18230. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  18231. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  18232. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  18233. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  18234. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  18235. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  18236. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  18237. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  18238. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  18239. (org-defkey org-mode-map "\C-c^" 'org-sort)
  18240. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  18241. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  18242. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  18243. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  18244. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  18245. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  18246. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  18247. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  18248. (org-defkey org-mode-map "\C-m" 'org-return)
  18249. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  18250. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  18251. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  18252. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  18253. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  18254. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  18255. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  18256. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  18257. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  18258. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  18259. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  18260. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  18261. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  18262. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  18263. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  18264. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  18265. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  18266. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  18267. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  18268. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  18269. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  18270. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  18271. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  18272. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  18273. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  18274. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  18275. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  18276. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  18277. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  18278. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  18279. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  18280. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  18281. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  18282. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  18283. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  18284. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  18285. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  18286. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  18287. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  18288. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  18289. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  18290. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  18291. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  18292. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  18293. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  18294. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  18295. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  18296. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  18297. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  18298. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  18299. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  18300. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  18301. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  18302. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  18303. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  18304. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  18305. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  18306. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  18307. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  18308. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  18309. (defconst org-speed-commands-default
  18310. '(
  18311. ("Outline Navigation")
  18312. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  18313. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  18314. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  18315. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  18316. ("F" . org-next-block)
  18317. ("B" . org-previous-block)
  18318. ("u" . (org-speed-move-safe 'outline-up-heading))
  18319. ("j" . org-goto)
  18320. ("g" . (org-refile t))
  18321. ("Outline Visibility")
  18322. ("c" . org-cycle)
  18323. ("C" . org-shifttab)
  18324. (" " . org-display-outline-path)
  18325. ("s" . org-narrow-to-subtree)
  18326. ("=" . org-columns)
  18327. ("Outline Structure Editing")
  18328. ("U" . org-metaup)
  18329. ("D" . org-metadown)
  18330. ("r" . org-metaright)
  18331. ("l" . org-metaleft)
  18332. ("R" . org-shiftmetaright)
  18333. ("L" . org-shiftmetaleft)
  18334. ("i" . (progn (forward-char 1) (call-interactively
  18335. 'org-insert-heading-respect-content)))
  18336. ("^" . org-sort)
  18337. ("w" . org-refile)
  18338. ("a" . org-archive-subtree-default-with-confirmation)
  18339. ("@" . org-mark-subtree)
  18340. ("#" . org-toggle-comment)
  18341. ("Clock Commands")
  18342. ("I" . org-clock-in)
  18343. ("O" . org-clock-out)
  18344. ("Meta Data Editing")
  18345. ("t" . org-todo)
  18346. ("," . (org-priority))
  18347. ("0" . (org-priority ?\ ))
  18348. ("1" . (org-priority ?A))
  18349. ("2" . (org-priority ?B))
  18350. ("3" . (org-priority ?C))
  18351. (":" . org-set-tags-command)
  18352. ("e" . org-set-effort)
  18353. ("E" . org-inc-effort)
  18354. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  18355. (org-entry-put (point) "APPT_WARNTIME" m)))
  18356. ("Agenda Views etc")
  18357. ("v" . org-agenda)
  18358. ("/" . org-sparse-tree)
  18359. ("Misc")
  18360. ("o" . org-open-at-point)
  18361. ("?" . org-speed-command-help)
  18362. ("<" . (org-agenda-set-restriction-lock 'subtree))
  18363. (">" . (org-agenda-remove-restriction-lock))
  18364. )
  18365. "The default speed commands.")
  18366. (defun org-print-speed-command (e)
  18367. (if (> (length (car e)) 1)
  18368. (progn
  18369. (princ "\n")
  18370. (princ (car e))
  18371. (princ "\n")
  18372. (princ (make-string (length (car e)) ?-))
  18373. (princ "\n"))
  18374. (princ (car e))
  18375. (princ " ")
  18376. (if (symbolp (cdr e))
  18377. (princ (symbol-name (cdr e)))
  18378. (prin1 (cdr e)))
  18379. (princ "\n")))
  18380. (defun org-speed-command-help ()
  18381. "Show the available speed commands."
  18382. (interactive)
  18383. (if (not org-use-speed-commands)
  18384. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  18385. (with-output-to-temp-buffer "*Help*"
  18386. (princ "User-defined Speed commands\n===========================\n")
  18387. (mapc #'org-print-speed-command org-speed-commands-user)
  18388. (princ "\n")
  18389. (princ "Built-in Speed commands\n=======================\n")
  18390. (mapc #'org-print-speed-command org-speed-commands-default))
  18391. (with-current-buffer "*Help*"
  18392. (setq truncate-lines t))))
  18393. (defun org-speed-move-safe (cmd)
  18394. "Execute CMD, but make sure that the cursor always ends up in a headline.
  18395. If not, return to the original position and throw an error."
  18396. (interactive)
  18397. (let ((pos (point)))
  18398. (call-interactively cmd)
  18399. (unless (and (bolp) (org-at-heading-p))
  18400. (goto-char pos)
  18401. (error "Boundary reached while executing %s" cmd))))
  18402. (defvar org-self-insert-command-undo-counter 0)
  18403. (defvar org-table-auto-blank-field) ; defined in org-table.el
  18404. (defvar org-speed-command nil)
  18405. (defun org-speed-command-activate (keys)
  18406. "Hook for activating single-letter speed commands.
  18407. `org-speed-commands-default' specifies a minimal command set.
  18408. Use `org-speed-commands-user' for further customization."
  18409. (when (or (and (bolp) (looking-at org-outline-regexp))
  18410. (and (functionp org-use-speed-commands)
  18411. (funcall org-use-speed-commands)))
  18412. (cdr (assoc keys (append org-speed-commands-user
  18413. org-speed-commands-default)))))
  18414. (defun org-babel-speed-command-activate (keys)
  18415. "Hook for activating single-letter code block commands."
  18416. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  18417. (cdr (assoc keys org-babel-key-bindings))))
  18418. (defcustom org-speed-command-hook
  18419. '(org-speed-command-default-hook org-babel-speed-command-hook)
  18420. "Hook for activating speed commands at strategic locations.
  18421. Hook functions are called in sequence until a valid handler is
  18422. found.
  18423. Each hook takes a single argument, a user-pressed command key
  18424. which is also a `self-insert-command' from the global map.
  18425. Within the hook, examine the cursor position and the command key
  18426. and return nil or a valid handler as appropriate. Handler could
  18427. be one of an interactive command, a function, or a form.
  18428. Set `org-use-speed-commands' to non-nil value to enable this
  18429. hook. The default setting is `org-speed-command-activate'."
  18430. :group 'org-structure
  18431. :version "24.1"
  18432. :type 'hook)
  18433. (defun org-self-insert-command (N)
  18434. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  18435. If the cursor is in a table looking at whitespace, the whitespace is
  18436. overwritten, and the table is not marked as requiring realignment."
  18437. (interactive "p")
  18438. (org-check-before-invisible-edit 'insert)
  18439. (cond
  18440. ((and org-use-speed-commands
  18441. (let ((kv (this-command-keys-vector)))
  18442. (setq org-speed-command
  18443. (run-hook-with-args-until-success
  18444. 'org-speed-command-hook
  18445. (make-string 1 (aref kv (1- (length kv))))))))
  18446. (cond
  18447. ((commandp org-speed-command)
  18448. (setq this-command org-speed-command)
  18449. (call-interactively org-speed-command))
  18450. ((functionp org-speed-command)
  18451. (funcall org-speed-command))
  18452. ((and org-speed-command (listp org-speed-command))
  18453. (eval org-speed-command))
  18454. (t (let (org-use-speed-commands)
  18455. (call-interactively 'org-self-insert-command)))))
  18456. ((and
  18457. (org-at-table-p)
  18458. (progn
  18459. ;; Check if we blank the field, and if that triggers align.
  18460. (and (featurep 'org-table) org-table-auto-blank-field
  18461. (memq last-command
  18462. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  18463. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  18464. ;; Got extra space, this field does not determine
  18465. ;; column width.
  18466. (let (org-table-may-need-update) (org-table-blank-field))
  18467. ;; No extra space, this field may determine column
  18468. ;; width.
  18469. (org-table-blank-field)))
  18470. t)
  18471. (eq N 1)
  18472. (looking-at "[^|\n]* \\( \\)|"))
  18473. ;; There is room for insertion without re-aligning the table.
  18474. (delete-region (match-beginning 1) (match-end 1))
  18475. (self-insert-command N))
  18476. (t
  18477. (setq org-table-may-need-update t)
  18478. (self-insert-command N)
  18479. (org-fix-tags-on-the-fly)
  18480. (when org-self-insert-cluster-for-undo
  18481. (if (not (eq last-command 'org-self-insert-command))
  18482. (setq org-self-insert-command-undo-counter 1)
  18483. (if (>= org-self-insert-command-undo-counter 20)
  18484. (setq org-self-insert-command-undo-counter 1)
  18485. (and (> org-self-insert-command-undo-counter 0)
  18486. buffer-undo-list (listp buffer-undo-list)
  18487. (not (cadr buffer-undo-list)) ; remove nil entry
  18488. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  18489. (setq org-self-insert-command-undo-counter
  18490. (1+ org-self-insert-command-undo-counter))))))))
  18491. (defun org-check-before-invisible-edit (kind)
  18492. "Check is editing if kind KIND would be dangerous with invisible text around.
  18493. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  18494. ;; First, try to get out of here as quickly as possible, to reduce overhead
  18495. (when (and org-catch-invisible-edits
  18496. (or (not (boundp 'visible-mode)) (not visible-mode))
  18497. (or (get-char-property (point) 'invisible)
  18498. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  18499. ;; OK, we need to take a closer look
  18500. (let* ((invisible-at-point (get-char-property (point) 'invisible))
  18501. (invisible-before-point (unless (bobp) (get-char-property
  18502. (1- (point)) 'invisible)))
  18503. (border-and-ok-direction
  18504. (or
  18505. ;; Check if we are acting predictably before invisible text
  18506. (and invisible-at-point (not invisible-before-point)
  18507. (memq kind '(insert delete-backward)))
  18508. ;; Check if we are acting predictably after invisible text
  18509. ;; This works not well, and I have turned it off. It seems
  18510. ;; better to always show and stop after invisible text.
  18511. ;; (and (not invisible-at-point) invisible-before-point
  18512. ;; (memq kind '(insert delete)))
  18513. )))
  18514. (when (or (memq invisible-at-point '(outline org-hide-block t))
  18515. (memq invisible-before-point '(outline org-hide-block t)))
  18516. (when (eq org-catch-invisible-edits 'error)
  18517. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  18518. (if (and org-custom-properties-overlays
  18519. (y-or-n-p "Display invisible properties in this buffer? "))
  18520. (org-toggle-custom-properties-visibility)
  18521. ;; Make the area visible
  18522. (save-excursion
  18523. (when invisible-before-point
  18524. (goto-char (previous-single-char-property-change
  18525. (point) 'invisible)))
  18526. (outline-show-subtree))
  18527. (cond
  18528. ((eq org-catch-invisible-edits 'show)
  18529. ;; That's it, we do the edit after showing
  18530. (message
  18531. "Unfolding invisible region around point before editing")
  18532. (sit-for 1))
  18533. ((and (eq org-catch-invisible-edits 'smart)
  18534. border-and-ok-direction)
  18535. (message "Unfolding invisible region around point before editing"))
  18536. (t
  18537. ;; Don't do the edit, make the user repeat it in full visibility
  18538. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  18539. (defun org-fix-tags-on-the-fly ()
  18540. "Align tags in headline at point.
  18541. Unlike to `org-set-tags', it ignores region and sorting."
  18542. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  18543. (org-at-heading-p))
  18544. (let ((org-ignore-region t)
  18545. (org-tags-sort-function nil))
  18546. (org-set-tags nil t))))
  18547. (defun org-delete-backward-char (N)
  18548. "Like `delete-backward-char', insert whitespace at field end in tables.
  18549. When deleting backwards, in tables this function will insert whitespace in
  18550. front of the next \"|\" separator, to keep the table aligned. The table will
  18551. still be marked for re-alignment if the field did fill the entire column,
  18552. because, in this case the deletion might narrow the column."
  18553. (interactive "p")
  18554. (save-match-data
  18555. (org-check-before-invisible-edit 'delete-backward)
  18556. (if (and (org-at-table-p)
  18557. (eq N 1)
  18558. (string-match "|" (buffer-substring (point-at-bol) (point)))
  18559. (looking-at ".*?|"))
  18560. (let ((pos (point))
  18561. (noalign (looking-at "[^|\n\r]* |"))
  18562. (c org-table-may-need-update))
  18563. (backward-delete-char N)
  18564. (unless overwrite-mode
  18565. (skip-chars-forward "^|")
  18566. (insert " ")
  18567. (goto-char (1- pos)))
  18568. ;; noalign: if there were two spaces at the end, this field
  18569. ;; does not determine the width of the column.
  18570. (when noalign (setq org-table-may-need-update c)))
  18571. (backward-delete-char N)
  18572. (org-fix-tags-on-the-fly))))
  18573. (defun org-delete-char (N)
  18574. "Like `delete-char', but insert whitespace at field end in tables.
  18575. When deleting characters, in tables this function will insert whitespace in
  18576. front of the next \"|\" separator, to keep the table aligned. The table will
  18577. still be marked for re-alignment if the field did fill the entire column,
  18578. because, in this case the deletion might narrow the column."
  18579. (interactive "p")
  18580. (save-match-data
  18581. (org-check-before-invisible-edit 'delete)
  18582. (if (and (org-at-table-p)
  18583. (not (bolp))
  18584. (not (= (char-after) ?|))
  18585. (eq N 1))
  18586. (if (looking-at ".*?|")
  18587. (let ((pos (point))
  18588. (noalign (looking-at "[^|\n\r]* |"))
  18589. (c org-table-may-need-update))
  18590. (replace-match
  18591. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18592. (goto-char pos)
  18593. ;; noalign: if there were two spaces at the end, this field
  18594. ;; does not determine the width of the column.
  18595. (when noalign (setq org-table-may-need-update c)))
  18596. (delete-char N))
  18597. (delete-char N)
  18598. (org-fix-tags-on-the-fly))))
  18599. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  18600. (put 'org-self-insert-command 'delete-selection
  18601. (lambda ()
  18602. (not (run-hook-with-args-until-success
  18603. 'self-insert-uses-region-functions))))
  18604. (put 'orgtbl-self-insert-command 'delete-selection
  18605. (lambda ()
  18606. (not (run-hook-with-args-until-success
  18607. 'self-insert-uses-region-functions))))
  18608. (put 'org-delete-char 'delete-selection 'supersede)
  18609. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18610. (put 'org-yank 'delete-selection 'yank)
  18611. ;; Make `flyspell-mode' delay after some commands
  18612. (put 'org-self-insert-command 'flyspell-delayed t)
  18613. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18614. (put 'org-delete-char 'flyspell-delayed t)
  18615. (put 'org-delete-backward-char 'flyspell-delayed t)
  18616. ;; Make pabbrev-mode expand after Org mode commands
  18617. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18618. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18619. (defun org-remap (map &rest commands)
  18620. "In MAP, remap the functions given in COMMANDS.
  18621. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  18622. (let (new old)
  18623. (while commands
  18624. (setq old (pop commands) new (pop commands))
  18625. (org-defkey map (vector 'remap old) new))))
  18626. (defun org-transpose-words ()
  18627. "Transpose words for Org.
  18628. This uses the `org-mode-transpose-word-syntax-table' syntax
  18629. table, which interprets characters in `org-emphasis-alist' as
  18630. word constituents."
  18631. (interactive)
  18632. (with-syntax-table org-mode-transpose-word-syntax-table
  18633. (call-interactively 'transpose-words)))
  18634. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18635. (when (eq org-enable-table-editor 'optimized)
  18636. ;; If the user wants maximum table support, we need to hijack
  18637. ;; some standard editing functions
  18638. (org-remap org-mode-map
  18639. 'self-insert-command 'org-self-insert-command
  18640. 'delete-char 'org-delete-char
  18641. 'delete-backward-char 'org-delete-backward-char)
  18642. (org-defkey org-mode-map "|" 'org-force-self-insert))
  18643. (defvar org-ctrl-c-ctrl-c-hook nil
  18644. "Hook for functions attaching themselves to `C-c C-c'.
  18645. This can be used to add additional functionality to the C-c C-c
  18646. key which executes context-dependent commands. This hook is run
  18647. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18648. run after the last test.
  18649. Each function will be called with no arguments. The function
  18650. must check if the context is appropriate for it to act. If yes,
  18651. it should do its thing and then return a non-nil value. If the
  18652. context is wrong, just do nothing and return nil.")
  18653. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18654. "Hook for functions attaching themselves to `C-c C-c'.
  18655. This can be used to add additional functionality to the C-c C-c
  18656. key which executes context-dependent commands. This hook is run
  18657. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18658. before the first test.
  18659. Each function will be called with no arguments. The function
  18660. must check if the context is appropriate for it to act. If yes,
  18661. it should do its thing and then return a non-nil value. If the
  18662. context is wrong, just do nothing and return nil.")
  18663. (defvar org-tab-first-hook nil
  18664. "Hook for functions to attach themselves to TAB.
  18665. See `org-ctrl-c-ctrl-c-hook' for more information.
  18666. This hook runs as the first action when TAB is pressed, even before
  18667. `org-cycle' messes around with the `outline-regexp' to cater for
  18668. inline tasks and plain list item folding.
  18669. If any function in this hook returns t, any other actions that
  18670. would have been caused by TAB (such as table field motion or visibility
  18671. cycling) will not occur.")
  18672. (defvar org-tab-after-check-for-table-hook nil
  18673. "Hook for functions to attach themselves to TAB.
  18674. See `org-ctrl-c-ctrl-c-hook' for more information.
  18675. This hook runs after it has been established that the cursor is not in a
  18676. table, but before checking if the cursor is in a headline or if global cycling
  18677. should be done.
  18678. If any function in this hook returns t, not other actions like visibility
  18679. cycling will be done.")
  18680. (defvar org-tab-after-check-for-cycling-hook nil
  18681. "Hook for functions to attach themselves to TAB.
  18682. See `org-ctrl-c-ctrl-c-hook' for more information.
  18683. This hook runs after it has been established that not table field motion and
  18684. not visibility should be done because of current context. This is probably
  18685. the place where a package like yasnippets can hook in.")
  18686. (defvar org-tab-before-tab-emulation-hook nil
  18687. "Hook for functions to attach themselves to TAB.
  18688. See `org-ctrl-c-ctrl-c-hook' for more information.
  18689. This hook runs after every other options for TAB have been exhausted, but
  18690. before indentation and \t insertion takes place.")
  18691. (defvar org-metaleft-hook nil
  18692. "Hook for functions attaching themselves to `M-left'.
  18693. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18694. (defvar org-metaright-hook nil
  18695. "Hook for functions attaching themselves to `M-right'.
  18696. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18697. (defvar org-metaup-hook nil
  18698. "Hook for functions attaching themselves to `M-up'.
  18699. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18700. (defvar org-metadown-hook nil
  18701. "Hook for functions attaching themselves to `M-down'.
  18702. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18703. (defvar org-shiftmetaleft-hook nil
  18704. "Hook for functions attaching themselves to `M-S-left'.
  18705. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18706. (defvar org-shiftmetaright-hook nil
  18707. "Hook for functions attaching themselves to `M-S-right'.
  18708. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18709. (defvar org-shiftmetaup-hook nil
  18710. "Hook for functions attaching themselves to `M-S-up'.
  18711. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18712. (defvar org-shiftmetadown-hook nil
  18713. "Hook for functions attaching themselves to `M-S-down'.
  18714. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18715. (defvar org-metareturn-hook nil
  18716. "Hook for functions attaching themselves to `M-RET'.
  18717. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18718. (defvar org-shiftup-hook nil
  18719. "Hook for functions attaching themselves to `S-up'.
  18720. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18721. (defvar org-shiftup-final-hook nil
  18722. "Hook for functions attaching themselves to `S-up'.
  18723. This one runs after all other options except shift-select have been excluded.
  18724. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18725. (defvar org-shiftdown-hook nil
  18726. "Hook for functions attaching themselves to `S-down'.
  18727. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18728. (defvar org-shiftdown-final-hook nil
  18729. "Hook for functions attaching themselves to `S-down'.
  18730. This one runs after all other options except shift-select have been excluded.
  18731. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18732. (defvar org-shiftleft-hook nil
  18733. "Hook for functions attaching themselves to `S-left'.
  18734. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18735. (defvar org-shiftleft-final-hook nil
  18736. "Hook for functions attaching themselves to `S-left'.
  18737. This one runs after all other options except shift-select have been excluded.
  18738. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18739. (defvar org-shiftright-hook nil
  18740. "Hook for functions attaching themselves to `S-right'.
  18741. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18742. (defvar org-shiftright-final-hook nil
  18743. "Hook for functions attaching themselves to `S-right'.
  18744. This one runs after all other options except shift-select have been excluded.
  18745. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18746. (defun org-modifier-cursor-error ()
  18747. "Throw an error, a modified cursor command was applied in wrong context."
  18748. (user-error "This command is active in special context like tables, headlines or items"))
  18749. (defun org-shiftselect-error ()
  18750. "Throw an error because Shift-Cursor command was applied in wrong context."
  18751. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18752. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  18753. (user-error "This command works only in special context like headlines or timestamps")))
  18754. (defun org-call-for-shift-select (cmd)
  18755. (let ((this-command-keys-shift-translated t))
  18756. (call-interactively cmd)))
  18757. (defun org-shifttab (&optional arg)
  18758. "Global visibility cycling or move to previous table field.
  18759. Call `org-table-previous-field' within a table.
  18760. When ARG is nil, cycle globally through visibility states.
  18761. When ARG is a numeric prefix, show contents of this level."
  18762. (interactive "P")
  18763. (cond
  18764. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18765. ((integerp arg)
  18766. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18767. (message "Content view to level: %d" arg)
  18768. (org-content (prefix-numeric-value arg2))
  18769. (org-cycle-show-empty-lines t)
  18770. (setq org-cycle-global-status 'overview)))
  18771. (t (call-interactively 'org-global-cycle))))
  18772. (defun org-shiftmetaleft ()
  18773. "Promote subtree or delete table column.
  18774. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18775. `org-table-delete-column', depending on context. See the
  18776. individual commands for more information."
  18777. (interactive)
  18778. (cond
  18779. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18780. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18781. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18782. ((if (not (org-region-active-p)) (org-at-item-p)
  18783. (save-excursion (goto-char (region-beginning))
  18784. (org-at-item-p)))
  18785. (call-interactively 'org-outdent-item-tree))
  18786. (t (org-modifier-cursor-error))))
  18787. (defun org-shiftmetaright ()
  18788. "Demote subtree or insert table column.
  18789. Calls `org-demote-subtree', `org-indent-item-tree', or
  18790. `org-table-insert-column', depending on context. See the
  18791. individual commands for more information."
  18792. (interactive)
  18793. (cond
  18794. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18795. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18796. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18797. ((if (not (org-region-active-p)) (org-at-item-p)
  18798. (save-excursion (goto-char (region-beginning))
  18799. (org-at-item-p)))
  18800. (call-interactively 'org-indent-item-tree))
  18801. (t (org-modifier-cursor-error))))
  18802. (defun org-shiftmetaup (&optional _arg)
  18803. "Drag the line at point up.
  18804. In a table, kill the current row.
  18805. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18806. but also adjust the previous clocked item in the clock history.
  18807. Everywhere else, drag the line at point up."
  18808. (interactive "P")
  18809. (cond
  18810. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18811. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18812. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18813. (call-interactively 'org-timestamp-up)))
  18814. (t (call-interactively 'org-drag-line-backward))))
  18815. (defun org-shiftmetadown (&optional _arg)
  18816. "Drag the line at point down.
  18817. In a table, insert an empty row at the current line.
  18818. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18819. but also adjust the previous clocked item in the clock history.
  18820. Everywhere else, drag the line at point down."
  18821. (interactive "P")
  18822. (cond
  18823. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18824. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18825. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18826. (call-interactively 'org-timestamp-down)))
  18827. (t (call-interactively 'org-drag-line-forward))))
  18828. (defsubst org-hidden-tree-error ()
  18829. (user-error
  18830. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18831. (defun org-metaleft (&optional _arg)
  18832. "Promote heading, list item at point or move table column left.
  18833. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18834. depending on context. With no specific context, calls the Emacs
  18835. default `backward-word'. See the individual commands for more
  18836. information.
  18837. This function runs the hook `org-metaleft-hook' as a first step,
  18838. and returns at first non-nil value."
  18839. (interactive "P")
  18840. (cond
  18841. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18842. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18843. ((org-with-limited-levels
  18844. (or (org-at-heading-p)
  18845. (and (org-region-active-p)
  18846. (save-excursion
  18847. (goto-char (region-beginning))
  18848. (org-at-heading-p)))))
  18849. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18850. (call-interactively 'org-do-promote))
  18851. ;; At an inline task.
  18852. ((org-at-heading-p)
  18853. (call-interactively 'org-inlinetask-promote))
  18854. ((or (org-at-item-p)
  18855. (and (org-region-active-p)
  18856. (save-excursion
  18857. (goto-char (region-beginning))
  18858. (org-at-item-p))))
  18859. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18860. (call-interactively 'org-outdent-item))
  18861. (t (call-interactively 'backward-word))))
  18862. (defun org-metaright (&optional _arg)
  18863. "Demote heading, list item at point or move table column right.
  18864. In front of a drawer or a block keyword, indent it correctly.
  18865. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18866. `org-indent-drawer' or `org-indent-block' depending on context.
  18867. With no specific context, calls the Emacs default `forward-word'.
  18868. See the individual commands for more information.
  18869. This function runs the hook `org-metaright-hook' as a first step,
  18870. and returns at first non-nil value."
  18871. (interactive "P")
  18872. (cond
  18873. ((run-hook-with-args-until-success 'org-metaright-hook))
  18874. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18875. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18876. ((org-at-block-p) (call-interactively 'org-indent-block))
  18877. ((org-with-limited-levels
  18878. (or (org-at-heading-p)
  18879. (and (org-region-active-p)
  18880. (save-excursion
  18881. (goto-char (region-beginning))
  18882. (org-at-heading-p)))))
  18883. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18884. (call-interactively 'org-do-demote))
  18885. ;; At an inline task.
  18886. ((org-at-heading-p)
  18887. (call-interactively 'org-inlinetask-demote))
  18888. ((or (org-at-item-p)
  18889. (and (org-region-active-p)
  18890. (save-excursion
  18891. (goto-char (region-beginning))
  18892. (org-at-item-p))))
  18893. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18894. (call-interactively 'org-indent-item))
  18895. (t (call-interactively 'forward-word))))
  18896. (defun org-check-for-hidden (what)
  18897. "Check if there are hidden headlines/items in the current visual line.
  18898. WHAT can be either `headlines' or `items'. If the current line is
  18899. an outline or item heading and it has a folded subtree below it,
  18900. this function returns t, nil otherwise."
  18901. (let ((re (cond
  18902. ((eq what 'headlines) org-outline-regexp-bol)
  18903. ((eq what 'items) (org-item-beginning-re))
  18904. (t (error "This should not happen"))))
  18905. beg end)
  18906. (save-excursion
  18907. (catch 'exit
  18908. (unless (org-region-active-p)
  18909. (setq beg (point-at-bol))
  18910. (beginning-of-line 2)
  18911. (while (and (not (eobp)) ;; this is like `next-line'
  18912. (get-char-property (1- (point)) 'invisible))
  18913. (beginning-of-line 2))
  18914. (setq end (point))
  18915. (goto-char beg)
  18916. (goto-char (point-at-eol))
  18917. (setq end (max end (point)))
  18918. (while (re-search-forward re end t)
  18919. (when (get-char-property (match-beginning 0) 'invisible)
  18920. (throw 'exit t))))
  18921. nil))))
  18922. (defun org-metaup (&optional _arg)
  18923. "Move subtree up or move table row up.
  18924. Calls `org-move-subtree-up' or `org-table-move-row' or
  18925. `org-move-item-up', depending on context. See the individual commands
  18926. for more information."
  18927. (interactive "P")
  18928. (cond
  18929. ((run-hook-with-args-until-success 'org-metaup-hook))
  18930. ((org-region-active-p)
  18931. (let* ((a (min (region-beginning) (region-end)))
  18932. (b (1- (max (region-beginning) (region-end))))
  18933. (c (save-excursion (goto-char a)
  18934. (move-beginning-of-line 0)))
  18935. (d (save-excursion (goto-char a)
  18936. (move-end-of-line 0) (point))))
  18937. (transpose-regions a b c d)
  18938. (goto-char c)))
  18939. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18940. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18941. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18942. (t (org-drag-element-backward))))
  18943. (defun org-metadown (&optional _arg)
  18944. "Move subtree down or move table row down.
  18945. Calls `org-move-subtree-down' or `org-table-move-row' or
  18946. `org-move-item-down', depending on context. See the individual
  18947. commands for more information."
  18948. (interactive "P")
  18949. (cond
  18950. ((run-hook-with-args-until-success 'org-metadown-hook))
  18951. ((org-region-active-p)
  18952. (let* ((a (min (region-beginning) (region-end)))
  18953. (b (max (region-beginning) (region-end)))
  18954. (c (save-excursion (goto-char b)
  18955. (move-beginning-of-line 1)))
  18956. (d (save-excursion (goto-char b)
  18957. (move-end-of-line 1) (1+ (point)))))
  18958. (transpose-regions a b c d)
  18959. (goto-char d)))
  18960. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18961. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18962. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18963. (t (org-drag-element-forward))))
  18964. (defun org-shiftup (&optional arg)
  18965. "Increase item in timestamp or increase priority of current headline.
  18966. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18967. depending on context. See the individual commands for more information."
  18968. (interactive "P")
  18969. (cond
  18970. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18971. ((and org-support-shift-select (org-region-active-p))
  18972. (org-call-for-shift-select 'previous-line))
  18973. ((org-at-timestamp-p t)
  18974. (call-interactively (if org-edit-timestamp-down-means-later
  18975. 'org-timestamp-down 'org-timestamp-up)))
  18976. ((and (not (eq org-support-shift-select 'always))
  18977. org-enable-priority-commands
  18978. (org-at-heading-p))
  18979. (call-interactively 'org-priority-up))
  18980. ((and (not org-support-shift-select) (org-at-item-p))
  18981. (call-interactively 'org-previous-item))
  18982. ((org-clocktable-try-shift 'up arg))
  18983. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18984. (org-support-shift-select
  18985. (org-call-for-shift-select 'previous-line))
  18986. (t (org-shiftselect-error))))
  18987. (defun org-shiftdown (&optional arg)
  18988. "Decrease item in timestamp or decrease priority of current headline.
  18989. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18990. depending on context. See the individual commands for more information."
  18991. (interactive "P")
  18992. (cond
  18993. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18994. ((and org-support-shift-select (org-region-active-p))
  18995. (org-call-for-shift-select 'next-line))
  18996. ((org-at-timestamp-p t)
  18997. (call-interactively (if org-edit-timestamp-down-means-later
  18998. 'org-timestamp-up 'org-timestamp-down)))
  18999. ((and (not (eq org-support-shift-select 'always))
  19000. org-enable-priority-commands
  19001. (org-at-heading-p))
  19002. (call-interactively 'org-priority-down))
  19003. ((and (not org-support-shift-select) (org-at-item-p))
  19004. (call-interactively 'org-next-item))
  19005. ((org-clocktable-try-shift 'down arg))
  19006. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  19007. (org-support-shift-select
  19008. (org-call-for-shift-select 'next-line))
  19009. (t (org-shiftselect-error))))
  19010. (defun org-shiftright (&optional arg)
  19011. "Cycle the thing at point or in the current line, depending on context.
  19012. Depending on context, this does one of the following:
  19013. - switch a timestamp at point one day into the future
  19014. - on a headline, switch to the next TODO keyword.
  19015. - on an item, switch entire list to the next bullet type
  19016. - on a property line, switch to the next allowed value
  19017. - on a clocktable definition line, move time block into the future"
  19018. (interactive "P")
  19019. (cond
  19020. ((run-hook-with-args-until-success 'org-shiftright-hook))
  19021. ((and org-support-shift-select (org-region-active-p))
  19022. (org-call-for-shift-select 'forward-char))
  19023. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
  19024. ((and (not (eq org-support-shift-select 'always))
  19025. (org-at-heading-p))
  19026. (let ((org-inhibit-logging
  19027. (not org-treat-S-cursor-todo-selection-as-state-change))
  19028. (org-inhibit-blocking
  19029. (not org-treat-S-cursor-todo-selection-as-state-change)))
  19030. (org-call-with-arg 'org-todo 'right)))
  19031. ((or (and org-support-shift-select
  19032. (not (eq org-support-shift-select 'always))
  19033. (org-at-item-bullet-p))
  19034. (and (not org-support-shift-select) (org-at-item-p)))
  19035. (org-call-with-arg 'org-cycle-list-bullet nil))
  19036. ((and (not (eq org-support-shift-select 'always))
  19037. (org-at-property-p))
  19038. (call-interactively 'org-property-next-allowed-value))
  19039. ((org-clocktable-try-shift 'right arg))
  19040. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  19041. (org-support-shift-select
  19042. (org-call-for-shift-select 'forward-char))
  19043. (t (org-shiftselect-error))))
  19044. (defun org-shiftleft (&optional arg)
  19045. "Cycle the thing at point or in the current line, depending on context.
  19046. Depending on context, this does one of the following:
  19047. - switch a timestamp at point one day into the past
  19048. - on a headline, switch to the previous TODO keyword.
  19049. - on an item, switch entire list to the previous bullet type
  19050. - on a property line, switch to the previous allowed value
  19051. - on a clocktable definition line, move time block into the past"
  19052. (interactive "P")
  19053. (cond
  19054. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  19055. ((and org-support-shift-select (org-region-active-p))
  19056. (org-call-for-shift-select 'backward-char))
  19057. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
  19058. ((and (not (eq org-support-shift-select 'always))
  19059. (org-at-heading-p))
  19060. (let ((org-inhibit-logging
  19061. (not org-treat-S-cursor-todo-selection-as-state-change))
  19062. (org-inhibit-blocking
  19063. (not org-treat-S-cursor-todo-selection-as-state-change)))
  19064. (org-call-with-arg 'org-todo 'left)))
  19065. ((or (and org-support-shift-select
  19066. (not (eq org-support-shift-select 'always))
  19067. (org-at-item-bullet-p))
  19068. (and (not org-support-shift-select) (org-at-item-p)))
  19069. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  19070. ((and (not (eq org-support-shift-select 'always))
  19071. (org-at-property-p))
  19072. (call-interactively 'org-property-previous-allowed-value))
  19073. ((org-clocktable-try-shift 'left arg))
  19074. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  19075. (org-support-shift-select
  19076. (org-call-for-shift-select 'backward-char))
  19077. (t (org-shiftselect-error))))
  19078. (defun org-shiftcontrolright ()
  19079. "Switch to next TODO set."
  19080. (interactive)
  19081. (cond
  19082. ((and org-support-shift-select (org-region-active-p))
  19083. (org-call-for-shift-select 'forward-word))
  19084. ((and (not (eq org-support-shift-select 'always))
  19085. (org-at-heading-p))
  19086. (org-call-with-arg 'org-todo 'nextset))
  19087. (org-support-shift-select
  19088. (org-call-for-shift-select 'forward-word))
  19089. (t (org-shiftselect-error))))
  19090. (defun org-shiftcontrolleft ()
  19091. "Switch to previous TODO set."
  19092. (interactive)
  19093. (cond
  19094. ((and org-support-shift-select (org-region-active-p))
  19095. (org-call-for-shift-select 'backward-word))
  19096. ((and (not (eq org-support-shift-select 'always))
  19097. (org-at-heading-p))
  19098. (org-call-with-arg 'org-todo 'previousset))
  19099. (org-support-shift-select
  19100. (org-call-for-shift-select 'backward-word))
  19101. (t (org-shiftselect-error))))
  19102. (defun org-shiftcontrolup (&optional n)
  19103. "Change timestamps synchronously up in CLOCK log lines.
  19104. Optional argument N tells to change by that many units."
  19105. (interactive "P")
  19106. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19107. (let (org-support-shift-select)
  19108. (org-clock-timestamps-up n))
  19109. (user-error "Not at a clock log")))
  19110. (defun org-shiftcontroldown (&optional n)
  19111. "Change timestamps synchronously down in CLOCK log lines.
  19112. Optional argument N tells to change by that many units."
  19113. (interactive "P")
  19114. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19115. (let (org-support-shift-select)
  19116. (org-clock-timestamps-down n))
  19117. (user-error "Not at a clock log")))
  19118. (defun org-increase-number-at-point (&optional inc)
  19119. "Increment the number at point.
  19120. With an optional prefix numeric argument INC, increment using
  19121. this numeric value."
  19122. (interactive "p")
  19123. (if (not (number-at-point))
  19124. (user-error "Not on a number")
  19125. (unless inc (setq inc 1))
  19126. (let ((pos (point))
  19127. (beg (skip-chars-backward "-+^/*0-9eE."))
  19128. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  19129. (setq nap (buffer-substring-no-properties
  19130. (+ pos beg) (+ pos beg end)))
  19131. (delete-region (+ pos beg) (+ pos beg end))
  19132. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  19133. (when (org-at-table-p)
  19134. (org-table-align)
  19135. (org-table-end-of-field 1))))
  19136. (defun org-decrease-number-at-point (&optional inc)
  19137. "Decrement the number at point.
  19138. With an optional prefix numeric argument INC, decrement using
  19139. this numeric value."
  19140. (interactive "p")
  19141. (org-increase-number-at-point (- (or inc 1))))
  19142. (defun org-ctrl-c-ret ()
  19143. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  19144. (interactive)
  19145. (cond
  19146. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  19147. (t (call-interactively 'org-insert-heading))))
  19148. (defun org-find-visible ()
  19149. (let ((s (point)))
  19150. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19151. (get-char-property s 'invisible)))
  19152. s))
  19153. (defun org-find-invisible ()
  19154. (let ((s (point)))
  19155. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19156. (not (get-char-property s 'invisible))))
  19157. s))
  19158. (defun org-copy-visible (beg end)
  19159. "Copy the visible parts of the region."
  19160. (interactive "r")
  19161. (let (snippets s)
  19162. (save-excursion
  19163. (save-restriction
  19164. (narrow-to-region beg end)
  19165. (setq s (goto-char (point-min)))
  19166. (while (not (= (point) (point-max)))
  19167. (goto-char (org-find-invisible))
  19168. (push (buffer-substring s (point)) snippets)
  19169. (setq s (goto-char (org-find-visible))))))
  19170. (kill-new (apply 'concat (nreverse snippets)))))
  19171. (defun org-copy-special ()
  19172. "Copy region in table or copy current subtree.
  19173. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  19174. context. See the individual commands for more information."
  19175. (interactive)
  19176. (call-interactively
  19177. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  19178. (defun org-cut-special ()
  19179. "Cut region in table or cut current subtree.
  19180. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  19181. context. See the individual commands for more information."
  19182. (interactive)
  19183. (call-interactively
  19184. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  19185. (defun org-paste-special (arg)
  19186. "Paste rectangular region into table, or past subtree relative to level.
  19187. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  19188. See the individual commands for more information."
  19189. (interactive "P")
  19190. (if (org-at-table-p)
  19191. (org-table-paste-rectangle)
  19192. (org-paste-subtree arg)))
  19193. (defun org-edit-special (&optional arg)
  19194. "Call a special editor for the element at point.
  19195. When at a table, call the formula editor with `org-table-edit-formulas'.
  19196. When in a source code block, call `org-edit-src-code'.
  19197. When in a fixed-width region, call `org-edit-fixed-width-region'.
  19198. When in an export block, call `org-edit-export-block'.
  19199. When at an #+INCLUDE keyword, visit the included file.
  19200. When at a footnote reference, call `org-edit-footnote-reference'
  19201. On a link, call `ffap' to visit the link at point.
  19202. Otherwise, return a user error."
  19203. (interactive "P")
  19204. (let ((element (org-element-at-point)))
  19205. (barf-if-buffer-read-only)
  19206. (pcase (org-element-type element)
  19207. (`src-block
  19208. (if (not arg) (org-edit-src-code)
  19209. (let* ((info (org-babel-get-src-block-info))
  19210. (lang (nth 0 info))
  19211. (params (nth 2 info))
  19212. (session (cdr (assq :session params))))
  19213. (if (not session) (org-edit-src-code)
  19214. ;; At a src-block with a session and function called with
  19215. ;; an ARG: switch to the buffer related to the inferior
  19216. ;; process.
  19217. (switch-to-buffer
  19218. (funcall (intern (concat "org-babel-prep-session:" lang))
  19219. session params))))))
  19220. (`keyword
  19221. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  19222. (org-open-link-from-string
  19223. (format "[[%s]]"
  19224. (expand-file-name
  19225. (let ((value (org-element-property :value element)))
  19226. (cond ((not (org-string-nw-p value))
  19227. (user-error "No file to edit"))
  19228. ((string-match "\\`\"\\(.*?\\)\"" value)
  19229. (match-string 1 value))
  19230. ((string-match "\\`[^ \t\"]\\S-*" value)
  19231. (match-string 0 value))
  19232. (t (user-error "No valid file specified")))))))
  19233. (user-error "No special environment to edit here")))
  19234. (`table
  19235. (if (eq (org-element-property :type element) 'table.el)
  19236. (org-edit-table.el)
  19237. (call-interactively 'org-table-edit-formulas)))
  19238. ;; Only Org tables contain `table-row' type elements.
  19239. (`table-row (call-interactively 'org-table-edit-formulas))
  19240. (`example-block (org-edit-src-code))
  19241. (`export-block (org-edit-export-block))
  19242. (`fixed-width (org-edit-fixed-width-region))
  19243. (_
  19244. ;; No notable element at point. Though, we may be at a link or
  19245. ;; a footnote reference, which are objects. Thus, scan deeper.
  19246. (let ((context (org-element-context element)))
  19247. (pcase (org-element-type context)
  19248. (`footnote-reference (org-edit-footnote-reference))
  19249. (`inline-src-block (org-edit-inline-src-code))
  19250. (`link (call-interactively #'ffap))
  19251. (_ (user-error "No special environment to edit here"))))))))
  19252. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  19253. (defun org-ctrl-c-ctrl-c (&optional arg)
  19254. "Set tags in headline, or update according to changed information at point.
  19255. This command does many different things, depending on context:
  19256. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  19257. this is what we do.
  19258. - If the cursor is on a statistics cookie, update it.
  19259. - If the cursor is in a headline, prompt for tags and insert them
  19260. into the current line, aligned to `org-tags-column'. When called
  19261. with prefix arg, realign all tags in the current buffer.
  19262. - If the cursor is in one of the special #+KEYWORD lines, this
  19263. triggers scanning the buffer for these lines and updating the
  19264. information.
  19265. - If the cursor is inside a table, realign the table. This command
  19266. works even if the automatic table editor has been turned off.
  19267. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  19268. the entire table.
  19269. - If the cursor is at a footnote reference or definition, jump to
  19270. the corresponding definition or references, respectively.
  19271. - If the cursor is a the beginning of a dynamic block, update it.
  19272. - If the current buffer is a capture buffer, close note and file it.
  19273. - If the cursor is on a <<<target>>>, update radio targets and
  19274. corresponding links in this buffer.
  19275. - If the cursor is on a numbered item in a plain list, renumber the
  19276. ordered list.
  19277. - If the cursor is on a checkbox, toggle it.
  19278. - If the cursor is on a code block, evaluate it. The variable
  19279. `org-confirm-babel-evaluate' can be used to control prompting
  19280. before code block evaluation, by default every code block
  19281. evaluation requires confirmation. Code block evaluation can be
  19282. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  19283. (interactive "P")
  19284. (cond
  19285. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  19286. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  19287. (org-remove-occur-highlights)
  19288. (message "Temporary highlights/overlays removed from current buffer"))
  19289. ((and (local-variable-p 'org-finish-function)
  19290. (fboundp org-finish-function))
  19291. (funcall org-finish-function))
  19292. ((org-babel-hash-at-point))
  19293. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  19294. ((save-excursion (beginning-of-line) (looking-at-p "[ \t]*$"))
  19295. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19296. (user-error
  19297. (substitute-command-keys
  19298. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  19299. (t
  19300. (let* ((context
  19301. (org-element-lineage
  19302. (org-element-context)
  19303. ;; Limit to supported contexts.
  19304. '(babel-call clock dynamic-block footnote-definition
  19305. footnote-reference inline-babel-call inline-src-block
  19306. item keyword node-property paragraph plain-list
  19307. property-drawer radio-target src-block
  19308. statistics-cookie table table-cell table-row
  19309. timestamp)
  19310. t))
  19311. (type (org-element-type context)))
  19312. ;; For convenience: at the first line of a paragraph on the same
  19313. ;; line as an item, apply function on that item instead.
  19314. (when (eq type 'paragraph)
  19315. (let ((parent (org-element-property :parent context)))
  19316. (when (and (eq (org-element-type parent) 'item)
  19317. (= (line-beginning-position)
  19318. (org-element-property :begin parent)))
  19319. (setq context parent)
  19320. (setq type 'item))))
  19321. ;; Act according to type of element or object at point.
  19322. (pcase type
  19323. ((or `babel-call `inline-babel-call)
  19324. (let ((info (org-babel-lob-get-info context)))
  19325. (when info (org-babel-execute-src-block nil info))))
  19326. (`clock (org-clock-update-time-maybe))
  19327. (`dynamic-block
  19328. (save-excursion
  19329. (goto-char (org-element-property :post-affiliated context))
  19330. (org-update-dblock)))
  19331. (`footnote-definition
  19332. (goto-char (org-element-property :post-affiliated context))
  19333. (call-interactively 'org-footnote-action))
  19334. (`footnote-reference (call-interactively #'org-footnote-action))
  19335. ((or `headline `inlinetask)
  19336. (save-excursion (goto-char (org-element-property :begin context))
  19337. (call-interactively #'org-set-tags)))
  19338. ((or `inline-src-block `src-block)
  19339. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  19340. (org-babel-eval-wipe-error-buffer)
  19341. (org-babel-execute-src-block
  19342. current-prefix-arg (org-babel-get-src-block-info nil context))))
  19343. (`item
  19344. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  19345. ;; unconditionally, whereas `C-u' will toggle its presence.
  19346. ;; Without a universal argument, if the item has a checkbox,
  19347. ;; toggle it. Otherwise repair the list.
  19348. (let* ((box (org-element-property :checkbox context))
  19349. (struct (org-element-property :structure context))
  19350. (old-struct (copy-tree struct))
  19351. (parents (org-list-parents-alist struct))
  19352. (prevs (org-list-prevs-alist struct))
  19353. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  19354. (org-list-set-checkbox
  19355. (org-element-property :begin context) struct
  19356. (cond ((equal arg '(16)) "[-]")
  19357. ((and (not box) (equal arg '(4))) "[ ]")
  19358. ((or (not box) (equal arg '(4))) nil)
  19359. ((eq box 'on) "[ ]")
  19360. (t "[X]")))
  19361. ;; Mimic `org-list-write-struct' but with grabbing a return
  19362. ;; value from `org-list-struct-fix-box'.
  19363. (org-list-struct-fix-ind struct parents 2)
  19364. (org-list-struct-fix-item-end struct)
  19365. (org-list-struct-fix-bul struct prevs)
  19366. (org-list-struct-fix-ind struct parents)
  19367. (let ((block-item
  19368. (org-list-struct-fix-box struct parents prevs orderedp)))
  19369. (if (and box (equal struct old-struct))
  19370. (if (equal arg '(16))
  19371. (message "Checkboxes already reset")
  19372. (user-error "Cannot toggle this checkbox: %s"
  19373. (if (eq box 'on)
  19374. "all subitems checked"
  19375. "unchecked subitems")))
  19376. (org-list-struct-apply-struct struct old-struct)
  19377. (org-update-checkbox-count-maybe))
  19378. (when block-item
  19379. (message "Checkboxes were removed due to empty box at line %d"
  19380. (org-current-line block-item))))))
  19381. (`keyword
  19382. (let ((org-inhibit-startup-visibility-stuff t)
  19383. (org-startup-align-all-tables nil))
  19384. (when (boundp 'org-table-coordinate-overlays)
  19385. (mapc #'delete-overlay org-table-coordinate-overlays)
  19386. (setq org-table-coordinate-overlays nil))
  19387. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  19388. (message "Local setup has been refreshed"))
  19389. (`plain-list
  19390. ;; At a plain list, with a double C-u argument, set
  19391. ;; checkboxes of each item to "[-]", whereas a single one
  19392. ;; will toggle their presence according to the state of the
  19393. ;; first item in the list. Without an argument, repair the
  19394. ;; list.
  19395. (let* ((begin (org-element-property :contents-begin context))
  19396. (beginm (move-marker (make-marker) begin))
  19397. (struct (org-element-property :structure context))
  19398. (old-struct (copy-tree struct))
  19399. (first-box (save-excursion
  19400. (goto-char begin)
  19401. (looking-at org-list-full-item-re)
  19402. (match-string-no-properties 3)))
  19403. (new-box (cond ((equal arg '(16)) "[-]")
  19404. ((equal arg '(4)) (unless first-box "[ ]"))
  19405. ((equal first-box "[X]") "[ ]")
  19406. (t "[X]"))))
  19407. (cond
  19408. (arg
  19409. (dolist (pos
  19410. (org-list-get-all-items
  19411. begin struct (org-list-prevs-alist struct)))
  19412. (org-list-set-checkbox pos struct new-box)))
  19413. ((and first-box (eq (point) begin))
  19414. ;; For convenience, when point is at bol on the first
  19415. ;; item of the list and no argument is provided, simply
  19416. ;; toggle checkbox of that item, if any.
  19417. (org-list-set-checkbox begin struct new-box)))
  19418. (org-list-write-struct
  19419. struct (org-list-parents-alist struct) old-struct)
  19420. (org-update-checkbox-count-maybe)
  19421. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  19422. ((or `property-drawer `node-property)
  19423. (call-interactively #'org-property-action))
  19424. (`radio-target
  19425. (call-interactively #'org-update-radio-target-regexp))
  19426. (`statistics-cookie
  19427. (call-interactively #'org-update-statistics-cookies))
  19428. ((or `table `table-cell `table-row)
  19429. ;; At a table, recalculate every field and align it. Also
  19430. ;; send the table if necessary. If the table has
  19431. ;; a `table.el' type, just give up. At a table row or cell,
  19432. ;; maybe recalculate line but always align table.
  19433. (if (eq (org-element-property :type context) 'table.el)
  19434. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  19435. Use `\\[org-edit-special]' to edit table.el tables"))
  19436. (let ((org-enable-table-editor t))
  19437. (if (or (eq type 'table)
  19438. ;; Check if point is at a TBLFM line.
  19439. (and (eq type 'table-row)
  19440. (= (point) (org-element-property :end context))))
  19441. (save-excursion
  19442. (if (org-at-TBLFM-p)
  19443. (progn (require 'org-table)
  19444. (org-table-calc-current-TBLFM))
  19445. (goto-char (org-element-property :contents-begin context))
  19446. (org-call-with-arg 'org-table-recalculate (or arg t))
  19447. (orgtbl-send-table 'maybe)))
  19448. (org-table-maybe-eval-formula)
  19449. (cond (arg (call-interactively #'org-table-recalculate))
  19450. ((org-table-maybe-recalculate-line))
  19451. (t (org-table-align)))))))
  19452. (`timestamp (org-timestamp-change 0 'day))
  19453. ((and `nil (guard (org-at-heading-p)))
  19454. ;; When point is on an unsupported object type, we can miss
  19455. ;; the fact that it also is at a heading. Handle it here.
  19456. (call-interactively #'org-set-tags))
  19457. ((guard
  19458. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  19459. (_
  19460. (user-error
  19461. (substitute-command-keys
  19462. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  19463. (defun org-mode-restart ()
  19464. (interactive)
  19465. (let ((indent-status (bound-and-true-p org-indent-mode)))
  19466. (funcall major-mode)
  19467. (hack-local-variables)
  19468. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  19469. (org-indent-mode -1)))
  19470. (message "%s restarted" major-mode))
  19471. (defun org-kill-note-or-show-branches ()
  19472. "Abort storing current note, or call `outline-show-branches'."
  19473. (interactive)
  19474. (if (not org-finish-function)
  19475. (progn
  19476. (outline-hide-subtree)
  19477. (call-interactively 'outline-show-branches))
  19478. (let ((org-note-abort t))
  19479. (funcall org-finish-function))))
  19480. (defun org-delete-indentation (&optional arg)
  19481. "Join current line to previous and fix whitespace at join.
  19482. If previous line is a headline add to headline title. Otherwise
  19483. the function calls `delete-indentation'.
  19484. With a non-nil optional argument, join it to the following one."
  19485. (interactive "*P")
  19486. (if (save-excursion
  19487. (beginning-of-line (if arg 1 0))
  19488. (looking-at org-complex-heading-regexp))
  19489. ;; At headline.
  19490. (let ((tags-column (when (match-beginning 5)
  19491. (save-excursion (goto-char (match-beginning 5))
  19492. (current-column))))
  19493. (string (concat " " (progn (when arg (forward-line 1))
  19494. (org-trim (delete-and-extract-region
  19495. (line-beginning-position)
  19496. (line-end-position)))))))
  19497. (unless (bobp) (delete-region (point) (1- (point))))
  19498. (goto-char (or (match-end 4)
  19499. (match-beginning 5)
  19500. (match-end 0)))
  19501. (skip-chars-backward " \t")
  19502. (save-excursion (insert string))
  19503. ;; Adjust alignment of tags.
  19504. (cond
  19505. ((not tags-column)) ;no tags
  19506. (org-auto-align-tags (org-set-tags nil t))
  19507. (t (org--align-tags-here tags-column)))) ;preserve tags column
  19508. (delete-indentation arg)))
  19509. (defun org-open-line (n)
  19510. "Insert a new row in tables, call `open-line' elsewhere.
  19511. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  19512. As a special case, when a document starts with a table, allow to
  19513. call `open-line' on the very first character."
  19514. (interactive "*p")
  19515. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  19516. (org-table-insert-row)
  19517. (open-line n)))
  19518. (defun org-return (&optional indent)
  19519. "Goto next table row or insert a newline.
  19520. Calls `org-table-next-row' or `newline', depending on context.
  19521. When optional INDENT argument is non-nil, call
  19522. `newline-and-indent' instead of `newline'.
  19523. When `org-return-follows-link' is non-nil and point is on
  19524. a timestamp or a link, call `org-open-at-point'. However, it
  19525. will not happen if point is in a table or on a \"dead\"
  19526. object (e.g., within a comment). In these case, you need to use
  19527. `org-open-at-point' directly."
  19528. (interactive)
  19529. (let ((context (if org-return-follows-link (org-element-context)
  19530. (org-element-at-point))))
  19531. (cond
  19532. ;; In a table, call `org-table-next-row'.
  19533. ((or (and (eq (org-element-type context) 'table)
  19534. (>= (point) (org-element-property :contents-begin context))
  19535. (< (point) (org-element-property :contents-end context)))
  19536. (org-element-lineage context '(table-row table-cell) t))
  19537. (org-table-justify-field-maybe)
  19538. (call-interactively #'org-table-next-row))
  19539. ;; On a link or a timestamp, call `org-open-at-point' if
  19540. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  19541. ;; locations, e.g., in a comment, as `org-open-at-point'.
  19542. ((and org-return-follows-link
  19543. (or (org-in-regexp org-ts-regexp-both nil t)
  19544. (org-in-regexp org-tsr-regexp-both nil t)
  19545. (org-in-regexp org-any-link-re nil t)))
  19546. (call-interactively #'org-open-at-point))
  19547. ;; Insert newline in heading, but preserve tags.
  19548. ((and (not (bolp))
  19549. (save-excursion (beginning-of-line)
  19550. (looking-at org-complex-heading-regexp)))
  19551. ;; At headline. Split line. However, if point is on keyword,
  19552. ;; priority cookie or tags, do not break any of them: add
  19553. ;; a newline after the headline instead.
  19554. (let ((tags-column (and (match-beginning 5)
  19555. (save-excursion (goto-char (match-beginning 5))
  19556. (current-column))))
  19557. (string
  19558. (when (and (match-end 4)
  19559. (>= (point)
  19560. (or (match-end 3) (match-end 2) (1+ (match-end 1))))
  19561. (<= (point) (match-end 4)))
  19562. (delete-and-extract-region (point) (match-end 4)))))
  19563. ;; Adjust tag alignment.
  19564. (cond
  19565. ((not (and tags-column string)))
  19566. (org-auto-align-tags (org-set-tags nil t))
  19567. (t (org--align-tags-here tags-column))) ;preserve tags column
  19568. (end-of-line)
  19569. (org-show-entry)
  19570. (if indent (newline-and-indent) (newline))
  19571. (when string (save-excursion (insert (org-trim string))))))
  19572. ;; In a list, make sure indenting keeps trailing text within.
  19573. ((and indent
  19574. (not (eolp))
  19575. (org-element-lineage context '(item)))
  19576. (let ((trailing-data
  19577. (delete-and-extract-region (point) (line-end-position))))
  19578. (newline-and-indent)
  19579. (save-excursion (insert trailing-data))))
  19580. (t (if indent (newline-and-indent) (newline))))))
  19581. (defun org-return-indent ()
  19582. "Goto next table row or insert a newline and indent.
  19583. Calls `org-table-next-row' or `newline-and-indent', depending on
  19584. context. See the individual commands for more information."
  19585. (interactive)
  19586. (org-return t))
  19587. (defun org-ctrl-c-star ()
  19588. "Compute table, or change heading status of lines.
  19589. Calls `org-table-recalculate' or `org-toggle-heading',
  19590. depending on context."
  19591. (interactive)
  19592. (cond
  19593. ((org-at-table-p)
  19594. (call-interactively 'org-table-recalculate))
  19595. (t
  19596. ;; Convert all lines in region to list items
  19597. (call-interactively 'org-toggle-heading))))
  19598. (defun org-ctrl-c-minus ()
  19599. "Insert separator line in table or modify bullet status of line.
  19600. Also turns a plain line or a region of lines into list items.
  19601. Calls `org-table-insert-hline', `org-toggle-item', or
  19602. `org-cycle-list-bullet', depending on context."
  19603. (interactive)
  19604. (cond
  19605. ((org-at-table-p)
  19606. (call-interactively 'org-table-insert-hline))
  19607. ((org-region-active-p)
  19608. (call-interactively 'org-toggle-item))
  19609. ((org-in-item-p)
  19610. (call-interactively 'org-cycle-list-bullet))
  19611. (t
  19612. (call-interactively 'org-toggle-item))))
  19613. (defun org-toggle-heading (&optional nstars)
  19614. "Convert headings to normal text, or items or text to headings.
  19615. If there is no active region, only convert the current line.
  19616. With a `\\[universal-argument]' prefix, convert the whole list at
  19617. point into heading.
  19618. In a region:
  19619. - If the first non blank line is a headline, remove the stars
  19620. from all headlines in the region.
  19621. - If it is a normal line, turn each and every normal line (i.e.,
  19622. not an heading or an item) in the region into headings. If you
  19623. want to convert only the first line of this region, use one
  19624. universal prefix argument.
  19625. - If it is a plain list item, turn all plain list items into headings.
  19626. When converting a line into a heading, the number of stars is chosen
  19627. such that the lines become children of the current entry. However,
  19628. when a numeric prefix argument is given, its value determines the
  19629. number of stars to add."
  19630. (interactive "P")
  19631. (let ((skip-blanks
  19632. (function
  19633. ;; Return beginning of first non-blank line, starting from
  19634. ;; line at POS.
  19635. (lambda (pos)
  19636. (save-excursion
  19637. (goto-char pos)
  19638. (while (org-at-comment-p) (forward-line))
  19639. (skip-chars-forward " \r\t\n")
  19640. (point-at-bol)))))
  19641. beg end toggled)
  19642. ;; Determine boundaries of changes. If a universal prefix has
  19643. ;; been given, put the list in a region. If region ends at a bol,
  19644. ;; do not consider the last line to be in the region.
  19645. (when (and current-prefix-arg (org-at-item-p))
  19646. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19647. (org-mark-element))
  19648. (if (org-region-active-p)
  19649. (setq beg (funcall skip-blanks (region-beginning))
  19650. end (copy-marker (save-excursion
  19651. (goto-char (region-end))
  19652. (if (bolp) (point) (point-at-eol)))))
  19653. (setq beg (funcall skip-blanks (point-at-bol))
  19654. end (copy-marker (point-at-eol))))
  19655. ;; Ensure inline tasks don't count as headings.
  19656. (org-with-limited-levels
  19657. (save-excursion
  19658. (goto-char beg)
  19659. (cond
  19660. ;; Case 1. Started at an heading: de-star headings.
  19661. ((org-at-heading-p)
  19662. (while (< (point) end)
  19663. (when (org-at-heading-p t)
  19664. (looking-at org-outline-regexp) (replace-match "")
  19665. (setq toggled t))
  19666. (forward-line)))
  19667. ;; Case 2. Started at an item: change items into headlines.
  19668. ;; One star will be added by `org-list-to-subtree'.
  19669. ((org-at-item-p)
  19670. (while (< (point) end)
  19671. (when (org-at-item-p)
  19672. ;; Pay attention to cases when region ends before list.
  19673. (let* ((struct (org-list-struct))
  19674. (list-end
  19675. (min (org-list-get-bottom-point struct) (1+ end))))
  19676. (save-restriction
  19677. (narrow-to-region (point) list-end)
  19678. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19679. (setq toggled t))
  19680. (forward-line)))
  19681. ;; Case 3. Started at normal text: make every line an heading,
  19682. ;; skipping headlines and items.
  19683. (t (let* ((stars
  19684. (make-string
  19685. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19686. (add-stars
  19687. (cond (nstars "") ; stars from prefix only
  19688. ((equal stars "") "*") ; before first heading
  19689. (org-odd-levels-only "**") ; inside heading, odd
  19690. (t "*"))) ; inside heading, oddeven
  19691. (rpl (concat stars add-stars " "))
  19692. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19693. (while (< (point) (if (equal nstars '(4)) lend end))
  19694. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19695. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19696. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19697. (forward-line)))))))
  19698. (unless toggled (message "Cannot toggle heading from here"))))
  19699. (defun org-meta-return (&optional _arg)
  19700. "Insert a new heading or wrap a region in a table.
  19701. Calls `org-insert-heading' or `org-table-wrap-region', depending
  19702. on context. See the individual commands for more information."
  19703. (interactive)
  19704. (org-check-before-invisible-edit 'insert)
  19705. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19706. (call-interactively (if (org-at-table-p) #'org-table-wrap-region
  19707. #'org-insert-heading))))
  19708. ;;; Menu entries
  19709. (defsubst org-in-subtree-not-table-p ()
  19710. "Are we in a subtree and not in a table?"
  19711. (and (not (org-before-first-heading-p))
  19712. (not (org-at-table-p))))
  19713. ;; Define the Org mode menus
  19714. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19715. '("Tbl"
  19716. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19717. ["Next Field" org-cycle (org-at-table-p)]
  19718. ["Previous Field" org-shifttab (org-at-table-p)]
  19719. ["Next Row" org-return (org-at-table-p)]
  19720. "--"
  19721. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19722. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19723. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19724. "--"
  19725. ("Column"
  19726. ["Move Column Left" org-metaleft (org-at-table-p)]
  19727. ["Move Column Right" org-metaright (org-at-table-p)]
  19728. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19729. ["Insert Column" org-shiftmetaright (org-at-table-p)])
  19730. ("Row"
  19731. ["Move Row Up" org-metaup (org-at-table-p)]
  19732. ["Move Row Down" org-metadown (org-at-table-p)]
  19733. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19734. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19735. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19736. "--"
  19737. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19738. ("Rectangle"
  19739. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19740. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19741. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19742. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19743. "--"
  19744. ("Calculate"
  19745. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19746. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19747. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19748. "--"
  19749. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19750. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19751. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19752. "--"
  19753. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19754. "--"
  19755. ["Sum Column/Rectangle" org-table-sum
  19756. (or (org-at-table-p) (org-region-active-p))]
  19757. ["Which Column?" org-table-current-column (org-at-table-p)])
  19758. ["Debug Formulas"
  19759. org-table-toggle-formula-debugger
  19760. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19761. ["Show Col/Row Numbers"
  19762. org-table-toggle-coordinate-overlays
  19763. :style toggle
  19764. :selected (bound-and-true-p org-table-overlay-coordinates)]
  19765. "--"
  19766. ["Create" org-table-create (and (not (org-at-table-p))
  19767. org-enable-table-editor)]
  19768. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19769. ["Import from File" org-table-import (not (org-at-table-p))]
  19770. ["Export to File" org-table-export (org-at-table-p)]
  19771. "--"
  19772. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19773. "--"
  19774. ("Plot"
  19775. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19776. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19777. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19778. '("Org"
  19779. ("Show/Hide"
  19780. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19781. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19782. ["Sparse Tree..." org-sparse-tree t]
  19783. ["Reveal Context" org-reveal t]
  19784. ["Show All" outline-show-all t]
  19785. "--"
  19786. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19787. "--"
  19788. ["New Heading" org-insert-heading t]
  19789. ("Navigate Headings"
  19790. ["Up" outline-up-heading t]
  19791. ["Next" outline-next-visible-heading t]
  19792. ["Previous" outline-previous-visible-heading t]
  19793. ["Next Same Level" outline-forward-same-level t]
  19794. ["Previous Same Level" outline-backward-same-level t]
  19795. "--"
  19796. ["Jump" org-goto t])
  19797. ("Edit Structure"
  19798. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19799. "--"
  19800. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19801. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19802. "--"
  19803. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19804. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19805. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19806. "--"
  19807. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19808. "--"
  19809. ["Copy visible text" org-copy-visible t]
  19810. "--"
  19811. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19812. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19813. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19814. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19815. "--"
  19816. ["Sort Region/Children" org-sort t]
  19817. "--"
  19818. ["Convert to odd levels" org-convert-to-odd-levels t]
  19819. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19820. ("Editing"
  19821. ["Emphasis..." org-emphasize t]
  19822. ["Edit Source Example" org-edit-special t]
  19823. "--"
  19824. ["Footnote new/jump" org-footnote-action t]
  19825. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19826. ("Archive"
  19827. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19828. "--"
  19829. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19830. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19831. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19832. )
  19833. "--"
  19834. ("Hyperlinks"
  19835. ["Store Link (Global)" org-store-link t]
  19836. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19837. ["Insert Link" org-insert-link t]
  19838. ["Follow Link" org-open-at-point t]
  19839. "--"
  19840. ["Next link" org-next-link t]
  19841. ["Previous link" org-previous-link t]
  19842. "--"
  19843. ["Descriptive Links"
  19844. org-toggle-link-display
  19845. :style radio
  19846. :selected org-descriptive-links
  19847. ]
  19848. ["Literal Links"
  19849. org-toggle-link-display
  19850. :style radio
  19851. :selected (not org-descriptive-links)])
  19852. "--"
  19853. ("TODO Lists"
  19854. ["TODO/DONE/-" org-todo t]
  19855. ("Select keyword"
  19856. ["Next keyword" org-shiftright (org-at-heading-p)]
  19857. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19858. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19859. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19860. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19861. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19862. ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
  19863. "--"
  19864. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19865. :selected org-enforce-todo-dependencies :style toggle :active t]
  19866. "Settings for tree at point"
  19867. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19868. :selected (org-entry-get nil "ORDERED")
  19869. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19870. ["Do Children parallel" org-toggle-ordered-property :style radio
  19871. :selected (not (org-entry-get nil "ORDERED"))
  19872. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19873. "--"
  19874. ["Set Priority" org-priority t]
  19875. ["Priority Up" org-shiftup t]
  19876. ["Priority Down" org-shiftdown t]
  19877. "--"
  19878. ["Get news from all feeds" org-feed-update-all t]
  19879. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19880. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19881. ("TAGS and Properties"
  19882. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19883. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19884. "--"
  19885. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19886. ["Column view of properties" org-columns t]
  19887. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19888. ("Dates and Scheduling"
  19889. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19890. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19891. ("Change Date"
  19892. ["1 Day Later" org-shiftright (org-at-timestamp-p)]
  19893. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
  19894. ["1 ... Later" org-shiftup (org-at-timestamp-p)]
  19895. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
  19896. ["Compute Time Range" org-evaluate-time-range t]
  19897. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19898. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19899. "--"
  19900. ["Custom time format" org-toggle-time-stamp-overlays
  19901. :style radio :selected org-display-custom-times]
  19902. "--"
  19903. ["Goto Calendar" org-goto-calendar t]
  19904. ["Date from Calendar" org-date-from-calendar t]
  19905. "--"
  19906. ["Start/Restart Timer" org-timer-start t]
  19907. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19908. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19909. ["Insert Timer String" org-timer t]
  19910. ["Insert Timer Item" org-timer-item t])
  19911. ("Logging work"
  19912. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19913. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19914. ["Clock out" org-clock-out t]
  19915. ["Clock cancel" org-clock-cancel t]
  19916. "--"
  19917. ["Mark as default task" org-clock-mark-default-task t]
  19918. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19919. ["Goto running clock" org-clock-goto t]
  19920. "--"
  19921. ["Display times" org-clock-display t]
  19922. ["Create clock table" org-clock-report t]
  19923. "--"
  19924. ["Record DONE time"
  19925. (progn (setq org-log-done (not org-log-done))
  19926. (message "Switching to %s will %s record a timestamp"
  19927. (car org-done-keywords)
  19928. (if org-log-done "automatically" "not")))
  19929. :style toggle :selected org-log-done])
  19930. "--"
  19931. ["Agenda Command..." org-agenda t]
  19932. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19933. ("File List for Agenda")
  19934. ("Special views current file"
  19935. ["TODO Tree" org-show-todo-tree t]
  19936. ["Check Deadlines" org-check-deadlines t]
  19937. ["Timeline" org-timeline t]
  19938. ["Tags/Property tree" org-match-sparse-tree t])
  19939. "--"
  19940. ["Export/Publish..." org-export-dispatch t]
  19941. ("LaTeX"
  19942. ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
  19943. :selected org-cdlatex-mode]
  19944. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19945. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19946. ["Modify math symbol" org-cdlatex-math-modify
  19947. (org-inside-LaTeX-fragment-p)]
  19948. ["Insert citation" org-reftex-citation t])
  19949. "--"
  19950. ("MobileOrg"
  19951. ["Push Files and Views" org-mobile-push t]
  19952. ["Get Captured and Flagged" org-mobile-pull t]
  19953. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
  19954. "--"
  19955. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19956. "--"
  19957. ("Documentation"
  19958. ["Show Version" org-version t]
  19959. ["Info Documentation" org-info t])
  19960. ("Customize"
  19961. ["Browse Org Group" org-customize t]
  19962. "--"
  19963. ["Expand This Menu" org-create-customize-menu
  19964. (fboundp 'customize-menu-create)])
  19965. ["Send bug report" org-submit-bug-report t]
  19966. "--"
  19967. ("Refresh/Reload"
  19968. ["Refresh setup current buffer" org-mode-restart t]
  19969. ["Reload Org (after update)" org-reload t]
  19970. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  19971. ))
  19972. (defun org-info (&optional node)
  19973. "Read documentation for Org in the info system.
  19974. With optional NODE, go directly to that node."
  19975. (interactive)
  19976. (info (format "(org)%s" (or node ""))))
  19977. ;;;###autoload
  19978. (defun org-submit-bug-report ()
  19979. "Submit a bug report on Org via mail.
  19980. Don't hesitate to report any problems or inaccurate documentation.
  19981. If you don't have setup sending mail from (X)Emacs, please copy the
  19982. output buffer into your mail program, as it gives us important
  19983. information about your Org version and configuration."
  19984. (interactive)
  19985. (require 'reporter)
  19986. (defvar reporter-prompt-for-summary-p)
  19987. (org-load-modules-maybe)
  19988. (org-require-autoloaded-modules)
  19989. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19990. (reporter-submit-bug-report
  19991. "emacs-orgmode@gnu.org"
  19992. (org-version nil 'full)
  19993. (let (list)
  19994. (save-window-excursion
  19995. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19996. (delete-other-windows)
  19997. (erase-buffer)
  19998. (insert "You are about to submit a bug report to the Org mailing list.
  19999. We would like to add your full Org and Outline configuration to the
  20000. bug report. This greatly simplifies the work of the maintainer and
  20001. other experts on the mailing list.
  20002. HOWEVER, some variables you have customized may contain private
  20003. information. The names of customers, colleagues, or friends, might
  20004. appear in the form of file names, tags, todo states, or search strings.
  20005. If you answer yes to the prompt, you might want to check and remove
  20006. such private information before sending the email.")
  20007. (add-text-properties (point-min) (point-max) '(face org-warning))
  20008. (when (yes-or-no-p "Include your Org configuration ")
  20009. (mapatoms
  20010. (lambda (v)
  20011. (and (boundp v)
  20012. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  20013. (or (and (symbol-value v)
  20014. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  20015. (and
  20016. (get v 'custom-type) (get v 'standard-value)
  20017. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  20018. (push v list)))))
  20019. (kill-buffer (get-buffer "*Warn about privacy*"))
  20020. list))
  20021. nil nil
  20022. "Remember to cover the basics, that is, what you expected to happen and
  20023. what in fact did happen. You don't know how to make a good report? See
  20024. http://orgmode.org/manual/Feedback.html#Feedback
  20025. Your bug report will be posted to the Org mailing list.
  20026. ------------------------------------------------------------------------")
  20027. (save-excursion
  20028. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  20029. (replace-match "\\1Bug: \\3 [\\2]")))))
  20030. (defun org-install-agenda-files-menu ()
  20031. (let ((bl (buffer-list)))
  20032. (save-excursion
  20033. (while bl
  20034. (set-buffer (pop bl))
  20035. (when (derived-mode-p 'org-mode) (setq bl nil)))
  20036. (when (derived-mode-p 'org-mode)
  20037. (easy-menu-change
  20038. '("Org") "File List for Agenda"
  20039. (append
  20040. (list
  20041. ["Edit File List" (org-edit-agenda-file-list) t]
  20042. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  20043. ["Remove Current File from List" org-remove-file t]
  20044. ["Cycle through agenda files" org-cycle-agenda-files t]
  20045. ["Occur in all agenda files" org-occur-in-agenda-files t]
  20046. "--")
  20047. (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
  20048. ;;;; Documentation
  20049. (defun org-require-autoloaded-modules ()
  20050. (interactive)
  20051. (mapc #'require
  20052. '(org-agenda org-archive org-attach org-clock org-colview org-id
  20053. org-table org-timer)))
  20054. ;;;###autoload
  20055. (defun org-reload (&optional uncompiled)
  20056. "Reload all org lisp files.
  20057. With prefix arg UNCOMPILED, load the uncompiled versions."
  20058. (interactive "P")
  20059. (require 'loadhist)
  20060. (let* ((org-dir (org-find-library-dir "org"))
  20061. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  20062. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  20063. (remove-re (format "\\`%s\\'"
  20064. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  20065. (feats (delete-dups
  20066. (mapcar 'file-name-sans-extension
  20067. (mapcar 'file-name-nondirectory
  20068. (delq nil
  20069. (mapcar 'feature-file
  20070. features))))))
  20071. (lfeat (append
  20072. (sort
  20073. (setq feats
  20074. (delq nil (mapcar
  20075. (lambda (f)
  20076. (if (and (string-match feature-re f)
  20077. (not (string-match remove-re f)))
  20078. f nil))
  20079. feats)))
  20080. 'string-lessp)
  20081. (list "org-version" "org")))
  20082. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  20083. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  20084. load-uncore load-misses)
  20085. (setq load-misses
  20086. (delq 't
  20087. (mapcar (lambda (f)
  20088. (or (org-load-noerror-mustsuffix (concat org-dir f))
  20089. (and (string= org-dir contrib-dir)
  20090. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  20091. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  20092. (add-to-list 'load-uncore f 'append)
  20093. 't)
  20094. f))
  20095. lfeat)))
  20096. (when load-uncore
  20097. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  20098. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  20099. (if load-misses
  20100. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  20101. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  20102. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  20103. ;;;###autoload
  20104. (defun org-customize ()
  20105. "Call the customize function with org as argument."
  20106. (interactive)
  20107. (org-load-modules-maybe)
  20108. (org-require-autoloaded-modules)
  20109. (customize-browse 'org))
  20110. (defun org-create-customize-menu ()
  20111. "Create a full customization menu for Org mode, insert it into the menu."
  20112. (interactive)
  20113. (org-load-modules-maybe)
  20114. (org-require-autoloaded-modules)
  20115. (if (fboundp 'customize-menu-create)
  20116. (progn
  20117. (easy-menu-change
  20118. '("Org") "Customize"
  20119. `(["Browse Org group" org-customize t]
  20120. "--"
  20121. ,(customize-menu-create 'org)
  20122. ["Set" Custom-set t]
  20123. ["Save" Custom-save t]
  20124. ["Reset to Current" Custom-reset-current t]
  20125. ["Reset to Saved" Custom-reset-saved t]
  20126. ["Reset to Standard Settings" Custom-reset-standard t]))
  20127. (message "\"Org\"-menu now contains full customization menu"))
  20128. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  20129. ;;;; Miscellaneous stuff
  20130. ;;; Generally useful functions
  20131. (defun org-get-at-eol (property n)
  20132. "Get text property PROPERTY at the end of line less N characters."
  20133. (get-text-property (- (point-at-eol) n) property))
  20134. (defun org-find-text-property-in-string (prop s)
  20135. "Return the first non-nil value of property PROP in string S."
  20136. (or (get-text-property 0 prop s)
  20137. (get-text-property (or (next-single-property-change 0 prop s) 0)
  20138. prop s)))
  20139. (defun org-display-warning (message)
  20140. "Display the given MESSAGE as a warning."
  20141. (display-warning 'org message :warning))
  20142. (defun org-eval (form)
  20143. "Eval FORM and return result."
  20144. (condition-case error
  20145. (eval form)
  20146. (error (format "%%![Error: %s]" error))))
  20147. (defun org-in-clocktable-p ()
  20148. "Check if the cursor is in a clocktable."
  20149. (let ((pos (point)) start)
  20150. (save-excursion
  20151. (end-of-line 1)
  20152. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  20153. (setq start (match-beginning 0))
  20154. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  20155. (>= (match-end 0) pos)
  20156. start))))
  20157. (defun org-in-verbatim-emphasis ()
  20158. (save-match-data
  20159. (and (org-in-regexp org-emph-re 2)
  20160. (>= (point) (match-beginning 3))
  20161. (<= (point) (match-end 4))
  20162. (member (match-string 3) '("=" "~")))))
  20163. (defun org-overlay-display (ovl text &optional face evap)
  20164. "Make overlay OVL display TEXT with face FACE."
  20165. (overlay-put ovl 'display text)
  20166. (if face (overlay-put ovl 'face face))
  20167. (if evap (overlay-put ovl 'evaporate t)))
  20168. (defun org-overlay-before-string (ovl text &optional face evap)
  20169. "Make overlay OVL display TEXT with face FACE."
  20170. (if face (org-add-props text nil 'face face))
  20171. (overlay-put ovl 'before-string text)
  20172. (if evap (overlay-put ovl 'evaporate t)))
  20173. (defun org-find-overlays (prop &optional pos delete)
  20174. "Find all overlays specifying PROP at POS or point.
  20175. If DELETE is non-nil, delete all those overlays."
  20176. (let (found)
  20177. (dolist (ov (overlays-at (or pos (point))) found)
  20178. (cond ((not (overlay-get ov prop)))
  20179. (delete (delete-overlay ov))
  20180. (t (push ov found))))))
  20181. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  20182. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  20183. (if (and marker (marker-buffer marker)
  20184. (buffer-live-p (marker-buffer marker)))
  20185. (progn
  20186. (pop-to-buffer-same-window (marker-buffer marker))
  20187. (when (or (> marker (point-max)) (< marker (point-min)))
  20188. (widen))
  20189. (goto-char marker)
  20190. (org-show-context 'org-goto))
  20191. (if bookmark
  20192. (bookmark-jump bookmark)
  20193. (error "Cannot find location"))))
  20194. (defun org-quote-csv-field (s)
  20195. "Quote field for inclusion in CSV material."
  20196. (if (string-match "[\",]" s)
  20197. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  20198. s))
  20199. (defun org-force-self-insert (N)
  20200. "Needed to enforce self-insert under remapping."
  20201. (interactive "p")
  20202. (self-insert-command N))
  20203. (defun org-string-width (s)
  20204. "Compute width of string, ignoring invisible characters.
  20205. This ignores character with invisibility property `org-link', and also
  20206. characters with property `org-cwidth', because these will become invisible
  20207. upon the next fontification round."
  20208. (let (b l)
  20209. (when (or (eq t buffer-invisibility-spec)
  20210. (assq 'org-link buffer-invisibility-spec))
  20211. (while (setq b (text-property-any 0 (length s)
  20212. 'invisible 'org-link s))
  20213. (setq s (concat (substring s 0 b)
  20214. (substring s (or (next-single-property-change
  20215. b 'invisible s)
  20216. (length s)))))))
  20217. (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
  20218. (setq s (concat (substring s 0 b)
  20219. (substring s (or (next-single-property-change
  20220. b 'org-cwidth s)
  20221. (length s))))))
  20222. (setq l (string-width s) b -1)
  20223. (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
  20224. (setq l (- l (get-text-property b 'org-dwidth-n s))))
  20225. l))
  20226. (defun org-shorten-string (s maxlength)
  20227. "Shorten string S so that it is no longer than MAXLENGTH characters.
  20228. If the string is shorter or has length MAXLENGTH, just return the
  20229. original string. If it is longer, the functions finds a space in the
  20230. string, breaks this string off at that locations and adds three dots
  20231. as ellipsis. Including the ellipsis, the string will not be longer
  20232. than MAXLENGTH. If finding a good breaking point in the string does
  20233. not work, the string is just chopped off in the middle of a word
  20234. if necessary."
  20235. (if (<= (length s) maxlength)
  20236. s
  20237. (let* ((n (max (- maxlength 4) 1))
  20238. (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
  20239. (if (string-match re s)
  20240. (concat (match-string 1 s) "...")
  20241. (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
  20242. (defun org-get-indentation (&optional line)
  20243. "Get the indentation of the current line, interpreting tabs.
  20244. When LINE is given, assume it represents a line and compute its indentation."
  20245. (if line
  20246. (when (string-match "^ *" (org-remove-tabs line))
  20247. (match-end 0))
  20248. (save-excursion
  20249. (beginning-of-line 1)
  20250. (skip-chars-forward " \t")
  20251. (current-column))))
  20252. (defun org-get-string-indentation (s)
  20253. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  20254. (let ((n -1) (i 0) (w tab-width) c)
  20255. (catch 'exit
  20256. (while (< (setq n (1+ n)) (length s))
  20257. (setq c (aref s n))
  20258. (cond ((= c ?\ ) (setq i (1+ i)))
  20259. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  20260. (t (throw 'exit t)))))
  20261. i))
  20262. (defun org-remove-tabs (s &optional width)
  20263. "Replace tabulators in S with spaces.
  20264. Assumes that s is a single line, starting in column 0."
  20265. (setq width (or width tab-width))
  20266. (while (string-match "\t" s)
  20267. (setq s (replace-match
  20268. (make-string
  20269. (- (* width (/ (+ (match-beginning 0) width) width))
  20270. (match-beginning 0)) ?\ )
  20271. t t s)))
  20272. s)
  20273. (defun org-fix-indentation (line ind)
  20274. "Fix indentation in LINE.
  20275. IND is a cons cell with target and minimum indentation.
  20276. If the current indentation in LINE is smaller than the minimum,
  20277. leave it alone. If it is larger than ind, set it to the target."
  20278. (let* ((l (org-remove-tabs line))
  20279. (i (org-get-indentation l))
  20280. (i1 (car ind)) (i2 (cdr ind)))
  20281. (when (>= i i2) (setq l (substring line i2)))
  20282. (if (> i1 0)
  20283. (concat (make-string i1 ?\ ) l)
  20284. l)))
  20285. (defun org-remove-indentation (code &optional n)
  20286. "Remove maximum common indentation in string CODE and return it.
  20287. N may optionally be the number of columns to remove. Return CODE
  20288. as-is if removal failed."
  20289. (with-temp-buffer
  20290. (insert code)
  20291. (if (org-do-remove-indentation n) (buffer-string) code)))
  20292. (defun org-do-remove-indentation (&optional n)
  20293. "Remove the maximum common indentation from the buffer.
  20294. When optional argument N is a positive integer, remove exactly
  20295. that much characters from indentation, if possible. Return nil
  20296. if it fails."
  20297. (catch :exit
  20298. (goto-char (point-min))
  20299. ;; Find maximum common indentation, if not specified.
  20300. (let ((n (or n
  20301. (let ((min-ind (point-max)))
  20302. (save-excursion
  20303. (while (re-search-forward "^[ \t]*\\S-" nil t)
  20304. (let ((ind (1- (current-column))))
  20305. (if (zerop ind) (throw :exit nil)
  20306. (setq min-ind (min min-ind ind))))))
  20307. min-ind))))
  20308. (if (zerop n) (throw :exit nil)
  20309. ;; Remove exactly N indentation, but give up if not possible.
  20310. (while (not (eobp))
  20311. (let ((ind (progn (skip-chars-forward " \t") (current-column))))
  20312. (cond ((eolp) (delete-region (line-beginning-position) (point)))
  20313. ((< ind n) (throw :exit nil))
  20314. (t (indent-line-to (- ind n))))
  20315. (forward-line)))
  20316. ;; Signal success.
  20317. t))))
  20318. (defun org-fill-template (template alist)
  20319. "Find each %key of ALIST in TEMPLATE and replace it."
  20320. (let ((case-fold-search nil))
  20321. (dolist (entry (sort (copy-sequence alist)
  20322. (lambda (a b) (< (length (car a)) (length (car b))))))
  20323. (setq template
  20324. (replace-regexp-in-string
  20325. (concat "%" (regexp-quote (car entry)))
  20326. (or (cdr entry) "") template t t)))
  20327. template))
  20328. (defun org-base-buffer (buffer)
  20329. "Return the base buffer of BUFFER, if it has one. Else return the buffer."
  20330. (if (not buffer)
  20331. buffer
  20332. (or (buffer-base-buffer buffer)
  20333. buffer)))
  20334. (defun org-wrap (string &optional width lines)
  20335. "Wrap string to either a number of lines, or a width in characters.
  20336. If WIDTH is non-nil, the string is wrapped to that width, however many lines
  20337. that costs. If there is a word longer than WIDTH, the text is actually
  20338. wrapped to the length of that word.
  20339. IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
  20340. many lines, whatever width that takes.
  20341. The return value is a list of lines, without newlines at the end."
  20342. (let* ((words (org-split-string string "[ \t\n]+"))
  20343. (maxword (apply 'max (mapcar 'org-string-width words)))
  20344. w ll)
  20345. (cond (width
  20346. (org-do-wrap words (max maxword width)))
  20347. (lines
  20348. (setq w maxword)
  20349. (setq ll (org-do-wrap words maxword))
  20350. (if (<= (length ll) lines)
  20351. ll
  20352. (setq ll words)
  20353. (while (> (length ll) lines)
  20354. (setq w (1+ w))
  20355. (setq ll (org-do-wrap words w)))
  20356. ll))
  20357. (t (error "Cannot wrap this")))))
  20358. (defun org-do-wrap (words width)
  20359. "Create lines of maximum width WIDTH (in characters) from word list WORDS."
  20360. (let (lines line)
  20361. (while words
  20362. (setq line (pop words))
  20363. (while (and words (< (+ (length line) (length (car words))) width))
  20364. (setq line (concat line " " (pop words))))
  20365. (setq lines (push line lines)))
  20366. (nreverse lines)))
  20367. (defun org-split-string (string &optional separators)
  20368. "Splits STRING into substrings at SEPARATORS.
  20369. SEPARATORS is a regular expression.
  20370. No empty strings are returned if there are matches at the beginning
  20371. and end of string."
  20372. ;; FIXME: why not use (split-string STRING SEPARATORS t)?
  20373. (let ((start 0) notfirst list)
  20374. (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
  20375. (if (and notfirst
  20376. (= start (match-beginning 0))
  20377. (< start (length string)))
  20378. (1+ start) start))
  20379. (< (match-beginning 0) (length string)))
  20380. (setq notfirst t)
  20381. (or (eq (match-beginning 0) 0)
  20382. (and (eq (match-beginning 0) (match-end 0))
  20383. (eq (match-beginning 0) start))
  20384. (push (substring string start (match-beginning 0)) list))
  20385. (setq start (match-end 0)))
  20386. (or (eq start (length string))
  20387. (push (substring string start) list))
  20388. (nreverse list)))
  20389. (defun org-quote-vert (s)
  20390. "Replace \"|\" with \"\\vert\"."
  20391. (while (string-match "|" s)
  20392. (setq s (replace-match "\\vert" t t s)))
  20393. s)
  20394. (defun org-uuidgen-p (s)
  20395. "Is S an ID created by UUIDGEN?"
  20396. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  20397. (defun org-in-src-block-p (&optional inside)
  20398. "Whether point is in a code source block.
  20399. When INSIDE is non-nil, don't consider we are within a src block
  20400. when point is at #+BEGIN_SRC or #+END_SRC."
  20401. (let ((case-fold-search t))
  20402. (or (and (eq (get-char-property (point) 'src-block) t))
  20403. (and (not inside)
  20404. (save-match-data
  20405. (save-excursion
  20406. (beginning-of-line)
  20407. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  20408. (defun org-context ()
  20409. "Return a list of contexts of the current cursor position.
  20410. If several contexts apply, all are returned.
  20411. Each context entry is a list with a symbol naming the context, and
  20412. two positions indicating start and end of the context. Possible
  20413. contexts are:
  20414. :headline anywhere in a headline
  20415. :headline-stars on the leading stars in a headline
  20416. :todo-keyword on a TODO keyword (including DONE) in a headline
  20417. :tags on the TAGS in a headline
  20418. :priority on the priority cookie in a headline
  20419. :item on the first line of a plain list item
  20420. :item-bullet on the bullet/number of a plain list item
  20421. :checkbox on the checkbox in a plain list item
  20422. :table in an Org table
  20423. :table-special on a special filed in a table
  20424. :table-table in a table.el table
  20425. :clocktable in a clocktable
  20426. :src-block in a source block
  20427. :link on a hyperlink
  20428. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  20429. :target on a <<target>>
  20430. :radio-target on a <<<radio-target>>>
  20431. :latex-fragment on a LaTeX fragment
  20432. :latex-preview on a LaTeX fragment with overlaid preview image
  20433. This function expects the position to be visible because it uses font-lock
  20434. faces as a help to recognize the following contexts: :table-special, :link,
  20435. and :keyword."
  20436. (let* ((f (get-text-property (point) 'face))
  20437. (faces (if (listp f) f (list f)))
  20438. (case-fold-search t)
  20439. (p (point)) clist o)
  20440. ;; First the large context
  20441. (cond
  20442. ((org-at-heading-p t)
  20443. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  20444. (when (progn
  20445. (beginning-of-line 1)
  20446. (looking-at org-todo-line-tags-regexp))
  20447. (push (org-point-in-group p 1 :headline-stars) clist)
  20448. (push (org-point-in-group p 2 :todo-keyword) clist)
  20449. (push (org-point-in-group p 4 :tags) clist))
  20450. (goto-char p)
  20451. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  20452. (when (looking-at "\\[#[A-Z0-9]\\]")
  20453. (push (org-point-in-group p 0 :priority) clist)))
  20454. ((org-at-item-p)
  20455. (push (org-point-in-group p 2 :item-bullet) clist)
  20456. (push (list :item (point-at-bol)
  20457. (save-excursion (org-end-of-item) (point)))
  20458. clist)
  20459. (and (org-at-item-checkbox-p)
  20460. (push (org-point-in-group p 0 :checkbox) clist)))
  20461. ((org-at-table-p)
  20462. (push (list :table (org-table-begin) (org-table-end)) clist)
  20463. (when (memq 'org-formula faces)
  20464. (push (list :table-special
  20465. (previous-single-property-change p 'face)
  20466. (next-single-property-change p 'face)) clist)))
  20467. ((org-at-table-p 'any)
  20468. (push (list :table-table) clist)))
  20469. (goto-char p)
  20470. (let ((case-fold-search t))
  20471. ;; New the "medium" contexts: clocktables, source blocks
  20472. (cond ((org-in-clocktable-p)
  20473. (push (list :clocktable
  20474. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  20475. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  20476. (match-beginning 1))
  20477. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  20478. (match-end 0))) clist))
  20479. ((org-in-src-block-p)
  20480. (push (list :src-block
  20481. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  20482. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  20483. (match-beginning 1))
  20484. (and (search-forward "#+END_SRC" nil t)
  20485. (match-beginning 0))) clist))))
  20486. (goto-char p)
  20487. ;; Now the small context
  20488. (cond
  20489. ((org-at-timestamp-p)
  20490. (push (org-point-in-group p 0 :timestamp) clist))
  20491. ((memq 'org-link faces)
  20492. (push (list :link
  20493. (previous-single-property-change p 'face)
  20494. (next-single-property-change p 'face)) clist))
  20495. ((memq 'org-special-keyword faces)
  20496. (push (list :keyword
  20497. (previous-single-property-change p 'face)
  20498. (next-single-property-change p 'face)) clist))
  20499. ((org-at-target-p)
  20500. (push (org-point-in-group p 0 :target) clist)
  20501. (goto-char (1- (match-beginning 0)))
  20502. (when (looking-at org-radio-target-regexp)
  20503. (push (org-point-in-group p 0 :radio-target) clist))
  20504. (goto-char p))
  20505. ((setq o (cl-some
  20506. (lambda (o)
  20507. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  20508. o))
  20509. (overlays-at (point))))
  20510. (push (list :latex-fragment
  20511. (overlay-start o) (overlay-end o)) clist)
  20512. (push (list :latex-preview
  20513. (overlay-start o) (overlay-end o)) clist))
  20514. ((org-inside-LaTeX-fragment-p)
  20515. ;; FIXME: positions wrong.
  20516. (push (list :latex-fragment (point) (point)) clist)))
  20517. (setq clist (nreverse (delq nil clist)))
  20518. clist))
  20519. (defun org-in-regexp (regexp &optional nlines visually)
  20520. "Check if point is inside a match of REGEXP.
  20521. Normally only the current line is checked, but you can include
  20522. NLINES extra lines around point into the search. If VISUALLY is
  20523. set, require that the cursor is not after the match but really
  20524. on, so that the block visually is on the match.
  20525. Return nil or a cons cell (BEG . END) where BEG and END are,
  20526. respectively, the positions at the beginning and the end of the
  20527. match."
  20528. (catch :exit
  20529. (let ((pos (point))
  20530. (eol (line-end-position (if nlines (1+ nlines) 1))))
  20531. (save-excursion
  20532. (beginning-of-line (- 1 (or nlines 0)))
  20533. (while (and (re-search-forward regexp eol t)
  20534. (<= (match-beginning 0) pos))
  20535. (let ((end (match-end 0)))
  20536. (when (or (> end pos) (and (= end pos) (not visually)))
  20537. (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
  20538. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  20539. "Non-nil when point is between matches of START-RE and END-RE.
  20540. Also return a non-nil value when point is on one of the matches.
  20541. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  20542. buffer positions. Default values are the positions of headlines
  20543. surrounding the point.
  20544. The functions returns a cons cell whose car (resp. cdr) is the
  20545. position before START-RE (resp. after END-RE)."
  20546. (save-match-data
  20547. (let ((pos (point))
  20548. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  20549. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  20550. beg end)
  20551. (save-excursion
  20552. ;; Point is on a block when on START-RE or if START-RE can be
  20553. ;; found before it...
  20554. (and (or (org-in-regexp start-re)
  20555. (re-search-backward start-re limit-up t))
  20556. (setq beg (match-beginning 0))
  20557. ;; ... and END-RE after it...
  20558. (goto-char (match-end 0))
  20559. (re-search-forward end-re limit-down t)
  20560. (> (setq end (match-end 0)) pos)
  20561. ;; ... without another START-RE in-between.
  20562. (goto-char (match-beginning 0))
  20563. (not (re-search-backward start-re (1+ beg) t))
  20564. ;; Return value.
  20565. (cons beg end))))))
  20566. (defun org-in-block-p (names)
  20567. "Non-nil when point belongs to a block whose name belongs to NAMES.
  20568. NAMES is a list of strings containing names of blocks.
  20569. Return first block name matched, or nil. Beware that in case of
  20570. nested blocks, the returned name may not belong to the closest
  20571. block from point."
  20572. (save-match-data
  20573. (catch 'exit
  20574. (let ((case-fold-search t)
  20575. (lim-up (save-excursion (outline-previous-heading)))
  20576. (lim-down (save-excursion (outline-next-heading))))
  20577. (dolist (name names)
  20578. (let ((n (regexp-quote name)))
  20579. (when (org-between-regexps-p
  20580. (concat "^[ \t]*#\\+begin_" n)
  20581. (concat "^[ \t]*#\\+end_" n)
  20582. lim-up lim-down)
  20583. (throw 'exit n)))))
  20584. nil)))
  20585. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  20586. "Call `multi-occur' with buffers for all agenda files."
  20587. (interactive "sOrg-files matching: ")
  20588. (let* ((files (org-agenda-files))
  20589. (tnames (mapcar #'file-truename files))
  20590. (extra org-agenda-text-search-extra-files))
  20591. (when (eq (car extra) 'agenda-archives)
  20592. (setq extra (cdr extra))
  20593. (setq files (org-add-archive-files files)))
  20594. (dolist (f extra)
  20595. (unless (member (file-truename f) tnames)
  20596. (unless (member f files) (setq files (append files (list f))))
  20597. (setq tnames (append tnames (list (file-truename f))))))
  20598. (multi-occur
  20599. (mapcar (lambda (x)
  20600. (with-current-buffer
  20601. ;; FIXME: Why not just (find-file-noselect x)?
  20602. ;; Is it to avoid the "revert buffer" prompt?
  20603. (or (get-file-buffer x) (find-file-noselect x))
  20604. (widen)
  20605. (current-buffer)))
  20606. files)
  20607. regexp)))
  20608. (add-hook 'occur-mode-find-occurrence-hook
  20609. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  20610. (defun org-occur-link-in-agenda-files ()
  20611. "Create a link and search for it in the agendas.
  20612. The link is not stored in `org-stored-links', it is just created
  20613. for the search purpose."
  20614. (interactive)
  20615. (let ((link (condition-case nil
  20616. (org-store-link nil)
  20617. (error "Unable to create a link to here"))))
  20618. (org-occur-in-agenda-files (regexp-quote link))))
  20619. (defun org-reverse-string (string)
  20620. "Return the reverse of STRING."
  20621. (apply 'string (reverse (string-to-list string))))
  20622. ;; defsubst org-uniquify must be defined before first use
  20623. (defun org-uniquify-alist (alist)
  20624. "Merge elements of ALIST with the same key.
  20625. For example, in this alist:
  20626. \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
  20627. => \\='((a 1 3) (b 2))
  20628. merge (a 1) and (a 3) into (a 1 3).
  20629. The function returns the new ALIST."
  20630. (let (rtn)
  20631. (dolist (e alist rtn)
  20632. (let (n)
  20633. (if (not (assoc (car e) rtn))
  20634. (push e rtn)
  20635. (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
  20636. (setq rtn (assq-delete-all (car e) rtn))
  20637. (push n rtn))))))
  20638. (defun org-delete-all (elts list)
  20639. "Remove all elements in ELTS from LIST.
  20640. Comparison is done with `equal'. It is a destructive operation
  20641. that may remove elements by altering the list structure."
  20642. (while elts
  20643. (setq list (delete (pop elts) list)))
  20644. list)
  20645. (defun org-back-over-empty-lines ()
  20646. "Move backwards over whitespace, to the beginning of the first empty line.
  20647. Returns the number of empty lines passed."
  20648. (let ((pos (point)))
  20649. (if (cdr (assq 'heading org-blank-before-new-entry))
  20650. (skip-chars-backward " \t\n\r")
  20651. (unless (eobp)
  20652. (forward-line -1)))
  20653. (beginning-of-line 2)
  20654. (goto-char (min (point) pos))
  20655. (count-lines (point) pos)))
  20656. (defun org-skip-whitespace ()
  20657. (skip-chars-forward " \t\n\r"))
  20658. (defun org-point-in-group (point group &optional context)
  20659. "Check if POINT is in match-group GROUP.
  20660. If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
  20661. match. If the match group does not exist or point is not inside it,
  20662. return nil."
  20663. (and (match-beginning group)
  20664. (>= point (match-beginning group))
  20665. (<= point (match-end group))
  20666. (if context
  20667. (list context (match-beginning group) (match-end group))
  20668. t)))
  20669. (defun org-switch-to-buffer-other-window (&rest args)
  20670. "Switch to buffer in a second window on the current frame.
  20671. In particular, do not allow pop-up frames.
  20672. Returns the newly created buffer."
  20673. (org-no-popups
  20674. (apply 'switch-to-buffer-other-window args)))
  20675. (defun org-combine-plists (&rest plists)
  20676. "Create a single property list from all plists in PLISTS.
  20677. The process starts by copying the first list, and then setting properties
  20678. from the other lists. Settings in the last list are the most significant
  20679. ones and overrule settings in the other lists."
  20680. (let ((rtn (copy-sequence (pop plists)))
  20681. p v ls)
  20682. (while plists
  20683. (setq ls (pop plists))
  20684. (while ls
  20685. (setq p (pop ls) v (pop ls))
  20686. (setq rtn (plist-put rtn p v))))
  20687. rtn))
  20688. (defun org-replace-escapes (string table)
  20689. "Replace %-escapes in STRING with values in TABLE.
  20690. TABLE is an association list with keys like \"%a\" and string values.
  20691. The sequences in STRING may contain normal field width and padding information,
  20692. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  20693. so values can contain further %-escapes if they are define later in TABLE."
  20694. (let ((tbl (copy-alist table))
  20695. (case-fold-search nil)
  20696. (pchg 0)
  20697. re rpl)
  20698. (dolist (e tbl)
  20699. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  20700. (when (and (cdr e) (string-match re (cdr e)))
  20701. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  20702. (safe "SREF"))
  20703. (add-text-properties 0 3 (list 'sref sref) safe)
  20704. (setcdr e (replace-match safe t t (cdr e)))))
  20705. (while (string-match re string)
  20706. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  20707. (cdr e)))
  20708. (setq string (replace-match rpl t t string))))
  20709. (while (setq pchg (next-property-change pchg string))
  20710. (let ((sref (get-text-property pchg 'sref string)))
  20711. (when (and sref (string-match "SREF" string pchg))
  20712. (setq string (replace-match sref t t string)))))
  20713. string))
  20714. (defun org-find-base-buffer-visiting (file)
  20715. "Like `find-buffer-visiting' but always return the base buffer and
  20716. not an indirect buffer."
  20717. (let ((buf (or (get-file-buffer file)
  20718. (find-buffer-visiting file))))
  20719. (if buf
  20720. (or (buffer-base-buffer buf) buf)
  20721. nil)))
  20722. ;;; TODO: Only called once, from ox-odt which should probably use
  20723. ;;; org-export-inline-image-p or something.
  20724. (defun org-file-image-p (file)
  20725. "Return non-nil if FILE is an image."
  20726. (save-match-data
  20727. (string-match (image-file-name-regexp) file)))
  20728. (defun org-get-cursor-date (&optional with-time)
  20729. "Return the date at cursor in as a time.
  20730. This works in the calendar and in the agenda, anywhere else it just
  20731. returns the current time.
  20732. If WITH-TIME is non-nil, returns the time of the event at point (in
  20733. the agenda) or the current time of the day."
  20734. (let (date day defd tp hod mod)
  20735. (when with-time
  20736. (setq tp (get-text-property (point) 'time))
  20737. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  20738. (setq hod (string-to-number (match-string 1 tp))
  20739. mod (string-to-number (match-string 2 tp))))
  20740. (or tp (let ((now (decode-time)))
  20741. (setq hod (nth 2 now)
  20742. mod (nth 1 now)))))
  20743. (cond
  20744. ((eq major-mode 'calendar-mode)
  20745. (setq date (calendar-cursor-to-date)
  20746. defd (encode-time 0 (or mod 0) (or hod 0)
  20747. (nth 1 date) (nth 0 date) (nth 2 date))))
  20748. ((eq major-mode 'org-agenda-mode)
  20749. (setq day (get-text-property (point) 'day))
  20750. (when day
  20751. (setq date (calendar-gregorian-from-absolute day)
  20752. defd (encode-time 0 (or mod 0) (or hod 0)
  20753. (nth 1 date) (nth 0 date) (nth 2 date))))))
  20754. (or defd (current-time))))
  20755. (defun org-mark-subtree (&optional up)
  20756. "Mark the current subtree.
  20757. This puts point at the start of the current subtree, and mark at
  20758. the end. If a numeric prefix UP is given, move up into the
  20759. hierarchy of headlines by UP levels before marking the subtree."
  20760. (interactive "P")
  20761. (org-with-limited-levels
  20762. (cond ((org-at-heading-p) (beginning-of-line))
  20763. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  20764. (t (outline-previous-visible-heading 1))))
  20765. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  20766. (if (called-interactively-p 'any)
  20767. (call-interactively 'org-mark-element)
  20768. (org-mark-element)))
  20769. (defun org-file-newer-than-p (file time)
  20770. "Non-nil if FILE is newer than TIME.
  20771. FILE is a filename, as a string, TIME is a list of integers, as
  20772. returned by, e.g., `current-time'."
  20773. (and (file-exists-p file)
  20774. ;; Only compare times up to whole seconds as some file-systems
  20775. ;; (e.g. HFS+) do not retain any finer granularity. As
  20776. ;; a consequence, make sure we return non-nil when the two
  20777. ;; times are equal.
  20778. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  20779. (cl-subseq time 0 2)))))
  20780. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  20781. "Compile a SOURCE file using PROCESS.
  20782. PROCESS is either a function or a list of shell commands, as
  20783. strings. EXT is a file extension, without the leading dot, as
  20784. a string. It is used to check if the process actually succeeded.
  20785. PROCESS must create a file with the same base name and directory
  20786. as SOURCE, but ending with EXT. The function then returns its
  20787. filename. Otherwise, it raises an error. The error message can
  20788. then be refined by providing string ERR-MSG, which is appended to
  20789. the standard message.
  20790. If PROCESS is a function, it is called with a single argument:
  20791. the SOURCE file.
  20792. If it is a list of commands, each of them is called using
  20793. `shell-command'. By default, in each command, %b, %f, %F and %o
  20794. are replaced with, respectively, SOURCE base name, name, full
  20795. name and directory. It is possible, however, to use more
  20796. place-holders by specifying them in optional argument SPEC, as an
  20797. alist following the pattern (CHARACTER . REPLACEMENT-STRING).
  20798. When PROCESS is a list of commands, optional argument LOG-BUF can
  20799. be set to a buffer or a buffer name. `shell-command' then uses
  20800. it for output.
  20801. `default-directory' is set to SOURCE directory during the whole
  20802. process."
  20803. (let* ((source-name (file-name-nondirectory source))
  20804. (base-name (file-name-sans-extension source-name))
  20805. (full-name (file-truename source))
  20806. (out-dir (file-name-directory source))
  20807. (time (current-time))
  20808. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  20809. (save-window-excursion
  20810. (let ((default-directory (file-name-directory full-name)))
  20811. (pcase process
  20812. ((pred functionp) (funcall process (shell-quote-argument source)))
  20813. ((pred consp)
  20814. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  20815. (spec (append spec
  20816. `((?b . ,(shell-quote-argument base-name))
  20817. (?f . ,(shell-quote-argument source-name))
  20818. (?F . ,(shell-quote-argument full-name))
  20819. (?o . ,(shell-quote-argument out-dir))))))
  20820. (dolist (command process)
  20821. (shell-command (format-spec command spec) log-buf))))
  20822. (_ (error "No valid command to process %S%s" source err-msg)))))
  20823. ;; Check for process failure.
  20824. (let ((output (concat out-dir base-name "." ext)))
  20825. (unless (org-file-newer-than-p output time)
  20826. (error (format "File %S wasn't produced%s" output err-msg)))
  20827. output)))
  20828. ;;; Indentation
  20829. (defun org--get-expected-indentation (element contentsp)
  20830. "Expected indentation column for current line, according to ELEMENT.
  20831. ELEMENT is an element containing point. CONTENTSP is non-nil
  20832. when indentation is to be computed according to contents of
  20833. ELEMENT."
  20834. (let ((type (org-element-type element))
  20835. (start (org-element-property :begin element))
  20836. (post-affiliated (org-element-property :post-affiliated element)))
  20837. (org-with-wide-buffer
  20838. (cond
  20839. (contentsp
  20840. (cl-case type
  20841. ((diary-sexp footnote-definition) 0)
  20842. ((headline inlinetask nil)
  20843. (if (not org-adapt-indentation) 0
  20844. (let ((level (org-current-level)))
  20845. (if level (1+ level) 0))))
  20846. ((item plain-list) (org-list-item-body-column post-affiliated))
  20847. (t
  20848. (goto-char start)
  20849. (org-get-indentation))))
  20850. ((memq type '(headline inlinetask nil))
  20851. (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
  20852. (org--get-expected-indentation element t)
  20853. 0))
  20854. ((memq type '(diary-sexp footnote-definition)) 0)
  20855. ;; First paragraph of a footnote definition or an item.
  20856. ;; Indent like parent.
  20857. ((< (line-beginning-position) start)
  20858. (org--get-expected-indentation
  20859. (org-element-property :parent element) t))
  20860. ;; At first line: indent according to previous sibling, if any,
  20861. ;; ignoring footnote definitions and inline tasks, or parent's
  20862. ;; contents.
  20863. ((= (line-beginning-position) start)
  20864. (catch 'exit
  20865. (while t
  20866. (if (= (point-min) start) (throw 'exit 0)
  20867. (goto-char (1- start))
  20868. (let* ((previous (org-element-at-point))
  20869. (parent previous))
  20870. (while (and parent (<= (org-element-property :end parent) start))
  20871. (setq previous parent
  20872. parent (org-element-property :parent parent)))
  20873. (cond
  20874. ((not previous) (throw 'exit 0))
  20875. ((> (org-element-property :end previous) start)
  20876. (throw 'exit (org--get-expected-indentation previous t)))
  20877. ((memq (org-element-type previous)
  20878. '(footnote-definition inlinetask))
  20879. (setq start (org-element-property :begin previous)))
  20880. (t (goto-char (org-element-property :begin previous))
  20881. (throw 'exit
  20882. (if (bolp) (org-get-indentation)
  20883. ;; At first paragraph in an item or
  20884. ;; a footnote definition.
  20885. (org--get-expected-indentation
  20886. (org-element-property :parent previous) t))))))))))
  20887. ;; Otherwise, move to the first non-blank line above.
  20888. (t
  20889. (beginning-of-line)
  20890. (let ((pos (point)))
  20891. (skip-chars-backward " \r\t\n")
  20892. (cond
  20893. ;; Two blank lines end a footnote definition or a plain
  20894. ;; list. When we indent an empty line after them, the
  20895. ;; containing list or footnote definition is over, so it
  20896. ;; qualifies as a previous sibling. Therefore, we indent
  20897. ;; like its first line.
  20898. ((and (memq type '(footnote-definition plain-list))
  20899. (> (count-lines (point) pos) 2))
  20900. (goto-char start)
  20901. (org-get-indentation))
  20902. ;; Line above is the first one of a paragraph at the
  20903. ;; beginning of an item or a footnote definition. Indent
  20904. ;; like parent.
  20905. ((< (line-beginning-position) start)
  20906. (org--get-expected-indentation
  20907. (org-element-property :parent element) t))
  20908. ;; Line above is the beginning of an element, i.e., point
  20909. ;; was originally on the blank lines between element's start
  20910. ;; and contents.
  20911. ((= (line-beginning-position) post-affiliated)
  20912. (org--get-expected-indentation element t))
  20913. ;; POS is after contents in a greater element. Indent like
  20914. ;; the beginning of the element.
  20915. ;;
  20916. ;; As a special case, if point is at the end of a footnote
  20917. ;; definition or an item, indent like the very last element
  20918. ;; within. If that last element is an item, indent like its
  20919. ;; contents.
  20920. ((and (not (eq type 'paragraph))
  20921. (let ((cend (org-element-property :contents-end element)))
  20922. (and cend (<= cend pos))))
  20923. (if (memq type '(footnote-definition item plain-list))
  20924. (let ((last (org-element-at-point)))
  20925. (org--get-expected-indentation
  20926. last (eq (org-element-type last) 'item)))
  20927. (goto-char start)
  20928. (org-get-indentation)))
  20929. ;; In any other case, indent like the current line.
  20930. (t (org-get-indentation)))))))))
  20931. (defun org--align-node-property ()
  20932. "Align node property at point.
  20933. Alignment is done according to `org-property-format', which see."
  20934. (when (save-excursion
  20935. (beginning-of-line)
  20936. (looking-at org-property-re))
  20937. (replace-match
  20938. (concat (match-string 4)
  20939. (org-trim
  20940. (format org-property-format (match-string 1) (match-string 3))))
  20941. t t)))
  20942. (defun org-indent-line ()
  20943. "Indent line depending on context.
  20944. Indentation is done according to the following rules:
  20945. - Footnote definitions, diary sexps, headlines and inline tasks
  20946. have to start at column 0.
  20947. - On the very first line of an element, consider, in order, the
  20948. next rules until one matches:
  20949. 1. If there's a sibling element before, ignoring footnote
  20950. definitions and inline tasks, indent like its first line.
  20951. 2. If element has a parent, indent like its contents. More
  20952. precisely, if parent is an item, indent after the
  20953. description part, if any, or the bullet (see
  20954. `org-list-description-max-indent'). Else, indent like
  20955. parent's first line.
  20956. 3. Otherwise, indent relatively to current level, if
  20957. `org-adapt-indentation' is non-nil, or to left margin.
  20958. - On a blank line at the end of an element, indent according to
  20959. the type of the element. More precisely
  20960. 1. If element is a plain list, an item, or a footnote
  20961. definition, indent like the very last element within.
  20962. 2. If element is a paragraph, indent like its last non blank
  20963. line.
  20964. 3. Otherwise, indent like its very first line.
  20965. - In the code part of a source block, use language major mode
  20966. to indent current line if `org-src-tab-acts-natively' is
  20967. non-nil. If it is nil, do nothing.
  20968. - Otherwise, indent like the first non-blank line above.
  20969. The function doesn't indent an item as it could break the whole
  20970. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  20971. `\\[org-shiftmetaright]'.
  20972. Also align node properties according to `org-property-format'."
  20973. (interactive)
  20974. (cond
  20975. (orgstruct-is-++
  20976. (let ((indent-line-function
  20977. (cl-cadadr (assq 'indent-line-function org-fb-vars))))
  20978. (indent-according-to-mode)))
  20979. ((org-at-heading-p) 'noindent)
  20980. (t
  20981. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  20982. (type (org-element-type element)))
  20983. (cond ((and (memq type '(plain-list item))
  20984. (= (line-beginning-position)
  20985. (org-element-property :post-affiliated element)))
  20986. 'noindent)
  20987. ((and (eq type 'src-block)
  20988. org-src-tab-acts-natively
  20989. (> (line-beginning-position)
  20990. (org-element-property :post-affiliated element))
  20991. (< (line-beginning-position)
  20992. (org-with-wide-buffer
  20993. (goto-char (org-element-property :end element))
  20994. (skip-chars-backward " \r\t\n")
  20995. (line-beginning-position))))
  20996. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  20997. (t
  20998. (let ((column (org--get-expected-indentation element nil)))
  20999. ;; Preserve current column.
  21000. (if (<= (current-column) (current-indentation))
  21001. (indent-line-to column)
  21002. (save-excursion (indent-line-to column))))
  21003. ;; Align node property. Also preserve current column.
  21004. (when (eq type 'node-property)
  21005. (let ((column (current-column)))
  21006. (org--align-node-property)
  21007. (org-move-to-column column)))))))))
  21008. (defun org-indent-region (start end)
  21009. "Indent each non-blank line in the region.
  21010. Called from a program, START and END specify the region to
  21011. indent. The function will not indent contents of example blocks,
  21012. verse blocks and export blocks as leading white spaces are
  21013. assumed to be significant there."
  21014. (interactive "r")
  21015. (save-excursion
  21016. (goto-char start)
  21017. (skip-chars-forward " \r\t\n")
  21018. (unless (eobp) (beginning-of-line))
  21019. (let ((indent-to
  21020. (lambda (ind pos)
  21021. ;; Set IND as indentation for all lines between point and
  21022. ;; POS. Blank lines are ignored. Leave point after POS
  21023. ;; once done.
  21024. (let ((limit (copy-marker pos)))
  21025. (while (< (point) limit)
  21026. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  21027. (forward-line))
  21028. (set-marker limit nil))))
  21029. (end (copy-marker end)))
  21030. (while (< (point) end)
  21031. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  21032. (let* ((element (org-element-at-point))
  21033. (type (org-element-type element))
  21034. (element-end (copy-marker (org-element-property :end element)))
  21035. (ind (org--get-expected-indentation element nil)))
  21036. (cond
  21037. ((or (memq type '(paragraph table table-row))
  21038. (not (or (org-element-property :contents-begin element)
  21039. (memq type
  21040. '(example-block export-block src-block)))))
  21041. ;; Elements here are indented as a single block. Also
  21042. ;; align node properties.
  21043. (when (eq type 'node-property)
  21044. (org--align-node-property)
  21045. (beginning-of-line))
  21046. (funcall indent-to ind (min element-end end)))
  21047. (t
  21048. ;; Elements in this category consist of three parts:
  21049. ;; before the contents, the contents, and after the
  21050. ;; contents. The contents are treated specially,
  21051. ;; according to the element type, or not indented at
  21052. ;; all. Other parts are indented as a single block.
  21053. (let* ((post (copy-marker
  21054. (org-element-property :post-affiliated element)))
  21055. (cbeg
  21056. (copy-marker
  21057. (cond
  21058. ((not (org-element-property :contents-begin element))
  21059. ;; Fake contents for source blocks.
  21060. (org-with-wide-buffer
  21061. (goto-char post)
  21062. (forward-line)
  21063. (point)))
  21064. ((memq type '(footnote-definition item plain-list))
  21065. ;; Contents in these elements could start on
  21066. ;; the same line as the beginning of the
  21067. ;; element. Make sure we start indenting
  21068. ;; from the second line.
  21069. (org-with-wide-buffer
  21070. (goto-char post)
  21071. (end-of-line)
  21072. (skip-chars-forward " \r\t\n")
  21073. (if (eobp) (point) (line-beginning-position))))
  21074. (t (org-element-property :contents-begin element)))))
  21075. (cend (copy-marker
  21076. (or (org-element-property :contents-end element)
  21077. ;; Fake contents for source blocks.
  21078. (org-with-wide-buffer
  21079. (goto-char element-end)
  21080. (skip-chars-backward " \r\t\n")
  21081. (line-beginning-position)))
  21082. t)))
  21083. ;; Do not change items indentation individually as it
  21084. ;; might break the list as a whole. On the other
  21085. ;; hand, when at a plain list, indent it as a whole.
  21086. (cond ((eq type 'plain-list)
  21087. (let ((offset (- ind (org-get-indentation))))
  21088. (unless (zerop offset)
  21089. (indent-rigidly (org-element-property :begin element)
  21090. (org-element-property :end element)
  21091. offset))
  21092. (goto-char cbeg)))
  21093. ((eq type 'item) (goto-char cbeg))
  21094. (t (funcall indent-to ind (min cbeg end))))
  21095. (when (< (point) end)
  21096. (cl-case type
  21097. ((example-block export-block verse-block))
  21098. (src-block
  21099. ;; In a source block, indent source code
  21100. ;; according to language major mode, but only if
  21101. ;; `org-src-tab-acts-natively' is non-nil.
  21102. (when (and (< (point) end) org-src-tab-acts-natively)
  21103. (ignore-errors
  21104. (org-babel-do-in-edit-buffer
  21105. (indent-region (point-min) (point-max))))))
  21106. (t (org-indent-region (point) (min cend end))))
  21107. (goto-char (min cend end))
  21108. (when (< (point) end)
  21109. (funcall indent-to ind (min element-end end))))
  21110. (set-marker post nil)
  21111. (set-marker cbeg nil)
  21112. (set-marker cend nil))))
  21113. (set-marker element-end nil))))
  21114. (set-marker end nil))))
  21115. (defun org-indent-drawer ()
  21116. "Indent the drawer at point."
  21117. (interactive)
  21118. (unless (save-excursion
  21119. (beginning-of-line)
  21120. (looking-at-p org-drawer-regexp))
  21121. (user-error "Not at a drawer"))
  21122. (let ((element (org-element-at-point)))
  21123. (unless (memq (org-element-type element) '(drawer property-drawer))
  21124. (user-error "Not at a drawer"))
  21125. (org-with-wide-buffer
  21126. (org-indent-region (org-element-property :begin element)
  21127. (org-element-property :end element))))
  21128. (message "Drawer at point indented"))
  21129. (defun org-indent-block ()
  21130. "Indent the block at point."
  21131. (interactive)
  21132. (unless (save-excursion
  21133. (beginning-of-line)
  21134. (let ((case-fold-search t))
  21135. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  21136. (user-error "Not at a block"))
  21137. (let ((element (org-element-at-point)))
  21138. (unless (memq (org-element-type element)
  21139. '(comment-block center-block dynamic-block example-block
  21140. export-block quote-block special-block
  21141. src-block verse-block))
  21142. (user-error "Not at a block"))
  21143. (org-with-wide-buffer
  21144. (org-indent-region (org-element-property :begin element)
  21145. (org-element-property :end element))))
  21146. (message "Block at point indented"))
  21147. ;;; Filling
  21148. ;; We use our own fill-paragraph and auto-fill functions.
  21149. ;; `org-fill-paragraph' relies on adaptive filling and context
  21150. ;; checking. Appropriate `fill-prefix' is computed with
  21151. ;; `org-adaptive-fill-function'.
  21152. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  21153. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  21154. ;; `org-adaptive-fill-function' value. Internally,
  21155. ;; `org-comment-line-break-function' breaks the line.
  21156. ;; `org-setup-filling' installs filling and auto-filling related
  21157. ;; variables during `org-mode' initialization.
  21158. (defvar org-element-paragraph-separate) ; org-element.el
  21159. (defun org-setup-filling ()
  21160. (require 'org-element)
  21161. ;; Prevent auto-fill from inserting unwanted new items.
  21162. (when (boundp 'fill-nobreak-predicate)
  21163. (setq-local
  21164. fill-nobreak-predicate
  21165. (org-uniquify
  21166. (append fill-nobreak-predicate
  21167. '(org-fill-line-break-nobreak-p
  21168. org-fill-paragraph-with-timestamp-nobreak-p)))))
  21169. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  21170. (setq-local paragraph-start paragraph-ending)
  21171. (setq-local paragraph-separate paragraph-ending))
  21172. (setq-local fill-paragraph-function 'org-fill-paragraph)
  21173. (setq-local auto-fill-inhibit-regexp nil)
  21174. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  21175. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  21176. (setq-local comment-line-break-function 'org-comment-line-break-function))
  21177. (defun org-fill-line-break-nobreak-p ()
  21178. "Non-nil when a new line at point would create an Org line break."
  21179. (save-excursion
  21180. (skip-chars-backward "[ \t]")
  21181. (skip-chars-backward "\\\\")
  21182. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  21183. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  21184. "Non-nil when a new line at point would split a timestamp."
  21185. (and (org-at-timestamp-p t)
  21186. (not (looking-at org-ts-regexp-both))))
  21187. (declare-function message-in-body-p "message" ())
  21188. (defvar orgtbl-line-start-regexp) ; From org-table.el
  21189. (defun org-adaptive-fill-function ()
  21190. "Compute a fill prefix for the current line.
  21191. Return fill prefix, as a string, or nil if current line isn't
  21192. meant to be filled. For convenience, if `adaptive-fill-regexp'
  21193. matches in paragraphs or comments, use it."
  21194. (catch 'exit
  21195. (when (derived-mode-p 'message-mode)
  21196. (save-excursion
  21197. (beginning-of-line)
  21198. (cond ((not (message-in-body-p)) (throw 'exit nil))
  21199. ((looking-at-p org-table-line-regexp) (throw 'exit nil))
  21200. ((looking-at message-cite-prefix-regexp)
  21201. (throw 'exit (match-string-no-properties 0)))
  21202. ((looking-at org-outline-regexp)
  21203. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  21204. (org-with-wide-buffer
  21205. (unless (org-at-heading-p)
  21206. (let* ((p (line-beginning-position))
  21207. (element (save-excursion
  21208. (beginning-of-line)
  21209. (org-element-at-point)))
  21210. (type (org-element-type element))
  21211. (post-affiliated (org-element-property :post-affiliated element)))
  21212. (unless (< p post-affiliated)
  21213. (cl-case type
  21214. (comment
  21215. (save-excursion
  21216. (beginning-of-line)
  21217. (looking-at "[ \t]*")
  21218. (concat (match-string 0) "# ")))
  21219. (footnote-definition "")
  21220. ((item plain-list)
  21221. (make-string (org-list-item-body-column post-affiliated) ?\s))
  21222. (paragraph
  21223. ;; Fill prefix is usually the same as the current line,
  21224. ;; unless the paragraph is at the beginning of an item.
  21225. (let ((parent (org-element-property :parent element)))
  21226. (save-excursion
  21227. (beginning-of-line)
  21228. (cond ((eq (org-element-type parent) 'item)
  21229. (make-string (org-list-item-body-column
  21230. (org-element-property :begin parent))
  21231. ?\s))
  21232. ((and adaptive-fill-regexp
  21233. ;; Locally disable
  21234. ;; `adaptive-fill-function' to let
  21235. ;; `fill-context-prefix' handle
  21236. ;; `adaptive-fill-regexp' variable.
  21237. (let (adaptive-fill-function)
  21238. (fill-context-prefix
  21239. post-affiliated
  21240. (org-element-property :end element)))))
  21241. ((looking-at "[ \t]+") (match-string 0))
  21242. (t "")))))
  21243. (comment-block
  21244. ;; Only fill contents if P is within block boundaries.
  21245. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  21246. (forward-line)
  21247. (point)))
  21248. (cend (save-excursion
  21249. (goto-char (org-element-property :end element))
  21250. (skip-chars-backward " \r\t\n")
  21251. (line-beginning-position))))
  21252. (when (and (>= p cbeg) (< p cend))
  21253. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  21254. (match-string 0)
  21255. "")))))))))))
  21256. (declare-function message-goto-body "message" ())
  21257. (defvar message-cite-prefix-regexp) ; From message.el
  21258. (defun org-fill-paragraph (&optional justify)
  21259. "Fill element at point, when applicable.
  21260. This function only applies to comment blocks, comments, example
  21261. blocks and paragraphs. Also, as a special case, re-align table
  21262. when point is at one.
  21263. If JUSTIFY is non-nil (interactively, with prefix argument),
  21264. justify as well. If `sentence-end-double-space' is non-nil, then
  21265. period followed by one space does not end a sentence, so don't
  21266. break a line there. The variable `fill-column' controls the
  21267. width for filling.
  21268. For convenience, when point is at a plain list, an item or
  21269. a footnote definition, try to fill the first paragraph within."
  21270. (interactive)
  21271. (if (and (derived-mode-p 'message-mode)
  21272. (or (not (message-in-body-p))
  21273. (save-excursion (move-beginning-of-line 1)
  21274. (looking-at message-cite-prefix-regexp))))
  21275. ;; First ensure filling is correct in message-mode.
  21276. (let ((fill-paragraph-function
  21277. (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
  21278. (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
  21279. (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
  21280. (paragraph-separate
  21281. (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
  21282. (fill-paragraph nil))
  21283. (with-syntax-table org-mode-transpose-word-syntax-table
  21284. ;; Move to end of line in order to get the first paragraph
  21285. ;; within a plain list or a footnote definition.
  21286. (let ((element (save-excursion
  21287. (end-of-line)
  21288. (or (ignore-errors (org-element-at-point))
  21289. (user-error "An element cannot be parsed line %d"
  21290. (line-number-at-pos (point)))))))
  21291. ;; First check if point is in a blank line at the beginning of
  21292. ;; the buffer. In that case, ignore filling.
  21293. (cl-case (org-element-type element)
  21294. ;; Use major mode filling function is src blocks.
  21295. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  21296. ;; Align Org tables, leave table.el tables as-is.
  21297. (table-row (org-table-align) t)
  21298. (table
  21299. (when (eq (org-element-property :type element) 'org)
  21300. (save-excursion
  21301. (goto-char (org-element-property :post-affiliated element))
  21302. (org-table-align)))
  21303. t)
  21304. (paragraph
  21305. ;; Paragraphs may contain `line-break' type objects.
  21306. (let ((beg (max (point-min)
  21307. (org-element-property :contents-begin element)))
  21308. (end (min (point-max)
  21309. (org-element-property :contents-end element))))
  21310. ;; Do nothing if point is at an affiliated keyword.
  21311. (if (< (line-end-position) beg) t
  21312. (when (derived-mode-p 'message-mode)
  21313. ;; In `message-mode', do not fill following citation
  21314. ;; in current paragraph nor text before message body.
  21315. (let ((body-start (save-excursion (message-goto-body))))
  21316. (when body-start (setq beg (max body-start beg))))
  21317. (when (save-excursion
  21318. (re-search-forward
  21319. (concat "^" message-cite-prefix-regexp) end t))
  21320. (setq end (match-beginning 0))))
  21321. ;; Fill paragraph, taking line breaks into account.
  21322. (save-excursion
  21323. (goto-char beg)
  21324. (let ((cuts (list beg)))
  21325. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  21326. (when (eq 'line-break
  21327. (org-element-type
  21328. (save-excursion (backward-char)
  21329. (org-element-context))))
  21330. (push (point) cuts)))
  21331. (dolist (c (delq end cuts))
  21332. (fill-region-as-paragraph c end justify)
  21333. (setq end c))))
  21334. t)))
  21335. ;; Contents of `comment-block' type elements should be
  21336. ;; filled as plain text, but only if point is within block
  21337. ;; markers.
  21338. (comment-block
  21339. (let* ((case-fold-search t)
  21340. (beg (save-excursion
  21341. (goto-char (org-element-property :begin element))
  21342. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  21343. (forward-line)
  21344. (point)))
  21345. (end (save-excursion
  21346. (goto-char (org-element-property :end element))
  21347. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  21348. (line-beginning-position))))
  21349. (if (or (< (point) beg) (> (point) end)) t
  21350. (fill-region-as-paragraph
  21351. (save-excursion (end-of-line)
  21352. (re-search-backward "^[ \t]*$" beg 'move)
  21353. (line-beginning-position))
  21354. (save-excursion (beginning-of-line)
  21355. (re-search-forward "^[ \t]*$" end 'move)
  21356. (line-beginning-position))
  21357. justify))))
  21358. ;; Fill comments.
  21359. (comment
  21360. (let ((begin (org-element-property :post-affiliated element))
  21361. (end (org-element-property :end element)))
  21362. (when (and (>= (point) begin) (<= (point) end))
  21363. (let ((begin (save-excursion
  21364. (end-of-line)
  21365. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  21366. (progn (forward-line) (point))
  21367. begin)))
  21368. (end (save-excursion
  21369. (end-of-line)
  21370. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  21371. (1- (line-beginning-position))
  21372. (skip-chars-backward " \r\t\n")
  21373. (line-end-position)))))
  21374. ;; Do not fill comments when at a blank line.
  21375. (when (> end begin)
  21376. (let ((fill-prefix
  21377. (save-excursion
  21378. (beginning-of-line)
  21379. (looking-at "[ \t]*#")
  21380. (let ((comment-prefix (match-string 0)))
  21381. (goto-char (match-end 0))
  21382. (if (looking-at adaptive-fill-regexp)
  21383. (concat comment-prefix (match-string 0))
  21384. (concat comment-prefix " "))))))
  21385. (save-excursion
  21386. (fill-region-as-paragraph begin end justify))))))
  21387. t))
  21388. ;; Ignore every other element.
  21389. (otherwise t))))))
  21390. (defun org-auto-fill-function ()
  21391. "Auto-fill function."
  21392. ;; Check if auto-filling is meaningful.
  21393. (let ((fc (current-fill-column)))
  21394. (when (and fc (> (current-column) fc))
  21395. (let* ((fill-prefix (org-adaptive-fill-function))
  21396. ;; Enforce empty fill prefix, if required. Otherwise, it
  21397. ;; will be computed again.
  21398. (adaptive-fill-mode (not (equal fill-prefix ""))))
  21399. (when fill-prefix (do-auto-fill))))))
  21400. (defun org-comment-line-break-function (&optional soft)
  21401. "Break line at point and indent, continuing comment if within one.
  21402. The inserted newline is marked hard if variable
  21403. `use-hard-newlines' is true, unless optional argument SOFT is
  21404. non-nil."
  21405. (if soft (insert-and-inherit ?\n) (newline 1))
  21406. (save-excursion (forward-char -1) (delete-horizontal-space))
  21407. (delete-horizontal-space)
  21408. (indent-to-left-margin)
  21409. (insert-before-markers-and-inherit fill-prefix))
  21410. ;;; Fixed Width Areas
  21411. (defun org-toggle-fixed-width ()
  21412. "Toggle fixed-width markup.
  21413. Add or remove fixed-width markup on current line, whenever it
  21414. makes sense. Return an error otherwise.
  21415. If a region is active and if it contains only fixed-width areas
  21416. or blank lines, remove all fixed-width markup in it. If the
  21417. region contains anything else, convert all non-fixed-width lines
  21418. to fixed-width ones.
  21419. Blank lines at the end of the region are ignored unless the
  21420. region only contains such lines."
  21421. (interactive)
  21422. (if (not (org-region-active-p))
  21423. ;; No region:
  21424. ;;
  21425. ;; Remove fixed width marker only in a fixed-with element.
  21426. ;;
  21427. ;; Add fixed width maker in paragraphs, in blank lines after
  21428. ;; elements or at the beginning of a headline or an inlinetask,
  21429. ;; and before any one-line elements (e.g., a clock).
  21430. (progn
  21431. (beginning-of-line)
  21432. (let* ((element (org-element-at-point))
  21433. (type (org-element-type element)))
  21434. (cond
  21435. ((and (eq type 'fixed-width)
  21436. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  21437. (replace-match
  21438. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  21439. ((and (memq type '(babel-call clock comment diary-sexp headline
  21440. horizontal-rule keyword paragraph
  21441. planning))
  21442. (<= (org-element-property :post-affiliated element) (point)))
  21443. (skip-chars-forward " \t")
  21444. (insert ": "))
  21445. ((and (looking-at-p "[ \t]*$")
  21446. (or (eq type 'inlinetask)
  21447. (save-excursion
  21448. (skip-chars-forward " \r\t\n")
  21449. (<= (org-element-property :end element) (point)))))
  21450. (delete-region (point) (line-end-position))
  21451. (org-indent-line)
  21452. (insert ": "))
  21453. (t (user-error "Cannot insert a fixed-width line here")))))
  21454. ;; Region active.
  21455. (let* ((begin (save-excursion
  21456. (goto-char (region-beginning))
  21457. (line-beginning-position)))
  21458. (end (copy-marker
  21459. (save-excursion
  21460. (goto-char (region-end))
  21461. (unless (eolp) (beginning-of-line))
  21462. (if (save-excursion (re-search-backward "\\S-" begin t))
  21463. (progn (skip-chars-backward " \r\t\n") (point))
  21464. (point)))))
  21465. (all-fixed-width-p
  21466. (catch 'not-all-p
  21467. (save-excursion
  21468. (goto-char begin)
  21469. (skip-chars-forward " \r\t\n")
  21470. (when (eobp) (throw 'not-all-p nil))
  21471. (while (< (point) end)
  21472. (let ((element (org-element-at-point)))
  21473. (if (eq (org-element-type element) 'fixed-width)
  21474. (goto-char (org-element-property :end element))
  21475. (throw 'not-all-p nil))))
  21476. t))))
  21477. (if all-fixed-width-p
  21478. (save-excursion
  21479. (goto-char begin)
  21480. (while (< (point) end)
  21481. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  21482. (replace-match
  21483. "" nil nil nil
  21484. (if (= (line-end-position) (match-end 0)) 0 1)))
  21485. (forward-line)))
  21486. (let ((min-ind (point-max)))
  21487. ;; Find minimum indentation across all lines.
  21488. (save-excursion
  21489. (goto-char begin)
  21490. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  21491. (setq min-ind 0)
  21492. (catch 'zerop
  21493. (while (< (point) end)
  21494. (unless (looking-at-p "[ \t]*$")
  21495. (let ((ind (org-get-indentation)))
  21496. (setq min-ind (min min-ind ind))
  21497. (when (zerop ind) (throw 'zerop t))))
  21498. (forward-line)))))
  21499. ;; Loop over all lines and add fixed-width markup everywhere
  21500. ;; but in fixed-width lines.
  21501. (save-excursion
  21502. (goto-char begin)
  21503. (while (< (point) end)
  21504. (cond
  21505. ((org-at-heading-p)
  21506. (insert ": ")
  21507. (forward-line)
  21508. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  21509. (insert ":")
  21510. (forward-line)))
  21511. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  21512. (let* ((element (org-element-at-point))
  21513. (element-end (org-element-property :end element)))
  21514. (if (eq (org-element-type element) 'fixed-width)
  21515. (progn (goto-char element-end)
  21516. (skip-chars-backward " \r\t\n")
  21517. (forward-line))
  21518. (let ((limit (min end element-end)))
  21519. (while (< (point) limit)
  21520. (org-move-to-column min-ind t)
  21521. (insert ": ")
  21522. (forward-line))))))
  21523. (t
  21524. (org-move-to-column min-ind t)
  21525. (insert ": ")
  21526. (forward-line)))))))
  21527. (set-marker end nil))))
  21528. ;;; Comments
  21529. ;; Org comments syntax is quite complex. It requires the entire line
  21530. ;; to be just a comment. Also, even with the right syntax at the
  21531. ;; beginning of line, some some elements (i.e. verse-block or
  21532. ;; example-block) don't accept comments. Usual Emacs comment commands
  21533. ;; cannot cope with those requirements. Therefore, Org replaces them.
  21534. ;; Org still relies on `comment-dwim', but cannot trust
  21535. ;; `comment-only-p'. So, `comment-region-function' and
  21536. ;; `uncomment-region-function' both point
  21537. ;; to`org-comment-or-uncomment-region'. Eventually,
  21538. ;; `org-insert-comment' takes care of insertion of comments at the
  21539. ;; beginning of line.
  21540. ;; `org-setup-comments-handling' install comments related variables
  21541. ;; during `org-mode' initialization.
  21542. (defun org-setup-comments-handling ()
  21543. (interactive)
  21544. (setq-local comment-use-syntax nil)
  21545. (setq-local comment-start "# ")
  21546. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  21547. (setq-local comment-insert-comment-function 'org-insert-comment)
  21548. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  21549. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  21550. (defun org-insert-comment ()
  21551. "Insert an empty comment above current line.
  21552. If the line is empty, insert comment at its beginning. When
  21553. point is within a source block, comment according to the related
  21554. major mode."
  21555. (if (let ((element (org-element-at-point)))
  21556. (and (eq (org-element-type element) 'src-block)
  21557. (< (save-excursion
  21558. (goto-char (org-element-property :post-affiliated element))
  21559. (line-end-position))
  21560. (point))
  21561. (> (save-excursion
  21562. (goto-char (org-element-property :end element))
  21563. (skip-chars-backward " \r\t\n")
  21564. (line-beginning-position))
  21565. (point))))
  21566. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21567. (beginning-of-line)
  21568. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  21569. (open-line 1))
  21570. (org-indent-line)
  21571. (insert "# ")))
  21572. (defvar comment-empty-lines) ; From newcomment.el.
  21573. (defun org-comment-or-uncomment-region (beg end &rest _)
  21574. "Comment or uncomment each non-blank line in the region.
  21575. Uncomment each non-blank line between BEG and END if it only
  21576. contains commented lines. Otherwise, comment them. If region is
  21577. strictly within a source block, use appropriate comment syntax."
  21578. (if (let ((element (org-element-at-point)))
  21579. (and (eq (org-element-type element) 'src-block)
  21580. (< (save-excursion
  21581. (goto-char (org-element-property :post-affiliated element))
  21582. (line-end-position))
  21583. beg)
  21584. (>= (save-excursion
  21585. (goto-char (org-element-property :end element))
  21586. (skip-chars-backward " \r\t\n")
  21587. (line-beginning-position))
  21588. end)))
  21589. ;; Translate region boundaries for the Org buffer to the source
  21590. ;; buffer.
  21591. (let ((offset (- end beg)))
  21592. (save-excursion
  21593. (goto-char beg)
  21594. (org-babel-do-in-edit-buffer
  21595. (comment-or-uncomment-region (point) (+ offset (point))))))
  21596. (save-restriction
  21597. ;; Restrict region
  21598. (narrow-to-region (save-excursion (goto-char beg)
  21599. (skip-chars-forward " \r\t\n" end)
  21600. (line-beginning-position))
  21601. (save-excursion (goto-char end)
  21602. (skip-chars-backward " \r\t\n" beg)
  21603. (line-end-position)))
  21604. (let ((uncommentp
  21605. ;; UNCOMMENTP is non-nil when every non blank line between
  21606. ;; BEG and END is a comment.
  21607. (save-excursion
  21608. (goto-char (point-min))
  21609. (while (and (not (eobp))
  21610. (let ((element (org-element-at-point)))
  21611. (and (eq (org-element-type element) 'comment)
  21612. (goto-char (min (point-max)
  21613. (org-element-property
  21614. :end element)))))))
  21615. (eobp))))
  21616. (if uncommentp
  21617. ;; Only blank lines and comments in region: uncomment it.
  21618. (save-excursion
  21619. (goto-char (point-min))
  21620. (while (not (eobp))
  21621. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  21622. (replace-match "" nil nil nil 1))
  21623. (forward-line)))
  21624. ;; Comment each line in region.
  21625. (let ((min-indent (point-max)))
  21626. ;; First find the minimum indentation across all lines.
  21627. (save-excursion
  21628. (goto-char (point-min))
  21629. (while (and (not (eobp)) (not (zerop min-indent)))
  21630. (unless (looking-at "[ \t]*$")
  21631. (setq min-indent (min min-indent (current-indentation))))
  21632. (forward-line)))
  21633. ;; Then loop over all lines.
  21634. (save-excursion
  21635. (goto-char (point-min))
  21636. (while (not (eobp))
  21637. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  21638. ;; Don't get fooled by invisible text (e.g. link path)
  21639. ;; when moving to column MIN-INDENT.
  21640. (let ((buffer-invisibility-spec nil))
  21641. (org-move-to-column min-indent t))
  21642. (insert comment-start))
  21643. (forward-line)))))))))
  21644. (defun org-comment-dwim (_arg)
  21645. "Call `comment-dwim' within a source edit buffer if needed."
  21646. (interactive "*P")
  21647. (if (org-in-src-block-p)
  21648. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21649. (call-interactively 'comment-dwim)))
  21650. ;;; Timestamps API
  21651. ;; This section contains tools to operate on timestamp objects, as
  21652. ;; returned by, e.g. `org-element-context'.
  21653. (defun org-timestamp--to-internal-time (timestamp &optional end)
  21654. "Encode TIMESTAMP object into Emacs internal time.
  21655. Use end of date range or time range when END is non-nil."
  21656. (apply #'encode-time
  21657. (cons 0
  21658. (mapcar
  21659. (lambda (prop) (or (org-element-property prop timestamp) 0))
  21660. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  21661. '(:minute-start :hour-start :day-start :month-start
  21662. :year-start))))))
  21663. (defun org-timestamp-has-time-p (timestamp)
  21664. "Non-nil when TIMESTAMP has a time specified."
  21665. (org-element-property :hour-start timestamp))
  21666. (defun org-timestamp-format (timestamp format &optional end utc)
  21667. "Format a TIMESTAMP object into a string.
  21668. FORMAT is a format specifier to be passed to
  21669. `format-time-string'.
  21670. When optional argument END is non-nil, use end of date-range or
  21671. time-range, if possible.
  21672. When optional argument UTC is non-nil, time will be expressed as
  21673. Universal Time."
  21674. (format-time-string
  21675. format (org-timestamp--to-internal-time timestamp end)
  21676. (and utc t)))
  21677. (defun org-timestamp-split-range (timestamp &optional end)
  21678. "Extract a TIMESTAMP object from a date or time range.
  21679. END, when non-nil, means extract the end of the range.
  21680. Otherwise, extract its start.
  21681. Return a new timestamp object."
  21682. (let ((type (org-element-property :type timestamp)))
  21683. (if (memq type '(active inactive diary)) timestamp
  21684. (let ((split-ts (org-element-copy timestamp)))
  21685. ;; Set new type.
  21686. (org-element-put-property
  21687. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  21688. ;; Copy start properties over end properties if END is
  21689. ;; non-nil. Otherwise, copy end properties over `start' ones.
  21690. (let ((p-alist '((:minute-start . :minute-end)
  21691. (:hour-start . :hour-end)
  21692. (:day-start . :day-end)
  21693. (:month-start . :month-end)
  21694. (:year-start . :year-end))))
  21695. (dolist (p-cell p-alist)
  21696. (org-element-put-property
  21697. split-ts
  21698. (funcall (if end #'car #'cdr) p-cell)
  21699. (org-element-property
  21700. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  21701. ;; Eventually refresh `:raw-value'.
  21702. (org-element-put-property split-ts :raw-value nil)
  21703. (org-element-put-property
  21704. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  21705. (defun org-timestamp-translate (timestamp &optional boundary)
  21706. "Translate TIMESTAMP object to custom format.
  21707. Format string is defined in `org-time-stamp-custom-formats',
  21708. which see.
  21709. When optional argument BOUNDARY is non-nil, it is either the
  21710. symbol `start' or `end'. In this case, only translate the
  21711. starting or ending part of TIMESTAMP if it is a date or time
  21712. range. Otherwise, translate both parts.
  21713. Return timestamp as-is if `org-display-custom-times' is nil or if
  21714. it has a `diary' type."
  21715. (let ((type (org-element-property :type timestamp)))
  21716. (if (or (not org-display-custom-times) (eq type 'diary))
  21717. (org-element-interpret-data timestamp)
  21718. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  21719. org-time-stamp-custom-formats)))
  21720. (if (and (not boundary) (memq type '(active-range inactive-range)))
  21721. (concat (org-timestamp-format timestamp fmt)
  21722. "--"
  21723. (org-timestamp-format timestamp fmt t))
  21724. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  21725. ;;; Other stuff.
  21726. (defvar reftex-docstruct-symbol)
  21727. (defvar org--rds)
  21728. (defun org-reftex-citation ()
  21729. "Use reftex-citation to insert a citation into the buffer.
  21730. This looks for a line like
  21731. #+BIBLIOGRAPHY: foo plain option:-d
  21732. and derives from it that foo.bib is the bibliography file relevant
  21733. for this document. It then installs the necessary environment for RefTeX
  21734. to work in this buffer and calls `reftex-citation' to insert a citation
  21735. into the buffer.
  21736. Export of such citations to both LaTeX and HTML is handled by the contributed
  21737. package ox-bibtex by Taru Karttunen."
  21738. (interactive)
  21739. (let ((reftex-docstruct-symbol 'org--rds)
  21740. org--rds bib)
  21741. (org-with-wide-buffer
  21742. (let ((case-fold-search t)
  21743. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21744. (if (not (save-excursion
  21745. (or (re-search-forward re nil t)
  21746. (re-search-backward re nil t))))
  21747. (user-error "No bibliography defined in file")
  21748. (setq bib (concat (match-string 1) ".bib")
  21749. org--rds (list (list 'bib bib))))))
  21750. (call-interactively 'reftex-citation)))
  21751. ;;;; Functions extending outline functionality
  21752. (defun org-beginning-of-line (&optional n)
  21753. "Go to the beginning of the current visible line.
  21754. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21755. tags on the first attempt, and only move to after the tags when
  21756. the cursor is already beyond the end of the headline.
  21757. With argument N not nil or 1, move forward N - 1 lines first."
  21758. (interactive "^p")
  21759. (let ((origin (point))
  21760. (special (pcase org-special-ctrl-a/e
  21761. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  21762. deactivate-mark)
  21763. ;; First move to a visible line.
  21764. (if (bound-and-true-p visual-line-mode)
  21765. (beginning-of-visual-line n)
  21766. (move-beginning-of-line n)
  21767. ;; `move-beginning-of-line' may leave point after invisible
  21768. ;; characters if line starts with such of these (e.g., with
  21769. ;; a link at column 0). Really move to the beginning of the
  21770. ;; current visible line.
  21771. (beginning-of-line))
  21772. (cond
  21773. ;; No special behavior. Point is already at the beginning of
  21774. ;; a line, logical or visual.
  21775. ((not special))
  21776. ;; `beginning-of-visual-line' left point before logical beginning
  21777. ;; of line: point is at the beginning of a visual line. Bail
  21778. ;; out.
  21779. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  21780. ((looking-at org-complex-heading-regexp)
  21781. ;; At a headline, special position is before the title, but
  21782. ;; after any TODO keyword or priority cookie.
  21783. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21784. (line-end-position)))
  21785. (bol (point)))
  21786. (if (eq special 'reversed)
  21787. (when (and (= origin bol) (eq last-command this-command))
  21788. (goto-char refpos))
  21789. (when (or (> origin refpos) (= origin bol))
  21790. (goto-char refpos)))))
  21791. ((and (looking-at org-list-full-item-re)
  21792. (memq (org-element-type (save-match-data (org-element-at-point)))
  21793. '(item plain-list)))
  21794. ;; Set special position at first white space character after
  21795. ;; bullet, and check-box, if any.
  21796. (let ((after-bullet
  21797. (let ((box (match-end 3)))
  21798. (cond ((not box) (match-end 1))
  21799. ((eq (char-after box) ?\s) (1+ box))
  21800. (t box)))))
  21801. (if (eq special 'reversed)
  21802. (when (and (= (point) origin) (eq last-command this-command))
  21803. (goto-char after-bullet))
  21804. (when (or (> origin after-bullet) (= (point) origin))
  21805. (goto-char after-bullet)))))
  21806. ;; No special context. Point is already at beginning of line.
  21807. (t nil))))
  21808. (defun org-end-of-line (&optional n)
  21809. "Go to the end of the line, but before ellipsis, if any.
  21810. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21811. tags on the first attempt, and only move to after the tags when
  21812. the cursor is already beyond the end of the headline.
  21813. With argument N not nil or 1, move forward N - 1 lines first."
  21814. (interactive "^p")
  21815. (let ((origin (point))
  21816. (special (pcase org-special-ctrl-a/e
  21817. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  21818. deactivate-mark)
  21819. ;; First move to a visible line.
  21820. (if (bound-and-true-p visual-line-mode)
  21821. (beginning-of-visual-line n)
  21822. (move-beginning-of-line n))
  21823. (cond
  21824. ;; At a headline, with tags.
  21825. ((and special
  21826. (save-excursion
  21827. (beginning-of-line)
  21828. (looking-at org-complex-heading-regexp))
  21829. (match-end 5))
  21830. (let ((tags (save-excursion
  21831. (goto-char (match-beginning 5))
  21832. (skip-chars-backward " \t")
  21833. (point)))
  21834. (visual-end (and (bound-and-true-p visual-line-mode)
  21835. (save-excursion
  21836. (end-of-visual-line)
  21837. (point)))))
  21838. ;; If `end-of-visual-line' brings us before end of line or
  21839. ;; even tags, i.e., the headline spans over multiple visual
  21840. ;; lines, move there.
  21841. (cond ((and visual-end
  21842. (< visual-end tags)
  21843. (<= origin visual-end))
  21844. (goto-char visual-end))
  21845. ((eq special 'reversed)
  21846. (if (and (= origin (line-end-position))
  21847. (eq this-command last-command))
  21848. (goto-char tags)
  21849. (end-of-line)))
  21850. (t
  21851. (if (or (< origin tags) (= origin (line-end-position)))
  21852. (goto-char tags)
  21853. (end-of-line))))))
  21854. ((bound-and-true-p visual-line-mode)
  21855. (let ((bol (line-beginning-position)))
  21856. (end-of-visual-line)
  21857. ;; If `end-of-visual-line' gets us past the ellipsis at the
  21858. ;; end of a line, backtrack and use `end-of-line' instead.
  21859. (when (/= bol (line-beginning-position))
  21860. (goto-char bol)
  21861. (end-of-line))))
  21862. (t (end-of-line)))))
  21863. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21864. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21865. (defun org-backward-sentence (&optional _arg)
  21866. "Go to beginning of sentence, or beginning of table field.
  21867. This will call `backward-sentence' or `org-table-beginning-of-field',
  21868. depending on context."
  21869. (interactive)
  21870. (let* ((element (org-element-at-point))
  21871. (contents-begin (org-element-property :contents-begin element))
  21872. (table (org-element-lineage element '(table) t)))
  21873. (if (and table
  21874. (> (point) contents-begin)
  21875. (<= (point) (org-element-property :contents-end table)))
  21876. (call-interactively #'org-table-beginning-of-field)
  21877. (save-restriction
  21878. (when (and contents-begin
  21879. (< (point-min) contents-begin)
  21880. (> (point) contents-begin))
  21881. (narrow-to-region contents-begin
  21882. (org-element-property :contents-end element)))
  21883. (call-interactively #'backward-sentence)))))
  21884. (defun org-forward-sentence (&optional _arg)
  21885. "Go to end of sentence, or end of table field.
  21886. This will call `forward-sentence' or `org-table-end-of-field',
  21887. depending on context."
  21888. (interactive)
  21889. (let* ((element (org-element-at-point))
  21890. (contents-end (org-element-property :contents-end element))
  21891. (table (org-element-lineage element '(table) t)))
  21892. (if (and table
  21893. (>= (point) (org-element-property :contents-begin table))
  21894. (< (point) contents-end))
  21895. (call-interactively #'org-table-end-of-field)
  21896. (save-restriction
  21897. (when (and contents-end
  21898. (> (point-max) contents-end)
  21899. ;; Skip blank lines between elements.
  21900. (< (org-element-property :end element)
  21901. (save-excursion (goto-char contents-end)
  21902. (skip-chars-forward " \r\t\n"))))
  21903. (narrow-to-region (org-element-property :contents-begin element)
  21904. contents-end))
  21905. (call-interactively #'forward-sentence)))))
  21906. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21907. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21908. (defun org-kill-line (&optional _arg)
  21909. "Kill line, to tags or end of line."
  21910. (interactive)
  21911. (cond
  21912. ((or (not org-special-ctrl-k)
  21913. (bolp)
  21914. (not (org-at-heading-p)))
  21915. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  21916. org-ctrl-k-protect-subtree
  21917. (or (eq org-ctrl-k-protect-subtree 'error)
  21918. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21919. (user-error "C-k aborted as it would kill a hidden subtree"))
  21920. (call-interactively
  21921. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21922. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  21923. (kill-region (point) (match-beginning 1))
  21924. (org-set-tags nil t))
  21925. (t (kill-region (point) (point-at-eol)))))
  21926. (define-key org-mode-map "\C-k" 'org-kill-line)
  21927. (defun org-yank (&optional arg)
  21928. "Yank. If the kill is a subtree, treat it specially.
  21929. This command will look at the current kill and check if is a single
  21930. subtree, or a series of subtrees[1]. If it passes the test, and if the
  21931. cursor is at the beginning of a line or after the stars of a currently
  21932. empty headline, then the yank is handled specially. How exactly depends
  21933. on the value of the following variables.
  21934. `org-yank-folded-subtrees'
  21935. By default, this variable is non-nil, which results in
  21936. subtree(s) being folded after insertion, except if doing so
  21937. would swallow text after the yanked text.
  21938. `org-yank-adjusted-subtrees'
  21939. When non-nil (the default value is nil), the subtree will be
  21940. promoted or demoted in order to fit into the local outline tree
  21941. structure, which means that the level will be adjusted so that it
  21942. becomes the smaller one of the two *visible* surrounding headings.
  21943. Any prefix to this command will cause `yank' to be called directly with
  21944. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  21945. will just
  21946. plainly yank the text as it is.
  21947. \[1] The test checks if the first non-white line is a heading
  21948. and if there are no other headings with fewer stars."
  21949. (interactive "P")
  21950. (org-yank-generic 'yank arg))
  21951. (defun org-yank-generic (command arg)
  21952. "Perform some yank-like command.
  21953. This function implements the behavior described in the `org-yank'
  21954. documentation. However, it has been generalized to work for any
  21955. interactive command with similar behavior."
  21956. ;; pretend to be command COMMAND
  21957. (setq this-command command)
  21958. (if arg
  21959. (call-interactively command)
  21960. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  21961. (and (org-kill-is-subtree-p)
  21962. (or (bolp)
  21963. (and (looking-at "[ \t]*$")
  21964. (string-match
  21965. "\\`\\*+\\'"
  21966. (buffer-substring (point-at-bol) (point)))))))
  21967. swallowp)
  21968. (cond
  21969. ((and subtreep org-yank-folded-subtrees)
  21970. (let ((beg (point))
  21971. end)
  21972. (if (and subtreep org-yank-adjusted-subtrees)
  21973. (org-paste-subtree nil nil 'for-yank)
  21974. (call-interactively command))
  21975. (setq end (point))
  21976. (goto-char beg)
  21977. (when (and (bolp) subtreep
  21978. (not (setq swallowp
  21979. (org-yank-folding-would-swallow-text beg end))))
  21980. (org-with-limited-levels
  21981. (or (looking-at org-outline-regexp)
  21982. (re-search-forward org-outline-regexp-bol end t))
  21983. (while (and (< (point) end) (looking-at org-outline-regexp))
  21984. (outline-hide-subtree)
  21985. (org-cycle-show-empty-lines 'folded)
  21986. (condition-case nil
  21987. (outline-forward-same-level 1)
  21988. (error (goto-char end))))))
  21989. (when swallowp
  21990. (message
  21991. "Inserted text not folded because that would swallow text"))
  21992. (goto-char end)
  21993. (skip-chars-forward " \t\n\r")
  21994. (beginning-of-line 1)
  21995. (push-mark beg 'nomsg)))
  21996. ((and subtreep org-yank-adjusted-subtrees)
  21997. (let ((beg (point-at-bol)))
  21998. (org-paste-subtree nil nil 'for-yank)
  21999. (push-mark beg 'nomsg)))
  22000. (t
  22001. (call-interactively command))))))
  22002. (defun org-yank-folding-would-swallow-text (beg end)
  22003. "Would hide-subtree at BEG swallow any text after END?"
  22004. (let (level)
  22005. (org-with-limited-levels
  22006. (save-excursion
  22007. (goto-char beg)
  22008. (when (or (looking-at org-outline-regexp)
  22009. (re-search-forward org-outline-regexp-bol end t))
  22010. (setq level (org-outline-level)))
  22011. (goto-char end)
  22012. (skip-chars-forward " \t\r\n\v\f")
  22013. (not (or (eobp)
  22014. (and (bolp) (looking-at-p org-outline-regexp)
  22015. (<= (org-outline-level) level))))))))
  22016. (define-key org-mode-map "\C-y" 'org-yank)
  22017. (defun org-truely-invisible-p ()
  22018. "Check if point is at a character currently not visible.
  22019. This version does not only check the character property, but also
  22020. `visible-mode'."
  22021. ;; Early versions of noutline don't have `outline-invisible-p'.
  22022. (unless (bound-and-true-p visible-mode)
  22023. (outline-invisible-p)))
  22024. (defun org-invisible-p2 ()
  22025. "Check if point is at a character currently not visible."
  22026. (save-excursion
  22027. (when (and (eolp) (not (bobp))) (backward-char 1))
  22028. ;; Early versions of noutline don't have `outline-invisible-p'.
  22029. (outline-invisible-p)))
  22030. (defun org-back-to-heading (&optional invisible-ok)
  22031. "Call `outline-back-to-heading', but provide a better error message."
  22032. (condition-case nil
  22033. (outline-back-to-heading invisible-ok)
  22034. (error (error "Before first headline at position %d in buffer %s"
  22035. (point) (current-buffer)))))
  22036. (defun org-before-first-heading-p ()
  22037. "Before first heading?"
  22038. (save-excursion
  22039. (end-of-line)
  22040. (null (re-search-backward org-outline-regexp-bol nil t))))
  22041. (defun org-at-heading-p (&optional ignored)
  22042. (outline-on-heading-p t))
  22043. (defun org-in-commented-heading-p (&optional no-inheritance)
  22044. "Non-nil if point is under a commented heading.
  22045. This function also checks ancestors of the current headline,
  22046. unless optional argument NO-INHERITANCE is non-nil."
  22047. (cond
  22048. ((org-before-first-heading-p) nil)
  22049. ((let ((headline (nth 4 (org-heading-components))))
  22050. (and headline
  22051. (let ((case-fold-search nil))
  22052. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  22053. headline)))))
  22054. (no-inheritance nil)
  22055. (t
  22056. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  22057. (defun org-at-comment-p nil
  22058. "Is cursor in a commented line?"
  22059. (save-excursion
  22060. (save-match-data
  22061. (beginning-of-line)
  22062. (looking-at "^[ \t]*# "))))
  22063. (defun org-at-drawer-p nil
  22064. "Is cursor at a drawer keyword?"
  22065. (save-excursion
  22066. (move-beginning-of-line 1)
  22067. (looking-at org-drawer-regexp)))
  22068. (defun org-at-block-p nil
  22069. "Is cursor at a block keyword?"
  22070. (save-excursion
  22071. (move-beginning-of-line 1)
  22072. (looking-at org-block-regexp)))
  22073. (defun org-point-at-end-of-empty-headline ()
  22074. "If point is at the end of an empty headline, return t, else nil.
  22075. If the heading only contains a TODO keyword, it is still still considered
  22076. empty."
  22077. (and (looking-at "[ \t]*$")
  22078. (when org-todo-line-regexp
  22079. (save-excursion
  22080. (beginning-of-line 1)
  22081. (let ((case-fold-search nil))
  22082. (looking-at org-todo-line-regexp)
  22083. (string= (match-string 3) ""))))))
  22084. (defun org-at-heading-or-item-p ()
  22085. (or (org-at-heading-p) (org-at-item-p)))
  22086. (defun org-at-target-p ()
  22087. (or (org-in-regexp org-radio-target-regexp)
  22088. (org-in-regexp org-target-regexp)))
  22089. ;; Compatibility alias with Org versions < 7.8.03
  22090. (defalias 'org-on-target-p 'org-at-target-p)
  22091. (defun org-up-heading-all (arg)
  22092. "Move to the heading line of which the present line is a subheading.
  22093. This function considers both visible and invisible heading lines.
  22094. With argument, move up ARG levels."
  22095. (outline-up-heading arg t))
  22096. (defun org-up-heading-safe ()
  22097. "Move to the heading line of which the present line is a subheading.
  22098. This version will not throw an error. It will return the level of the
  22099. headline found, or nil if no higher level is found.
  22100. Also, this function will be a lot faster than `outline-up-heading',
  22101. because it relies on stars being the outline starters. This can really
  22102. make a significant difference in outlines with very many siblings."
  22103. (when (ignore-errors (org-back-to-heading t))
  22104. (let ((level-up (1- (funcall outline-level))))
  22105. (and (> level-up 0)
  22106. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  22107. (funcall outline-level)))))
  22108. (defun org-first-sibling-p ()
  22109. "Is this heading the first child of its parents?"
  22110. (interactive)
  22111. (let ((re org-outline-regexp-bol)
  22112. level l)
  22113. (unless (org-at-heading-p t)
  22114. (user-error "Not at a heading"))
  22115. (setq level (funcall outline-level))
  22116. (save-excursion
  22117. (if (not (re-search-backward re nil t))
  22118. t
  22119. (setq l (funcall outline-level))
  22120. (< l level)))))
  22121. (defun org-goto-sibling (&optional previous)
  22122. "Goto the next sibling, even if it is invisible.
  22123. When PREVIOUS is set, go to the previous sibling instead. Returns t
  22124. when a sibling was found. When none is found, return nil and don't
  22125. move point."
  22126. (let ((fun (if previous 're-search-backward 're-search-forward))
  22127. (pos (point))
  22128. (re org-outline-regexp-bol)
  22129. level l)
  22130. (when (ignore-errors (org-back-to-heading t))
  22131. (setq level (funcall outline-level))
  22132. (catch 'exit
  22133. (or previous (forward-char 1))
  22134. (while (funcall fun re nil t)
  22135. (setq l (funcall outline-level))
  22136. (when (< l level) (goto-char pos) (throw 'exit nil))
  22137. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  22138. (goto-char pos)
  22139. nil))))
  22140. (defun org-show-siblings ()
  22141. "Show all siblings of the current headline."
  22142. (save-excursion
  22143. (while (org-goto-sibling) (org-flag-heading nil)))
  22144. (save-excursion
  22145. (while (org-goto-sibling 'previous)
  22146. (org-flag-heading nil))))
  22147. (defun org-goto-first-child ()
  22148. "Goto the first child, even if it is invisible.
  22149. Return t when a child was found. Otherwise don't move point and
  22150. return nil."
  22151. (let (level (pos (point)) (re org-outline-regexp-bol))
  22152. (when (ignore-errors (org-back-to-heading t))
  22153. (setq level (outline-level))
  22154. (forward-char 1)
  22155. (if (and (re-search-forward re nil t) (> (outline-level) level))
  22156. (progn (goto-char (match-beginning 0)) t)
  22157. (goto-char pos) nil))))
  22158. (defun org-show-hidden-entry ()
  22159. "Show an entry where even the heading is hidden."
  22160. (save-excursion
  22161. (org-show-entry)))
  22162. (defun org-flag-heading (flag &optional entry)
  22163. "Flag the current heading. FLAG non-nil means make invisible.
  22164. When ENTRY is non-nil, show the entire entry."
  22165. (save-excursion
  22166. (org-back-to-heading t)
  22167. ;; Check if we should show the entire entry
  22168. (if entry
  22169. (progn
  22170. (org-show-entry)
  22171. (save-excursion
  22172. (and (outline-next-heading)
  22173. (org-flag-heading nil))))
  22174. (outline-flag-region (max (point-min) (1- (point)))
  22175. (save-excursion (outline-end-of-heading) (point))
  22176. flag))))
  22177. (defun org-get-next-sibling ()
  22178. "Move to next heading of the same level, and return point.
  22179. If there is no such heading, return nil.
  22180. This is like outline-next-sibling, but invisible headings are ok."
  22181. (let ((level (funcall outline-level)))
  22182. (outline-next-heading)
  22183. (while (and (not (eobp)) (> (funcall outline-level) level))
  22184. (outline-next-heading))
  22185. (unless (or (eobp) (< (funcall outline-level) level))
  22186. (point))))
  22187. (defun org-get-last-sibling ()
  22188. "Move to previous heading of the same level, and return point.
  22189. If there is no such heading, return nil."
  22190. (let ((opoint (point))
  22191. (level (funcall outline-level)))
  22192. (outline-previous-heading)
  22193. (when (and (/= (point) opoint) (outline-on-heading-p t))
  22194. (while (and (> (funcall outline-level) level)
  22195. (not (bobp)))
  22196. (outline-previous-heading))
  22197. (unless (< (funcall outline-level) level)
  22198. (point)))))
  22199. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  22200. "Goto to the end of a subtree."
  22201. ;; This contains an exact copy of the original function, but it uses
  22202. ;; `org-back-to-heading', to make it work also in invisible
  22203. ;; trees. And is uses an invisible-ok argument.
  22204. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  22205. ;; Furthermore, when used inside Org, finding the end of a large subtree
  22206. ;; with many children and grandchildren etc, this can be much faster
  22207. ;; than the outline version.
  22208. (org-back-to-heading invisible-ok)
  22209. (let ((first t)
  22210. (level (funcall outline-level)))
  22211. (if (and (derived-mode-p 'org-mode) (< level 1000))
  22212. ;; A true heading (not a plain list item), in Org
  22213. ;; This means we can easily find the end by looking
  22214. ;; only for the right number of stars. Using a regexp to do
  22215. ;; this is so much faster than using a Lisp loop.
  22216. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  22217. (forward-char 1)
  22218. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  22219. ;; something else, do it the slow way
  22220. (while (and (not (eobp))
  22221. (or first (> (funcall outline-level) level)))
  22222. (setq first nil)
  22223. (outline-next-heading)))
  22224. (unless to-heading
  22225. (when (memq (preceding-char) '(?\n ?\^M))
  22226. ;; Go to end of line before heading
  22227. (forward-char -1)
  22228. (when (memq (preceding-char) '(?\n ?\^M))
  22229. ;; leave blank line before heading
  22230. (forward-char -1)))))
  22231. (point))
  22232. (defun org-end-of-meta-data (&optional full)
  22233. "Skip planning line and properties drawer in current entry.
  22234. When optional argument FULL is non-nil, also skip empty lines,
  22235. clocking lines and regular drawers at the beginning of the
  22236. entry."
  22237. (org-back-to-heading t)
  22238. (forward-line)
  22239. (when (looking-at-p org-planning-line-re) (forward-line))
  22240. (when (looking-at org-property-drawer-re)
  22241. (goto-char (match-end 0))
  22242. (forward-line))
  22243. (when (and full (not (org-at-heading-p)))
  22244. (catch 'exit
  22245. (let ((end (save-excursion (outline-next-heading) (point)))
  22246. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  22247. (while (not (eobp))
  22248. (cond ((looking-at-p org-drawer-regexp)
  22249. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  22250. (forward-line)
  22251. (throw 'exit t)))
  22252. ((looking-at-p re) (forward-line))
  22253. (t (throw 'exit t))))))))
  22254. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  22255. "Move forward to the ARG'th subheading at same level as this one.
  22256. Stop at the first and last subheadings of a superior heading.
  22257. Normally this only looks at visible headings, but when INVISIBLE-OK is
  22258. non-nil it will also look at invisible ones."
  22259. (interactive "p")
  22260. (if (not (ignore-errors (org-back-to-heading invisible-ok)))
  22261. (if (and arg (< arg 0))
  22262. (goto-char (point-min))
  22263. (outline-next-heading))
  22264. (org-at-heading-p)
  22265. (let ((level (- (match-end 0) (match-beginning 0) 1))
  22266. (f (if (and arg (< arg 0))
  22267. 're-search-backward
  22268. 're-search-forward))
  22269. (count (if arg (abs arg) 1))
  22270. (result (point)))
  22271. (while (and (prog1 (> count 0)
  22272. (forward-char (if (and arg (< arg 0)) -1 1)))
  22273. (funcall f org-outline-regexp-bol nil 'move))
  22274. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  22275. (cond ((< l level) (setq count 0))
  22276. ((and (= l level)
  22277. (or invisible-ok
  22278. (progn
  22279. (goto-char (line-beginning-position))
  22280. (not (outline-invisible-p)))))
  22281. (setq count (1- count))
  22282. (when (eq l level)
  22283. (setq result (point)))))))
  22284. (goto-char result))
  22285. (beginning-of-line 1)))
  22286. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  22287. "Move backward to the ARG'th subheading at same level as this one.
  22288. Stop at the first and last subheadings of a superior heading."
  22289. (interactive "p")
  22290. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  22291. (defun org-next-visible-heading (arg)
  22292. "Move to the next visible heading.
  22293. This function wraps `outline-next-visible-heading' with
  22294. `org-with-limited-levels' in order to skip over inline tasks and
  22295. respect customization of `org-odd-levels-only'."
  22296. (interactive "p")
  22297. (org-with-limited-levels
  22298. (outline-next-visible-heading arg)))
  22299. (defun org-previous-visible-heading (arg)
  22300. "Move to the previous visible heading.
  22301. This function wraps `outline-previous-visible-heading' with
  22302. `org-with-limited-levels' in order to skip over inline tasks and
  22303. respect customization of `org-odd-levels-only'."
  22304. (interactive "p")
  22305. (org-with-limited-levels
  22306. (outline-previous-visible-heading arg)))
  22307. (defun org-next-block (arg &optional backward block-regexp)
  22308. "Jump to the next block.
  22309. With a prefix argument ARG, jump forward ARG many blocks.
  22310. When BACKWARD is non-nil, jump to the previous block.
  22311. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  22312. Match data is set according to this regexp when the function
  22313. returns.
  22314. Return point at beginning of the opening line of found block.
  22315. Throw an error if no block is found."
  22316. (interactive "p")
  22317. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  22318. (case-fold-search t)
  22319. (search-fn (if backward #'re-search-backward #'re-search-forward))
  22320. (count (or arg 1))
  22321. (origin (point))
  22322. last-element)
  22323. (if backward (beginning-of-line) (end-of-line))
  22324. (while (and (> count 0) (funcall search-fn re nil t))
  22325. (let ((element (save-excursion
  22326. (goto-char (match-beginning 0))
  22327. (save-match-data (org-element-at-point)))))
  22328. (when (and (memq (org-element-type element)
  22329. '(center-block comment-block dynamic-block
  22330. example-block export-block quote-block
  22331. special-block src-block verse-block))
  22332. (<= (match-beginning 0)
  22333. (org-element-property :post-affiliated element)))
  22334. (setq last-element element)
  22335. (cl-decf count))))
  22336. (if (= count 0)
  22337. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  22338. (save-match-data (org-show-context)))
  22339. (goto-char origin)
  22340. (user-error "No %s code blocks" (if backward "previous" "further")))))
  22341. (defun org-previous-block (arg &optional block-regexp)
  22342. "Jump to the previous block.
  22343. With a prefix argument ARG, jump backward ARG many source blocks.
  22344. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  22345. (interactive "p")
  22346. (org-next-block arg t block-regexp))
  22347. (defun org-forward-paragraph ()
  22348. "Move forward to beginning of next paragraph or equivalent.
  22349. The function moves point to the beginning of the next visible
  22350. structural element, which can be a paragraph, a table, a list
  22351. item, etc. It also provides some special moves for convenience:
  22352. - On an affiliated keyword, jump to the beginning of the
  22353. relative element.
  22354. - On an item or a footnote definition, move to the second
  22355. element inside, if any.
  22356. - On a table or a property drawer, jump after it.
  22357. - On a verse or source block, stop after blank lines."
  22358. (interactive)
  22359. (when (eobp) (user-error "Cannot move further down"))
  22360. (let* ((deactivate-mark nil)
  22361. (element (org-element-at-point))
  22362. (type (org-element-type element))
  22363. (post-affiliated (org-element-property :post-affiliated element))
  22364. (contents-begin (org-element-property :contents-begin element))
  22365. (contents-end (org-element-property :contents-end element))
  22366. (end (let ((end (org-element-property :end element)) (parent element))
  22367. (while (and (setq parent (org-element-property :parent parent))
  22368. (= (org-element-property :contents-end parent) end))
  22369. (setq end (org-element-property :end parent)))
  22370. end)))
  22371. (cond ((not element)
  22372. (skip-chars-forward " \r\t\n")
  22373. (or (eobp) (beginning-of-line)))
  22374. ;; On affiliated keywords, move to element's beginning.
  22375. ((< (point) post-affiliated)
  22376. (goto-char post-affiliated))
  22377. ;; At a table row, move to the end of the table. Similarly,
  22378. ;; at a node property, move to the end of the property
  22379. ;; drawer.
  22380. ((memq type '(node-property table-row))
  22381. (goto-char (org-element-property
  22382. :end (org-element-property :parent element))))
  22383. ((memq type '(property-drawer table)) (goto-char end))
  22384. ;; Consider blank lines as separators in verse and source
  22385. ;; blocks to ease editing.
  22386. ((memq type '(src-block verse-block))
  22387. (when (eq type 'src-block)
  22388. (setq contents-end
  22389. (save-excursion (goto-char end)
  22390. (skip-chars-backward " \r\t\n")
  22391. (line-beginning-position))))
  22392. (beginning-of-line)
  22393. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  22394. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  22395. (goto-char end)
  22396. (skip-chars-forward " \r\t\n")
  22397. (if (= (point) contents-end) (goto-char end)
  22398. (beginning-of-line))))
  22399. ;; With no contents, just skip element.
  22400. ((not contents-begin) (goto-char end))
  22401. ;; If contents are invisible, skip the element altogether.
  22402. ((outline-invisible-p (line-end-position))
  22403. (cl-case type
  22404. (headline
  22405. (org-with-limited-levels (outline-next-visible-heading 1)))
  22406. ;; At a plain list, make sure we move to the next item
  22407. ;; instead of skipping the whole list.
  22408. (plain-list (forward-char)
  22409. (org-forward-paragraph))
  22410. (otherwise (goto-char end))))
  22411. ((>= (point) contents-end) (goto-char end))
  22412. ((>= (point) contents-begin)
  22413. ;; This can only happen on paragraphs and plain lists.
  22414. (cl-case type
  22415. (paragraph (goto-char end))
  22416. ;; At a plain list, try to move to second element in
  22417. ;; first item, if possible.
  22418. (plain-list (end-of-line)
  22419. (org-forward-paragraph))))
  22420. ;; When contents start on the middle of a line (e.g. in
  22421. ;; items and footnote definitions), try to reach first
  22422. ;; element starting after current line.
  22423. ((> (line-end-position) contents-begin)
  22424. (end-of-line)
  22425. (org-forward-paragraph))
  22426. (t (goto-char contents-begin)))))
  22427. (defun org-backward-paragraph ()
  22428. "Move backward to start of previous paragraph or equivalent.
  22429. The function moves point to the beginning of the current
  22430. structural element, which can be a paragraph, a table, a list
  22431. item, etc., or to the beginning of the previous visible one if
  22432. point is already there. It also provides some special moves for
  22433. convenience:
  22434. - On an affiliated keyword, jump to the first one.
  22435. - On a table or a property drawer, move to its beginning.
  22436. - On a verse or source block, stop before blank lines."
  22437. (interactive)
  22438. (when (bobp) (user-error "Cannot move further up"))
  22439. (let* ((deactivate-mark nil)
  22440. (element (org-element-at-point))
  22441. (type (org-element-type element))
  22442. (contents-begin (org-element-property :contents-begin element))
  22443. (contents-end (org-element-property :contents-end element))
  22444. (post-affiliated (org-element-property :post-affiliated element))
  22445. (begin (org-element-property :begin element)))
  22446. (cond
  22447. ((not element) (goto-char (point-min)))
  22448. ((= (point) begin)
  22449. (backward-char)
  22450. (org-backward-paragraph))
  22451. ((<= (point) post-affiliated) (goto-char begin))
  22452. ((memq type '(node-property table-row))
  22453. (goto-char (org-element-property
  22454. :post-affiliated (org-element-property :parent element))))
  22455. ((memq type '(property-drawer table)) (goto-char begin))
  22456. ((memq type '(src-block verse-block))
  22457. (when (eq type 'src-block)
  22458. (setq contents-begin
  22459. (save-excursion (goto-char begin) (forward-line) (point))))
  22460. (if (= (point) contents-begin) (goto-char post-affiliated)
  22461. ;; Inside a verse block, see blank lines as paragraph
  22462. ;; separators.
  22463. (let ((origin (point)))
  22464. (skip-chars-backward " \r\t\n" contents-begin)
  22465. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  22466. (skip-chars-forward " \r\t\n" origin)
  22467. (if (= (point) origin) (goto-char contents-begin)
  22468. (beginning-of-line))))))
  22469. ((not contents-begin) (goto-char (or post-affiliated begin)))
  22470. ((eq type 'paragraph)
  22471. (goto-char contents-begin)
  22472. ;; When at first paragraph in an item or a footnote definition,
  22473. ;; move directly to beginning of line.
  22474. (let ((parent-contents
  22475. (org-element-property
  22476. :contents-begin (org-element-property :parent element))))
  22477. (when (and parent-contents (= parent-contents contents-begin))
  22478. (beginning-of-line))))
  22479. ;; At the end of a greater element, move to the beginning of the
  22480. ;; last element within.
  22481. ((>= (point) contents-end)
  22482. (goto-char (1- contents-end))
  22483. (org-backward-paragraph))
  22484. (t (goto-char (or post-affiliated begin))))
  22485. ;; Ensure we never leave point invisible.
  22486. (when (outline-invisible-p (point)) (beginning-of-visual-line))))
  22487. (defun org-forward-element ()
  22488. "Move forward by one element.
  22489. Move to the next element at the same level, when possible."
  22490. (interactive)
  22491. (cond ((eobp) (user-error "Cannot move further down"))
  22492. ((org-with-limited-levels (org-at-heading-p))
  22493. (let ((origin (point)))
  22494. (goto-char (org-end-of-subtree nil t))
  22495. (unless (org-with-limited-levels (org-at-heading-p))
  22496. (goto-char origin)
  22497. (user-error "Cannot move further down"))))
  22498. (t
  22499. (let* ((elem (org-element-at-point))
  22500. (end (org-element-property :end elem))
  22501. (parent (org-element-property :parent elem)))
  22502. (cond ((and parent (= (org-element-property :contents-end parent) end))
  22503. (goto-char (org-element-property :end parent)))
  22504. ((integer-or-marker-p end) (goto-char end))
  22505. (t (message "No element at point")))))))
  22506. (defun org-backward-element ()
  22507. "Move backward by one element.
  22508. Move to the previous element at the same level, when possible."
  22509. (interactive)
  22510. (cond ((bobp) (user-error "Cannot move further up"))
  22511. ((org-with-limited-levels (org-at-heading-p))
  22512. ;; At a headline, move to the previous one, if any, or stay
  22513. ;; here.
  22514. (let ((origin (point)))
  22515. (org-with-limited-levels (org-backward-heading-same-level 1))
  22516. ;; When current headline has no sibling above, move to its
  22517. ;; parent.
  22518. (when (= (point) origin)
  22519. (or (org-with-limited-levels (org-up-heading-safe))
  22520. (progn (goto-char origin)
  22521. (user-error "Cannot move further up"))))))
  22522. (t
  22523. (let* ((elem (org-element-at-point))
  22524. (beg (org-element-property :begin elem)))
  22525. (cond
  22526. ;; Move to beginning of current element if point isn't
  22527. ;; there already.
  22528. ((null beg) (message "No element at point"))
  22529. ((/= (point) beg) (goto-char beg))
  22530. (t (goto-char beg)
  22531. (skip-chars-backward " \r\t\n")
  22532. (unless (bobp)
  22533. (let ((prev (org-element-at-point)))
  22534. (goto-char (org-element-property :begin prev))
  22535. (while (and (setq prev (org-element-property :parent prev))
  22536. (<= (org-element-property :end prev) beg))
  22537. (goto-char (org-element-property :begin prev)))))))))))
  22538. (defun org-up-element ()
  22539. "Move to upper element."
  22540. (interactive)
  22541. (if (org-with-limited-levels (org-at-heading-p))
  22542. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  22543. (let* ((elem (org-element-at-point))
  22544. (parent (org-element-property :parent elem)))
  22545. (if parent (goto-char (org-element-property :begin parent))
  22546. (if (org-with-limited-levels (org-before-first-heading-p))
  22547. (user-error "No surrounding element")
  22548. (org-with-limited-levels (org-back-to-heading)))))))
  22549. (defvar org-element-greater-elements)
  22550. (defun org-down-element ()
  22551. "Move to inner element."
  22552. (interactive)
  22553. (let ((element (org-element-at-point)))
  22554. (cond
  22555. ((memq (org-element-type element) '(plain-list table))
  22556. (goto-char (org-element-property :contents-begin element))
  22557. (forward-char))
  22558. ((memq (org-element-type element) org-element-greater-elements)
  22559. ;; If contents are hidden, first disclose them.
  22560. (when (outline-invisible-p (line-end-position)) (org-cycle))
  22561. (goto-char (or (org-element-property :contents-begin element)
  22562. (user-error "No content for this element"))))
  22563. (t (user-error "No inner element")))))
  22564. (defun org-drag-element-backward ()
  22565. "Move backward element at point."
  22566. (interactive)
  22567. (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
  22568. (let* ((elem (org-element-at-point))
  22569. (prev-elem
  22570. (save-excursion
  22571. (goto-char (org-element-property :begin elem))
  22572. (skip-chars-backward " \r\t\n")
  22573. (unless (bobp)
  22574. (let* ((beg (org-element-property :begin elem))
  22575. (prev (org-element-at-point))
  22576. (up prev))
  22577. (while (and (setq up (org-element-property :parent up))
  22578. (<= (org-element-property :end up) beg))
  22579. (setq prev up))
  22580. prev)))))
  22581. ;; Error out if no previous element or previous element is
  22582. ;; a parent of the current one.
  22583. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  22584. (user-error "Cannot drag element backward")
  22585. (let ((pos (point)))
  22586. (org-element-swap-A-B prev-elem elem)
  22587. (goto-char (+ (org-element-property :begin prev-elem)
  22588. (- pos (org-element-property :begin elem)))))))))
  22589. (defun org-drag-element-forward ()
  22590. "Move forward element at point."
  22591. (interactive)
  22592. (let* ((pos (point))
  22593. (elem (org-element-at-point)))
  22594. (when (= (point-max) (org-element-property :end elem))
  22595. (user-error "Cannot drag element forward"))
  22596. (goto-char (org-element-property :end elem))
  22597. (let ((next-elem (org-element-at-point)))
  22598. (when (or (org-element-nested-p elem next-elem)
  22599. (and (eq (org-element-type next-elem) 'headline)
  22600. (not (eq (org-element-type elem) 'headline))))
  22601. (goto-char pos)
  22602. (user-error "Cannot drag element forward"))
  22603. ;; Compute new position of point: it's shifted by NEXT-ELEM
  22604. ;; body's length (without final blanks) and by the length of
  22605. ;; blanks between ELEM and NEXT-ELEM.
  22606. (let ((size-next (- (save-excursion
  22607. (goto-char (org-element-property :end next-elem))
  22608. (skip-chars-backward " \r\t\n")
  22609. (forward-line)
  22610. ;; Small correction if buffer doesn't end
  22611. ;; with a newline character.
  22612. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  22613. (org-element-property :begin next-elem)))
  22614. (size-blank (- (org-element-property :end elem)
  22615. (save-excursion
  22616. (goto-char (org-element-property :end elem))
  22617. (skip-chars-backward " \r\t\n")
  22618. (forward-line)
  22619. (point)))))
  22620. (org-element-swap-A-B elem next-elem)
  22621. (goto-char (+ pos size-next size-blank))))))
  22622. (defun org-drag-line-forward (arg)
  22623. "Drag the line at point ARG lines forward."
  22624. (interactive "p")
  22625. (dotimes (_ (abs arg))
  22626. (let ((c (current-column)))
  22627. (if (< 0 arg)
  22628. (progn
  22629. (beginning-of-line 2)
  22630. (transpose-lines 1)
  22631. (beginning-of-line 0))
  22632. (transpose-lines 1)
  22633. (beginning-of-line -1))
  22634. (org-move-to-column c))))
  22635. (defun org-drag-line-backward (arg)
  22636. "Drag the line at point ARG lines backward."
  22637. (interactive "p")
  22638. (org-drag-line-forward (- arg)))
  22639. (defun org-mark-element ()
  22640. "Put point at beginning of this element, mark at end.
  22641. Interactively, if this command is repeated or (in Transient Mark
  22642. mode) if the mark is active, it marks the next element after the
  22643. ones already marked."
  22644. (interactive)
  22645. (let (deactivate-mark)
  22646. (if (and (called-interactively-p 'any)
  22647. (or (and (eq last-command this-command) (mark t))
  22648. (and transient-mark-mode mark-active)))
  22649. (set-mark
  22650. (save-excursion
  22651. (goto-char (mark))
  22652. (goto-char (org-element-property :end (org-element-at-point)))))
  22653. (let ((element (org-element-at-point)))
  22654. (end-of-line)
  22655. (push-mark (org-element-property :end element) t t)
  22656. (goto-char (org-element-property :begin element))))))
  22657. (defun org-narrow-to-element ()
  22658. "Narrow buffer to current element."
  22659. (interactive)
  22660. (let ((elem (org-element-at-point)))
  22661. (cond
  22662. ((eq (car elem) 'headline)
  22663. (narrow-to-region
  22664. (org-element-property :begin elem)
  22665. (org-element-property :end elem)))
  22666. ((memq (car elem) org-element-greater-elements)
  22667. (narrow-to-region
  22668. (org-element-property :contents-begin elem)
  22669. (org-element-property :contents-end elem)))
  22670. (t
  22671. (narrow-to-region
  22672. (org-element-property :begin elem)
  22673. (org-element-property :end elem))))))
  22674. (defun org-transpose-element ()
  22675. "Transpose current and previous elements, keeping blank lines between.
  22676. Point is moved after both elements."
  22677. (interactive)
  22678. (org-skip-whitespace)
  22679. (let ((end (org-element-property :end (org-element-at-point))))
  22680. (org-drag-element-backward)
  22681. (goto-char end)))
  22682. (defun org-unindent-buffer ()
  22683. "Un-indent the visible part of the buffer.
  22684. Relative indentation (between items, inside blocks, etc.) isn't
  22685. modified."
  22686. (interactive)
  22687. (unless (eq major-mode 'org-mode)
  22688. (user-error "Cannot un-indent a buffer not in Org mode"))
  22689. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  22690. (unindent-tree
  22691. (lambda (contents)
  22692. (dolist (element (reverse contents))
  22693. (if (memq (org-element-type element) '(headline section))
  22694. (funcall unindent-tree (org-element-contents element))
  22695. (save-excursion
  22696. (save-restriction
  22697. (narrow-to-region
  22698. (org-element-property :begin element)
  22699. (org-element-property :end element))
  22700. (org-do-remove-indentation))))))))
  22701. (funcall unindent-tree (org-element-contents parse-tree))))
  22702. (defun org-show-children (&optional level)
  22703. "Show all direct subheadings of this heading.
  22704. Prefix arg LEVEL is how many levels below the current level
  22705. should be shown. Default is enough to cause the following
  22706. heading to appear."
  22707. (interactive "p")
  22708. ;; If `orgstruct-mode' is active, use the slower version.
  22709. (if orgstruct-mode (call-interactively #'outline-show-children)
  22710. (save-excursion
  22711. (org-back-to-heading t)
  22712. (let* ((current-level (funcall outline-level))
  22713. (max-level (org-get-valid-level
  22714. current-level
  22715. (if level (prefix-numeric-value level) 1)))
  22716. (end (save-excursion (org-end-of-subtree t t)))
  22717. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  22718. (past-first-child nil)
  22719. ;; Make sure to skip inlinetasks.
  22720. (re (format regexp-fmt
  22721. current-level
  22722. (cond
  22723. ((not (featurep 'org-inlinetask)) "")
  22724. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  22725. 3))
  22726. (t (1- org-inlinetask-min-level))))))
  22727. ;; Display parent heading.
  22728. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  22729. (forward-line)
  22730. ;; Display children. First child may be deeper than expected
  22731. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  22732. ;; MAX-LEVEL accordingly.
  22733. (while (re-search-forward re end t)
  22734. (unless past-first-child
  22735. (setq re (format regexp-fmt
  22736. current-level
  22737. (max (funcall outline-level) max-level)))
  22738. (setq past-first-child t))
  22739. (outline-flag-region
  22740. (line-end-position 0) (line-end-position) nil))))))
  22741. (defun org-show-subtree ()
  22742. "Show everything after this heading at deeper levels."
  22743. (interactive)
  22744. (outline-flag-region
  22745. (point)
  22746. (save-excursion
  22747. (org-end-of-subtree t t))
  22748. nil))
  22749. (defun org-show-entry ()
  22750. "Show the body directly following this heading.
  22751. Show the heading too, if it is currently invisible."
  22752. (interactive)
  22753. (save-excursion
  22754. (ignore-errors
  22755. (org-back-to-heading t)
  22756. (outline-flag-region
  22757. (max (point-min) (1- (point)))
  22758. (save-excursion
  22759. (if (re-search-forward
  22760. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22761. (match-beginning 1)
  22762. (point-max)))
  22763. nil)
  22764. (org-cycle-hide-drawers 'children))))
  22765. (defun org-make-options-regexp (kwds &optional extra)
  22766. "Make a regular expression for keyword lines.
  22767. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22768. when non-nil, is a regexp matching keywords names."
  22769. (concat "^[ \t]*#\\+\\("
  22770. (regexp-opt kwds)
  22771. (and extra (concat (and kwds "\\|") extra))
  22772. "\\):[ \t]*\\(.*\\)"))
  22773. ;;;; Integration with and fixes for other packages
  22774. ;;; Imenu support
  22775. (defvar-local org-imenu-markers nil
  22776. "All markers currently used by Imenu.")
  22777. (defun org-imenu-new-marker (&optional pos)
  22778. "Return a new marker for use by Imenu, and remember the marker."
  22779. (let ((m (make-marker)))
  22780. (move-marker m (or pos (point)))
  22781. (push m org-imenu-markers)
  22782. m))
  22783. (defun org-imenu-get-tree ()
  22784. "Produce the index for Imenu."
  22785. (dolist (x org-imenu-markers) (move-marker x nil))
  22786. (setq org-imenu-markers nil)
  22787. (let* ((case-fold-search nil)
  22788. (n org-imenu-depth)
  22789. (re (concat "^" (org-get-limited-outline-regexp)))
  22790. (subs (make-vector (1+ n) nil))
  22791. (last-level 0)
  22792. m level head0 head)
  22793. (org-with-wide-buffer
  22794. (goto-char (point-max))
  22795. (while (re-search-backward re nil t)
  22796. (setq level (org-reduced-level (funcall outline-level)))
  22797. (when (and (<= level n)
  22798. (looking-at org-complex-heading-regexp)
  22799. (setq head0 (match-string-no-properties 4)))
  22800. (setq head (org-link-display-format head0)
  22801. m (org-imenu-new-marker))
  22802. (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
  22803. (if (>= level last-level)
  22804. (push (cons head m) (aref subs level))
  22805. (push (cons head (aref subs (1+ level))) (aref subs level))
  22806. (cl-loop for i from (1+ level) to n do (aset subs i nil)))
  22807. (setq last-level level))))
  22808. (aref subs 1)))
  22809. (eval-after-load "imenu"
  22810. '(progn
  22811. (add-hook 'imenu-after-jump-hook
  22812. (lambda ()
  22813. (when (derived-mode-p 'org-mode)
  22814. (org-show-context 'org-goto))))))
  22815. (defun org-link-display-format (s)
  22816. "Replace links in string S with their description.
  22817. If there is no description, use the link target."
  22818. (save-match-data
  22819. (replace-regexp-in-string
  22820. org-bracket-link-analytic-regexp
  22821. (lambda (m)
  22822. (if (match-end 5) (match-string 5 m)
  22823. (concat (match-string 1 m) (match-string 3 m))))
  22824. s nil t)))
  22825. (defun org-toggle-link-display ()
  22826. "Toggle the literal or descriptive display of links."
  22827. (interactive)
  22828. (if org-descriptive-links
  22829. (progn (org-remove-from-invisibility-spec '(org-link))
  22830. (org-restart-font-lock)
  22831. (setq org-descriptive-links nil))
  22832. (progn (add-to-invisibility-spec '(org-link))
  22833. (org-restart-font-lock)
  22834. (setq org-descriptive-links t))))
  22835. ;; Speedbar support
  22836. (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
  22837. "Overlay marking the agenda restriction line in speedbar.")
  22838. (overlay-put org-speedbar-restriction-lock-overlay
  22839. 'face 'org-agenda-restriction-lock)
  22840. (overlay-put org-speedbar-restriction-lock-overlay
  22841. 'help-echo "Agendas are currently limited to this item.")
  22842. (delete-overlay org-speedbar-restriction-lock-overlay)
  22843. (defun org-speedbar-set-agenda-restriction ()
  22844. "Restrict future agenda commands to the location at point in speedbar.
  22845. To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
  22846. (interactive)
  22847. (require 'org-agenda)
  22848. (let (p m tp np dir txt)
  22849. (cond
  22850. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22851. 'org-imenu t))
  22852. (setq m (get-text-property p 'org-imenu-marker))
  22853. (with-current-buffer (marker-buffer m)
  22854. (goto-char m)
  22855. (org-agenda-set-restriction-lock 'subtree)))
  22856. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22857. 'speedbar-function 'speedbar-find-file))
  22858. (setq tp (previous-single-property-change
  22859. (1+ p) 'speedbar-function)
  22860. np (next-single-property-change
  22861. tp 'speedbar-function)
  22862. dir (speedbar-line-directory)
  22863. txt (buffer-substring-no-properties (or tp (point-min))
  22864. (or np (point-max))))
  22865. (with-current-buffer (find-file-noselect
  22866. (let ((default-directory dir))
  22867. (expand-file-name txt)))
  22868. (unless (derived-mode-p 'org-mode)
  22869. (user-error "Cannot restrict to non-Org mode file"))
  22870. (org-agenda-set-restriction-lock 'file)))
  22871. (t (user-error "Don't know how to restrict Org mode agenda")))
  22872. (move-overlay org-speedbar-restriction-lock-overlay
  22873. (point-at-bol) (point-at-eol))
  22874. (setq current-prefix-arg nil)
  22875. (org-agenda-maybe-redo)))
  22876. (defvar speedbar-file-key-map)
  22877. (declare-function speedbar-add-supported-extension "speedbar" (extension))
  22878. (eval-after-load "speedbar"
  22879. '(progn
  22880. (speedbar-add-supported-extension ".org")
  22881. (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
  22882. (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
  22883. (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
  22884. (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  22885. (add-hook 'speedbar-visiting-tag-hook
  22886. (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
  22887. ;;; Fixes and Hacks for problems with other packages
  22888. (defun org--flyspell-object-check-p (element)
  22889. "Non-nil when Flyspell can check object at point.
  22890. ELEMENT is the element at point."
  22891. (let ((object (save-excursion
  22892. (when (looking-at-p "\\>") (backward-char))
  22893. (org-element-context element))))
  22894. (cl-case (org-element-type object)
  22895. ;; Prevent checks in links due to keybinding conflict with
  22896. ;; Flyspell.
  22897. ((code entity export-snippet inline-babel-call
  22898. inline-src-block line-break latex-fragment link macro
  22899. statistics-cookie target timestamp verbatim)
  22900. nil)
  22901. (footnote-reference
  22902. ;; Only in inline footnotes, within the definition.
  22903. (and (eq (org-element-property :type object) 'inline)
  22904. (< (save-excursion
  22905. (goto-char (org-element-property :begin object))
  22906. (search-forward ":" nil t 2))
  22907. (point))))
  22908. (otherwise t))))
  22909. (defun org-mode-flyspell-verify ()
  22910. "Function used for `flyspell-generic-check-word-predicate'."
  22911. (if (org-at-heading-p)
  22912. ;; At a headline or an inlinetask, check title only. This is
  22913. ;; faster than relying on `org-element-at-point'.
  22914. (and (save-excursion (beginning-of-line)
  22915. (and (let ((case-fold-search t))
  22916. (not (looking-at "\\*+ END[ \t]*$")))
  22917. (looking-at org-complex-heading-regexp)))
  22918. (match-beginning 4)
  22919. (>= (point) (match-beginning 4))
  22920. (or (not (match-beginning 5))
  22921. (< (point) (match-beginning 5))))
  22922. (let* ((element (org-element-at-point))
  22923. (post-affiliated (org-element-property :post-affiliated element)))
  22924. (cond
  22925. ;; Ignore checks in all affiliated keywords but captions.
  22926. ((< (point) post-affiliated)
  22927. (and (save-excursion
  22928. (beginning-of-line)
  22929. (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
  22930. (> (point) (match-end 0))
  22931. (org--flyspell-object-check-p element)))
  22932. ;; Ignore checks in LOGBOOK (or equivalent) drawer.
  22933. ((let ((log (org-log-into-drawer)))
  22934. (and log
  22935. (let ((drawer (org-element-lineage element '(drawer))))
  22936. (and drawer
  22937. (eq (compare-strings
  22938. log nil nil
  22939. (org-element-property :drawer-name drawer) nil nil t)
  22940. t)))))
  22941. nil)
  22942. (t
  22943. (cl-case (org-element-type element)
  22944. ((comment quote-section) t)
  22945. (comment-block
  22946. ;; Allow checks between block markers, not on them.
  22947. (and (> (line-beginning-position) post-affiliated)
  22948. (save-excursion
  22949. (end-of-line)
  22950. (skip-chars-forward " \r\t\n")
  22951. (< (point) (org-element-property :end element)))))
  22952. ;; Arbitrary list of keywords where checks are meaningful.
  22953. ;; Make sure point is on the value part of the element.
  22954. (keyword
  22955. (and (member (org-element-property :key element)
  22956. '("DESCRIPTION" "TITLE"))
  22957. (save-excursion
  22958. (search-backward ":" (line-beginning-position) t))))
  22959. ;; Check is globally allowed in paragraphs verse blocks and
  22960. ;; table rows (after affiliated keywords) but some objects
  22961. ;; must not be affected.
  22962. ((paragraph table-row verse-block)
  22963. (let ((cbeg (org-element-property :contents-begin element))
  22964. (cend (org-element-property :contents-end element)))
  22965. (and cbeg (>= (point) cbeg) (< (point) cend)
  22966. (org--flyspell-object-check-p element))))))))))
  22967. (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
  22968. (defun org-remove-flyspell-overlays-in (beg end)
  22969. "Remove flyspell overlays in region."
  22970. (and (bound-and-true-p flyspell-mode)
  22971. (fboundp 'flyspell-delete-region-overlays)
  22972. (flyspell-delete-region-overlays beg end)))
  22973. (defvar flyspell-delayed-commands)
  22974. (eval-after-load "flyspell"
  22975. '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
  22976. ;; Make `bookmark-jump' shows the jump location if it was hidden.
  22977. (eval-after-load "bookmark"
  22978. '(if (boundp 'bookmark-after-jump-hook)
  22979. ;; We can use the hook
  22980. (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
  22981. ;; Hook not available, use advice
  22982. (defadvice bookmark-jump (after org-make-visible activate)
  22983. "Make the position visible."
  22984. (org-bookmark-jump-unhide))))
  22985. ;; Make sure saveplace shows the location if it was hidden
  22986. (eval-after-load "saveplace"
  22987. '(defadvice save-place-find-file-hook (after org-make-visible activate)
  22988. "Make the position visible."
  22989. (org-bookmark-jump-unhide)))
  22990. ;; Make sure ecb shows the location if it was hidden
  22991. (eval-after-load "ecb"
  22992. '(defadvice ecb-method-clicked (after esf/org-show-context activate)
  22993. "Make hierarchy visible when jumping into location from ECB tree buffer."
  22994. (when (derived-mode-p 'org-mode)
  22995. (org-show-context))))
  22996. (defun org-bookmark-jump-unhide ()
  22997. "Unhide the current position, to show the bookmark location."
  22998. (and (derived-mode-p 'org-mode)
  22999. (or (outline-invisible-p)
  23000. (save-excursion (goto-char (max (point-min) (1- (point))))
  23001. (outline-invisible-p)))
  23002. (org-show-context 'bookmark-jump)))
  23003. (defun org-mark-jump-unhide ()
  23004. "Make the point visible with `org-show-context' after jumping to the mark."
  23005. (when (and (derived-mode-p 'org-mode)
  23006. (outline-invisible-p))
  23007. (org-show-context 'mark-goto)))
  23008. (eval-after-load "simple"
  23009. '(defadvice pop-to-mark-command (after org-make-visible activate)
  23010. "Make the point visible with `org-show-context'."
  23011. (org-mark-jump-unhide)))
  23012. (eval-after-load "simple"
  23013. '(defadvice exchange-point-and-mark (after org-make-visible activate)
  23014. "Make the point visible with `org-show-context'."
  23015. (org-mark-jump-unhide)))
  23016. (eval-after-load "simple"
  23017. '(defadvice pop-global-mark (after org-make-visible activate)
  23018. "Make the point visible with `org-show-context'."
  23019. (org-mark-jump-unhide)))
  23020. ;; Make session.el ignore our circular variable
  23021. (defvar session-globals-exclude)
  23022. (eval-after-load "session"
  23023. '(add-to-list 'session-globals-exclude 'org-mark-ring))
  23024. ;;;; Finish up
  23025. (provide 'org)
  23026. (run-hooks 'org-load-hook)
  23027. ;;; org.el ends here