org.el 950 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128
  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-2017 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" (&optional arg start-day span with-hour))
  105. (declare-function org-agenda-redo "org-agenda" (&optional all))
  106. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  107. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  108. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  109. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  110. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  111. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  112. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  113. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  114. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  115. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  116. (declare-function org-clock-update-time-maybe "org-clock" ())
  117. (declare-function org-clocking-buffer "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-link-parser "org-element" ())
  128. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  129. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  130. (declare-function org-element-property "org-element" (property element))
  131. (declare-function org-element-put-property "org-element" (element property value))
  132. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  133. (declare-function org-element-type "org-element" (element))
  134. (declare-function org-element-update-syntax "org-element" ())
  135. (declare-function org-id-find-id-file "org-id" (id))
  136. (declare-function org-id-get-create "org-id" (&optional force))
  137. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  138. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  139. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  140. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  141. (declare-function org-table-align "org-table" ())
  142. (declare-function org-table-begin "org-table" (&optional table-type))
  143. (declare-function org-table-beginning-of-field "org-table" (&optional n))
  144. (declare-function org-table-blank-field "org-table" ())
  145. (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
  146. (declare-function org-table-copy-region "org-table" (beg end &optional cut))
  147. (declare-function org-table-cut-region "org-table" (beg end))
  148. (declare-function org-table-edit-field "org-table" (arg))
  149. (declare-function org-table-end "org-table" (&optional table-type))
  150. (declare-function org-table-end-of-field "org-table" (&optional n))
  151. (declare-function org-table-insert-row "org-table" (&optional arg))
  152. (declare-function org-table-justify-field-maybe "org-table" (&optional new))
  153. (declare-function org-table-maybe-eval-formula "org-table" ())
  154. (declare-function org-table-maybe-recalculate-line "org-table" ())
  155. (declare-function org-table-next-row "org-table" ())
  156. (declare-function org-table-paste-rectangle "org-table" ())
  157. (declare-function org-table-recalculate "org-table" (&optional all noalign))
  158. (declare-function org-table-wrap-region "org-table" (arg))
  159. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  160. (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
  161. (declare-function orgtbl-mode "org-table" (&optional arg))
  162. (declare-function org-export-get-backend "ox" (name))
  163. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  164. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  165. (defsubst org-uniquify (list)
  166. "Non-destructively remove duplicate elements from LIST."
  167. (let ((res (copy-sequence list))) (delete-dups res)))
  168. (defsubst org-get-at-bol (property)
  169. "Get text property PROPERTY at the beginning of line."
  170. (get-text-property (point-at-bol) property))
  171. (defsubst org-trim (s &optional keep-lead)
  172. "Remove whitespace at the beginning and the end of string S.
  173. When optional argument KEEP-LEAD is non-nil, removing blank lines
  174. at the beginning of the string does not affect leading indentation."
  175. (replace-regexp-in-string
  176. (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
  177. (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
  178. ;; load languages based on value of `org-babel-load-languages'
  179. (defvar org-babel-load-languages)
  180. ;;;###autoload
  181. (defun org-babel-do-load-languages (sym value)
  182. "Load the languages defined in `org-babel-load-languages'."
  183. (set-default sym value)
  184. (dolist (pair org-babel-load-languages)
  185. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  186. (if active
  187. (require (intern (concat "ob-" lang)))
  188. (funcall 'fmakunbound
  189. (intern (concat "org-babel-execute:" lang)))
  190. (funcall 'fmakunbound
  191. (intern (concat "org-babel-expand-body:" lang)))))))
  192. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  193. ;;;###autoload
  194. (defun org-babel-load-file (file &optional compile)
  195. "Load Emacs Lisp source code blocks in the Org FILE.
  196. This function exports the source code using `org-babel-tangle'
  197. and then loads the resulting file using `load-file'. With prefix
  198. arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
  199. file to byte-code before it is loaded."
  200. (interactive "fFile to load: \nP")
  201. (let* ((age (lambda (file)
  202. (float-time
  203. (time-subtract (current-time)
  204. (nth 5 (or (file-attributes (file-truename file))
  205. (file-attributes file)))))))
  206. (base-name (file-name-sans-extension file))
  207. (exported-file (concat base-name ".el")))
  208. ;; tangle if the Org file is newer than the elisp file
  209. (unless (and (file-exists-p exported-file)
  210. (> (funcall age file) (funcall age exported-file)))
  211. ;; Tangle-file traversal returns reversed list of tangled files
  212. ;; and we want to evaluate the first target.
  213. (setq exported-file
  214. (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
  215. (message "%s %s"
  216. (if compile
  217. (progn (byte-compile-file exported-file 'load)
  218. "Compiled and loaded")
  219. (progn (load-file exported-file) "Loaded"))
  220. exported-file)))
  221. (defcustom org-babel-load-languages '((emacs-lisp . t))
  222. "Languages which can be evaluated in Org buffers.
  223. This list can be used to load support for any of the languages
  224. below, note that each language will depend on a different set of
  225. system executables and/or Emacs modes. When a language is
  226. \"loaded\", then code blocks in that language can be evaluated
  227. with `org-babel-execute-src-block' bound by default to C-c
  228. C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
  229. be set to remove code block evaluation from the C-c C-c
  230. keybinding. By default only Emacs Lisp (which has no
  231. requirements) is loaded."
  232. :group 'org-babel
  233. :set 'org-babel-do-load-languages
  234. :version "24.1"
  235. :type '(alist :tag "Babel Languages"
  236. :key-type
  237. (choice
  238. (const :tag "Awk" awk)
  239. (const :tag "C" C)
  240. (const :tag "R" R)
  241. (const :tag "Asymptote" asymptote)
  242. (const :tag "Calc" calc)
  243. (const :tag "Clojure" clojure)
  244. (const :tag "CSS" css)
  245. (const :tag "Ditaa" ditaa)
  246. (const :tag "Dot" dot)
  247. (const :tag "Emacs Lisp" emacs-lisp)
  248. (const :tag "Forth" forth)
  249. (const :tag "Fortran" fortran)
  250. (const :tag "Gnuplot" gnuplot)
  251. (const :tag "Haskell" haskell)
  252. (const :tag "IO" io)
  253. (const :tag "J" J)
  254. (const :tag "Java" java)
  255. (const :tag "Javascript" js)
  256. (const :tag "LaTeX" latex)
  257. (const :tag "Ledger" ledger)
  258. (const :tag "Lilypond" lilypond)
  259. (const :tag "Lisp" lisp)
  260. (const :tag "Makefile" makefile)
  261. (const :tag "Maxima" maxima)
  262. (const :tag "Matlab" matlab)
  263. (const :tag "Mscgen" mscgen)
  264. (const :tag "Ocaml" ocaml)
  265. (const :tag "Octave" octave)
  266. (const :tag "Org" org)
  267. (const :tag "Perl" perl)
  268. (const :tag "Pico Lisp" picolisp)
  269. (const :tag "PlantUML" plantuml)
  270. (const :tag "Python" python)
  271. (const :tag "Ruby" ruby)
  272. (const :tag "Sass" sass)
  273. (const :tag "Scala" scala)
  274. (const :tag "Scheme" scheme)
  275. (const :tag "Screen" screen)
  276. (const :tag "Shell Script" shell)
  277. (const :tag "Shen" shen)
  278. (const :tag "Sql" sql)
  279. (const :tag "Sqlite" sqlite)
  280. (const :tag "Stan" stan)
  281. (const :tag "ebnf2ps" ebnf2ps))
  282. :value-type (boolean :tag "Activate" :value t)))
  283. ;;;; Customization variables
  284. (defcustom org-clone-delete-id nil
  285. "Remove ID property of clones of a subtree.
  286. When non-nil, clones of a subtree don't inherit the ID property.
  287. Otherwise they inherit the ID property with a new unique
  288. identifier."
  289. :type 'boolean
  290. :version "24.1"
  291. :group 'org-id)
  292. ;;; Version
  293. (org-check-version)
  294. ;;;###autoload
  295. (defun org-version (&optional here full message)
  296. "Show the Org version.
  297. Interactively, or when MESSAGE is non-nil, show it in echo area.
  298. With prefix argument, or when HERE is non-nil, insert it at point.
  299. In non-interactive uses, a reduced version string is output unless
  300. FULL is given."
  301. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  302. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  303. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  304. (load-suffixes (list ".el"))
  305. (org-install-dir
  306. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  307. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  308. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  309. (let* ((load-suffixes save-load-suffixes)
  310. (release (org-release))
  311. (git-version (org-git-version))
  312. (version (format "Org mode version %s (%s @ %s)"
  313. release
  314. git-version
  315. (if org-install-dir
  316. (if (string= org-dir org-install-dir)
  317. org-install-dir
  318. (concat "mixed installation! "
  319. org-install-dir
  320. " and "
  321. org-dir))
  322. "org-loaddefs.el can not be found!")))
  323. (version1 (if full version release)))
  324. (when here (insert version1))
  325. (when message (message "%s" version1))
  326. version1)))
  327. (defconst org-version (org-version))
  328. ;;; Syntax Constants
  329. ;;;; Block
  330. (defconst org-block-regexp
  331. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  332. "Regular expression for hiding blocks.")
  333. (defconst org-dblock-start-re
  334. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  335. "Matches the start line of a dynamic block, with parameters.")
  336. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  337. "Matches the end of a dynamic block.")
  338. ;;;; Clock and Planning
  339. (defconst org-clock-string "CLOCK:"
  340. "String used as prefix for timestamps clocking work hours on an item.")
  341. (defvar org-closed-string "CLOSED:"
  342. "String used as the prefix for timestamps logging closing a TODO entry.")
  343. (defvar org-deadline-string "DEADLINE:"
  344. "String to mark deadline entries.
  345. \\<org-mode-map>
  346. A deadline is this string, followed by a time stamp. It must be
  347. a word, terminated by a colon. You can insert a schedule keyword
  348. and a timestamp with `\\[org-deadline]'.")
  349. (defvar org-scheduled-string "SCHEDULED:"
  350. "String to mark scheduled TODO entries.
  351. \\<org-mode-map>
  352. A schedule is this string, followed by a time stamp. It must be
  353. a word, terminated by a colon. You can insert a schedule keyword
  354. and a timestamp with `\\[org-schedule]'.")
  355. (defconst org-ds-keyword-length
  356. (+ 2
  357. (apply #'max
  358. (mapcar #'length
  359. (list org-deadline-string org-scheduled-string
  360. org-clock-string org-closed-string))))
  361. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  362. (defconst org-planning-line-re
  363. (concat "^[ \t]*"
  364. (regexp-opt
  365. (list org-closed-string org-deadline-string org-scheduled-string)
  366. t))
  367. "Matches a line with planning info.
  368. Matched keyword is in group 1.")
  369. (defconst org-clock-line-re
  370. (concat "^[ \t]*" org-clock-string)
  371. "Matches a line with clock info.")
  372. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  373. "Matches the DEADLINE keyword.")
  374. (defconst org-deadline-time-regexp
  375. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  376. "Matches the DEADLINE keyword together with a time stamp.")
  377. (defconst org-deadline-time-hour-regexp
  378. (concat "\\<" org-deadline-string
  379. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  380. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  381. (defconst org-deadline-line-regexp
  382. (concat "\\<\\(" org-deadline-string "\\).*")
  383. "Matches the DEADLINE keyword and the rest of the line.")
  384. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  385. "Matches the SCHEDULED keyword.")
  386. (defconst org-scheduled-time-regexp
  387. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  388. "Matches the SCHEDULED keyword together with a time stamp.")
  389. (defconst org-scheduled-time-hour-regexp
  390. (concat "\\<" org-scheduled-string
  391. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
  392. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  393. (defconst org-closed-time-regexp
  394. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  395. "Matches the CLOSED keyword together with a time stamp.")
  396. (defconst org-keyword-time-regexp
  397. (concat "\\<"
  398. (regexp-opt
  399. (list org-scheduled-string org-deadline-string org-closed-string
  400. org-clock-string)
  401. t)
  402. " *[[<]\\([^]>]+\\)[]>]")
  403. "Matches any of the 4 keywords, together with the time stamp.")
  404. (defconst org-keyword-time-not-clock-regexp
  405. (concat
  406. "\\<"
  407. (regexp-opt
  408. (list org-scheduled-string org-deadline-string org-closed-string) t)
  409. " *[[<]\\([^]>]+\\)[]>]")
  410. "Matches any of the 3 keywords, together with the time stamp.")
  411. (defconst org-maybe-keyword-time-regexp
  412. (concat "\\(\\<"
  413. (regexp-opt
  414. (list org-scheduled-string org-deadline-string org-closed-string
  415. org-clock-string)
  416. t)
  417. "\\)?"
  418. " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
  419. "\\|"
  420. "<%%([^\r\n>]*>\\)")
  421. "Matches a timestamp, possibly preceded by a keyword.")
  422. (defconst org-all-time-keywords
  423. (mapcar (lambda (w) (substring w 0 -1))
  424. (list org-scheduled-string org-deadline-string
  425. org-clock-string org-closed-string))
  426. "List of time keywords.")
  427. ;;;; Drawer
  428. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  429. "Matches first or last line of a hidden block.
  430. Group 1 contains drawer's name or \"END\".")
  431. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  432. "Regular expression matching the first line of a property drawer.")
  433. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  434. "Regular expression matching the last line of a property drawer.")
  435. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  436. "Regular expression matching the first line of a clock drawer.")
  437. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  438. "Regular expression matching the last line of a clock drawer.")
  439. (defconst org-property-drawer-re
  440. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  441. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  442. "[ \t]*:END:[ \t]*$")
  443. "Matches an entire property drawer.")
  444. (defconst org-clock-drawer-re
  445. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  446. org-clock-drawer-end-re "\\)\n?")
  447. "Matches an entire clock drawer.")
  448. ;;;; Headline
  449. (defconst org-heading-keyword-regexp-format
  450. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  451. "Printf format for a regexp matching a headline with some keyword.
  452. This regexp will match the headline of any node which has the
  453. exact keyword that is put into the format. The keyword isn't in
  454. any group by default, but the stars and the body are.")
  455. (defconst org-heading-keyword-maybe-regexp-format
  456. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  457. "Printf format for a regexp matching a headline, possibly with some keyword.
  458. This regexp can match any headline with the specified keyword, or
  459. without a keyword. The keyword isn't in any group by default,
  460. but the stars and the body are.")
  461. (defconst org-archive-tag "ARCHIVE"
  462. "The tag that marks a subtree as archived.
  463. An archived subtree does not open during visibility cycling, and does
  464. not contribute to the agenda listings.")
  465. (defconst org-comment-string "COMMENT"
  466. "Entries starting with this keyword will never be exported.
  467. \\<org-mode-map>
  468. An entry can be toggled between COMMENT and normal with
  469. `\\[org-toggle-comment]'.")
  470. ;;;; LaTeX Environments and Fragments
  471. (defconst org-latex-regexps
  472. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  473. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  474. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  475. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  476. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  477. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  478. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  479. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  480. "Regular expressions for matching embedded LaTeX.")
  481. ;;;; Node Property
  482. (defconst org-effort-property "Effort"
  483. "The property that is being used to keep track of effort estimates.
  484. Effort estimates given in this property need to have the format H:MM.")
  485. ;;;; Table
  486. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  487. "Detect an org-type or table-type table.")
  488. (defconst org-table-line-regexp "^[ \t]*|"
  489. "Detect an org-type table line.")
  490. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  491. "Detect an org-type table line.")
  492. (defconst org-table-hline-regexp "^[ \t]*|-"
  493. "Detect an org-type table hline.")
  494. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  495. "Detect a table-type table hline.")
  496. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  497. "Detect the first line outside a table when searching from within it.
  498. This works for both table types.")
  499. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  500. "Detect a #+TBLFM line.")
  501. ;;;; Timestamp
  502. (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
  503. "Regular expression for fast time stamp matching.")
  504. (defconst org-ts-regexp-inactive
  505. "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
  506. "Regular expression for fast inactive time stamp matching.")
  507. (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
  508. "Regular expression for fast time stamp matching.")
  509. (defconst org-ts-regexp0
  510. "\\(\\([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. This one does not require the space after the date, so it can be used
  513. on a string that terminates immediately after the date.")
  514. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  515. "Regular expression matching time strings for analysis.")
  516. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  517. "Regular expression matching time stamps, with groups.")
  518. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  519. "Regular expression matching time stamps (also [..]), with groups.")
  520. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  521. "Regular expression matching a time stamp range.")
  522. (defconst org-tr-regexp-both
  523. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  524. "Regular expression matching a time stamp range.")
  525. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  526. org-ts-regexp "\\)?")
  527. "Regular expression matching a time stamp or time stamp range.")
  528. (defconst org-tsr-regexp-both
  529. (concat org-ts-regexp-both "\\(--?-?"
  530. org-ts-regexp-both "\\)?")
  531. "Regular expression matching a time stamp or time stamp range.
  532. The time stamps may be either active or inactive.")
  533. (defconst org-repeat-re
  534. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  535. "Regular expression for specifying repeated events.
  536. After a match, group 1 contains the repeat expression.")
  537. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  538. "Formats for `format-time-string' which are used for time stamps.")
  539. ;;; The custom variables
  540. (defgroup org nil
  541. "Outline-based notes management and organizer."
  542. :tag "Org"
  543. :group 'outlines
  544. :group 'calendar)
  545. (defcustom org-mode-hook nil
  546. "Mode hook for Org mode, run after the mode was turned on."
  547. :group 'org
  548. :type 'hook)
  549. (defcustom org-load-hook nil
  550. "Hook that is run after org.el has been loaded."
  551. :group 'org
  552. :type 'hook)
  553. (defcustom org-log-buffer-setup-hook nil
  554. "Hook that is run after an Org log buffer is created."
  555. :group 'org
  556. :version "24.1"
  557. :type 'hook)
  558. (defvar org-modules) ; defined below
  559. (defvar org-modules-loaded nil
  560. "Have the modules been loaded already?")
  561. (defun org-load-modules-maybe (&optional force)
  562. "Load all extensions listed in `org-modules'."
  563. (when (or force (not org-modules-loaded))
  564. (dolist (ext org-modules)
  565. (condition-case nil (require ext)
  566. (error (message "Problems while trying to load feature `%s'" ext))))
  567. (setq org-modules-loaded t)))
  568. (defun org-set-modules (var value)
  569. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  570. (set var value)
  571. (when (featurep 'org)
  572. (org-load-modules-maybe 'force)
  573. (org-element-cache-reset 'all)))
  574. (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
  575. "Modules that should always be loaded together with org.el.
  576. If a description starts with <C>, the file is not part of Emacs
  577. and loading it will require that you have downloaded and properly
  578. installed the Org mode distribution.
  579. You can also use this system to load external packages (i.e. neither Org
  580. core modules, nor modules from the CONTRIB directory). Just add symbols
  581. to the end of the list. If the package is called org-xyz.el, then you need
  582. to add the symbol `xyz', and the package must have a call to:
  583. (provide \\='org-xyz)
  584. For export specific modules, see also `org-export-backends'."
  585. :group 'org
  586. :set 'org-set-modules
  587. :version "24.4"
  588. :package-version '(Org . "8.0")
  589. :type
  590. '(set :greedy t
  591. (const :tag " bbdb: Links to BBDB entries" org-bbdb)
  592. (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
  593. (const :tag " crypt: Encryption of subtrees" org-crypt)
  594. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  595. (const :tag " docview: Links to doc-view buffers" org-docview)
  596. (const :tag " eww: Store link to url of eww" org-eww)
  597. (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
  598. (const :tag " habit: Track your consistency with habits" org-habit)
  599. (const :tag " id: Global IDs for identifying entries" org-id)
  600. (const :tag " info: Links to Info nodes" org-info)
  601. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  602. (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
  603. (const :tag " mhe: Links to MHE folders/messages" org-mhe)
  604. (const :tag " mouse: Additional mouse support" org-mouse)
  605. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  606. (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
  607. (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
  608. (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
  609. (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
  610. (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
  611. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  612. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  613. (const :tag "C collector: Collect properties into tables" org-collector)
  614. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  615. (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
  616. (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
  617. (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
  618. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  619. (const :tag "C eval: Include command output as text" org-eval)
  620. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  621. (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
  622. (const :tag "C git-link: Provide org links to specific file version" org-git-link)
  623. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  624. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  625. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  626. (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  627. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  628. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  629. (const :tag "C man: Support for links to manpages in Org mode" org-man)
  630. (const :tag "C mew: Links to Mew folders/messages" org-mew)
  631. (const :tag "C mtags: Support for muse-like tags" org-mtags)
  632. (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
  633. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  634. (const :tag "C registry: A registry for Org links" org-registry)
  635. (const :tag "C screen: Visit screen sessions through Org links" org-screen)
  636. (const :tag "C secretary: Team management with org-mode" org-secretary)
  637. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  638. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  639. (const :tag "C track: Keep up with Org mode development" org-track)
  640. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  641. (const :tag "C vm: Links to VM folders/messages" org-vm)
  642. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  643. (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
  644. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  645. (defvar org-export-registered-backends) ; From ox.el.
  646. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  647. (declare-function org-export-backend-name "ox" (backend) t)
  648. (defcustom org-export-backends '(ascii html icalendar latex odt)
  649. "List of export back-ends that should be always available.
  650. If a description starts with <C>, the file is not part of Emacs
  651. and loading it will require that you have downloaded and properly
  652. installed the Org mode distribution.
  653. Unlike to `org-modules', libraries in this list will not be
  654. loaded along with Org, but only once the export framework is
  655. needed.
  656. This variable needs to be set before org.el is loaded. If you
  657. need to make a change while Emacs is running, use the customize
  658. interface or run the following code, where VAL stands for the new
  659. value of the variable, after updating it:
  660. (progn
  661. (setq org-export-registered-backends
  662. (cl-remove-if-not
  663. (lambda (backend)
  664. (let ((name (org-export-backend-name backend)))
  665. (or (memq name val)
  666. (catch \\='parentp
  667. (dolist (b val)
  668. (and (org-export-derived-backend-p b name)
  669. (throw \\='parentp t)))))))
  670. org-export-registered-backends))
  671. (let ((new-list (mapcar #\\='org-export-backend-name
  672. org-export-registered-backends)))
  673. (dolist (backend val)
  674. (cond
  675. ((not (load (format \"ox-%s\" backend) t t))
  676. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  677. backend))
  678. ((not (memq backend new-list)) (push backend new-list))))
  679. (set-default \\='org-export-backends new-list)))
  680. Adding a back-end to this list will also pull the back-end it
  681. depends on, if any."
  682. :group 'org
  683. :group 'org-export
  684. :version "26.1"
  685. :package-version '(Org . "9.0")
  686. :initialize 'custom-initialize-set
  687. :set (lambda (var val)
  688. (if (not (featurep 'ox)) (set-default var val)
  689. ;; Any back-end not required anymore (not present in VAL and not
  690. ;; a parent of any back-end in the new value) is removed from the
  691. ;; list of registered back-ends.
  692. (setq org-export-registered-backends
  693. (cl-remove-if-not
  694. (lambda (backend)
  695. (let ((name (org-export-backend-name backend)))
  696. (or (memq name val)
  697. (catch 'parentp
  698. (dolist (b val)
  699. (and (org-export-derived-backend-p b name)
  700. (throw 'parentp t)))))))
  701. org-export-registered-backends))
  702. ;; Now build NEW-LIST of both new back-ends and required
  703. ;; parents.
  704. (let ((new-list (mapcar #'org-export-backend-name
  705. org-export-registered-backends)))
  706. (dolist (backend val)
  707. (cond
  708. ((not (load (format "ox-%s" backend) t t))
  709. (message "Problems while trying to load export back-end `%s'"
  710. backend))
  711. ((not (memq backend new-list)) (push backend new-list))))
  712. ;; Set VAR to that list with fixed dependencies.
  713. (set-default var new-list))))
  714. :type '(set :greedy t
  715. (const :tag " ascii Export buffer to ASCII format" ascii)
  716. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  717. (const :tag " html Export buffer to HTML format" html)
  718. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  719. (const :tag " latex Export buffer to LaTeX format" latex)
  720. (const :tag " man Export buffer to MAN format" man)
  721. (const :tag " md Export buffer to Markdown format" md)
  722. (const :tag " odt Export buffer to ODT format" odt)
  723. (const :tag " org Export buffer to Org format" org)
  724. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  725. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  726. (const :tag "C deck Export buffer to deck.js presentations" deck)
  727. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  728. (const :tag "C groff Export buffer to Groff format" groff)
  729. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  730. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  731. (const :tag "C s5 Export buffer to s5 presentations" s5)
  732. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  733. (eval-after-load 'ox
  734. '(dolist (backend org-export-backends)
  735. (condition-case nil (require (intern (format "ox-%s" backend)))
  736. (error (message "Problems while trying to load export back-end `%s'"
  737. backend)))))
  738. (defcustom org-support-shift-select nil
  739. "Non-nil means make shift-cursor commands select text when possible.
  740. \\<org-mode-map>\
  741. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  742. start selecting a region, or enlarge regions started in this way.
  743. In Org mode, in special contexts, these same keys are used for
  744. other purposes, important enough to compete with shift selection.
  745. Org tries to balance these needs by supporting `shift-select-mode'
  746. outside these special contexts, under control of this variable.
  747. The default of this variable is nil, to avoid confusing behavior. Shifted
  748. cursor keys will then execute Org commands in the following contexts:
  749. - on a headline, changing TODO state (left/right) and priority (up/down)
  750. - on a time stamp, changing the time
  751. - in a plain list item, changing the bullet type
  752. - in a property definition line, switching between allowed values
  753. - in the BEGIN line of a clock table (changing the time block).
  754. Outside these contexts, the commands will throw an error.
  755. When this variable is t and the cursor is not in a special
  756. context, Org mode will support shift-selection for making and
  757. enlarging regions. To make this more effective, the bullet
  758. cycling will no longer happen anywhere in an item line, but only
  759. if the cursor is exactly on the bullet.
  760. If you set this variable to the symbol `always', then the keys
  761. will not be special in headlines, property lines, and item lines,
  762. to make shift selection work there as well. If this is what you
  763. want, you can use the following alternative commands:
  764. `\\[org-todo]' and `\\[org-priority]' \
  765. to change TODO state and priority,
  766. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  767. can be used to switch TODO sets,
  768. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  769. and properties can be edited by hand or in column view.
  770. However, when the cursor is on a timestamp, shift-cursor commands
  771. will still edit the time stamp - this is just too good to give up."
  772. :group 'org
  773. :type '(choice
  774. (const :tag "Never" nil)
  775. (const :tag "When outside special context" t)
  776. (const :tag "Everywhere except timestamps" always)))
  777. (defcustom org-loop-over-headlines-in-active-region nil
  778. "Shall some commands act upon headlines in the active region?
  779. When set to t, some commands will be performed in all headlines
  780. within the active region.
  781. When set to `start-level', some commands will be performed in all
  782. headlines within the active region, provided that these headlines
  783. are of the same level than the first one.
  784. When set to a string, those commands will be performed on the
  785. matching headlines within the active region. Such string must be
  786. a tags/property/todo match as it is used in the agenda tags view.
  787. The list of commands is: `org-schedule', `org-deadline',
  788. `org-todo', `org-archive-subtree', `org-archive-set-tag' and
  789. `org-archive-to-archive-sibling'. The archiving commands skip
  790. already archived entries."
  791. :type '(choice (const :tag "Don't loop" nil)
  792. (const :tag "All headlines in active region" t)
  793. (const :tag "In active region, headlines at the same level than the first one" start-level)
  794. (string :tag "Tags/Property/Todo matcher"))
  795. :version "24.1"
  796. :group 'org-todo
  797. :group 'org-archive)
  798. (defgroup org-startup nil
  799. "Options concerning startup of Org mode."
  800. :tag "Org Startup"
  801. :group 'org)
  802. (defcustom org-startup-folded t
  803. "Non-nil means entering Org mode will switch to OVERVIEW.
  804. This can also be configured on a per-file basis by adding one of
  805. the following lines anywhere in the buffer:
  806. #+STARTUP: fold (or `overview', this is equivalent)
  807. #+STARTUP: nofold (or `showall', this is equivalent)
  808. #+STARTUP: content
  809. #+STARTUP: showeverything
  810. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  811. to ignore this option when Org opens agenda files for the first
  812. time."
  813. :group 'org-startup
  814. :type '(choice
  815. (const :tag "nofold: show all" nil)
  816. (const :tag "fold: overview" t)
  817. (const :tag "content: all headlines" content)
  818. (const :tag "show everything, even drawers" showeverything)))
  819. (defcustom org-startup-truncated t
  820. "Non-nil means entering Org mode will set `truncate-lines'.
  821. This is useful since some lines containing links can be very long and
  822. uninteresting. Also tables look terrible when wrapped.
  823. The variable `org-startup-truncated' allows to configure
  824. truncation for Org mode different to the other modes that use the
  825. variable `truncate-lines' and as a shortcut instead of putting
  826. the variable `truncate-lines' into the `org-mode-hook'. If one
  827. wants to configure truncation for Org mode not statically but
  828. dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
  829. the variable `truncate-lines' has to be used because in such a
  830. case it is too late to set the variable `org-startup-truncated'."
  831. :group 'org-startup
  832. :type 'boolean)
  833. (defcustom org-startup-indented nil
  834. "Non-nil means turn on `org-indent-mode' on startup.
  835. This can also be configured on a per-file basis by adding one of
  836. the following lines anywhere in the buffer:
  837. #+STARTUP: indent
  838. #+STARTUP: noindent"
  839. :group 'org-structure
  840. :type '(choice
  841. (const :tag "Not" nil)
  842. (const :tag "Globally (slow on startup in large files)" t)))
  843. (defcustom org-use-sub-superscripts t
  844. "Non-nil means interpret \"_\" and \"^\" for display.
  845. If you want to control how Org exports those characters, see
  846. `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
  847. used to be an alias for `org-export-with-sub-superscripts' in
  848. Org <8.0, it is not anymore.
  849. When this option is turned on, you can use TeX-like syntax for
  850. sub- and superscripts within the buffer. Several characters after
  851. \"_\" or \"^\" will be considered as a single item - so grouping
  852. with {} is normally not needed. For example, the following things
  853. will be parsed as single sub- or superscripts:
  854. 10^24 or 10^tau several digits will be considered 1 item.
  855. 10^-12 or 10^-tau a leading sign with digits or a word
  856. x^2-y^3 will be read as x^2 - y^3, because items are
  857. terminated by almost any nonword/nondigit char.
  858. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  859. Still, ambiguity is possible. So when in doubt, use {} to enclose
  860. the sub/superscript. If you set this variable to the symbol `{}',
  861. the braces are *required* in order to trigger interpretations as
  862. sub/superscript. This can be helpful in documents that need \"_\"
  863. frequently in plain text."
  864. :group 'org-startup
  865. :version "24.4"
  866. :package-version '(Org . "8.0")
  867. :type '(choice
  868. (const :tag "Always interpret" t)
  869. (const :tag "Only with braces" {})
  870. (const :tag "Never interpret" nil)))
  871. (defcustom org-startup-with-beamer-mode nil
  872. "Non-nil means turn on `org-beamer-mode' on startup.
  873. This can also be configured on a per-file basis by adding one of
  874. the following lines anywhere in the buffer:
  875. #+STARTUP: beamer"
  876. :group 'org-startup
  877. :version "24.1"
  878. :type 'boolean)
  879. (defcustom org-startup-align-all-tables nil
  880. "Non-nil means align all tables when visiting a file.
  881. This is useful when the column width in tables is forced with <N> cookies
  882. in table fields. Such tables will look correct only after the first re-align.
  883. This can also be configured on a per-file basis by adding one of
  884. the following lines anywhere in the buffer:
  885. #+STARTUP: align
  886. #+STARTUP: noalign"
  887. :group 'org-startup
  888. :type 'boolean)
  889. (defcustom org-startup-with-inline-images nil
  890. "Non-nil means show inline images when loading a new Org file.
  891. This can also be configured on a per-file basis by adding one of
  892. the following lines anywhere in the buffer:
  893. #+STARTUP: inlineimages
  894. #+STARTUP: noinlineimages"
  895. :group 'org-startup
  896. :version "24.1"
  897. :type 'boolean)
  898. (defcustom org-startup-with-latex-preview nil
  899. "Non-nil means preview LaTeX fragments when loading a new Org file.
  900. This can also be configured on a per-file basis by adding one of
  901. the following lines anywhere in the buffer:
  902. #+STARTUP: latexpreview
  903. #+STARTUP: nolatexpreview"
  904. :group 'org-startup
  905. :version "24.4"
  906. :package-version '(Org . "8.0")
  907. :type 'boolean)
  908. (defcustom org-insert-mode-line-in-empty-file nil
  909. "Non-nil means insert the first line setting Org mode in empty files.
  910. When the function `org-mode' is called interactively in an empty file, this
  911. normally means that the file name does not automatically trigger Org mode.
  912. To ensure that the file will always be in Org mode in the future, a
  913. line enforcing Org mode will be inserted into the buffer, if this option
  914. has been set."
  915. :group 'org-startup
  916. :type 'boolean)
  917. (defcustom org-replace-disputed-keys nil
  918. "Non-nil means use alternative key bindings for some keys.
  919. Org mode uses S-<cursor> keys for changing timestamps and priorities.
  920. These keys are also used by other packages like shift-selection-mode'
  921. \(built into Emacs 23), `CUA-mode' or `windmove.el'.
  922. If you want to use Org mode together with one of these other modes,
  923. or more generally if you would like to move some Org mode commands to
  924. other keys, set this variable and configure the keys with the variable
  925. `org-disputed-keys'.
  926. This option is only relevant at load-time of Org mode, and must be set
  927. *before* org.el is loaded. Changing it requires a restart of Emacs to
  928. become effective."
  929. :group 'org-startup
  930. :type 'boolean)
  931. (defcustom org-use-extra-keys nil
  932. "Non-nil means use extra key sequence definitions for certain commands.
  933. This happens automatically if `window-system' is nil. This
  934. variable lets you do the same manually. You must set it before
  935. loading Org."
  936. :group 'org-startup
  937. :type 'boolean)
  938. (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
  939. (defcustom org-disputed-keys
  940. '(([(shift up)] . [(meta p)])
  941. ([(shift down)] . [(meta n)])
  942. ([(shift left)] . [(meta -)])
  943. ([(shift right)] . [(meta +)])
  944. ([(control shift right)] . [(meta shift +)])
  945. ([(control shift left)] . [(meta shift -)]))
  946. "Keys for which Org mode and other modes compete.
  947. This is an alist, cars are the default keys, second element specifies
  948. the alternative to use when `org-replace-disputed-keys' is t.
  949. Keys can be specified in any syntax supported by `define-key'.
  950. The value of this option takes effect only at Org mode startup,
  951. therefore you'll have to restart Emacs to apply it after changing."
  952. :group 'org-startup
  953. :type 'alist)
  954. (defun org-key (key)
  955. "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
  956. Or return the original if not disputed."
  957. (when org-replace-disputed-keys
  958. (let* ((nkey (key-description key))
  959. (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
  960. org-disputed-keys)))
  961. (setq key (if x (cdr x) key))))
  962. key)
  963. (defun org-defkey (keymap key def)
  964. "Define a key, possibly translated, as returned by `org-key'."
  965. (define-key keymap (org-key key) def))
  966. (defcustom org-ellipsis nil
  967. "The ellipsis to use in the Org mode outline.
  968. When nil, just use the standard three dots. When a non-empty string,
  969. use that string instead.
  970. The change affects only Org mode (which will then use its own display table).
  971. Changing this requires executing `\\[org-mode]' in a buffer to become
  972. effective."
  973. :group 'org-startup
  974. :type '(choice (const :tag "Default" nil)
  975. (string :tag "String" :value "...#"))
  976. :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
  977. (defvar org-display-table nil
  978. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  979. (defgroup org-keywords nil
  980. "Keywords in Org mode."
  981. :tag "Org Keywords"
  982. :group 'org)
  983. (defcustom org-closed-keep-when-no-todo nil
  984. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  985. :group 'org-todo
  986. :group 'org-keywords
  987. :version "24.4"
  988. :package-version '(Org . "8.0")
  989. :type 'boolean)
  990. (defgroup org-structure nil
  991. "Options concerning the general structure of Org files."
  992. :tag "Org Structure"
  993. :group 'org)
  994. (defgroup org-reveal-location nil
  995. "Options about how to make context of a location visible."
  996. :tag "Org Reveal Location"
  997. :group 'org-structure)
  998. (defcustom org-show-context-detail '((agenda . local)
  999. (bookmark-jump . lineage)
  1000. (isearch . lineage)
  1001. (default . ancestors))
  1002. "Alist between context and visibility span when revealing a location.
  1003. \\<org-mode-map>Some actions may move point into invisible
  1004. locations. As a consequence, Org always expose a neighborhood
  1005. around point. How much is shown depends on the initial action,
  1006. or context. Valid contexts are
  1007. agenda when exposing an entry from the agenda
  1008. org-goto when using the command `org-goto' (`\\[org-goto]')
  1009. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1010. tags-tree when constructing a sparse tree based on tags matches
  1011. link-search when exposing search matches associated with a link
  1012. mark-goto when exposing the jump goal of a mark
  1013. bookmark-jump when exposing a bookmark location
  1014. isearch when exiting from an incremental search
  1015. default default for all contexts not set explicitly
  1016. Allowed visibility spans are
  1017. minimal show current headline; if point is not on headline,
  1018. also show entry
  1019. local show current headline, entry and next headline
  1020. ancestors show current headline and its direct ancestors; if
  1021. point is not on headline, also show entry
  1022. lineage show current headline, its direct ancestors and all
  1023. their children; if point is not on headline, also show
  1024. entry and first child
  1025. tree show current headline, its direct ancestors and all
  1026. their children; if point is not on headline, also show
  1027. entry and all children
  1028. canonical show current headline, its direct ancestors along with
  1029. their entries and children; if point is not located on
  1030. the headline, also show current entry and all children
  1031. As special cases, a nil or t value means show all contexts in
  1032. `minimal' or `canonical' view, respectively.
  1033. Some views can make displayed information very compact, but also
  1034. make it harder to edit the location of the match. In such
  1035. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1036. more context."
  1037. :group 'org-reveal-location
  1038. :version "26.1"
  1039. :package-version '(Org . "9.0")
  1040. :type '(choice
  1041. (const :tag "Canonical" t)
  1042. (const :tag "Minimal" nil)
  1043. (repeat :greedy t :tag "Individual contexts"
  1044. (cons
  1045. (choice :tag "Context"
  1046. (const agenda)
  1047. (const org-goto)
  1048. (const occur-tree)
  1049. (const tags-tree)
  1050. (const link-search)
  1051. (const mark-goto)
  1052. (const bookmark-jump)
  1053. (const isearch)
  1054. (const default))
  1055. (choice :tag "Detail level"
  1056. (const minimal)
  1057. (const local)
  1058. (const ancestors)
  1059. (const lineage)
  1060. (const tree)
  1061. (const canonical))))))
  1062. (defcustom org-indirect-buffer-display 'other-window
  1063. "How should indirect tree buffers be displayed?
  1064. This applies to indirect buffers created with the commands
  1065. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1066. Valid values are:
  1067. current-window Display in the current window
  1068. other-window Just display in another window.
  1069. dedicated-frame Create one new frame, and re-use it each time.
  1070. new-frame Make a new frame each time. Note that in this case
  1071. previously-made indirect buffers are kept, and you need to
  1072. kill these buffers yourself."
  1073. :group 'org-structure
  1074. :group 'org-agenda-windows
  1075. :type '(choice
  1076. (const :tag "In current window" current-window)
  1077. (const :tag "In current frame, other window" other-window)
  1078. (const :tag "Each time a new frame" new-frame)
  1079. (const :tag "One dedicated frame" dedicated-frame)))
  1080. (defcustom org-use-speed-commands nil
  1081. "Non-nil means activate single letter commands at beginning of a headline.
  1082. This may also be a function to test for appropriate locations where speed
  1083. commands should be active.
  1084. For example, to activate speed commands when the point is on any
  1085. star at the beginning of the headline, you can do this:
  1086. (setq org-use-speed-commands
  1087. (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
  1088. :group 'org-structure
  1089. :type '(choice
  1090. (const :tag "Never" nil)
  1091. (const :tag "At beginning of headline stars" t)
  1092. (function)))
  1093. (defcustom org-speed-commands-user nil
  1094. "Alist of additional speed commands.
  1095. This list will be checked before `org-speed-commands-default'
  1096. when the variable `org-use-speed-commands' is non-nil
  1097. and when the cursor is at the beginning of a headline.
  1098. The car if each entry is a string with a single letter, which must
  1099. be assigned to `self-insert-command' in the global map.
  1100. The cdr is either a command to be called interactively, a function
  1101. to be called, or a form to be evaluated.
  1102. An entry that is just a list with a single string will be interpreted
  1103. as a descriptive headline that will be added when listing the speed
  1104. commands in the Help buffer using the `?' speed command."
  1105. :group 'org-structure
  1106. :type '(repeat :value ("k" . ignore)
  1107. (choice :value ("k" . ignore)
  1108. (list :tag "Descriptive Headline" (string :tag "Headline"))
  1109. (cons :tag "Letter and Command"
  1110. (string :tag "Command letter")
  1111. (choice
  1112. (function)
  1113. (sexp))))))
  1114. (defcustom org-bookmark-names-plist
  1115. '(:last-capture "org-capture-last-stored"
  1116. :last-refile "org-refile-last-stored"
  1117. :last-capture-marker "org-capture-last-stored-marker")
  1118. "Names for bookmarks automatically set by some Org commands.
  1119. This can provide strings as names for a number of bookmarks Org sets
  1120. automatically. The following keys are currently implemented:
  1121. :last-capture
  1122. :last-capture-marker
  1123. :last-refile
  1124. When a key does not show up in the property list, the corresponding bookmark
  1125. is not set."
  1126. :group 'org-structure
  1127. :type 'plist)
  1128. (defgroup org-cycle nil
  1129. "Options concerning visibility cycling in Org mode."
  1130. :tag "Org Cycle"
  1131. :group 'org-structure)
  1132. (defcustom org-cycle-skip-children-state-if-no-children t
  1133. "Non-nil means skip CHILDREN state in entries that don't have any."
  1134. :group 'org-cycle
  1135. :type 'boolean)
  1136. (defcustom org-cycle-max-level nil
  1137. "Maximum level which should still be subject to visibility cycling.
  1138. Levels higher than this will, for cycling, be treated as text, not a headline.
  1139. When `org-odd-levels-only' is set, a value of N in this variable actually
  1140. means 2N-1 stars as the limiting headline.
  1141. When nil, cycle all levels.
  1142. Note that the limiting level of cycling is also influenced by
  1143. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1144. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1145. than its value."
  1146. :group 'org-cycle
  1147. :type '(choice
  1148. (const :tag "No limit" nil)
  1149. (integer :tag "Maximum level")))
  1150. (defcustom org-hide-block-startup nil
  1151. "Non-nil means entering Org mode will fold all blocks.
  1152. This can also be set in on a per-file basis with
  1153. #+STARTUP: hideblocks
  1154. #+STARTUP: showblocks"
  1155. :group 'org-startup
  1156. :group 'org-cycle
  1157. :type 'boolean)
  1158. (defcustom org-cycle-global-at-bob nil
  1159. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1160. This makes it possible to do global cycling without having to use `S-TAB'
  1161. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1162. line of the buffer
  1163. must not be a headline -- it may be empty or some other text.
  1164. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1165. sure the cursor stays at the beginning of the buffer.
  1166. When this option is nil, don't do anything special at the beginning of
  1167. the buffer."
  1168. :group 'org-cycle
  1169. :type 'boolean)
  1170. (defcustom org-cycle-level-after-item/entry-creation t
  1171. "Non-nil means cycle entry level or item indentation in new empty entries.
  1172. When the cursor is at the end of an empty headline, i.e., with only stars
  1173. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1174. and then all possible ancestor states, before returning to the original state.
  1175. This makes data entry extremely fast: M-RET to create a new headline,
  1176. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1177. When the cursor is at the end of an empty plain list item, one TAB will
  1178. make it a subitem, two or more tabs will back up to make this an item
  1179. higher up in the item hierarchy."
  1180. :group 'org-cycle
  1181. :type 'boolean)
  1182. (defcustom org-cycle-emulate-tab t
  1183. "Where should `org-cycle' emulate TAB.
  1184. nil Never
  1185. white Only in completely white lines
  1186. whitestart Only at the beginning of lines, before the first non-white char
  1187. t Everywhere except in headlines
  1188. exc-hl-bol Everywhere except at the start of a headline
  1189. If TAB is used in a place where it does not emulate TAB, the current subtree
  1190. visibility is cycled."
  1191. :group 'org-cycle
  1192. :type '(choice (const :tag "Never" nil)
  1193. (const :tag "Only in completely white lines" white)
  1194. (const :tag "Before first char in a line" whitestart)
  1195. (const :tag "Everywhere except in headlines" t)
  1196. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1197. (defcustom org-cycle-separator-lines 2
  1198. "Number of empty lines needed to keep an empty line between collapsed trees.
  1199. If you leave an empty line between the end of a subtree and the following
  1200. headline, this empty line is hidden when the subtree is folded.
  1201. Org mode will leave (exactly) one empty line visible if the number of
  1202. empty lines is equal or larger to the number given in this variable.
  1203. So the default 2 means at least 2 empty lines after the end of a subtree
  1204. are needed to produce free space between a collapsed subtree and the
  1205. following headline.
  1206. If the number is negative, and the number of empty lines is at least -N,
  1207. all empty lines are shown.
  1208. Special case: when 0, never leave empty lines in collapsed view."
  1209. :group 'org-cycle
  1210. :type 'integer)
  1211. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1212. (defcustom org-pre-cycle-hook nil
  1213. "Hook that is run before visibility cycling is happening.
  1214. The function(s) in this hook must accept a single argument which indicates
  1215. the new state that will be set right after running this hook. The
  1216. argument is a symbol. Before a global state change, it can have the values
  1217. `overview', `content', or `all'. Before a local state change, it can have
  1218. the values `folded', `children', or `subtree'."
  1219. :group 'org-cycle
  1220. :type 'hook)
  1221. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1222. org-cycle-hide-drawers
  1223. org-cycle-show-empty-lines
  1224. org-optimize-window-after-visibility-change)
  1225. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1226. The function(s) in this hook must accept a single argument which indicates
  1227. the new state that was set by the most recent `org-cycle' command. The
  1228. argument is a symbol. After a global state change, it can have the values
  1229. `overview', `contents', or `all'. After a local state change, it can have
  1230. the values `folded', `children', or `subtree'."
  1231. :group 'org-cycle
  1232. :type 'hook
  1233. :version "26.1"
  1234. :package-version '(Org . "8.3"))
  1235. (defgroup org-edit-structure nil
  1236. "Options concerning structure editing in Org mode."
  1237. :tag "Org Edit Structure"
  1238. :group 'org-structure)
  1239. (defcustom org-odd-levels-only nil
  1240. "Non-nil means skip even levels and only use odd levels for the outline.
  1241. This has the effect that two stars are being added/taken away in
  1242. promotion/demotion commands. It also influences how levels are
  1243. handled by the exporters.
  1244. Changing it requires restart of `font-lock-mode' to become effective
  1245. for fontification also in regions already fontified.
  1246. You may also set this on a per-file basis by adding one of the following
  1247. lines to the buffer:
  1248. #+STARTUP: odd
  1249. #+STARTUP: oddeven"
  1250. :group 'org-edit-structure
  1251. :group 'org-appearance
  1252. :type 'boolean)
  1253. (defcustom org-adapt-indentation t
  1254. "Non-nil means adapt indentation to outline node level.
  1255. When this variable is set, Org assumes that you write outlines by
  1256. indenting text in each node to align with the headline (after the
  1257. stars). The following issues are influenced by this variable:
  1258. - The indentation is increased by one space in a demotion
  1259. command, and decreased by one in a promotion command. However,
  1260. in the latter case, if shifting some line in the entry body
  1261. would alter document structure (e.g., insert a new headline),
  1262. indentation is not changed at all.
  1263. - Property drawers and planning information is inserted indented
  1264. when this variable is set. When nil, they will not be indented.
  1265. - TAB indents a line relative to current level. The lines below
  1266. a headline will be indented when this variable is set.
  1267. Note that this is all about true indentation, by adding and
  1268. removing space characters. See also `org-indent.el' which does
  1269. level-dependent indentation in a virtual way, i.e. at display
  1270. time in Emacs."
  1271. :group 'org-edit-structure
  1272. :type 'boolean)
  1273. (defcustom org-special-ctrl-a/e nil
  1274. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1275. When t, `C-a' will bring back the cursor to the beginning of the
  1276. headline text, i.e. after the stars and after a possible TODO
  1277. keyword. In an item, this will be the position after bullet and
  1278. check-box, if any. When the cursor is already at that position,
  1279. another `C-a' will bring it to the beginning of the line.
  1280. `C-e' will jump to the end of the headline, ignoring the presence
  1281. of tags in the headline. A second `C-e' will then jump to the
  1282. true end of the line, after any tags. This also means that, when
  1283. this variable is non-nil, `C-e' also will never jump beyond the
  1284. end of the heading of a folded section, i.e. not after the
  1285. ellipses.
  1286. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1287. normally, going to the true line boundary first. Only a directly
  1288. following, identical keypress will bring the cursor to the
  1289. special positions.
  1290. This may also be a cons cell where the behavior for `C-a' and
  1291. `C-e' is set separately."
  1292. :group 'org-edit-structure
  1293. :type '(choice
  1294. (const :tag "off" nil)
  1295. (const :tag "on: after stars/bullet and before tags first" t)
  1296. (const :tag "reversed: true line boundary first" reversed)
  1297. (cons :tag "Set C-a and C-e separately"
  1298. (choice :tag "Special C-a"
  1299. (const :tag "off" nil)
  1300. (const :tag "on: after stars/bullet first" t)
  1301. (const :tag "reversed: before stars/bullet first" reversed))
  1302. (choice :tag "Special C-e"
  1303. (const :tag "off" nil)
  1304. (const :tag "on: before tags first" t)
  1305. (const :tag "reversed: after tags first" reversed)))))
  1306. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1307. (defcustom org-special-ctrl-k nil
  1308. "Non-nil means `C-k' will behave specially in headlines.
  1309. When nil, `C-k' will call the default `kill-line' command.
  1310. When t, the following will happen while the cursor is in the headline:
  1311. - When the cursor is at the beginning of a headline, kill the entire
  1312. line and possible the folded subtree below the line.
  1313. - When in the middle of the headline text, kill the headline up to the tags.
  1314. - When after the headline text, kill the tags."
  1315. :group 'org-edit-structure
  1316. :type 'boolean)
  1317. (defcustom org-ctrl-k-protect-subtree nil
  1318. "Non-nil means, do not delete a hidden subtree with C-k.
  1319. When set to the symbol `error', simply throw an error when C-k is
  1320. used to kill (part-of) a headline that has hidden text behind it.
  1321. Any other non-nil value will result in a query to the user, if it is
  1322. OK to kill that hidden subtree. When nil, kill without remorse."
  1323. :group 'org-edit-structure
  1324. :version "24.1"
  1325. :type '(choice
  1326. (const :tag "Do not protect hidden subtrees" nil)
  1327. (const :tag "Protect hidden subtrees with a security query" t)
  1328. (const :tag "Never kill a hidden subtree with C-k" error)))
  1329. (defcustom org-special-ctrl-o t
  1330. "Non-nil means, make `C-o' insert a row in tables."
  1331. :group 'org-edit-structure
  1332. :type 'boolean)
  1333. (defcustom org-catch-invisible-edits nil
  1334. "Check if in invisible region before inserting or deleting a character.
  1335. Valid values are:
  1336. nil Do not check, so just do invisible edits.
  1337. error Throw an error and do nothing.
  1338. show Make point visible, and do the requested edit.
  1339. show-and-error Make point visible, then throw an error and abort the edit.
  1340. smart Make point visible, and do insertion/deletion if it is
  1341. adjacent to visible text and the change feels predictable.
  1342. Never delete a previously invisible character or add in the
  1343. middle or right after an invisible region. Basically, this
  1344. allows insertion and backward-delete right before ellipses.
  1345. FIXME: maybe in this case we should not even show?"
  1346. :group 'org-edit-structure
  1347. :version "24.1"
  1348. :type '(choice
  1349. (const :tag "Do not check" nil)
  1350. (const :tag "Throw error when trying to edit" error)
  1351. (const :tag "Unhide, but do not do the edit" show-and-error)
  1352. (const :tag "Show invisible part and do the edit" show)
  1353. (const :tag "Be smart and do the right thing" smart)))
  1354. (defcustom org-yank-folded-subtrees t
  1355. "Non-nil means when yanking subtrees, fold them.
  1356. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1357. it starts with a heading and all other headings in it are either children
  1358. or siblings, then fold all the subtrees. However, do this only if no
  1359. text after the yank would be swallowed into a folded tree by this action."
  1360. :group 'org-edit-structure
  1361. :type 'boolean)
  1362. (defcustom org-yank-adjusted-subtrees nil
  1363. "Non-nil means when yanking subtrees, adjust the level.
  1364. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1365. this function for details."
  1366. :group 'org-edit-structure
  1367. :type 'boolean)
  1368. (defcustom org-M-RET-may-split-line '((default . t))
  1369. "Non-nil means M-RET will split the line at the cursor position.
  1370. When nil, it will go to the end of the line before making a
  1371. new line.
  1372. You may also set this option in a different way for different
  1373. contexts. Valid contexts are:
  1374. headline when creating a new headline
  1375. item when creating a new item
  1376. table in a table field
  1377. default the value to be used for all contexts not explicitly
  1378. customized"
  1379. :group 'org-structure
  1380. :group 'org-table
  1381. :type '(choice
  1382. (const :tag "Always" t)
  1383. (const :tag "Never" nil)
  1384. (repeat :greedy t :tag "Individual contexts"
  1385. (cons
  1386. (choice :tag "Context"
  1387. (const headline)
  1388. (const item)
  1389. (const table)
  1390. (const default))
  1391. (boolean)))))
  1392. (defcustom org-insert-heading-respect-content nil
  1393. "Non-nil means insert new headings after the current subtree.
  1394. \\<org-mode-map>
  1395. When nil, the new heading is created directly after the current line.
  1396. The commands `\\[org-insert-heading-respect-content]' and \
  1397. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1398. for the duration of the command."
  1399. :group 'org-structure
  1400. :type 'boolean)
  1401. (defcustom org-blank-before-new-entry '((heading . auto)
  1402. (plain-list-item . auto))
  1403. "Should `org-insert-heading' leave a blank line before new heading/item?
  1404. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1405. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1406. which case Org will look at the surrounding headings/items and try to
  1407. make an intelligent decision whether to insert a blank line or not."
  1408. :group 'org-edit-structure
  1409. :type '(list
  1410. (cons (const heading)
  1411. (choice (const :tag "Never" nil)
  1412. (const :tag "Always" t)
  1413. (const :tag "Auto" auto)))
  1414. (cons (const plain-list-item)
  1415. (choice (const :tag "Never" nil)
  1416. (const :tag "Always" t)
  1417. (const :tag "Auto" auto)))))
  1418. (defcustom org-insert-heading-hook nil
  1419. "Hook being run after inserting a new heading."
  1420. :group 'org-edit-structure
  1421. :type 'hook)
  1422. (defcustom org-enable-fixed-width-editor t
  1423. "Non-nil means lines starting with \":\" are treated as fixed-width.
  1424. This currently only means they are never auto-wrapped.
  1425. When nil, such lines will be treated like ordinary lines."
  1426. :group 'org-edit-structure
  1427. :type 'boolean)
  1428. (defcustom org-goto-auto-isearch t
  1429. "Non-nil means typing characters in `org-goto' starts incremental search.
  1430. When nil, you can use these keybindings to navigate the buffer:
  1431. q Quit the org-goto interface
  1432. n Go to the next visible heading
  1433. p Go to the previous visible heading
  1434. f Go one heading forward on same level
  1435. b Go one heading backward on same level
  1436. u Go one heading up"
  1437. :group 'org-edit-structure
  1438. :type 'boolean)
  1439. (defgroup org-sparse-trees nil
  1440. "Options concerning sparse trees in Org mode."
  1441. :tag "Org Sparse Trees"
  1442. :group 'org-structure)
  1443. (defcustom org-highlight-sparse-tree-matches t
  1444. "Non-nil means highlight all matches that define a sparse tree.
  1445. The highlights will automatically disappear the next time the buffer is
  1446. changed by an edit command."
  1447. :group 'org-sparse-trees
  1448. :type 'boolean)
  1449. (defcustom org-remove-highlights-with-change t
  1450. "Non-nil means any change to the buffer will remove temporary highlights.
  1451. \\<org-mode-map>\
  1452. Such highlights are created by `org-occur' and `org-clock-display'.
  1453. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1454. to get rid of the highlights.
  1455. The highlights created by `org-toggle-latex-fragment' always need
  1456. `\\[org-toggle-latex-fragment]' to be removed."
  1457. :group 'org-sparse-trees
  1458. :group 'org-time
  1459. :type 'boolean)
  1460. (defcustom org-occur-case-fold-search t
  1461. "Non-nil means `org-occur' should be case-insensitive.
  1462. If set to `smart' the search will be case-insensitive only if it
  1463. doesn't specify any upper case character."
  1464. :group 'org-sparse-trees
  1465. :version "26.1"
  1466. :type '(choice
  1467. (const :tag "Case-sensitive" nil)
  1468. (const :tag "Case-insensitive" t)
  1469. (const :tag "Case-insensitive for lower case searches only" 'smart)))
  1470. (defcustom org-occur-hook '(org-first-headline-recenter)
  1471. "Hook that is run after `org-occur' has constructed a sparse tree.
  1472. This can be used to recenter the window to show as much of the structure
  1473. as possible."
  1474. :group 'org-sparse-trees
  1475. :type 'hook)
  1476. (defgroup org-imenu-and-speedbar nil
  1477. "Options concerning imenu and speedbar in Org mode."
  1478. :tag "Org Imenu and Speedbar"
  1479. :group 'org-structure)
  1480. (defcustom org-imenu-depth 2
  1481. "The maximum level for Imenu access to Org headlines.
  1482. This also applied for speedbar access."
  1483. :group 'org-imenu-and-speedbar
  1484. :type 'integer)
  1485. (defgroup org-table nil
  1486. "Options concerning tables in Org mode."
  1487. :tag "Org Table"
  1488. :group 'org)
  1489. (defcustom org-enable-table-editor 'optimized
  1490. "Non-nil means lines starting with \"|\" are handled by the table editor.
  1491. When nil, such lines will be treated like ordinary lines.
  1492. When equal to the symbol `optimized', the table editor will be optimized to
  1493. do the following:
  1494. - Automatic overwrite mode in front of whitespace in table fields.
  1495. This makes the structure of the table stay in tact as long as the edited
  1496. field does not exceed the column width.
  1497. - Minimize the number of realigns. Normally, the table is aligned each time
  1498. TAB or RET are pressed to move to another field. With optimization this
  1499. happens only if changes to a field might have changed the column width.
  1500. Optimization requires replacing the functions `self-insert-command',
  1501. `delete-char', and `backward-delete-char' in Org buffers, with a
  1502. slight (in fact: unnoticeable) speed impact for normal typing. Org is very
  1503. good at guessing when a re-align will be necessary, but you can always
  1504. force one with `\\[org-ctrl-c-ctrl-c]'.
  1505. If you would like to use the optimized version in Org mode, but the
  1506. un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
  1507. This variable can be used to turn on and off the table editor during a session,
  1508. but in order to toggle optimization, a restart is required.
  1509. See also the variable `org-table-auto-blank-field'."
  1510. :group 'org-table
  1511. :type '(choice
  1512. (const :tag "off" nil)
  1513. (const :tag "on" t)
  1514. (const :tag "on, optimized" optimized)))
  1515. (defcustom org-self-insert-cluster-for-undo nil
  1516. "Non-nil means cluster self-insert commands for undo when possible.
  1517. If this is set, then, like in the Emacs command loop, 20 consecutive
  1518. characters will be undone together.
  1519. This is configurable, because there is some impact on typing performance."
  1520. :group 'org-table
  1521. :type 'boolean)
  1522. (defcustom org-table-tab-recognizes-table.el t
  1523. "Non-nil means TAB will automatically notice a table.el table.
  1524. When it sees such a table, it moves point into it and - if necessary -
  1525. calls `table-recognize-table'."
  1526. :group 'org-table-editing
  1527. :type 'boolean)
  1528. (defgroup org-link nil
  1529. "Options concerning links in Org mode."
  1530. :tag "Org Link"
  1531. :group 'org)
  1532. (defvar-local org-link-abbrev-alist-local nil
  1533. "Buffer-local version of `org-link-abbrev-alist', which see.
  1534. The value of this is taken from the #+LINK lines.")
  1535. (defcustom org-link-parameters
  1536. '(("doi" :follow org--open-doi-link)
  1537. ("elisp" :follow org--open-elisp-link)
  1538. ("file" :complete org-file-complete-link)
  1539. ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
  1540. ("help" :follow org--open-help-link)
  1541. ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
  1542. ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
  1543. ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
  1544. ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
  1545. ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
  1546. ("shell" :follow org--open-shell-link))
  1547. "An alist of properties that defines all the links in Org mode.
  1548. The key in each association is a string of the link type.
  1549. Subsequent optional elements make up a p-list of link properties.
  1550. :follow - A function that takes the link path as an argument.
  1551. :export - A function that takes the link path, description and
  1552. export-backend as arguments.
  1553. :store - A function responsible for storing the link. See the
  1554. function `org-store-link-functions'.
  1555. :complete - A function that inserts a link with completion. The
  1556. function takes one optional prefix arg.
  1557. :face - A face for the link, or a function that returns a face.
  1558. The function takes one argument which is the link path. The
  1559. default face is `org-link'.
  1560. :mouse-face - The mouse-face. The default is `highlight'.
  1561. :display - `full' will not fold the link in descriptive
  1562. display. Default is `org-link'.
  1563. :help-echo - A string or function that takes (window object position)
  1564. as arguments and returns a string.
  1565. :keymap - A keymap that is active on the link. The default is
  1566. `org-mouse-map'.
  1567. :htmlize-link - A function for the htmlize-link. Defaults
  1568. to (list :uri \"type:path\")
  1569. :activate-func - A function to run at the end of font-lock
  1570. activation. The function must accept (link-start link-end path bracketp)
  1571. as arguments."
  1572. :group 'org-link
  1573. :type '(alist :tag "Link display parameters"
  1574. :value-type plist))
  1575. (defun org-link-get-parameter (type key)
  1576. "Get TYPE link property for KEY.
  1577. TYPE is a string and KEY is a plist keyword."
  1578. (plist-get
  1579. (cdr (assoc type org-link-parameters))
  1580. key))
  1581. (defun org-link-set-parameters (type &rest parameters)
  1582. "Set link TYPE properties to PARAMETERS.
  1583. PARAMETERS should be :key val pairs."
  1584. (let ((data (assoc type org-link-parameters)))
  1585. (if data (setcdr data (org-combine-plists (cdr data) parameters))
  1586. (push (cons type parameters) org-link-parameters)
  1587. (org-make-link-regexps)
  1588. (org-element-update-syntax))))
  1589. (defun org-link-types ()
  1590. "Return a list of known link types."
  1591. (mapcar #'car org-link-parameters))
  1592. (defcustom org-link-abbrev-alist nil
  1593. "Alist of link abbreviations.
  1594. The car of each element is a string, to be replaced at the start of a link.
  1595. The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
  1596. links in Org buffers can have an optional tag after a double colon, e.g.,
  1597. [[linkkey:tag][description]]
  1598. The `linkkey' must be a single word, starting with a letter, followed
  1599. by letters, numbers, `-' or `_'.
  1600. If REPLACE is a string, the tag will simply be appended to create the link.
  1601. If the string contains \"%s\", the tag will be inserted there. If the string
  1602. contains \"%h\", it will cause a url-encoded version of the tag to be inserted
  1603. at that point (see the function `url-hexify-string'). If the string contains
  1604. the specifier \"%(my-function)\", then the custom function `my-function' will
  1605. be invoked: this function takes the tag as its only argument and must return
  1606. a string.
  1607. REPLACE may also be a function that will be called with the tag as the
  1608. only argument to create the link, which should be returned as a string.
  1609. See the manual for examples."
  1610. :group 'org-link
  1611. :type '(repeat
  1612. (cons
  1613. (string :tag "Protocol")
  1614. (choice
  1615. (string :tag "Format")
  1616. (function)))))
  1617. (defcustom org-descriptive-links t
  1618. "Non-nil means Org will display descriptive links.
  1619. E.g. [[http://orgmode.org][Org website]] will be displayed as
  1620. \"Org Website\", hiding the link itself and just displaying its
  1621. description. When set to nil, Org will display the full links
  1622. literally.
  1623. You can interactively set the value of this variable by calling
  1624. `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
  1625. :group 'org-link
  1626. :type 'boolean)
  1627. (defcustom org-link-file-path-type 'adaptive
  1628. "How the path name in file links should be stored.
  1629. Valid values are:
  1630. relative Relative to the current directory, i.e. the directory of the file
  1631. into which the link is being inserted.
  1632. absolute Absolute path, if possible with ~ for home directory.
  1633. noabbrev Absolute path, no abbreviation of home directory.
  1634. adaptive Use relative path for files in the current directory and sub-
  1635. directories of it. For other files, use an absolute path."
  1636. :group 'org-link
  1637. :type '(choice
  1638. (const relative)
  1639. (const absolute)
  1640. (const noabbrev)
  1641. (const adaptive)))
  1642. (defvaralias 'org-activate-links 'org-highlight-links)
  1643. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1644. "Types of links that should be highlighted in Org files.
  1645. This is a list of symbols, each one of them leading to the
  1646. highlighting of a certain link type.
  1647. You can still open links that are not highlighted.
  1648. In principle, it does not hurt to turn on highlighting for all
  1649. link types. There may be a small gain when turning off unused
  1650. link types. The types are:
  1651. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1652. angle Links in angular brackets that may contain whitespace like
  1653. <bbdb:Carsten Dominik>.
  1654. plain Plain links in normal text, no whitespace, like http://google.com.
  1655. radio Text that is matched by a radio target, see manual for details.
  1656. tag Tag settings in a headline (link to tag search).
  1657. date Time stamps (link to calendar).
  1658. footnote Footnote labels.
  1659. If you set this variable during an Emacs session, use `org-mode-restart'
  1660. in the Org buffer so that the change takes effect."
  1661. :group 'org-link
  1662. :group 'org-appearance
  1663. :type '(set :greedy t
  1664. (const :tag "Double bracket links" bracket)
  1665. (const :tag "Angular bracket links" angle)
  1666. (const :tag "Plain text links" plain)
  1667. (const :tag "Radio target matches" radio)
  1668. (const :tag "Tags" tag)
  1669. (const :tag "Timestamps" date)
  1670. (const :tag "Footnotes" footnote)))
  1671. (defcustom org-make-link-description-function nil
  1672. "Function to use for generating link descriptions from links.
  1673. When nil, the link location will be used. This function must take
  1674. two parameters: the first one is the link, the second one is the
  1675. description generated by `org-insert-link'. The function should
  1676. return the description to use."
  1677. :group 'org-link
  1678. :type '(choice (const nil) (function)))
  1679. (defgroup org-link-store nil
  1680. "Options concerning storing links in Org mode."
  1681. :tag "Org Store Link"
  1682. :group 'org-link)
  1683. (defcustom org-url-hexify-p t
  1684. "When non-nil, hexify URL when creating a link."
  1685. :type 'boolean
  1686. :version "24.3"
  1687. :group 'org-link-store)
  1688. (defcustom org-email-link-description-format "Email %c: %.30s"
  1689. "Format of the description part of a link to an email or usenet message.
  1690. The following %-escapes will be replaced by corresponding information:
  1691. %F full \"From\" field
  1692. %f name, taken from \"From\" field, address if no name
  1693. %T full \"To\" field
  1694. %t first name in \"To\" field, address if no name
  1695. %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
  1696. will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
  1697. %s subject
  1698. %d date
  1699. %m message-id.
  1700. You may use normal field width specification between the % and the letter.
  1701. This is for example useful to limit the length of the subject.
  1702. Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
  1703. :group 'org-link-store
  1704. :type 'string)
  1705. (defcustom org-from-is-user-regexp
  1706. (let (r1 r2)
  1707. (when (and user-mail-address (not (string= user-mail-address "")))
  1708. (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
  1709. (when (and user-full-name (not (string= user-full-name "")))
  1710. (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
  1711. (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
  1712. "Regexp matched against the \"From:\" header of an email or usenet message.
  1713. It should match if the message is from the user him/herself."
  1714. :group 'org-link-store
  1715. :type 'regexp)
  1716. (defcustom org-context-in-file-links t
  1717. "Non-nil means file links from `org-store-link' contain context.
  1718. \\<org-mode-map>
  1719. A search string will be added to the file name with :: as separator
  1720. and used to find the context when the link is activated by the command
  1721. `org-open-at-point'. When this option is t, the entire active region
  1722. will be placed in the search string of the file link. If set to a
  1723. positive integer, only the first n lines of context will be stored.
  1724. Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
  1725. \\[org-store-link]')
  1726. negates this setting for the duration of the command."
  1727. :group 'org-link-store
  1728. :type '(choice boolean integer))
  1729. (defcustom org-keep-stored-link-after-insertion nil
  1730. "Non-nil means keep link in list for entire session.
  1731. \\<org-mode-map>
  1732. The command `org-store-link' adds a link pointing to the current
  1733. location to an internal list. These links accumulate during a session.
  1734. The command `org-insert-link' can be used to insert links into any
  1735. Org file (offering completion for all stored links).
  1736. When this option is nil, every link which has been inserted once using
  1737. `\\[org-insert-link]' will be removed from the list, to make completing the \
  1738. unused
  1739. links more efficient."
  1740. :group 'org-link-store
  1741. :type 'boolean)
  1742. (defgroup org-link-follow nil
  1743. "Options concerning following links in Org mode."
  1744. :tag "Org Follow Link"
  1745. :group 'org-link)
  1746. (defcustom org-link-translation-function nil
  1747. "Function to translate links with different syntax to Org syntax.
  1748. This can be used to translate links created for example by the Planner
  1749. or emacs-wiki packages to Org syntax.
  1750. The function must accept two parameters, a TYPE containing the link
  1751. protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
  1752. which is everything after the link protocol. It should return a cons
  1753. with possibly modified values of type and path.
  1754. Org contains a function for this, so if you set this variable to
  1755. `org-translate-link-from-planner', you should be able follow many
  1756. links created by planner."
  1757. :group 'org-link-follow
  1758. :type '(choice (const nil) (function)))
  1759. (defcustom org-follow-link-hook nil
  1760. "Hook that is run after a link has been followed."
  1761. :group 'org-link-follow
  1762. :type 'hook)
  1763. (defcustom org-tab-follows-link nil
  1764. "Non-nil means on links TAB will follow the link.
  1765. Needs to be set before org.el is loaded.
  1766. This really should not be used, it does not make sense, and the
  1767. implementation is bad."
  1768. :group 'org-link-follow
  1769. :type 'boolean)
  1770. (defcustom org-return-follows-link nil
  1771. "Non-nil means on links RET will follow the link.
  1772. In tables, the special behavior of RET has precedence."
  1773. :group 'org-link-follow
  1774. :type 'boolean)
  1775. (defcustom org-mouse-1-follows-link
  1776. (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
  1777. "Non-nil means mouse-1 on a link will follow the link.
  1778. A longer mouse click will still set point. Needs to be set
  1779. before org.el is loaded."
  1780. :group 'org-link-follow
  1781. :version "24.4"
  1782. :package-version '(Org . "8.3")
  1783. :type '(choice
  1784. (const :tag "A double click follows the link" double)
  1785. (const :tag "Unconditionally follow the link with mouse-1" t)
  1786. (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
  1787. (defcustom org-mark-ring-length 4
  1788. "Number of different positions to be recorded in the ring.
  1789. Changing this requires a restart of Emacs to work correctly."
  1790. :group 'org-link-follow
  1791. :type 'integer)
  1792. (defcustom org-link-search-must-match-exact-headline 'query-to-create
  1793. "Non-nil means internal fuzzy links can only match headlines.
  1794. When nil, the a fuzzy link may point to a target or a named
  1795. construct in the document. When set to the special value
  1796. `query-to-create', offer to create a new headline when none
  1797. matched.
  1798. Spaces and statistics cookies are ignored during heading searches."
  1799. :group 'org-link-follow
  1800. :version "24.1"
  1801. :type '(choice
  1802. (const :tag "Use fuzzy text search" nil)
  1803. (const :tag "Match only exact headline" t)
  1804. (const :tag "Match exact headline or query to create it"
  1805. query-to-create))
  1806. :safe #'symbolp)
  1807. (defcustom org-link-frame-setup
  1808. '((vm . vm-visit-folder-other-frame)
  1809. (vm-imap . vm-visit-imap-folder-other-frame)
  1810. (gnus . org-gnus-no-new-news)
  1811. (file . find-file-other-window)
  1812. (wl . wl-other-frame))
  1813. "Setup the frame configuration for following links.
  1814. When following a link with Emacs, it may often be useful to display
  1815. this link in another window or frame. This variable can be used to
  1816. set this up for the different types of links.
  1817. For VM, use any of
  1818. `vm-visit-folder'
  1819. `vm-visit-folder-other-window'
  1820. `vm-visit-folder-other-frame'
  1821. For Gnus, use any of
  1822. `gnus'
  1823. `gnus-other-frame'
  1824. `org-gnus-no-new-news'
  1825. For FILE, use any of
  1826. `find-file'
  1827. `find-file-other-window'
  1828. `find-file-other-frame'
  1829. For Wanderlust use any of
  1830. `wl'
  1831. `wl-other-frame'
  1832. For the calendar, use the variable `calendar-setup'.
  1833. For BBDB, it is currently only possible to display the matches in
  1834. another window."
  1835. :group 'org-link-follow
  1836. :type '(list
  1837. (cons (const vm)
  1838. (choice
  1839. (const vm-visit-folder)
  1840. (const vm-visit-folder-other-window)
  1841. (const vm-visit-folder-other-frame)))
  1842. (cons (const vm-imap)
  1843. (choice
  1844. (const vm-visit-imap-folder)
  1845. (const vm-visit-imap-folder-other-window)
  1846. (const vm-visit-imap-folder-other-frame)))
  1847. (cons (const gnus)
  1848. (choice
  1849. (const gnus)
  1850. (const gnus-other-frame)
  1851. (const org-gnus-no-new-news)))
  1852. (cons (const file)
  1853. (choice
  1854. (const find-file)
  1855. (const find-file-other-window)
  1856. (const find-file-other-frame)))
  1857. (cons (const wl)
  1858. (choice
  1859. (const wl)
  1860. (const wl-other-frame)))))
  1861. (defcustom org-display-internal-link-with-indirect-buffer nil
  1862. "Non-nil means use indirect buffer to display infile links.
  1863. Activating internal links (from one location in a file to another location
  1864. in the same file) normally just jumps to the location. When the link is
  1865. activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
  1866. is displayed in
  1867. another window. When this option is set, the other window actually displays
  1868. an indirect buffer clone of the current buffer, to avoid any visibility
  1869. changes to the current buffer."
  1870. :group 'org-link-follow
  1871. :type 'boolean)
  1872. (defcustom org-open-non-existing-files nil
  1873. "Non-nil means `org-open-file' will open non-existing files.
  1874. When nil, an error will be generated.
  1875. This variable applies only to external applications because they
  1876. might choke on non-existing files. If the link is to a file that
  1877. will be opened in Emacs, the variable is ignored."
  1878. :group 'org-link-follow
  1879. :type 'boolean)
  1880. (defcustom org-open-directory-means-index-dot-org nil
  1881. "Non-nil means a link to a directory really means to index.org.
  1882. When nil, following a directory link will run dired or open a finder/explorer
  1883. window on that directory."
  1884. :group 'org-link-follow
  1885. :type 'boolean)
  1886. (defcustom org-confirm-shell-link-function 'yes-or-no-p
  1887. "Non-nil means ask for confirmation before executing shell links.
  1888. Shell links can be dangerous: just think about a link
  1889. [[shell:rm -rf ~/*][Google Search]]
  1890. This link would show up in your Org document as \"Google Search\",
  1891. but really it would remove your entire home directory.
  1892. Therefore we advise against setting this variable to nil.
  1893. Just change it to `y-or-n-p' if you want to confirm with a
  1894. single keystroke rather than having to type \"yes\"."
  1895. :group 'org-link-follow
  1896. :type '(choice
  1897. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1898. (const :tag "with y-or-n (faster)" y-or-n-p)
  1899. (const :tag "no confirmation (dangerous)" nil)))
  1900. (put 'org-confirm-shell-link-function
  1901. 'safe-local-variable
  1902. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1903. (defcustom org-confirm-shell-link-not-regexp ""
  1904. "A regexp to skip confirmation for shell links."
  1905. :group 'org-link-follow
  1906. :version "24.1"
  1907. :type 'regexp)
  1908. (defcustom org-confirm-elisp-link-function 'yes-or-no-p
  1909. "Non-nil means ask for confirmation before executing Emacs Lisp links.
  1910. Elisp links can be dangerous: just think about a link
  1911. [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
  1912. This link would show up in your Org document as \"Google Search\",
  1913. but really it would remove your entire home directory.
  1914. Therefore we advise against setting this variable to nil.
  1915. Just change it to `y-or-n-p' if you want to confirm with a
  1916. single keystroke rather than having to type \"yes\"."
  1917. :group 'org-link-follow
  1918. :type '(choice
  1919. (const :tag "with yes-or-no (safer)" yes-or-no-p)
  1920. (const :tag "with y-or-n (faster)" y-or-n-p)
  1921. (const :tag "no confirmation (dangerous)" nil)))
  1922. (put 'org-confirm-shell-link-function
  1923. 'safe-local-variable
  1924. (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  1925. (defcustom org-confirm-elisp-link-not-regexp ""
  1926. "A regexp to skip confirmation for Elisp links."
  1927. :group 'org-link-follow
  1928. :version "24.1"
  1929. :type 'regexp)
  1930. (defconst org-file-apps-defaults-gnu
  1931. '((remote . emacs)
  1932. (system . mailcap)
  1933. (t . mailcap))
  1934. "Default file applications on a UNIX or GNU/Linux system.
  1935. See `org-file-apps'.")
  1936. (defconst org-file-apps-defaults-macosx
  1937. '((remote . emacs)
  1938. (system . "open %s")
  1939. ("ps.gz" . "gv %s")
  1940. ("eps.gz" . "gv %s")
  1941. ("dvi" . "xdvi %s")
  1942. ("fig" . "xfig %s")
  1943. (t . "open %s"))
  1944. "Default file applications on a macOS system.
  1945. The system \"open\" is known as a default, but we use X11 applications
  1946. for some files for which the OS does not have a good default.
  1947. See `org-file-apps'.")
  1948. (defconst org-file-apps-defaults-windowsnt
  1949. (list '(remote . emacs)
  1950. (cons 'system (lambda (file _path)
  1951. (with-no-warnings (w32-shell-execute "open" file))))
  1952. (cons t (lambda (file _path)
  1953. (with-no-warnings (w32-shell-execute "open" file)))))
  1954. "Default file applications on a Windows NT system.
  1955. The system \"open\" is used for most files.
  1956. See `org-file-apps'.")
  1957. (defcustom org-file-apps
  1958. '((auto-mode . emacs)
  1959. ("\\.mm\\'" . default)
  1960. ("\\.x?html?\\'" . default)
  1961. ("\\.pdf\\'" . default))
  1962. "External applications for opening `file:path' items in a document.
  1963. \\<org-mode-map>\
  1964. Org mode uses system defaults for different file types, but
  1965. you can use this variable to set the application for a given file
  1966. extension. The entries in this list are cons cells where the car identifies
  1967. files and the cdr the corresponding command.
  1968. Possible values for the file identifier are:
  1969. \"string\" A string as a file identifier can be interpreted in different
  1970. ways, depending on its contents:
  1971. - Alphanumeric characters only:
  1972. Match links with this file extension.
  1973. Example: (\"pdf\" . \"evince %s\")
  1974. to open PDFs with evince.
  1975. - Regular expression: Match links where the
  1976. filename matches the regexp. If you want to
  1977. use groups here, use shy groups.
  1978. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1979. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1980. to open *.html and *.xhtml with firefox.
  1981. - Regular expression which contains (non-shy) groups:
  1982. Match links where the whole link, including \"::\", and
  1983. anything after that, matches the regexp.
  1984. In a custom command string, %1, %2, etc. are replaced with
  1985. the parts of the link that were matched by the groups.
  1986. For backwards compatibility, if a command string is given
  1987. that does not use any of the group matches, this case is
  1988. handled identically to the second one (i.e. match against
  1989. file name only).
  1990. In a custom function, you can access the group matches with
  1991. (match-string n link).
  1992. Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
  1993. \"evince -p %1 %s\")
  1994. to open [[file:document.pdf::5]] with evince at page 5.
  1995. `directory' Matches a directory
  1996. `remote' Matches a remote file, accessible through tramp or efs.
  1997. Remote files most likely should be visited through Emacs
  1998. because external applications cannot handle such paths.
  1999. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  2000. so all files Emacs knows how to handle. Using this with
  2001. command `emacs' will open most files in Emacs. Beware that this
  2002. will also open html files inside Emacs, unless you add
  2003. (\"html\" . default) to the list as well.
  2004. `system' The system command to open files, like `open' on Windows
  2005. and macOS, and mailcap under GNU/Linux. This is the command
  2006. that will be selected if you call `org-open-at-point' with a
  2007. double prefix argument (`\\[universal-argument] \
  2008. \\[universal-argument] \\[org-open-at-point]').
  2009. t Default for files not matched by any of the other options.
  2010. Possible values for the command are:
  2011. `emacs' The file will be visited by the current Emacs process.
  2012. `default' Use the default application for this file type, which is the
  2013. association for t in the list, most likely in the system-specific
  2014. part. This can be used to overrule an unwanted setting in the
  2015. system-specific variable.
  2016. `system' Use the system command for opening files, like \"open\".
  2017. This command is specified by the entry whose car is `system'.
  2018. Most likely, the system-specific version of this variable
  2019. does define this command, but you can overrule/replace it
  2020. here.
  2021. `mailcap' Use command specified in the mailcaps.
  2022. string A command to be executed by a shell; %s will be replaced
  2023. by the path to the file.
  2024. function A Lisp function, which will be called with two arguments:
  2025. the file path and the original link string, without the
  2026. \"file:\" prefix.
  2027. For more examples, see the system specific constants
  2028. `org-file-apps-defaults-macosx'
  2029. `org-file-apps-defaults-windowsnt'
  2030. `org-file-apps-defaults-gnu'."
  2031. :group 'org-link-follow
  2032. :type '(repeat
  2033. (cons (choice :value ""
  2034. (string :tag "Extension")
  2035. (const :tag "System command to open files" system)
  2036. (const :tag "Default for unrecognized files" t)
  2037. (const :tag "Remote file" remote)
  2038. (const :tag "Links to a directory" directory)
  2039. (const :tag "Any files that have Emacs modes"
  2040. auto-mode))
  2041. (choice :value ""
  2042. (const :tag "Visit with Emacs" emacs)
  2043. (const :tag "Use default" default)
  2044. (const :tag "Use the system command" system)
  2045. (string :tag "Command")
  2046. (function :tag "Function")))))
  2047. (defcustom org-doi-server-url "http://dx.doi.org/"
  2048. "The URL of the DOI server."
  2049. :type 'string
  2050. :version "24.3"
  2051. :group 'org-link-follow)
  2052. (defgroup org-refile nil
  2053. "Options concerning refiling entries in Org mode."
  2054. :tag "Org Refile"
  2055. :group 'org)
  2056. (defcustom org-directory "~/org"
  2057. "Directory with Org files.
  2058. This is just a default location to look for Org files. There is no need
  2059. at all to put your files into this directory. It is used in the
  2060. following situations:
  2061. 1. When a capture template specifies a target file that is not an
  2062. absolute path. The path will then be interpreted relative to
  2063. `org-directory'
  2064. 2. When the value of variable `org-agenda-files' is a single file, any
  2065. relative paths in this file will be taken as relative to
  2066. `org-directory'."
  2067. :group 'org-refile
  2068. :group 'org-capture
  2069. :type 'directory)
  2070. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  2071. "Default target for storing notes.
  2072. Used as a fall back file for org-capture.el, for templates that
  2073. do not specify a target file."
  2074. :group 'org-refile
  2075. :group 'org-capture
  2076. :type 'file)
  2077. (defcustom org-goto-interface 'outline
  2078. "The default interface to be used for `org-goto'.
  2079. Allowed values are:
  2080. outline The interface shows an outline of the relevant file
  2081. and the correct heading is found by moving through
  2082. the outline or by searching with incremental search.
  2083. outline-path-completion Headlines in the current buffer are offered via
  2084. completion. This is the interface also used by
  2085. the refile command."
  2086. :group 'org-refile
  2087. :type '(choice
  2088. (const :tag "Outline" outline)
  2089. (const :tag "Outline-path-completion" outline-path-completion)))
  2090. (defcustom org-goto-max-level 5
  2091. "Maximum target level when running `org-goto' with refile interface."
  2092. :group 'org-refile
  2093. :type 'integer)
  2094. (defcustom org-reverse-note-order nil
  2095. "Non-nil means store new notes at the beginning of a file or entry.
  2096. When nil, new notes will be filed to the end of a file or entry.
  2097. This can also be a list with cons cells of regular expressions that
  2098. are matched against file names, and values."
  2099. :group 'org-capture
  2100. :group 'org-refile
  2101. :type '(choice
  2102. (const :tag "Reverse always" t)
  2103. (const :tag "Reverse never" nil)
  2104. (repeat :tag "By file name regexp"
  2105. (cons regexp boolean))))
  2106. (defcustom org-log-refile nil
  2107. "Information to record when a task is refiled.
  2108. Possible values are:
  2109. nil Don't add anything
  2110. time Add a time stamp to the task
  2111. note Prompt for a note and add it with template `org-log-note-headings'
  2112. This option can also be set with on a per-file-basis with
  2113. #+STARTUP: nologrefile
  2114. #+STARTUP: logrefile
  2115. #+STARTUP: lognoterefile
  2116. You can have local logging settings for a subtree by setting the LOGGING
  2117. property to one or more of these keywords.
  2118. When bulk-refiling from the agenda, the value `note' is forbidden and
  2119. will temporarily be changed to `time'."
  2120. :group 'org-refile
  2121. :group 'org-progress
  2122. :version "24.1"
  2123. :type '(choice
  2124. (const :tag "No logging" nil)
  2125. (const :tag "Record timestamp" time)
  2126. (const :tag "Record timestamp with note." note)))
  2127. (defcustom org-refile-targets nil
  2128. "Targets for refiling entries with `\\[org-refile]'.
  2129. This is a list of cons cells. Each cell contains:
  2130. - a specification of the files to be considered, either a list of files,
  2131. or a symbol whose function or variable value will be used to retrieve
  2132. a file name or a list of file names. If you use `org-agenda-files' for
  2133. that, all agenda files will be scanned for targets. Nil means consider
  2134. headings in the current buffer.
  2135. - A specification of how to find candidate refile targets. This may be
  2136. any of:
  2137. - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
  2138. This tag has to be present in all target headlines, inheritance will
  2139. not be considered.
  2140. - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
  2141. todo keyword.
  2142. - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
  2143. headlines that are refiling targets.
  2144. - a cons cell (:level . N). Any headline of level N is considered a target.
  2145. Note that, when `org-odd-levels-only' is set, level corresponds to
  2146. order in hierarchy, not to the number of stars.
  2147. - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
  2148. Note that, when `org-odd-levels-only' is set, level corresponds to
  2149. order in hierarchy, not to the number of stars.
  2150. Each element of this list generates a set of possible targets.
  2151. The union of these sets is presented (with completion) to
  2152. the user by `org-refile'.
  2153. You can set the variable `org-refile-target-verify-function' to a function
  2154. to verify each headline found by the simple criteria above.
  2155. When this variable is nil, all top-level headlines in the current buffer
  2156. are used, equivalent to the value `((nil . (:level . 1))'."
  2157. :group 'org-refile
  2158. :type '(repeat
  2159. (cons
  2160. (choice :value org-agenda-files
  2161. (const :tag "All agenda files" org-agenda-files)
  2162. (const :tag "Current buffer" nil)
  2163. (function) (variable) (file))
  2164. (choice :tag "Identify target headline by"
  2165. (cons :tag "Specific tag" (const :value :tag) (string))
  2166. (cons :tag "TODO keyword" (const :value :todo) (string))
  2167. (cons :tag "Regular expression" (const :value :regexp) (regexp))
  2168. (cons :tag "Level number" (const :value :level) (integer))
  2169. (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
  2170. (defcustom org-refile-target-verify-function nil
  2171. "Function to verify if the headline at point should be a refile target.
  2172. The function will be called without arguments, with point at the
  2173. beginning of the headline. It should return t and leave point
  2174. where it is if the headline is a valid target for refiling.
  2175. If the target should not be selected, the function must return nil.
  2176. In addition to this, it may move point to a place from where the search
  2177. should be continued. For example, the function may decide that the entire
  2178. subtree of the current entry should be excluded and move point to the end
  2179. of the subtree."
  2180. :group 'org-refile
  2181. :type '(choice
  2182. (const nil)
  2183. (function)))
  2184. (defcustom org-refile-use-cache nil
  2185. "Non-nil means cache refile targets to speed up the process.
  2186. \\<org-mode-map>\
  2187. The cache for a particular file will be updated automatically when
  2188. the buffer has been killed, or when any of the marker used for flagging
  2189. refile targets no longer points at a live buffer.
  2190. If you have added new entries to a buffer that might themselves be targets,
  2191. you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
  2192. if you find that easier, \
  2193. `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
  2194. \\[org-refile]'."
  2195. :group 'org-refile
  2196. :version "24.1"
  2197. :type 'boolean)
  2198. (defcustom org-refile-use-outline-path nil
  2199. "Non-nil means provide refile targets as paths.
  2200. So a level 3 headline will be available as level1/level2/level3.
  2201. When the value is `file', also include the file name (without directory)
  2202. into the path. In this case, you can also stop the completion after
  2203. the file name, to get entries inserted as top level in the file.
  2204. When `full-file-path', include the full file path."
  2205. :group 'org-refile
  2206. :type '(choice
  2207. (const :tag "Not" nil)
  2208. (const :tag "Yes" t)
  2209. (const :tag "Start with file name" file)
  2210. (const :tag "Start with full file path" full-file-path)))
  2211. (defcustom org-outline-path-complete-in-steps t
  2212. "Non-nil means complete the outline path in hierarchical steps.
  2213. When Org uses the refile interface to select an outline path (see
  2214. `org-refile-use-outline-path'), the completion of the path can be
  2215. done in a single go, or it can be done in steps down the headline
  2216. hierarchy. Going in steps is probably the best if you do not use
  2217. a special completion package like `ido' or `icicles'. However,
  2218. when using these packages, going in one step can be very fast,
  2219. while still showing the whole path to the entry."
  2220. :group 'org-refile
  2221. :type 'boolean)
  2222. (defcustom org-refile-allow-creating-parent-nodes nil
  2223. "Non-nil means allow the creation of new nodes as refile targets.
  2224. New nodes are then created by adding \"/new node name\" to the completion
  2225. of an existing node. When the value of this variable is `confirm',
  2226. new node creation must be confirmed by the user (recommended).
  2227. When nil, the completion must match an existing entry.
  2228. Note that, if the new heading is not seen by the criteria
  2229. listed in `org-refile-targets', multiple instances of the same
  2230. heading would be created by trying again to file under the new
  2231. heading."
  2232. :group 'org-refile
  2233. :type '(choice
  2234. (const :tag "Never" nil)
  2235. (const :tag "Always" t)
  2236. (const :tag "Prompt for confirmation" confirm)))
  2237. (defcustom org-refile-active-region-within-subtree nil
  2238. "Non-nil means also refile active region within a subtree.
  2239. By default `org-refile' doesn't allow refiling regions if they
  2240. don't contain a set of subtrees, but it might be convenient to
  2241. do so sometimes: in that case, the first line of the region is
  2242. converted to a headline before refiling."
  2243. :group 'org-refile
  2244. :version "24.1"
  2245. :type 'boolean)
  2246. (defgroup org-todo nil
  2247. "Options concerning TODO items in Org mode."
  2248. :tag "Org TODO"
  2249. :group 'org)
  2250. (defgroup org-progress nil
  2251. "Options concerning Progress logging in Org mode."
  2252. :tag "Org Progress"
  2253. :group 'org-time)
  2254. (defvar org-todo-interpretation-widgets
  2255. '((:tag "Sequence (cycling hits every state)" sequence)
  2256. (:tag "Type (cycling directly to DONE)" type))
  2257. "The available interpretation symbols for customizing `org-todo-keywords'.
  2258. Interested libraries should add to this list.")
  2259. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  2260. "List of TODO entry keyword sequences and their interpretation.
  2261. \\<org-mode-map>This is a list of sequences.
  2262. Each sequence starts with a symbol, either `sequence' or `type',
  2263. indicating if the keywords should be interpreted as a sequence of
  2264. action steps, or as different types of TODO items. The first
  2265. keywords are states requiring action - these states will select a headline
  2266. for inclusion into the global TODO list Org produces. If one of the
  2267. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  2268. signify that no further action is necessary. If \"|\" is not found,
  2269. the last keyword is treated as the only DONE state of the sequence.
  2270. The command `\\[org-todo]' cycles an entry through these states, and one
  2271. additional state where no keyword is present. For details about this
  2272. cycling, see the manual.
  2273. TODO keywords and interpretation can also be set on a per-file basis with
  2274. the special #+SEQ_TODO and #+TYP_TODO lines.
  2275. Each keyword can optionally specify a character for fast state selection
  2276. \(in combination with the variable `org-use-fast-todo-selection')
  2277. and specifiers for state change logging, using the same syntax that
  2278. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  2279. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  2280. indicates to record a time stamp each time this state is selected.
  2281. Each keyword may also specify if a timestamp or a note should be
  2282. recorded when entering or leaving the state, by adding additional
  2283. characters in the parenthesis after the keyword. This looks like this:
  2284. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  2285. record only the time of the state change. With X and Y being either
  2286. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  2287. Y when leaving the state if and only if the *target* state does not
  2288. define X. You may omit any of the fast-selection key or X or /Y,
  2289. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  2290. For backward compatibility, this variable may also be just a list
  2291. of keywords. In this case the interpretation (sequence or type) will be
  2292. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  2293. :group 'org-todo
  2294. :group 'org-keywords
  2295. :type '(choice
  2296. (repeat :tag "Old syntax, just keywords"
  2297. (string :tag "Keyword"))
  2298. (repeat :tag "New syntax"
  2299. (cons
  2300. (choice
  2301. :tag "Interpretation"
  2302. ;;Quick and dirty way to see
  2303. ;;`org-todo-interpretations'. This takes the
  2304. ;;place of item arguments
  2305. :convert-widget
  2306. (lambda (widget)
  2307. (widget-put widget
  2308. :args (mapcar
  2309. (lambda (x)
  2310. (widget-convert
  2311. (cons 'const x)))
  2312. org-todo-interpretation-widgets))
  2313. widget))
  2314. (repeat
  2315. (string :tag "Keyword"))))))
  2316. (defvar-local org-todo-keywords-1 nil
  2317. "All TODO and DONE keywords active in a buffer.")
  2318. (defvar org-todo-keywords-for-agenda nil)
  2319. (defvar org-done-keywords-for-agenda nil)
  2320. (defvar org-todo-keyword-alist-for-agenda nil)
  2321. (defvar org-tag-alist-for-agenda nil
  2322. "Alist of all tags from all agenda files.")
  2323. (defvar org-tag-groups-alist-for-agenda nil
  2324. "Alist of all groups tags from all current agenda files.")
  2325. (defvar-local org-tag-groups-alist nil)
  2326. (defvar org-agenda-contributing-files nil)
  2327. (defvar-local org-current-tag-alist nil
  2328. "Alist of all tag groups in current buffer.
  2329. This variable takes into consideration `org-tag-alist',
  2330. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  2331. (defvar-local org-not-done-keywords nil)
  2332. (defvar-local org-done-keywords nil)
  2333. (defvar-local org-todo-heads nil)
  2334. (defvar-local org-todo-sets nil)
  2335. (defvar-local org-todo-log-states nil)
  2336. (defvar-local org-todo-kwd-alist nil)
  2337. (defvar-local org-todo-key-alist nil)
  2338. (defvar-local org-todo-key-trigger nil)
  2339. (defcustom org-todo-interpretation 'sequence
  2340. "Controls how TODO keywords are interpreted.
  2341. This variable is in principle obsolete and is only used for
  2342. backward compatibility, if the interpretation of todo keywords is
  2343. not given already in `org-todo-keywords'. See that variable for
  2344. more information."
  2345. :group 'org-todo
  2346. :group 'org-keywords
  2347. :type '(choice (const sequence)
  2348. (const type)))
  2349. (defcustom org-use-fast-todo-selection t
  2350. "\\<org-mode-map>\
  2351. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  2352. This variable describes if and under what circumstances the cycling
  2353. mechanism for TODO keywords will be replaced by a single-key, direct
  2354. selection scheme.
  2355. When nil, fast selection is never used.
  2356. When the symbol `prefix', it will be used when `org-todo' is called
  2357. with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
  2358. in an Org buffer, and
  2359. `\\[universal-argument] t' in an agenda buffer.
  2360. When t, fast selection is used by default. In this case, the prefix
  2361. argument forces cycling instead.
  2362. In all cases, the special interface is only used if access keys have
  2363. actually been assigned by the user, i.e. if keywords in the configuration
  2364. are followed by a letter in parenthesis, like TODO(t)."
  2365. :group 'org-todo
  2366. :type '(choice
  2367. (const :tag "Never" nil)
  2368. (const :tag "By default" t)
  2369. (const :tag "Only with C-u C-c C-t" prefix)))
  2370. (defcustom org-provide-todo-statistics t
  2371. "Non-nil means update todo statistics after insert and toggle.
  2372. ALL-HEADLINES means update todo statistics by including headlines
  2373. with no TODO keyword as well, counting them as not done.
  2374. A list of TODO keywords means the same, but skip keywords that are
  2375. not in this list.
  2376. When set to a list of two lists, the first list contains keywords
  2377. to consider as TODO keywords, the second list contains keywords
  2378. to consider as DONE keywords.
  2379. When this is set, todo statistics is updated in the parent of the
  2380. current entry each time a todo state is changed."
  2381. :group 'org-todo
  2382. :type '(choice
  2383. (const :tag "Yes, only for TODO entries" t)
  2384. (const :tag "Yes, including all entries" all-headlines)
  2385. (repeat :tag "Yes, for TODOs in this list"
  2386. (string :tag "TODO keyword"))
  2387. (list :tag "Yes, for TODOs and DONEs in these lists"
  2388. (repeat (string :tag "TODO keyword"))
  2389. (repeat (string :tag "DONE keyword")))
  2390. (other :tag "No TODO statistics" nil)))
  2391. (defcustom org-hierarchical-todo-statistics t
  2392. "Non-nil means TODO statistics covers just direct children.
  2393. When nil, all entries in the subtree are considered.
  2394. This has only an effect if `org-provide-todo-statistics' is set.
  2395. To set this to nil for only a single subtree, use a COOKIE_DATA
  2396. property and include the word \"recursive\" into the value."
  2397. :group 'org-todo
  2398. :type 'boolean)
  2399. (defcustom org-after-todo-state-change-hook nil
  2400. "Hook which is run after the state of a TODO item was changed.
  2401. The new state (a string with a TODO keyword, or nil) is available in the
  2402. Lisp variable `org-state'."
  2403. :group 'org-todo
  2404. :type 'hook)
  2405. (defvar org-blocker-hook nil
  2406. "Hook for functions that are allowed to block a state change.
  2407. Functions in this hook should not modify the buffer.
  2408. Each function gets as its single argument a property list,
  2409. see `org-trigger-hook' for more information about this list.
  2410. If any of the functions in this hook returns nil, the state change
  2411. is blocked.")
  2412. (defvar org-trigger-hook nil
  2413. "Hook for functions that are triggered by a state change.
  2414. Each function gets as its single argument a property list with at
  2415. least the following elements:
  2416. (:type type-of-change :position pos-at-entry-start
  2417. :from old-state :to new-state)
  2418. Depending on the type, more properties may be present.
  2419. This mechanism is currently implemented for:
  2420. TODO state changes
  2421. ------------------
  2422. :type todo-state-change
  2423. :from previous state (keyword as a string), or nil, or a symbol
  2424. `todo' or `done', to indicate the general type of state.
  2425. :to new state, like in :from")
  2426. (defcustom org-enforce-todo-dependencies nil
  2427. "Non-nil means undone TODO entries will block switching the parent to DONE.
  2428. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  2429. be blocked if any prior sibling is not yet done.
  2430. Finally, if the parent is blocked because of ordered siblings of its own,
  2431. the child will also be blocked."
  2432. :set (lambda (var val)
  2433. (set var val)
  2434. (if val
  2435. (add-hook 'org-blocker-hook
  2436. 'org-block-todo-from-children-or-siblings-or-parent)
  2437. (remove-hook 'org-blocker-hook
  2438. 'org-block-todo-from-children-or-siblings-or-parent)))
  2439. :group 'org-todo
  2440. :type 'boolean)
  2441. (defcustom org-enforce-todo-checkbox-dependencies nil
  2442. "Non-nil means unchecked boxes will block switching the parent to DONE.
  2443. When this is nil, checkboxes have no influence on switching TODO states.
  2444. When non-nil, you first need to check off all check boxes before the TODO
  2445. entry can be switched to DONE.
  2446. This variable needs to be set before org.el is loaded, and you need to
  2447. restart Emacs after a change to make the change effective. The only way
  2448. to change is while Emacs is running is through the customize interface."
  2449. :set (lambda (var val)
  2450. (set var val)
  2451. (if val
  2452. (add-hook 'org-blocker-hook
  2453. 'org-block-todo-from-checkboxes)
  2454. (remove-hook 'org-blocker-hook
  2455. 'org-block-todo-from-checkboxes)))
  2456. :group 'org-todo
  2457. :type 'boolean)
  2458. (defcustom org-treat-insert-todo-heading-as-state-change nil
  2459. "Non-nil means inserting a TODO heading is treated as state change.
  2460. So when the command `\\[org-insert-todo-heading]' is used, state change
  2461. logging will apply if appropriate. When nil, the new TODO item will
  2462. be inserted directly, and no logging will take place."
  2463. :group 'org-todo
  2464. :type 'boolean)
  2465. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  2466. "Non-nil means switching TODO states with S-cursor counts as state change.
  2467. This is the default behavior. However, setting this to nil allows a
  2468. convenient way to select a TODO state and bypass any logging associated
  2469. with that."
  2470. :group 'org-todo
  2471. :type 'boolean)
  2472. (defcustom org-todo-state-tags-triggers nil
  2473. "Tag changes that should be triggered by TODO state changes.
  2474. This is a list. Each entry is
  2475. (state-change (tag . flag) .......)
  2476. State-change can be a string with a state, and empty string to indicate the
  2477. state that has no TODO keyword, or it can be one of the symbols `todo'
  2478. or `done', meaning any not-done or done state, respectively."
  2479. :group 'org-todo
  2480. :group 'org-tags
  2481. :type '(repeat
  2482. (cons (choice :tag "When changing to"
  2483. (const :tag "Not-done state" todo)
  2484. (const :tag "Done state" done)
  2485. (string :tag "State"))
  2486. (repeat
  2487. (cons :tag "Tag action"
  2488. (string :tag "Tag")
  2489. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  2490. (defcustom org-log-done nil
  2491. "Information to record when a task moves to the DONE state.
  2492. Possible values are:
  2493. nil Don't add anything, just change the keyword
  2494. time Add a time stamp to the task
  2495. note Prompt for a note and add it with template `org-log-note-headings'
  2496. This option can also be set with on a per-file-basis with
  2497. #+STARTUP: nologdone
  2498. #+STARTUP: logdone
  2499. #+STARTUP: lognotedone
  2500. You can have local logging settings for a subtree by setting the LOGGING
  2501. property to one or more of these keywords."
  2502. :group 'org-todo
  2503. :group 'org-progress
  2504. :type '(choice
  2505. (const :tag "No logging" nil)
  2506. (const :tag "Record CLOSED timestamp" time)
  2507. (const :tag "Record CLOSED timestamp with note." note)))
  2508. ;; Normalize old uses of org-log-done.
  2509. (cond
  2510. ((eq org-log-done t) (setq org-log-done 'time))
  2511. ((and (listp org-log-done) (memq 'done org-log-done))
  2512. (setq org-log-done 'note)))
  2513. (defcustom org-log-reschedule nil
  2514. "Information to record when the scheduling date of a tasks is modified.
  2515. Possible values are:
  2516. nil Don't add anything, just change the date
  2517. time Add a time stamp to the task
  2518. note Prompt for a note and add it with template `org-log-note-headings'
  2519. This option can also be set with on a per-file-basis with
  2520. #+STARTUP: nologreschedule
  2521. #+STARTUP: logreschedule
  2522. #+STARTUP: lognotereschedule"
  2523. :group 'org-todo
  2524. :group 'org-progress
  2525. :type '(choice
  2526. (const :tag "No logging" nil)
  2527. (const :tag "Record timestamp" time)
  2528. (const :tag "Record timestamp with note." note)))
  2529. (defcustom org-log-redeadline nil
  2530. "Information to record when the deadline date of a tasks is modified.
  2531. Possible values are:
  2532. nil Don't add anything, just change the date
  2533. time Add a time stamp to the task
  2534. note Prompt for a note and add it with template `org-log-note-headings'
  2535. This option can also be set with on a per-file-basis with
  2536. #+STARTUP: nologredeadline
  2537. #+STARTUP: logredeadline
  2538. #+STARTUP: lognoteredeadline
  2539. You can have local logging settings for a subtree by setting the LOGGING
  2540. property to one or more of these keywords."
  2541. :group 'org-todo
  2542. :group 'org-progress
  2543. :type '(choice
  2544. (const :tag "No logging" nil)
  2545. (const :tag "Record timestamp" time)
  2546. (const :tag "Record timestamp with note." note)))
  2547. (defcustom org-log-note-clock-out nil
  2548. "Non-nil means record a note when clocking out of an item.
  2549. This can also be configured on a per-file basis by adding one of
  2550. the following lines anywhere in the buffer:
  2551. #+STARTUP: lognoteclock-out
  2552. #+STARTUP: nolognoteclock-out"
  2553. :group 'org-todo
  2554. :group 'org-progress
  2555. :type 'boolean)
  2556. (defcustom org-log-done-with-time t
  2557. "Non-nil means the CLOSED time stamp will contain date and time.
  2558. When nil, only the date will be recorded."
  2559. :group 'org-progress
  2560. :type 'boolean)
  2561. (defcustom org-log-note-headings
  2562. '((done . "CLOSING NOTE %t")
  2563. (state . "State %-12s from %-12S %t")
  2564. (note . "Note taken on %t")
  2565. (reschedule . "Rescheduled from %S on %t")
  2566. (delschedule . "Not scheduled, was %S on %t")
  2567. (redeadline . "New deadline from %S on %t")
  2568. (deldeadline . "Removed deadline, was %S on %t")
  2569. (refile . "Refiled on %t")
  2570. (clock-out . ""))
  2571. "Headings for notes added to entries.
  2572. The value is an alist, with the car being a symbol indicating the
  2573. note context, and the cdr is the heading to be used. The heading
  2574. may also be the empty string. The following placeholders can be
  2575. used:
  2576. %t a time stamp.
  2577. %T an active time stamp instead the default inactive one
  2578. %d a short-format time stamp.
  2579. %D an active short-format time stamp.
  2580. %s the new TODO state or time stamp (inactive), in double quotes.
  2581. %S the old TODO state or time stamp (inactive), in double quotes.
  2582. %u the user name.
  2583. %U full user name.
  2584. In fact, it is not a good idea to change the `state' entry,
  2585. because Agenda Log mode depends on the format of these entries."
  2586. :group 'org-todo
  2587. :group 'org-progress
  2588. :type '(list :greedy t
  2589. (cons (const :tag "Heading when closing an item" done) string)
  2590. (cons (const :tag
  2591. "Heading when changing todo state (todo sequence only)"
  2592. state) string)
  2593. (cons (const :tag "Heading when just taking a note" note) string)
  2594. (cons (const :tag "Heading when rescheduling" reschedule) string)
  2595. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  2596. (cons (const :tag "Heading when changing deadline" redeadline) string)
  2597. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  2598. (cons (const :tag "Heading when refiling" refile) string)
  2599. (cons (const :tag "Heading when clocking out" clock-out) string)))
  2600. (unless (assq 'note org-log-note-headings)
  2601. (push '(note . "%t") org-log-note-headings))
  2602. (defcustom org-log-into-drawer nil
  2603. "Non-nil means insert state change notes and time stamps into a drawer.
  2604. When nil, state changes notes will be inserted after the headline and
  2605. any scheduling and clock lines, but not inside a drawer.
  2606. The value of this variable should be the name of the drawer to use.
  2607. LOGBOOK is proposed as the default drawer for this purpose, you can
  2608. also set this to a string to define the drawer of your choice.
  2609. A value of t is also allowed, representing \"LOGBOOK\".
  2610. A value of t or nil can also be set with on a per-file-basis with
  2611. #+STARTUP: logdrawer
  2612. #+STARTUP: nologdrawer
  2613. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2614. will be ignored.
  2615. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2616. a subtree.
  2617. Do not check directly this variable in a Lisp program. Call
  2618. function `org-log-into-drawer' instead."
  2619. :group 'org-todo
  2620. :group 'org-progress
  2621. :type '(choice
  2622. (const :tag "Not into a drawer" nil)
  2623. (const :tag "LOGBOOK" t)
  2624. (string :tag "Other")))
  2625. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2626. (defun org-log-into-drawer ()
  2627. "Name of the log drawer, as a string, or nil.
  2628. This is the value of `org-log-into-drawer'. However, if the
  2629. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2630. be used instead of the default value."
  2631. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2632. (cond ((equal p "nil") nil)
  2633. ((equal p "t") "LOGBOOK")
  2634. ((stringp p) p)
  2635. (p "LOGBOOK")
  2636. ((stringp org-log-into-drawer) org-log-into-drawer)
  2637. (org-log-into-drawer "LOGBOOK"))))
  2638. (defcustom org-log-state-notes-insert-after-drawers nil
  2639. "Non-nil means insert state change notes after any drawers in entry.
  2640. Only the drawers that *immediately* follow the headline and the
  2641. deadline/scheduled line are skipped.
  2642. When nil, insert notes right after the heading and perhaps the line
  2643. with deadline/scheduling if present.
  2644. This variable will have no effect if `org-log-into-drawer' is
  2645. set."
  2646. :group 'org-todo
  2647. :group 'org-progress
  2648. :type 'boolean)
  2649. (defcustom org-log-states-order-reversed t
  2650. "Non-nil means the latest state note will be directly after heading.
  2651. When nil, the state change notes will be ordered according to time.
  2652. This option can also be set with on a per-file-basis with
  2653. #+STARTUP: logstatesreversed
  2654. #+STARTUP: nologstatesreversed"
  2655. :group 'org-todo
  2656. :group 'org-progress
  2657. :type 'boolean)
  2658. (defcustom org-todo-repeat-to-state nil
  2659. "The TODO state to which a repeater should return the repeating task.
  2660. By default this is the first task in a TODO sequence, or the previous state
  2661. in a TODO_TYP set. But you can specify another task here.
  2662. alternatively, set the :REPEAT_TO_STATE: property of the entry."
  2663. :group 'org-todo
  2664. :version "24.1"
  2665. :type '(choice (const :tag "Head of sequence" nil)
  2666. (string :tag "Specific state")))
  2667. (defcustom org-log-repeat 'time
  2668. "Non-nil means record moving through the DONE state when triggering repeat.
  2669. An auto-repeating task is immediately switched back to TODO when
  2670. marked DONE. If you are not logging state changes (by adding \"@\"
  2671. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2672. record a closing note, there will be no record of the task moving
  2673. through DONE. This variable forces taking a note anyway.
  2674. nil Don't force a record
  2675. time Record a time stamp
  2676. note Prompt for a note and add it with template `org-log-note-headings'
  2677. This option can also be set with on a per-file-basis with
  2678. #+STARTUP: nologrepeat
  2679. #+STARTUP: logrepeat
  2680. #+STARTUP: lognoterepeat
  2681. You can have local logging settings for a subtree by setting the LOGGING
  2682. property to one or more of these keywords."
  2683. :group 'org-todo
  2684. :group 'org-progress
  2685. :type '(choice
  2686. (const :tag "Don't force a record" nil)
  2687. (const :tag "Force recording the DONE state" time)
  2688. (const :tag "Force recording a note with the DONE state" note)))
  2689. (defgroup org-priorities nil
  2690. "Priorities in Org mode."
  2691. :tag "Org Priorities"
  2692. :group 'org-todo)
  2693. (defcustom org-enable-priority-commands t
  2694. "Non-nil means priority commands are active.
  2695. When nil, these commands will be disabled, so that you never accidentally
  2696. set a priority."
  2697. :group 'org-priorities
  2698. :type 'boolean)
  2699. (defcustom org-highest-priority ?A
  2700. "The highest priority of TODO items. A character like ?A, ?B etc.
  2701. Must have a smaller ASCII number than `org-lowest-priority'."
  2702. :group 'org-priorities
  2703. :type 'character)
  2704. (defcustom org-lowest-priority ?C
  2705. "The lowest priority of TODO items. A character like ?A, ?B etc.
  2706. Must have a larger ASCII number than `org-highest-priority'."
  2707. :group 'org-priorities
  2708. :type 'character)
  2709. (defcustom org-default-priority ?B
  2710. "The default priority of TODO items.
  2711. This is the priority an item gets if no explicit priority is given.
  2712. When starting to cycle on an empty priority the first step in the cycle
  2713. depends on `org-priority-start-cycle-with-default'. The resulting first
  2714. step priority must not exceed the range from `org-highest-priority' to
  2715. `org-lowest-priority' which means that `org-default-priority' has to be
  2716. in this range exclusive or inclusive the range boundaries. Else the
  2717. first step refuses to set the default and the second will fall back
  2718. to (depending on the command used) the highest or lowest priority."
  2719. :group 'org-priorities
  2720. :type 'character)
  2721. (defcustom org-priority-start-cycle-with-default t
  2722. "Non-nil means start with default priority when starting to cycle.
  2723. When this is nil, the first step in the cycle will be (depending on the
  2724. command used) one higher or lower than the default priority.
  2725. See also `org-default-priority'."
  2726. :group 'org-priorities
  2727. :type 'boolean)
  2728. (defcustom org-get-priority-function nil
  2729. "Function to extract the priority from a string.
  2730. The string is normally the headline. If this is nil Org computes the
  2731. priority from the priority cookie like [#A] in the headline. It returns
  2732. an integer, increasing by 1000 for each priority level.
  2733. The user can set a different function here, which should take a string
  2734. as an argument and return the numeric priority."
  2735. :group 'org-priorities
  2736. :version "24.1"
  2737. :type '(choice
  2738. (const nil)
  2739. (function)))
  2740. (defgroup org-time nil
  2741. "Options concerning time stamps and deadlines in Org mode."
  2742. :tag "Org Time"
  2743. :group 'org)
  2744. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2745. "Number of minutes to round time stamps to.
  2746. \\<org-mode-map>\
  2747. These are two values, the first applies when first creating a time stamp.
  2748. The second applies when changing it with the commands `S-up' and `S-down'.
  2749. When changing the time stamp, this means that it will change in steps
  2750. of N minutes, as given by the second value.
  2751. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2752. numbers should be factors of 60, so for example 5, 10, 15.
  2753. When this is larger than 1, you can still force an exact time stamp by using
  2754. a double prefix argument to a time stamp command like \
  2755. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2756. and by using a prefix arg to `S-up/down' to specify the exact number
  2757. of minutes to shift."
  2758. :group 'org-time
  2759. :get (lambda (var) ; Make sure both elements are there
  2760. (if (integerp (default-value var))
  2761. (list (default-value var) 5)
  2762. (default-value var)))
  2763. :type '(list
  2764. (integer :tag "when inserting times")
  2765. (integer :tag "when modifying times")))
  2766. ;; Normalize old customizations of this variable.
  2767. (when (integerp org-time-stamp-rounding-minutes)
  2768. (setq org-time-stamp-rounding-minutes
  2769. (list org-time-stamp-rounding-minutes
  2770. org-time-stamp-rounding-minutes)))
  2771. (defcustom org-display-custom-times nil
  2772. "Non-nil means overlay custom formats over all time stamps.
  2773. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2774. To turn this on on a per-file basis, insert anywhere in the file:
  2775. #+STARTUP: customtime"
  2776. :group 'org-time
  2777. :set 'set-default
  2778. :type 'sexp)
  2779. (make-variable-buffer-local 'org-display-custom-times)
  2780. (defcustom org-time-stamp-custom-formats
  2781. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2782. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2783. These are overlaid over the default ISO format if the variable
  2784. `org-display-custom-times' is set. Time like %H:%M should be at the
  2785. end of the second format. The custom formats are also honored by export
  2786. commands, if custom time display is turned on at the time of export."
  2787. :group 'org-time
  2788. :type 'sexp)
  2789. (defun org-time-stamp-format (&optional long inactive)
  2790. "Get the right format for a time string."
  2791. (let ((f (if long (cdr org-time-stamp-formats)
  2792. (car org-time-stamp-formats))))
  2793. (if inactive
  2794. (concat "[" (substring f 1 -1) "]")
  2795. f)))
  2796. (defcustom org-time-clocksum-format
  2797. '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
  2798. "The format string used when creating CLOCKSUM lines.
  2799. This is also used when Org mode generates a time duration.
  2800. The value can be a single format string containing two
  2801. %-sequences, which will be filled with the number of hours and
  2802. minutes in that order.
  2803. Alternatively, the value can be a plist associating any of the
  2804. keys :years, :months, :weeks, :days, :hours or :minutes with
  2805. format strings. The time duration is formatted using only the
  2806. time components that are needed and concatenating the results.
  2807. If a time unit in absent, it falls back to the next smallest
  2808. unit.
  2809. The keys :require-years, :require-months, :require-days,
  2810. :require-weeks, :require-hours, :require-minutes are also
  2811. meaningful. A non-nil value for these keys indicates that the
  2812. corresponding time component should always be included, even if
  2813. its value is 0.
  2814. For example,
  2815. (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
  2816. :require-minutes t)
  2817. means durations longer than a day will be expressed in days,
  2818. hours and minutes, and durations less than a day will always be
  2819. expressed in hours and minutes (even for durations less than an
  2820. hour).
  2821. The value
  2822. (:days \"%dd\" :minutes \"%dm\")
  2823. means durations longer than a day will be expressed in days and
  2824. minutes, and durations less than a day will be expressed entirely
  2825. in minutes (even for durations longer than an hour)."
  2826. :group 'org-time
  2827. :group 'org-clock
  2828. :version "24.4"
  2829. :package-version '(Org . "8.0")
  2830. :type '(choice (string :tag "Format string")
  2831. (set :tag "Plist"
  2832. (group :inline t (const :tag "Years" :years)
  2833. (string :tag "Format string"))
  2834. (group :inline t
  2835. (const :tag "Always show years" :require-years)
  2836. (const t))
  2837. (group :inline t (const :tag "Months" :months)
  2838. (string :tag "Format string"))
  2839. (group :inline t
  2840. (const :tag "Always show months" :require-months)
  2841. (const t))
  2842. (group :inline t (const :tag "Weeks" :weeks)
  2843. (string :tag "Format string"))
  2844. (group :inline t
  2845. (const :tag "Always show weeks" :require-weeks)
  2846. (const t))
  2847. (group :inline t (const :tag "Days" :days)
  2848. (string :tag "Format string"))
  2849. (group :inline t
  2850. (const :tag "Always show days" :require-days)
  2851. (const t))
  2852. (group :inline t (const :tag "Hours" :hours)
  2853. (string :tag "Format string"))
  2854. (group :inline t
  2855. (const :tag "Always show hours" :require-hours)
  2856. (const t))
  2857. (group :inline t (const :tag "Minutes" :minutes)
  2858. (string :tag "Format string"))
  2859. (group :inline t
  2860. (const :tag "Always show minutes" :require-minutes)
  2861. (const t)))))
  2862. (defcustom org-time-clocksum-use-fractional nil
  2863. "When non-nil, `\\[org-clock-display]' uses fractional times.
  2864. See `org-time-clocksum-format' for more on time clock formats."
  2865. :group 'org-time
  2866. :group 'org-clock
  2867. :version "24.3"
  2868. :type 'boolean)
  2869. (defcustom org-time-clocksum-use-effort-durations nil
  2870. "When non-nil, `\\[org-clock-display]' uses effort durations.
  2871. E.g. by default, one day is considered to be a 8 hours effort,
  2872. so a task that has been clocked for 16 hours will be displayed
  2873. as during 2 days in the clock display or in the clocktable.
  2874. See `org-effort-durations' on how to set effort durations
  2875. and `org-time-clocksum-format' for more on time clock formats."
  2876. :group 'org-time
  2877. :group 'org-clock
  2878. :version "24.4"
  2879. :package-version '(Org . "8.0")
  2880. :type 'boolean)
  2881. (defcustom org-time-clocksum-fractional-format "%.2f"
  2882. "The format string used when creating CLOCKSUM lines,
  2883. or when Org mode generates a time duration, if
  2884. `org-time-clocksum-use-fractional' is enabled.
  2885. The value can be a single format string containing one
  2886. %-sequence, which will be filled with the number of hours as
  2887. a float.
  2888. Alternatively, the value can be a plist associating any of the
  2889. keys :years, :months, :weeks, :days, :hours or :minutes with
  2890. a format string. The time duration is formatted using the
  2891. largest time unit which gives a non-zero integer part. If all
  2892. specified formats have zero integer part, the smallest time unit
  2893. is used."
  2894. :group 'org-time
  2895. :type '(choice (string :tag "Format string")
  2896. (set (group :inline t (const :tag "Years" :years)
  2897. (string :tag "Format string"))
  2898. (group :inline t (const :tag "Months" :months)
  2899. (string :tag "Format string"))
  2900. (group :inline t (const :tag "Weeks" :weeks)
  2901. (string :tag "Format string"))
  2902. (group :inline t (const :tag "Days" :days)
  2903. (string :tag "Format string"))
  2904. (group :inline t (const :tag "Hours" :hours)
  2905. (string :tag "Format string"))
  2906. (group :inline t (const :tag "Minutes" :minutes)
  2907. (string :tag "Format string")))))
  2908. (defcustom org-deadline-warning-days 14
  2909. "Number of days before expiration during which a deadline becomes active.
  2910. This variable governs the display in sparse trees and in the agenda.
  2911. When 0 or negative, it means use this number (the absolute value of it)
  2912. even if a deadline has a different individual lead time specified.
  2913. Custom commands can set this variable in the options section."
  2914. :group 'org-time
  2915. :group 'org-agenda-daily/weekly
  2916. :type 'integer)
  2917. (defcustom org-scheduled-delay-days 0
  2918. "Number of days before a scheduled item becomes active.
  2919. This variable governs the display in sparse trees and in the agenda.
  2920. The default value (i.e. 0) means: don't delay scheduled item.
  2921. When negative, it means use this number (the absolute value of it)
  2922. even if a scheduled item has a different individual delay time
  2923. specified.
  2924. Custom commands can set this variable in the options section."
  2925. :group 'org-time
  2926. :group 'org-agenda-daily/weekly
  2927. :version "24.4"
  2928. :package-version '(Org . "8.0")
  2929. :type 'integer)
  2930. (defcustom org-read-date-prefer-future t
  2931. "Non-nil means assume future for incomplete date input from user.
  2932. This affects the following situations:
  2933. 1. The user gives a month but not a year.
  2934. For example, if it is April and you enter \"feb 2\", this will be read
  2935. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2936. 2. The user gives a day, but no month.
  2937. For example, if today is the 15th, and you enter \"3\", Org will read
  2938. this as the third of *next* month. However, if you enter \"17\",
  2939. it will be considered as *this* month.
  2940. If you set this variable to the symbol `time', then also the following
  2941. will work:
  2942. 3. If the user gives a time.
  2943. If the time is before now, it will be interpreted as tomorrow.
  2944. Currently none of this works for ISO week specifications.
  2945. When this option is nil, the current day, month and year will always be
  2946. used as defaults.
  2947. See also `org-agenda-jump-prefer-future'."
  2948. :group 'org-time
  2949. :type '(choice
  2950. (const :tag "Never" nil)
  2951. (const :tag "Check month and day" t)
  2952. (const :tag "Check month, day, and time" time)))
  2953. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2954. "Should the agenda jump command prefer the future for incomplete dates?
  2955. The default is to do the same as configured in `org-read-date-prefer-future'.
  2956. But you can also set a deviating value here.
  2957. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2958. :group 'org-agenda
  2959. :group 'org-time
  2960. :version "24.1"
  2961. :type '(choice
  2962. (const :tag "Use org-read-date-prefer-future"
  2963. org-read-date-prefer-future)
  2964. (const :tag "Never" nil)
  2965. (const :tag "Always" t)))
  2966. (defcustom org-read-date-force-compatible-dates t
  2967. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2968. Depending on the system Emacs is running on, certain dates cannot
  2969. be represented with the type used internally to represent time.
  2970. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2971. correctly. Some systems allow for earlier dates, some for later,
  2972. some for both. One way to find out it to insert any date into an
  2973. Org buffer, putting the cursor on the year and hitting S-up and
  2974. S-down to test the range.
  2975. When this variable is set to t, the date/time prompt will not let
  2976. you specify dates outside the 1970-2037 range, so it is certain that
  2977. these dates will work in whatever version of Emacs you are
  2978. running, and also that you can move a file from one Emacs implementation
  2979. to another. WHenever Org is forcing the year for you, it will display
  2980. a message and beep.
  2981. When this variable is nil, Org will check if the date is
  2982. representable in the specific Emacs implementation you are using.
  2983. If not, it will force a year, usually the current year, and beep
  2984. to remind you. Currently this setting is not recommended because
  2985. the likelihood that you will open your Org files in an Emacs that
  2986. has limited date range is not negligible.
  2987. A workaround for this problem is to use diary sexp dates for time
  2988. stamps outside of this range."
  2989. :group 'org-time
  2990. :version "24.1"
  2991. :type 'boolean)
  2992. (defcustom org-read-date-display-live t
  2993. "Non-nil means display current interpretation of date prompt live.
  2994. This display will be in an overlay, in the minibuffer."
  2995. :group 'org-time
  2996. :type 'boolean)
  2997. (defcustom org-read-date-popup-calendar t
  2998. "Non-nil means pop up a calendar when prompting for a date.
  2999. In the calendar, the date can be selected with mouse-1. However, the
  3000. minibuffer will also be active, and you can simply enter the date as well.
  3001. When nil, only the minibuffer will be available."
  3002. :group 'org-time
  3003. :type 'boolean)
  3004. (defvaralias 'org-popup-calendar-for-date-prompt
  3005. 'org-read-date-popup-calendar)
  3006. (defcustom org-extend-today-until 0
  3007. "The hour when your day really ends. Must be an integer.
  3008. This has influence for the following applications:
  3009. - When switching the agenda to \"today\". It it is still earlier than
  3010. the time given here, the day recognized as TODAY is actually yesterday.
  3011. - When a date is read from the user and it is still before the time given
  3012. here, the current date and time will be assumed to be yesterday, 23:59.
  3013. Also, timestamps inserted in capture templates follow this rule.
  3014. IMPORTANT: This is a feature whose implementation is and likely will
  3015. remain incomplete. Really, it is only here because past midnight seems to
  3016. be the favorite working time of John Wiegley :-)"
  3017. :group 'org-time
  3018. :type 'integer)
  3019. (defcustom org-use-effective-time nil
  3020. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  3021. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  3022. \"effective time\" of any timestamps between midnight and 8am will be
  3023. 23:59 of the previous day."
  3024. :group 'org-time
  3025. :version "24.1"
  3026. :type 'boolean)
  3027. (defcustom org-use-last-clock-out-time-as-effective-time nil
  3028. "When non-nil, use the last clock out time for `org-todo'.
  3029. Note that this option has precedence over the combined use of
  3030. `org-use-effective-time' and `org-extend-today-until'."
  3031. :group 'org-time
  3032. :version "24.4"
  3033. :package-version '(Org . "8.0")
  3034. :type 'boolean)
  3035. (defcustom org-edit-timestamp-down-means-later nil
  3036. "Non-nil means S-down will increase the time in a time stamp.
  3037. When nil, S-up will increase."
  3038. :group 'org-time
  3039. :type 'boolean)
  3040. (defcustom org-calendar-follow-timestamp-change t
  3041. "Non-nil means make the calendar window follow timestamp changes.
  3042. When a timestamp is modified and the calendar window is visible, it will be
  3043. moved to the new date."
  3044. :group 'org-time
  3045. :type 'boolean)
  3046. (defgroup org-tags nil
  3047. "Options concerning tags in Org mode."
  3048. :tag "Org Tags"
  3049. :group 'org)
  3050. (defcustom org-tag-alist nil
  3051. "Default tags available in Org files.
  3052. The value of this variable is an alist. Associations either:
  3053. (TAG)
  3054. (TAG . SELECT)
  3055. (SPECIAL)
  3056. where TAG is a tag as a string, SELECT is character, used to
  3057. select that tag through the fast tag selection interface, and
  3058. SPECIAL is one of the following keywords: `:startgroup',
  3059. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  3060. `:newline'. These keywords are used to define a hierarchy of
  3061. tags. See manual for details.
  3062. When this variable is nil, Org mode bases tag input on what is
  3063. already in the buffer. The value can be overridden locally by
  3064. using a TAGS keyword, e.g.,
  3065. #+TAGS: tag1 tag2
  3066. See also `org-tag-persistent-alist' to sidestep this behavior."
  3067. :group 'org-tags
  3068. :type '(repeat
  3069. (choice
  3070. (cons :tag "Tag with key"
  3071. (string :tag "Tag name")
  3072. (character :tag "Access char"))
  3073. (list :tag "Tag" (string :tag "Tag name"))
  3074. (const :tag "Start radio group" (:startgroup))
  3075. (const :tag "Start tag group, non distinct" (:startgrouptag))
  3076. (const :tag "Group tags delimiter" (:grouptags))
  3077. (const :tag "End radio group" (:endgroup))
  3078. (const :tag "End tag group, non distinct" (:endgrouptag))
  3079. (const :tag "New line" (:newline)))))
  3080. (defcustom org-tag-persistent-alist nil
  3081. "Tags always available in Org files.
  3082. The value of this variable is an alist. Associations either:
  3083. (TAG)
  3084. (TAG . SELECT)
  3085. (SPECIAL)
  3086. where TAG is a tag as a string, SELECT is a character, used to
  3087. select that tag through the fast tag selection interface, and
  3088. SPECIAL is one of the following keywords: `:startgroup',
  3089. `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
  3090. `:newline'. These keywords are used to define a hierarchy of
  3091. tags. See manual for details.
  3092. Unlike to `org-tag-alist', tags defined in this variable do not
  3093. depend on a local TAGS keyword. Instead, to disable these tags
  3094. on a per-file basis, insert anywhere in the file:
  3095. #+STARTUP: noptag"
  3096. :group 'org-tags
  3097. :type '(repeat
  3098. (choice
  3099. (cons :tag "Tag with key"
  3100. (string :tag "Tag name")
  3101. (character :tag "Access char"))
  3102. (list :tag "Tag" (string :tag "Tag name"))
  3103. (const :tag "Start radio group" (:startgroup))
  3104. (const :tag "Start tag group, non distinct" (:startgrouptag))
  3105. (const :tag "Group tags delimiter" (:grouptags))
  3106. (const :tag "End radio group" (:endgroup))
  3107. (const :tag "End tag group, non distinct" (:endgrouptag))
  3108. (const :tag "New line" (:newline)))))
  3109. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  3110. "If non-nil, always offer completion for all tags of all agenda files.
  3111. Instead of customizing this variable directly, you might want to
  3112. set it locally for capture buffers, because there no list of
  3113. tags in that file can be created dynamically (there are none).
  3114. (add-hook \\='org-capture-mode-hook
  3115. (lambda ()
  3116. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  3117. :group 'org-tags
  3118. :version "24.1"
  3119. :type 'boolean)
  3120. (defvar org-file-tags nil
  3121. "List of tags that can be inherited by all entries in the file.
  3122. The tags will be inherited if the variable `org-use-tag-inheritance'
  3123. says they should be.
  3124. This variable is populated from #+FILETAGS lines.")
  3125. (defcustom org-use-fast-tag-selection 'auto
  3126. "Non-nil means use fast tag selection scheme.
  3127. This is a special interface to select and deselect tags with single keys.
  3128. When nil, fast selection is never used.
  3129. When the symbol `auto', fast selection is used if and only if selection
  3130. characters for tags have been configured, either through the variable
  3131. `org-tag-alist' or through a #+TAGS line in the buffer.
  3132. When t, fast selection is always used and selection keys are assigned
  3133. automatically if necessary."
  3134. :group 'org-tags
  3135. :type '(choice
  3136. (const :tag "Always" t)
  3137. (const :tag "Never" nil)
  3138. (const :tag "When selection characters are configured" auto)))
  3139. (defcustom org-fast-tag-selection-single-key nil
  3140. "Non-nil means fast tag selection exits after first change.
  3141. When nil, you have to press RET to exit it.
  3142. During fast tag selection, you can toggle this flag with `C-c'.
  3143. This variable can also have the value `expert'. In this case, the window
  3144. displaying the tags menu is not even shown, until you press C-c again."
  3145. :group 'org-tags
  3146. :type '(choice
  3147. (const :tag "No" nil)
  3148. (const :tag "Yes" t)
  3149. (const :tag "Expert" expert)))
  3150. (defvar org-fast-tag-selection-include-todo nil
  3151. "Non-nil means fast tags selection interface will also offer TODO states.
  3152. This is an undocumented feature, you should not rely on it.")
  3153. (defcustom org-tags-column -77
  3154. "The column to which tags should be indented in a headline.
  3155. If this number is positive, it specifies the column. If it is negative,
  3156. it means that the tags should be flushright to that column. For example,
  3157. -80 works well for a normal 80 character screen.
  3158. When 0, place tags directly after headline text, with only one space in
  3159. between."
  3160. :group 'org-tags
  3161. :type 'integer)
  3162. (defcustom org-auto-align-tags t
  3163. "Non-nil keeps tags aligned when modifying headlines.
  3164. Some operations (i.e. demoting) change the length of a headline and
  3165. therefore shift the tags around. With this option turned on, after
  3166. each such operation the tags are again aligned to `org-tags-column'."
  3167. :group 'org-tags
  3168. :type 'boolean)
  3169. (defcustom org-use-tag-inheritance t
  3170. "Non-nil means tags in levels apply also for sublevels.
  3171. When nil, only the tags directly given in a specific line apply there.
  3172. This may also be a list of tags that should be inherited, or a regexp that
  3173. matches tags that should be inherited. Additional control is possible
  3174. with the variable `org-tags-exclude-from-inheritance' which gives an
  3175. explicit list of tags to be excluded from inheritance, even if the value of
  3176. `org-use-tag-inheritance' would select it for inheritance.
  3177. If this option is t, a match early-on in a tree can lead to a large
  3178. number of matches in the subtree when constructing the agenda or creating
  3179. a sparse tree. If you only want to see the first match in a tree during
  3180. a search, check out the variable `org-tags-match-list-sublevels'."
  3181. :group 'org-tags
  3182. :type '(choice
  3183. (const :tag "Not" nil)
  3184. (const :tag "Always" t)
  3185. (repeat :tag "Specific tags" (string :tag "Tag"))
  3186. (regexp :tag "Tags matched by regexp")))
  3187. (defcustom org-tags-exclude-from-inheritance nil
  3188. "List of tags that should never be inherited.
  3189. This is a way to exclude a few tags from inheritance. For way to do
  3190. the opposite, to actively allow inheritance for selected tags,
  3191. see the variable `org-use-tag-inheritance'."
  3192. :group 'org-tags
  3193. :type '(repeat (string :tag "Tag")))
  3194. (defun org-tag-inherit-p (tag)
  3195. "Check if TAG is one that should be inherited."
  3196. (cond
  3197. ((member tag org-tags-exclude-from-inheritance) nil)
  3198. ((eq org-use-tag-inheritance t) t)
  3199. ((not org-use-tag-inheritance) nil)
  3200. ((stringp org-use-tag-inheritance)
  3201. (string-match org-use-tag-inheritance tag))
  3202. ((listp org-use-tag-inheritance)
  3203. (member tag org-use-tag-inheritance))
  3204. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  3205. (defcustom org-tags-match-list-sublevels t
  3206. "Non-nil means list also sublevels of headlines matching a search.
  3207. This variable applies to tags/property searches, and also to stuck
  3208. projects because this search is based on a tags match as well.
  3209. When set to the symbol `indented', sublevels are indented with
  3210. leading dots.
  3211. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  3212. the sublevels of a headline matching a tag search often also match
  3213. the same search. Listing all of them can create very long lists.
  3214. Setting this variable to nil causes subtrees of a match to be skipped.
  3215. This variable is semi-obsolete and probably should always be true. It
  3216. is better to limit inheritance to certain tags using the variables
  3217. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  3218. :group 'org-tags
  3219. :type '(choice
  3220. (const :tag "No, don't list them" nil)
  3221. (const :tag "Yes, do list them" t)
  3222. (const :tag "List them, indented with leading dots" indented)))
  3223. (defcustom org-tags-sort-function nil
  3224. "When set, tags are sorted using this function as a comparator."
  3225. :group 'org-tags
  3226. :type '(choice
  3227. (const :tag "No sorting" nil)
  3228. (const :tag "Alphabetical" string<)
  3229. (const :tag "Reverse alphabetical" string>)
  3230. (function :tag "Custom function" nil)))
  3231. (defvar org-tags-history nil
  3232. "History of minibuffer reads for tags.")
  3233. (defvar org-last-tags-completion-table nil
  3234. "The last used completion table for tags.")
  3235. (defvar org-after-tags-change-hook nil
  3236. "Hook that is run after the tags in a line have changed.")
  3237. (defgroup org-properties nil
  3238. "Options concerning properties in Org mode."
  3239. :tag "Org Properties"
  3240. :group 'org)
  3241. (defcustom org-property-format "%-10s %s"
  3242. "How property key/value pairs should be formatted by `indent-line'.
  3243. When `indent-line' hits a property definition, it will format the line
  3244. according to this format, mainly to make sure that the values are
  3245. lined-up with respect to each other."
  3246. :group 'org-properties
  3247. :type 'string)
  3248. (defcustom org-properties-postprocess-alist nil
  3249. "Alist of properties and functions to adjust inserted values.
  3250. Elements of this alist must be of the form
  3251. ([string] [function])
  3252. where [string] must be a property name and [function] must be a
  3253. lambda expression: this lambda expression must take one argument,
  3254. the value to adjust, and return the new value as a string.
  3255. For example, this element will allow the property \"Remaining\"
  3256. to be updated wrt the relation between the \"Effort\" property
  3257. and the clock summary:
  3258. ((\"Remaining\" (lambda(value)
  3259. (let ((clocksum (org-clock-sum-current-item))
  3260. (effort (org-duration-string-to-minutes
  3261. (org-entry-get (point) \"Effort\"))))
  3262. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  3263. :group 'org-properties
  3264. :version "24.1"
  3265. :type '(alist :key-type (string :tag "Property")
  3266. :value-type (function :tag "Function")))
  3267. (defcustom org-use-property-inheritance nil
  3268. "Non-nil means properties apply also for sublevels.
  3269. This setting is chiefly used during property searches. Turning it on can
  3270. cause significant overhead when doing a search, which is why it is not
  3271. on by default.
  3272. When nil, only the properties directly given in the current entry count.
  3273. When t, every property is inherited. The value may also be a list of
  3274. properties that should have inheritance, or a regular expression matching
  3275. properties that should be inherited.
  3276. However, note that some special properties use inheritance under special
  3277. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  3278. and the properties ending in \"_ALL\" when they are used as descriptor
  3279. for valid values of a property.
  3280. Note for programmers:
  3281. When querying an entry with `org-entry-get', you can control if inheritance
  3282. should be used. By default, `org-entry-get' looks only at the local
  3283. properties. You can request inheritance by setting the inherit argument
  3284. to t (to force inheritance) or to `selective' (to respect the setting
  3285. in this variable)."
  3286. :group 'org-properties
  3287. :type '(choice
  3288. (const :tag "Not" nil)
  3289. (const :tag "Always" t)
  3290. (repeat :tag "Specific properties" (string :tag "Property"))
  3291. (regexp :tag "Properties matched by regexp")))
  3292. (defun org-property-inherit-p (property)
  3293. "Return a non-nil value if PROPERTY should be inherited."
  3294. (cond
  3295. ((eq org-use-property-inheritance t) t)
  3296. ((not org-use-property-inheritance) nil)
  3297. ((stringp org-use-property-inheritance)
  3298. (string-match org-use-property-inheritance property))
  3299. ((listp org-use-property-inheritance)
  3300. (member-ignore-case property org-use-property-inheritance))
  3301. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  3302. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  3303. "The default column format, if no other format has been defined.
  3304. This variable can be set on the per-file basis by inserting a line
  3305. #+COLUMNS: %25ITEM ....."
  3306. :group 'org-properties
  3307. :type 'string)
  3308. (defcustom org-columns-ellipses ".."
  3309. "The ellipses to be used when a field in column view is truncated.
  3310. When this is the empty string, as many characters as possible are shown,
  3311. but then there will be no visual indication that the field has been truncated.
  3312. When this is a string of length N, the last N characters of a truncated
  3313. field are replaced by this string. If the column is narrower than the
  3314. ellipses string, only part of the ellipses string will be shown."
  3315. :group 'org-properties
  3316. :type 'string)
  3317. (defconst org-global-properties-fixed
  3318. '(("VISIBILITY_ALL" . "folded children content all")
  3319. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  3320. "List of property/value pairs that can be inherited by any entry.
  3321. These are fixed values, for the preset properties. The user variable
  3322. that can be used to add to this list is `org-global-properties'.
  3323. The entries in this list are cons cells where the car is a property
  3324. name and cdr is a string with the value. If the value represents
  3325. multiple items like an \"_ALL\" property, separate the items by
  3326. spaces.")
  3327. (defcustom org-global-properties nil
  3328. "List of property/value pairs that can be inherited by any entry.
  3329. This list will be combined with the constant `org-global-properties-fixed'.
  3330. The entries in this list are cons cells where the car is a property
  3331. name and cdr is a string with the value.
  3332. You can set buffer-local values for the same purpose in the variable
  3333. `org-file-properties' this by adding lines like
  3334. #+PROPERTY: NAME VALUE"
  3335. :group 'org-properties
  3336. :type '(repeat
  3337. (cons (string :tag "Property")
  3338. (string :tag "Value"))))
  3339. (defvar-local org-file-properties nil
  3340. "List of property/value pairs that can be inherited by any entry.
  3341. Valid for the current buffer.
  3342. This variable is populated from #+PROPERTY lines.")
  3343. (defgroup org-agenda nil
  3344. "Options concerning agenda views in Org mode."
  3345. :tag "Org Agenda"
  3346. :group 'org)
  3347. (defvar-local org-category nil
  3348. "Variable used by org files to set a category for agenda display.
  3349. Such files should use a file variable to set it, for example
  3350. # -*- mode: org; org-category: \"ELisp\"
  3351. or contain a special line
  3352. #+CATEGORY: ELisp
  3353. If the file does not specify a category, then file's base name
  3354. is used instead.")
  3355. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  3356. (defcustom org-agenda-files nil
  3357. "The files to be used for agenda display.
  3358. If an entry is a directory, all files in that directory that are matched
  3359. by `org-agenda-file-regexp' will be part of the file list.
  3360. If the value of the variable is not a list but a single file name, then
  3361. the list of agenda files is actually stored and maintained in that file,
  3362. one agenda file per line. In this file paths can be given relative to
  3363. `org-directory'. Tilde expansion and environment variable substitution
  3364. are also made.
  3365. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  3366. and removed with `\\[org-remove-file]'."
  3367. :group 'org-agenda
  3368. :type '(choice
  3369. (repeat :tag "List of files and directories" file)
  3370. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  3371. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  3372. "Regular expression to match files for `org-agenda-files'.
  3373. If any element in the list in that variable contains a directory instead
  3374. of a normal file, all files in that directory that are matched by this
  3375. regular expression will be included."
  3376. :group 'org-agenda
  3377. :type 'regexp)
  3378. (defcustom org-agenda-text-search-extra-files nil
  3379. "List of extra files to be searched by text search commands.
  3380. These files will be searched in addition to the agenda files by the
  3381. commands `org-search-view' (`\\[org-agenda] s') \
  3382. and `org-occur-in-agenda-files'.
  3383. Note that these files will only be searched for text search commands,
  3384. not for the other agenda views like todo lists, tag searches or the weekly
  3385. agenda. This variable is intended to list notes and possibly archive files
  3386. that should also be searched by these two commands.
  3387. In fact, if the first element in the list is the symbol `agenda-archives',
  3388. then all archive files of all agenda files will be added to the search
  3389. scope."
  3390. :group 'org-agenda
  3391. :type '(set :greedy t
  3392. (const :tag "Agenda Archives" agenda-archives)
  3393. (repeat :inline t (file))))
  3394. (defvaralias 'org-agenda-multi-occur-extra-files
  3395. 'org-agenda-text-search-extra-files)
  3396. (defcustom org-agenda-skip-unavailable-files nil
  3397. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  3398. A nil value means to remove them, after a query, from the list."
  3399. :group 'org-agenda
  3400. :type 'boolean)
  3401. (defcustom org-calendar-to-agenda-key [?c]
  3402. "The key to be installed in `calendar-mode-map' for switching to the agenda.
  3403. The command `org-calendar-goto-agenda' will be bound to this key. The
  3404. default is the character `c' because then `c' can be used to switch back and
  3405. forth between agenda and calendar."
  3406. :group 'org-agenda
  3407. :type 'sexp)
  3408. (defcustom org-calendar-insert-diary-entry-key [?i]
  3409. "The key to be installed in `calendar-mode-map' for adding diary entries.
  3410. This option is irrelevant until `org-agenda-diary-file' has been configured
  3411. to point to an Org file. When that is the case, the command
  3412. `org-agenda-diary-entry' will be bound to the key given here, by default
  3413. `i'. In the calendar, `i' normally adds entries to `diary-file'. So
  3414. if you want to continue doing this, you need to change this to a different
  3415. key."
  3416. :group 'org-agenda
  3417. :type 'sexp)
  3418. (defcustom org-agenda-diary-file 'diary-file
  3419. "File to which to add new entries with the `i' key in agenda and calendar.
  3420. When this is the symbol `diary-file', the functionality in the Emacs
  3421. calendar will be used to add entries to the `diary-file'. But when this
  3422. points to a file, `org-agenda-diary-entry' will be used instead."
  3423. :group 'org-agenda
  3424. :type '(choice
  3425. (const :tag "The standard Emacs diary file" diary-file)
  3426. (file :tag "Special Org file diary entries")))
  3427. (eval-after-load "calendar"
  3428. '(progn
  3429. (org-defkey calendar-mode-map org-calendar-to-agenda-key
  3430. 'org-calendar-goto-agenda)
  3431. (add-hook 'calendar-mode-hook
  3432. (lambda ()
  3433. (unless (eq org-agenda-diary-file 'diary-file)
  3434. (define-key calendar-mode-map
  3435. org-calendar-insert-diary-entry-key
  3436. 'org-agenda-diary-entry))))))
  3437. (defgroup org-latex nil
  3438. "Options for embedding LaTeX code into Org mode."
  3439. :tag "Org LaTeX"
  3440. :group 'org)
  3441. (defcustom org-format-latex-options
  3442. '(:foreground default :background default :scale 1.0
  3443. :html-foreground "Black" :html-background "Transparent"
  3444. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  3445. "Options for creating images from LaTeX fragments.
  3446. This is a property list with the following properties:
  3447. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  3448. `default' means use the foreground of the default face.
  3449. `auto' means use the foreground from the text face.
  3450. :background the background color, or \"Transparent\".
  3451. `default' means use the background of the default face.
  3452. `auto' means use the background from the text face.
  3453. :scale a scaling factor for the size of the images, to get more pixels
  3454. :html-foreground, :html-background, :html-scale
  3455. the same numbers for HTML export.
  3456. :matchers a list indicating which matchers should be used to
  3457. find LaTeX fragments. Valid members of this list are:
  3458. \"begin\" find environments
  3459. \"$1\" find single characters surrounded by $.$
  3460. \"$\" find math expressions surrounded by $...$
  3461. \"$$\" find math expressions surrounded by $$....$$
  3462. \"\\(\" find math expressions surrounded by \\(...\\)
  3463. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  3464. :group 'org-latex
  3465. :type 'plist)
  3466. (defcustom org-format-latex-signal-error t
  3467. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  3468. When nil, just push out a message."
  3469. :group 'org-latex
  3470. :version "24.1"
  3471. :type 'boolean)
  3472. (defcustom org-latex-to-mathml-jar-file nil
  3473. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  3474. Use this to specify additional executable file say a jar file.
  3475. When using MathToWeb as the converter, specify the full-path to
  3476. your mathtoweb.jar file."
  3477. :group 'org-latex
  3478. :version "24.1"
  3479. :type '(choice
  3480. (const :tag "None" nil)
  3481. (file :tag "JAR file" :must-match t)))
  3482. (defcustom org-latex-to-mathml-convert-command nil
  3483. "Command to convert LaTeX fragments to MathML.
  3484. Replace format-specifiers in the command as noted below and use
  3485. `shell-command' to convert LaTeX to MathML.
  3486. %j: Executable file in fully expanded form as specified by
  3487. `org-latex-to-mathml-jar-file'.
  3488. %I: Input LaTeX file in fully expanded form.
  3489. %i: The latex fragment to be converted.
  3490. %o: Output MathML file.
  3491. This command is used by `org-create-math-formula'.
  3492. When using MathToWeb as the converter, set this option to
  3493. \"java -jar %j -unicode -force -df %o %I\".
  3494. When using LaTeXML set this option to
  3495. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  3496. :group 'org-latex
  3497. :version "24.1"
  3498. :type '(choice
  3499. (const :tag "None" nil)
  3500. (string :tag "\nShell command")))
  3501. (defcustom org-preview-latex-default-process 'dvipng
  3502. "The default process to convert LaTeX fragments to image files.
  3503. All available processes and theirs documents can be found in
  3504. `org-preview-latex-process-alist', which see."
  3505. :group 'org-latex
  3506. :version "26.1"
  3507. :package-version '(Org . "9.0")
  3508. :type 'symbol)
  3509. (defcustom org-preview-latex-process-alist
  3510. '((dvipng
  3511. :programs ("latex" "dvipng")
  3512. :description "dvi > png"
  3513. :message "you need to install the programs: latex and dvipng."
  3514. :image-input-type "dvi"
  3515. :image-output-type "png"
  3516. :image-size-adjust (1.0 . 1.0)
  3517. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3518. :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
  3519. (dvisvgm
  3520. :programs ("latex" "dvisvgm")
  3521. :description "dvi > svg"
  3522. :message "you need to install the programs: latex and dvisvgm."
  3523. :use-xcolor t
  3524. :image-input-type "dvi"
  3525. :image-output-type "svg"
  3526. :image-size-adjust (1.7 . 1.5)
  3527. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  3528. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  3529. (imagemagick
  3530. :programs ("latex" "convert")
  3531. :description "pdf > png"
  3532. :message "you need to install the programs: latex and imagemagick."
  3533. :use-xcolor t
  3534. :image-input-type "pdf"
  3535. :image-output-type "png"
  3536. :image-size-adjust (1.0 . 1.0)
  3537. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  3538. :image-converter
  3539. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  3540. "Definitions of external processes for LaTeX previewing.
  3541. Org mode can use some external commands to generate TeX snippet's images for
  3542. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  3543. `org-create-formula-image' how to call them.
  3544. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  3545. PROPERTIES accepts the following attributes:
  3546. :programs list of strings, required programs.
  3547. :description string, describe the process.
  3548. :message string, message it when required programs cannot be found.
  3549. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  3550. :image-output-type string, output file type of image converter (e.g., \"png\").
  3551. :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
  3552. deal with background and foreground color of image.
  3553. Otherwise, dvipng style background and foreground color
  3554. format are generated. You may then refer to them in
  3555. command options with \"%F\" and \"%B\".
  3556. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  3557. image size showed in buffer and the cdr element is for
  3558. HTML file. This option is only useful for process
  3559. developers, users should use variable
  3560. `org-format-latex-options' instead.
  3561. :post-clean list of strings, files matched are to be cleaned up once
  3562. the image is generated. When nil, the files with \".dvi\",
  3563. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  3564. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  3565. be cleaned up.
  3566. :latex-header list of strings, the LaTeX header of the snippet file.
  3567. When nil, the fallback value is used instead, which is
  3568. controlled by `org-format-latex-header',
  3569. `org-latex-default-packages-alist' and
  3570. `org-latex-packages-alist', which see.
  3571. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  3572. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  3573. replaced with values defined below.
  3574. :image-converter list of image converter commands strings. Each of them is
  3575. given to the shell and supports any of the following
  3576. place-holders defined below.
  3577. Place-holders used by `:image-converter' and `:latex-compiler':
  3578. %f input file name
  3579. %b base name of input file
  3580. %o base directory of input file
  3581. %O absolute output file name
  3582. Place-holders only used by `:image-converter':
  3583. %F foreground of image
  3584. %B background of image
  3585. %D dpi, which is used to adjust image size by some processing commands.
  3586. %S the image size scale ratio, which is used to adjust image size by some
  3587. processing commands."
  3588. :group 'org-latex
  3589. :version "26.1"
  3590. :package-version '(Org . "9.0")
  3591. :type '(alist :tag "LaTeX to image backends"
  3592. :value-type (plist)))
  3593. (defcustom org-preview-latex-image-directory "ltximg/"
  3594. "Path to store latex preview images.
  3595. A relative path here creates many directories relative to the
  3596. processed org files paths. An absolute path puts all preview
  3597. images at the same place."
  3598. :group 'org-latex
  3599. :version "26.1"
  3600. :package-version '(Org . "9.0")
  3601. :type 'string)
  3602. (defun org-format-latex-mathml-available-p ()
  3603. "Return t if `org-latex-to-mathml-convert-command' is usable."
  3604. (save-match-data
  3605. (when (and (boundp 'org-latex-to-mathml-convert-command)
  3606. org-latex-to-mathml-convert-command)
  3607. (let ((executable (car (split-string
  3608. org-latex-to-mathml-convert-command))))
  3609. (when (executable-find executable)
  3610. (if (string-match
  3611. "%j" org-latex-to-mathml-convert-command)
  3612. (file-readable-p org-latex-to-mathml-jar-file)
  3613. t))))))
  3614. (defcustom org-format-latex-header "\\documentclass{article}
  3615. \\usepackage[usenames]{color}
  3616. \[PACKAGES]
  3617. \[DEFAULT-PACKAGES]
  3618. \\pagestyle{empty} % do not remove
  3619. % The settings below are copied from fullpage.sty
  3620. \\setlength{\\textwidth}{\\paperwidth}
  3621. \\addtolength{\\textwidth}{-3cm}
  3622. \\setlength{\\oddsidemargin}{1.5cm}
  3623. \\addtolength{\\oddsidemargin}{-2.54cm}
  3624. \\setlength{\\evensidemargin}{\\oddsidemargin}
  3625. \\setlength{\\textheight}{\\paperheight}
  3626. \\addtolength{\\textheight}{-\\headheight}
  3627. \\addtolength{\\textheight}{-\\headsep}
  3628. \\addtolength{\\textheight}{-\\footskip}
  3629. \\addtolength{\\textheight}{-3cm}
  3630. \\setlength{\\topmargin}{1.5cm}
  3631. \\addtolength{\\topmargin}{-2.54cm}"
  3632. "The document header used for processing LaTeX fragments.
  3633. It is imperative that this header make sure that no page number
  3634. appears on the page. The package defined in the variables
  3635. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  3636. will either replace the placeholder \"[PACKAGES]\" in this
  3637. header, or they will be appended."
  3638. :group 'org-latex
  3639. :type 'string)
  3640. (defun org-set-packages-alist (var val)
  3641. "Set the packages alist and make sure it has 3 elements per entry."
  3642. (set var (mapcar (lambda (x)
  3643. (if (and (consp x) (= (length x) 2))
  3644. (list (car x) (nth 1 x) t)
  3645. x))
  3646. val)))
  3647. (defun org-get-packages-alist (var)
  3648. "Get the packages alist and make sure it has 3 elements per entry."
  3649. (mapcar (lambda (x)
  3650. (if (and (consp x) (= (length x) 2))
  3651. (list (car x) (nth 1 x) t)
  3652. x))
  3653. (default-value var)))
  3654. (defcustom org-latex-default-packages-alist
  3655. '(("AUTO" "inputenc" t ("pdflatex"))
  3656. ("T1" "fontenc" t ("pdflatex"))
  3657. ("" "graphicx" t)
  3658. ("" "grffile" t)
  3659. ("" "longtable" nil)
  3660. ("" "wrapfig" nil)
  3661. ("" "rotating" nil)
  3662. ("normalem" "ulem" t)
  3663. ("" "amsmath" t)
  3664. ("" "textcomp" t)
  3665. ("" "amssymb" t)
  3666. ("" "capt-of" nil)
  3667. ("" "hyperref" nil))
  3668. "Alist of default packages to be inserted in the header.
  3669. Change this only if one of the packages here causes an
  3670. incompatibility with another package you are using.
  3671. The packages in this list are needed by one part or another of
  3672. Org mode to function properly:
  3673. - inputenc, fontenc: for basic font and character selection
  3674. - graphicx: for including images
  3675. - grffile: allow periods and spaces in graphics file names
  3676. - longtable: For multipage tables
  3677. - wrapfig: for figure placement
  3678. - rotating: for sideways figures and tables
  3679. - ulem: for underline and strike-through
  3680. - amsmath: for subscript and superscript and math environments
  3681. - textcomp, amssymb: for various symbols used
  3682. for interpreting the entities in `org-entities'. You can skip
  3683. some of these packages if you don't use any of their symbols.
  3684. - capt-of: for captions outside of floats
  3685. - hyperref: for cross references
  3686. Therefore you should not modify this variable unless you know
  3687. what you are doing. The one reason to change it anyway is that
  3688. you might be loading some other package that conflicts with one
  3689. of the default packages. Each element is either a cell or
  3690. a string.
  3691. A cell is of the format
  3692. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3693. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3694. when compiling LaTeX snippets into images for inclusion into
  3695. non-LaTeX output. COMPILERS is a list of compilers that should
  3696. include the package, see `org-latex-compiler'. If the document
  3697. compiler is not in the list, and the list is non-nil, the package
  3698. will not be inserted in the final document.
  3699. A string will be inserted as-is in the header of the document."
  3700. :group 'org-latex
  3701. :group 'org-export-latex
  3702. :set 'org-set-packages-alist
  3703. :get 'org-get-packages-alist
  3704. :version "26.1"
  3705. :package-version '(Org . "8.3")
  3706. :type '(repeat
  3707. (choice
  3708. (list :tag "options/package pair"
  3709. (string :tag "options")
  3710. (string :tag "package")
  3711. (boolean :tag "Snippet"))
  3712. (string :tag "A line of LaTeX"))))
  3713. (defcustom org-latex-packages-alist nil
  3714. "Alist of packages to be inserted in every LaTeX header.
  3715. These will be inserted after `org-latex-default-packages-alist'.
  3716. Each element is either a cell or a string.
  3717. A cell is of the format:
  3718. (\"options\" \"package\" SNIPPET-FLAG)
  3719. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3720. needed when turning LaTeX snippets into images for inclusion into
  3721. non-LaTeX output.
  3722. A string will be inserted as-is in the header of the document.
  3723. Make sure that you only list packages here which:
  3724. - you want in every file;
  3725. - do not conflict with the setup in `org-format-latex-header';
  3726. - do not conflict with the default packages in
  3727. `org-latex-default-packages-alist'."
  3728. :group 'org-latex
  3729. :group 'org-export-latex
  3730. :set 'org-set-packages-alist
  3731. :get 'org-get-packages-alist
  3732. :type '(repeat
  3733. (choice
  3734. (list :tag "options/package pair"
  3735. (string :tag "options")
  3736. (string :tag "package")
  3737. (boolean :tag "Snippet"))
  3738. (string :tag "A line of LaTeX"))))
  3739. (defgroup org-appearance nil
  3740. "Settings for Org mode appearance."
  3741. :tag "Org Appearance"
  3742. :group 'org)
  3743. (defcustom org-level-color-stars-only nil
  3744. "Non-nil means fontify only the stars in each headline.
  3745. When nil, the entire headline is fontified.
  3746. Changing it requires restart of `font-lock-mode' to become effective
  3747. also in regions already fontified."
  3748. :group 'org-appearance
  3749. :type 'boolean)
  3750. (defcustom org-hide-leading-stars nil
  3751. "Non-nil means hide the first N-1 stars in a headline.
  3752. This works by using the face `org-hide' for these stars. This
  3753. face is white for a light background, and black for a dark
  3754. background. You may have to customize the face `org-hide' to
  3755. make this work.
  3756. Changing it requires restart of `font-lock-mode' to become effective
  3757. also in regions already fontified.
  3758. You may also set this on a per-file basis by adding one of the following
  3759. lines to the buffer:
  3760. #+STARTUP: hidestars
  3761. #+STARTUP: showstars"
  3762. :group 'org-appearance
  3763. :type 'boolean)
  3764. (defcustom org-hidden-keywords nil
  3765. "List of symbols corresponding to keywords to be hidden the org buffer.
  3766. For example, a value \\='(title) for this list will make the document's title
  3767. appear in the buffer without the initial #+TITLE: keyword."
  3768. :group 'org-appearance
  3769. :version "24.1"
  3770. :type '(set (const :tag "#+AUTHOR" author)
  3771. (const :tag "#+DATE" date)
  3772. (const :tag "#+EMAIL" email)
  3773. (const :tag "#+TITLE" title)))
  3774. (defcustom org-custom-properties nil
  3775. "List of properties (as strings) with a special meaning.
  3776. The default use of these custom properties is to let the user
  3777. hide them with `org-toggle-custom-properties-visibility'."
  3778. :group 'org-properties
  3779. :group 'org-appearance
  3780. :version "24.3"
  3781. :type '(repeat (string :tag "Property Name")))
  3782. (defcustom org-fontify-done-headline nil
  3783. "Non-nil means change the face of a headline if it is marked DONE.
  3784. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3785. When this is non-nil, the headline after the keyword is set to the
  3786. `org-headline-done' as an additional indication."
  3787. :group 'org-appearance
  3788. :type 'boolean)
  3789. (defcustom org-fontify-emphasized-text t
  3790. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3791. Changing this variable requires a restart of Emacs to take effect."
  3792. :group 'org-appearance
  3793. :type 'boolean)
  3794. (defcustom org-fontify-whole-heading-line nil
  3795. "Non-nil means fontify the whole line for headings.
  3796. This is useful when setting a background color for the
  3797. org-level-* faces."
  3798. :group 'org-appearance
  3799. :type 'boolean)
  3800. (defcustom org-highlight-latex-and-related nil
  3801. "Non-nil means highlight LaTeX related syntax in the buffer.
  3802. When non nil, the value should be a list containing any of the
  3803. following symbols:
  3804. `latex' Highlight LaTeX snippets and environments.
  3805. `script' Highlight subscript and superscript.
  3806. `entities' Highlight entities."
  3807. :group 'org-appearance
  3808. :version "24.4"
  3809. :package-version '(Org . "8.0")
  3810. :type '(choice
  3811. (const :tag "No highlighting" nil)
  3812. (set :greedy t :tag "Highlight"
  3813. (const :tag "LaTeX snippets and environments" latex)
  3814. (const :tag "Subscript and superscript" script)
  3815. (const :tag "Entities" entities))))
  3816. (defcustom org-hide-emphasis-markers nil
  3817. "Non-nil mean font-lock should hide the emphasis marker characters."
  3818. :group 'org-appearance
  3819. :type 'boolean)
  3820. (defcustom org-hide-macro-markers nil
  3821. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3822. :group 'org-appearance
  3823. :type 'boolean)
  3824. (defcustom org-pretty-entities nil
  3825. "Non-nil means show entities as UTF8 characters.
  3826. When nil, the \\name form remains in the buffer."
  3827. :group 'org-appearance
  3828. :version "24.1"
  3829. :type 'boolean)
  3830. (defcustom org-pretty-entities-include-sub-superscripts t
  3831. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3832. :group 'org-appearance
  3833. :version "24.1"
  3834. :type 'boolean)
  3835. (defvar org-emph-re nil
  3836. "Regular expression for matching emphasis.
  3837. After a match, the match groups contain these elements:
  3838. 0 The match of the full regular expression, including the characters
  3839. before and after the proper match
  3840. 1 The character before the proper match, or empty at beginning of line
  3841. 2 The proper match, including the leading and trailing markers
  3842. 3 The leading marker like * or /, indicating the type of highlighting
  3843. 4 The text between the emphasis markers, not including the markers
  3844. 5 The character after the match, empty at the end of a line")
  3845. (defvar org-verbatim-re nil
  3846. "Regular expression for matching verbatim text.")
  3847. (defvar org-emphasis-regexp-components) ; defined just below
  3848. (defvar org-emphasis-alist) ; defined just below
  3849. (defun org-set-emph-re (var val)
  3850. "Set variable and compute the emphasis regular expression."
  3851. (set var val)
  3852. (when (and (boundp 'org-emphasis-alist)
  3853. (boundp 'org-emphasis-regexp-components)
  3854. org-emphasis-alist org-emphasis-regexp-components)
  3855. (let* ((e org-emphasis-regexp-components)
  3856. (pre (car e))
  3857. (post (nth 1 e))
  3858. (border (nth 2 e))
  3859. (body (nth 3 e))
  3860. (nl (nth 4 e))
  3861. (body1 (concat body "*?"))
  3862. (markers (mapconcat 'car org-emphasis-alist ""))
  3863. (vmarkers (mapconcat
  3864. (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
  3865. org-emphasis-alist "")))
  3866. ;; make sure special characters appear at the right position in the class
  3867. (if (string-match "\\^" markers)
  3868. (setq markers (concat (replace-match "" t t markers) "^")))
  3869. (if (string-match "-" markers)
  3870. (setq markers (concat (replace-match "" t t markers) "-")))
  3871. (if (string-match "\\^" vmarkers)
  3872. (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
  3873. (if (string-match "-" vmarkers)
  3874. (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
  3875. (if (> nl 0)
  3876. (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
  3877. (int-to-string nl) "\\}")))
  3878. ;; Make the regexp
  3879. (setq org-emph-re
  3880. (concat "\\([" pre "]\\|^\\)"
  3881. "\\("
  3882. "\\([" markers "]\\)"
  3883. "\\("
  3884. "[^" border "]\\|"
  3885. "[^" border "]"
  3886. body1
  3887. "[^" border "]"
  3888. "\\)"
  3889. "\\3\\)"
  3890. "\\([" post "]\\|$\\)"))
  3891. (setq org-verbatim-re
  3892. (concat "\\([" pre "]\\|^\\)"
  3893. "\\("
  3894. "\\([" vmarkers "]\\)"
  3895. "\\("
  3896. "[^" border "]\\|"
  3897. "[^" border "]"
  3898. body1
  3899. "[^" border "]"
  3900. "\\)"
  3901. "\\3\\)"
  3902. "\\([" post "]\\|$\\)")))))
  3903. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3904. ;; set this option proved cumbersome. See this message/thread:
  3905. ;; http://article.gmane.org/gmane.emacs.orgmode/68681
  3906. (defvar org-emphasis-regexp-components
  3907. '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
  3908. "Components used to build the regular expression for emphasis.
  3909. This is a list with five entries. Terminology: In an emphasis string
  3910. like \" *strong word* \", we call the initial space PREMATCH, the final
  3911. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3912. and \"trong wor\" is the body. The different components in this variable
  3913. specify what is allowed/forbidden in each part:
  3914. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3915. post Chars allowed as postmatch. End of line will be allowed too.
  3916. border The chars *forbidden* as border characters.
  3917. body-regexp A regexp like \".\" to match a body character. Don't use
  3918. non-shy groups here, and don't allow newline here.
  3919. newline The maximum number of newlines allowed in an emphasis exp.
  3920. You need to reload Org or to restart Emacs after customizing this.")
  3921. (defcustom org-emphasis-alist
  3922. '(("*" bold)
  3923. ("/" italic)
  3924. ("_" underline)
  3925. ("=" org-verbatim verbatim)
  3926. ("~" org-code verbatim)
  3927. ("+" (:strike-through t)))
  3928. "Alist of characters and faces to emphasize text.
  3929. Text starting and ending with a special character will be emphasized,
  3930. for example *bold*, _underlined_ and /italic/. This variable sets the
  3931. marker characters and the face to be used by font-lock for highlighting
  3932. in Org buffers.
  3933. You need to reload Org or to restart Emacs after customizing this."
  3934. :group 'org-appearance
  3935. :set 'org-set-emph-re
  3936. :version "24.4"
  3937. :package-version '(Org . "8.0")
  3938. :type '(repeat
  3939. (list
  3940. (string :tag "Marker character")
  3941. (choice
  3942. (face :tag "Font-lock-face")
  3943. (plist :tag "Face property list"))
  3944. (option (const verbatim)))))
  3945. (defvar org-protecting-blocks '("src" "example" "export")
  3946. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3947. This is needed for font-lock setup.")
  3948. ;;; Functions and variables from their packages
  3949. ;; Declared here to avoid compiler warnings
  3950. (defvar mark-active)
  3951. ;; Various packages
  3952. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3953. (declare-function calendar-forward-day "cal-move" (arg))
  3954. (declare-function calendar-goto-date "cal-move" (date))
  3955. (declare-function calendar-goto-today "cal-move" ())
  3956. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3957. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3958. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3959. (declare-function cdlatex-tab "ext:cdlatex" ())
  3960. (declare-function dired-get-filename
  3961. "dired"
  3962. (&optional localp no-error-if-not-filep))
  3963. (declare-function iswitchb-read-buffer
  3964. "iswitchb"
  3965. (prompt &optional
  3966. default require-match _predicate start matches-set))
  3967. (declare-function org-agenda-change-all-lines
  3968. "org-agenda"
  3969. (newhead hdmarker &optional fixface just-this))
  3970. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3971. "org-agenda"
  3972. (&optional end))
  3973. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3974. (declare-function org-agenda-format-item
  3975. "org-agenda"
  3976. (extra txt &optional level category tags dotime
  3977. remove-re habitp))
  3978. (declare-function org-agenda-maybe-redo "org-agenda" ())
  3979. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3980. (declare-function org-agenda-save-markers-for-cut-and-paste
  3981. "org-agenda"
  3982. (beg end))
  3983. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3984. (declare-function org-agenda-skip "org-agenda" ())
  3985. (declare-function org-attach-reveal "org-attach" (&optional if-exists))
  3986. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3987. (declare-function org-indent-mode "org-indent" (&optional arg))
  3988. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3989. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3990. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3991. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3992. (declare-function orgtbl-send-table "org-table" (&optional maybe))
  3993. (declare-function parse-time-string "parse-time" (string))
  3994. (declare-function speedbar-line-directory "speedbar" (&optional depth))
  3995. (defvar align-mode-rules-list)
  3996. (defvar calc-embedded-close-formula)
  3997. (defvar calc-embedded-open-formula)
  3998. (defvar calc-embedded-open-mode)
  3999. (defvar font-lock-unfontify-region-function)
  4000. (defvar iswitchb-temp-buflist)
  4001. (defvar org-agenda-tags-todo-honor-ignore-options)
  4002. (defvar remember-data-file)
  4003. (defvar texmathp-why)
  4004. ;;;###autoload
  4005. (defun turn-on-orgtbl ()
  4006. "Unconditionally turn on `orgtbl-mode'."
  4007. (require 'org-table)
  4008. (orgtbl-mode 1))
  4009. (defun org-at-table-p (&optional table-type)
  4010. "Non-nil if the cursor is inside an Org table.
  4011. If TABLE-TYPE is non-nil, also check for table.el-type tables.
  4012. If `org-enable-table-editor' is nil, return nil unconditionally."
  4013. (and
  4014. org-enable-table-editor
  4015. (save-excursion
  4016. (beginning-of-line)
  4017. (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
  4018. (or (not (derived-mode-p 'org-mode))
  4019. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  4020. (and e (or table-type (eq (org-element-property :type e) 'org)))))))
  4021. (defun org-at-table.el-p ()
  4022. "Non-nil when point is at a table.el table."
  4023. (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
  4024. (let ((element (org-element-at-point)))
  4025. (and (eq (org-element-type element) 'table)
  4026. (eq (org-element-property :type element) 'table.el)))))
  4027. (defun org-at-table-hline-p ()
  4028. "Non-nil when point is inside a hline in a table.
  4029. Assume point is already in a table. If `org-enable-table-editor'
  4030. is nil, return nil unconditionally."
  4031. (and org-enable-table-editor
  4032. (save-excursion
  4033. (beginning-of-line)
  4034. (looking-at org-table-hline-regexp))))
  4035. (defun org-table-map-tables (function &optional quietly)
  4036. "Apply FUNCTION to the start of all tables in the buffer."
  4037. (org-with-wide-buffer
  4038. (goto-char (point-min))
  4039. (while (re-search-forward org-table-any-line-regexp nil t)
  4040. (unless quietly
  4041. (message "Mapping tables: %d%%"
  4042. (floor (* 100.0 (point)) (buffer-size))))
  4043. (beginning-of-line 1)
  4044. (when (and (looking-at org-table-line-regexp)
  4045. ;; Exclude tables in src/example/verbatim/clocktable blocks
  4046. (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
  4047. (save-excursion (funcall function))
  4048. (or (looking-at org-table-line-regexp)
  4049. (forward-char 1)))
  4050. (re-search-forward org-table-any-border-regexp nil 1)))
  4051. (unless quietly (message "Mapping tables: done")))
  4052. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  4053. (declare-function org-clock-update-mode-line "org-clock" ())
  4054. (declare-function org-resolve-clocks "org-clock"
  4055. (&optional also-non-dangling-p prompt last-valid))
  4056. (defun org-at-TBLFM-p (&optional pos)
  4057. "Non-nil when point (or POS) is in #+TBLFM line."
  4058. (save-excursion
  4059. (goto-char (or pos (point)))
  4060. (beginning-of-line)
  4061. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  4062. (eq (org-element-type (org-element-at-point)) 'table))))
  4063. (defvar org-clock-start-time)
  4064. (defvar org-clock-marker (make-marker)
  4065. "Marker recording the last clock-in.")
  4066. (defvar org-clock-hd-marker (make-marker)
  4067. "Marker recording the last clock-in, but the headline position.")
  4068. (defvar org-clock-heading ""
  4069. "The heading of the current clock entry.")
  4070. (defun org-clock-is-active ()
  4071. "Return the buffer where the clock is currently running.
  4072. Return nil if no clock is running."
  4073. (marker-buffer org-clock-marker))
  4074. (defun org-check-running-clock ()
  4075. "Check if the current buffer contains the running clock.
  4076. If yes, offer to stop it and to save the buffer with the changes."
  4077. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  4078. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  4079. (buffer-name))))
  4080. (org-clock-out)
  4081. (when (y-or-n-p "Save changed buffer?")
  4082. (save-buffer))))
  4083. (defun org-clocktable-try-shift (dir n)
  4084. "Check if this line starts a clock table, if yes, shift the time block."
  4085. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  4086. (org-clocktable-shift dir n)))
  4087. ;;;###autoload
  4088. (defun org-clock-persistence-insinuate ()
  4089. "Set up hooks for clock persistence."
  4090. (require 'org-clock)
  4091. (add-hook 'org-mode-hook 'org-clock-load)
  4092. (add-hook 'kill-emacs-hook 'org-clock-save))
  4093. (defgroup org-archive nil
  4094. "Options concerning archiving in Org mode."
  4095. :tag "Org Archive"
  4096. :group 'org-structure)
  4097. (defcustom org-archive-location "%s_archive::"
  4098. "The location where subtrees should be archived.
  4099. The value of this variable is a string, consisting of two parts,
  4100. separated by a double-colon. The first part is a filename and
  4101. the second part is a headline.
  4102. When the filename is omitted, archiving happens in the same file.
  4103. %s in the filename will be replaced by the current file
  4104. name (without the directory part). Archiving to a different file
  4105. is useful to keep archived entries from contributing to the
  4106. Org Agenda.
  4107. The archived entries will be filed as subtrees of the specified
  4108. headline. When the headline is omitted, the subtrees are simply
  4109. filed away at the end of the file, as top-level entries. Also in
  4110. the heading you can use %s to represent the file name, this can be
  4111. useful when using the same archive for a number of different files.
  4112. Here are a few examples:
  4113. \"%s_archive::\"
  4114. If the current file is Projects.org, archive in file
  4115. Projects.org_archive, as top-level trees. This is the default.
  4116. \"::* Archived Tasks\"
  4117. Archive in the current file, under the top-level headline
  4118. \"* Archived Tasks\".
  4119. \"~/org/archive.org::\"
  4120. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  4121. \"~/org/archive.org::* From %s\"
  4122. Archive in file ~/org/archive.org (absolute path), under headlines
  4123. \"From FILENAME\" where file name is the current file name.
  4124. \"~/org/datetree.org::datetree/* Finished Tasks\"
  4125. The \"datetree/\" string is special, signifying to archive
  4126. items to the datetree. Items are placed in either the CLOSED
  4127. date of the item, or the current date if there is no CLOSED date.
  4128. The heading will be a subentry to the current date. There doesn't
  4129. need to be a heading, but there always needs to be a slash after
  4130. datetree. For example, to store archived items directly in the
  4131. datetree, use \"~/org/datetree.org::datetree/\".
  4132. \"basement::** Finished Tasks\"
  4133. Archive in file ./basement (relative path), as level 3 trees
  4134. below the level 2 heading \"** Finished Tasks\".
  4135. You may set this option on a per-file basis by adding to the buffer a
  4136. line like
  4137. #+ARCHIVE: basement::** Finished Tasks
  4138. You may also define it locally for a subtree by setting an ARCHIVE property
  4139. in the entry. If such a property is found in an entry, or anywhere up
  4140. the hierarchy, it will be used."
  4141. :group 'org-archive
  4142. :type 'string)
  4143. (defcustom org-agenda-skip-archived-trees t
  4144. "Non-nil means the agenda will skip any items located in archived trees.
  4145. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  4146. variable is no longer recommended, you should leave it at the value t.
  4147. Instead, use the key `v' to cycle the archives-mode in the agenda."
  4148. :group 'org-archive
  4149. :group 'org-agenda-skip
  4150. :type 'boolean)
  4151. (defcustom org-columns-skip-archived-trees t
  4152. "Non-nil means ignore archived trees when creating column view."
  4153. :group 'org-archive
  4154. :group 'org-properties
  4155. :type 'boolean)
  4156. (defcustom org-cycle-open-archived-trees nil
  4157. "Non-nil means `org-cycle' will open archived trees.
  4158. An archived tree is a tree marked with the tag ARCHIVE.
  4159. When nil, archived trees will stay folded. You can still open them with
  4160. normal outline commands like `show-all', but not with the cycling commands."
  4161. :group 'org-archive
  4162. :group 'org-cycle
  4163. :type 'boolean)
  4164. (defcustom org-sparse-tree-open-archived-trees nil
  4165. "Non-nil means sparse tree construction shows matches in archived trees.
  4166. When nil, matches in these trees are highlighted, but the trees are kept in
  4167. collapsed state."
  4168. :group 'org-archive
  4169. :group 'org-sparse-trees
  4170. :type 'boolean)
  4171. (defcustom org-sparse-tree-default-date-type nil
  4172. "The default date type when building a sparse tree.
  4173. When this is nil, a date is a scheduled or a deadline timestamp.
  4174. Otherwise, these types are allowed:
  4175. all: all timestamps
  4176. active: only active timestamps (<...>)
  4177. inactive: only inactive timestamps ([...])
  4178. scheduled: only scheduled timestamps
  4179. deadline: only deadline timestamps"
  4180. :type '(choice (const :tag "Scheduled or deadline" nil)
  4181. (const :tag "All timestamps" all)
  4182. (const :tag "Only active timestamps" active)
  4183. (const :tag "Only inactive timestamps" inactive)
  4184. (const :tag "Only scheduled timestamps" scheduled)
  4185. (const :tag "Only deadline timestamps" deadline)
  4186. (const :tag "Only closed timestamps" closed))
  4187. :version "26.1"
  4188. :package-version '(Org . "8.3")
  4189. :group 'org-sparse-trees)
  4190. (defun org-cycle-hide-archived-subtrees (state)
  4191. "Re-hide all archived subtrees after a visibility state change.
  4192. STATE should be one of the symbols listed in the docstring of
  4193. `org-cycle-hook'."
  4194. (when (and (not org-cycle-open-archived-trees)
  4195. (not (memq state '(overview folded))))
  4196. (save-excursion
  4197. (let* ((globalp (memq state '(contents all)))
  4198. (beg (if globalp (point-min) (point)))
  4199. (end (if globalp (point-max) (org-end-of-subtree t))))
  4200. (org-hide-archived-subtrees beg end)
  4201. (goto-char beg)
  4202. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  4203. (message "%s" (substitute-command-keys
  4204. "Subtree is archived and stays closed. Use \
  4205. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  4206. (defun org-force-cycle-archived ()
  4207. "Cycle subtree even if it is archived."
  4208. (interactive)
  4209. (setq this-command 'org-cycle)
  4210. (let ((org-cycle-open-archived-trees t))
  4211. (call-interactively 'org-cycle)))
  4212. (defun org-hide-archived-subtrees (beg end)
  4213. "Re-hide all archived subtrees after a visibility state change."
  4214. (org-with-wide-buffer
  4215. (let ((case-fold-search nil)
  4216. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  4217. (goto-char beg)
  4218. ;; Include headline point is currently on.
  4219. (beginning-of-line)
  4220. (while (and (< (point) end) (re-search-forward re end t))
  4221. (when (member org-archive-tag (org-get-tags))
  4222. (org-flag-subtree t)
  4223. (org-end-of-subtree t))))))
  4224. (declare-function outline-end-of-heading "outline" ())
  4225. (declare-function outline-flag-region "outline" (from to flag))
  4226. (defun org-flag-subtree (flag)
  4227. (save-excursion
  4228. (org-back-to-heading t)
  4229. (outline-end-of-heading)
  4230. (outline-flag-region (point)
  4231. (progn (org-end-of-subtree t) (point))
  4232. flag)))
  4233. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  4234. ;; Declare Column View Code
  4235. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  4236. (declare-function org-columns-compute "org-colview" (property))
  4237. ;; Declare ID code
  4238. (declare-function org-id-store-link "org-id")
  4239. (declare-function org-id-locations-load "org-id")
  4240. (declare-function org-id-locations-save "org-id")
  4241. (defvar org-id-track-globally)
  4242. ;;; Variables for pre-computed regular expressions, all buffer local
  4243. (defvar-local org-todo-regexp nil
  4244. "Matches any of the TODO state keywords.
  4245. Since TODO keywords are case-sensitive, `case-fold-search' is
  4246. expected to be bound to nil when matching against this regexp.")
  4247. (defvar-local org-not-done-regexp nil
  4248. "Matches any of the TODO state keywords except the last one.
  4249. Since TODO keywords are case-sensitive, `case-fold-search' is
  4250. expected to be bound to nil when matching against this regexp.")
  4251. (defvar-local org-not-done-heading-regexp nil
  4252. "Matches a TODO headline that is not done.
  4253. Since TODO keywords are case-sensitive, `case-fold-search' is
  4254. expected to be bound to nil when matching against this regexp.")
  4255. (defvar-local org-todo-line-regexp nil
  4256. "Matches a headline and puts TODO state into group 2 if present.
  4257. Since TODO keywords are case-sensitive, `case-fold-search' is
  4258. expected to be bound to nil when matching against this regexp.")
  4259. (defvar-local org-complex-heading-regexp nil
  4260. "Matches a headline and puts everything into groups:
  4261. group 1: Stars
  4262. group 2: The TODO keyword, maybe
  4263. group 3: Priority cookie
  4264. group 4: True headline
  4265. group 5: Tags
  4266. Since TODO keywords are case-sensitive, `case-fold-search' is
  4267. expected to be bound to nil when matching against this regexp.")
  4268. (defvar-local org-complex-heading-regexp-format nil
  4269. "Printf format to make regexp to match an exact headline.
  4270. This regexp will match the headline of any node which has the
  4271. exact headline text that is put into the format, but may have any
  4272. TODO state, priority and tags.")
  4273. (defvar-local org-todo-line-tags-regexp nil
  4274. "Matches a headline and puts TODO state into group 2 if present.
  4275. Also put tags into group 4 if tags are present.")
  4276. (defconst org-plain-time-of-day-regexp
  4277. (concat
  4278. "\\(\\<[012]?[0-9]"
  4279. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4280. "\\(--?"
  4281. "\\(\\<[012]?[0-9]"
  4282. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4283. "\\)?")
  4284. "Regular expression to match a plain time or time range.
  4285. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4286. groups carry important information:
  4287. 0 the full match
  4288. 1 the first time, range or not
  4289. 8 the second time, if it is a range.")
  4290. (defconst org-plain-time-extension-regexp
  4291. (concat
  4292. "\\(\\<[012]?[0-9]"
  4293. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  4294. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  4295. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  4296. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  4297. groups carry important information:
  4298. 0 the full match
  4299. 7 hours of duration
  4300. 9 minutes of duration")
  4301. (defconst org-stamp-time-of-day-regexp
  4302. (concat
  4303. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  4304. "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
  4305. "\\(--?"
  4306. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  4307. "Regular expression to match a timestamp time or time range.
  4308. After a match, the following groups carry important information:
  4309. 0 the full match
  4310. 1 date plus weekday, for back referencing to make sure both times are on the same day
  4311. 2 the first time, range or not
  4312. 4 the second time, if it is a range.")
  4313. (defconst org-startup-options
  4314. '(("fold" org-startup-folded t)
  4315. ("overview" org-startup-folded t)
  4316. ("nofold" org-startup-folded nil)
  4317. ("showall" org-startup-folded nil)
  4318. ("showeverything" org-startup-folded showeverything)
  4319. ("content" org-startup-folded content)
  4320. ("indent" org-startup-indented t)
  4321. ("noindent" org-startup-indented nil)
  4322. ("hidestars" org-hide-leading-stars t)
  4323. ("showstars" org-hide-leading-stars nil)
  4324. ("odd" org-odd-levels-only t)
  4325. ("oddeven" org-odd-levels-only nil)
  4326. ("align" org-startup-align-all-tables t)
  4327. ("noalign" org-startup-align-all-tables nil)
  4328. ("inlineimages" org-startup-with-inline-images t)
  4329. ("noinlineimages" org-startup-with-inline-images nil)
  4330. ("latexpreview" org-startup-with-latex-preview t)
  4331. ("nolatexpreview" org-startup-with-latex-preview nil)
  4332. ("customtime" org-display-custom-times t)
  4333. ("logdone" org-log-done time)
  4334. ("lognotedone" org-log-done note)
  4335. ("nologdone" org-log-done nil)
  4336. ("lognoteclock-out" org-log-note-clock-out t)
  4337. ("nolognoteclock-out" org-log-note-clock-out nil)
  4338. ("logrepeat" org-log-repeat state)
  4339. ("lognoterepeat" org-log-repeat note)
  4340. ("logdrawer" org-log-into-drawer t)
  4341. ("nologdrawer" org-log-into-drawer nil)
  4342. ("logstatesreversed" org-log-states-order-reversed t)
  4343. ("nologstatesreversed" org-log-states-order-reversed nil)
  4344. ("nologrepeat" org-log-repeat nil)
  4345. ("logreschedule" org-log-reschedule time)
  4346. ("lognotereschedule" org-log-reschedule note)
  4347. ("nologreschedule" org-log-reschedule nil)
  4348. ("logredeadline" org-log-redeadline time)
  4349. ("lognoteredeadline" org-log-redeadline note)
  4350. ("nologredeadline" org-log-redeadline nil)
  4351. ("logrefile" org-log-refile time)
  4352. ("lognoterefile" org-log-refile note)
  4353. ("nologrefile" org-log-refile nil)
  4354. ("fninline" org-footnote-define-inline t)
  4355. ("nofninline" org-footnote-define-inline nil)
  4356. ("fnlocal" org-footnote-section nil)
  4357. ("fnauto" org-footnote-auto-label t)
  4358. ("fnprompt" org-footnote-auto-label nil)
  4359. ("fnconfirm" org-footnote-auto-label confirm)
  4360. ("fnplain" org-footnote-auto-label plain)
  4361. ("fnadjust" org-footnote-auto-adjust t)
  4362. ("nofnadjust" org-footnote-auto-adjust nil)
  4363. ("constcgs" constants-unit-system cgs)
  4364. ("constSI" constants-unit-system SI)
  4365. ("noptag" org-tag-persistent-alist nil)
  4366. ("hideblocks" org-hide-block-startup t)
  4367. ("nohideblocks" org-hide-block-startup nil)
  4368. ("beamer" org-startup-with-beamer-mode t)
  4369. ("entitiespretty" org-pretty-entities t)
  4370. ("entitiesplain" org-pretty-entities nil))
  4371. "Variable associated with STARTUP options for org-mode.
  4372. Each element is a list of three items: the startup options (as written
  4373. in the #+STARTUP line), the corresponding variable, and the value to set
  4374. this variable to if the option is found. An optional forth element PUSH
  4375. means to push this value onto the list in the variable.")
  4376. (defcustom org-group-tags t
  4377. "When non-nil (the default), use group tags.
  4378. This can be turned on/off through `org-toggle-tags-groups'."
  4379. :group 'org-tags
  4380. :group 'org-startup
  4381. :type 'boolean)
  4382. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  4383. (defun org-toggle-tags-groups ()
  4384. "Toggle support for group tags.
  4385. Support for group tags is controlled by the option
  4386. `org-group-tags', which is non-nil by default."
  4387. (interactive)
  4388. (setq org-group-tags (not org-group-tags))
  4389. (cond ((and (derived-mode-p 'org-agenda-mode)
  4390. org-group-tags)
  4391. (org-agenda-redo))
  4392. ((derived-mode-p 'org-mode)
  4393. (let ((org-inhibit-startup t)) (org-mode))))
  4394. (message "Groups tags support has been turned %s"
  4395. (if org-group-tags "on" "off")))
  4396. (defun org-set-regexps-and-options (&optional tags-only)
  4397. "Precompute regular expressions used in the current buffer.
  4398. When optional argument TAGS-ONLY is non-nil, only compute tags
  4399. related expressions."
  4400. (when (derived-mode-p 'org-mode)
  4401. (let ((alist (org--setup-collect-keywords
  4402. (org-make-options-regexp
  4403. (append '("FILETAGS" "TAGS" "SETUPFILE")
  4404. (and (not tags-only)
  4405. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  4406. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  4407. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
  4408. ;; Startup options. Get this early since it does change
  4409. ;; behavior for other options (e.g., tags).
  4410. (let ((startup (cdr (assq 'startup alist))))
  4411. (dolist (option startup)
  4412. (let ((entry (assoc-string option org-startup-options t)))
  4413. (when entry
  4414. (let ((var (nth 1 entry))
  4415. (val (nth 2 entry)))
  4416. (if (not (nth 3 entry)) (set (make-local-variable var) val)
  4417. (unless (listp (symbol-value var))
  4418. (set (make-local-variable var) nil))
  4419. (add-to-list var val)))))))
  4420. (setq-local org-file-tags
  4421. (mapcar #'org-add-prop-inherited
  4422. (cdr (assq 'filetags alist))))
  4423. (setq org-current-tag-alist
  4424. (append org-tag-persistent-alist
  4425. (let ((tags (cdr (assq 'tags alist))))
  4426. (if tags (org-tag-string-to-alist tags)
  4427. org-tag-alist))))
  4428. (setq org-tag-groups-alist
  4429. (org-tag-alist-to-groups org-current-tag-alist))
  4430. (unless tags-only
  4431. ;; File properties.
  4432. (setq-local org-file-properties (cdr (assq 'property alist)))
  4433. ;; Archive location.
  4434. (let ((archive (cdr (assq 'archive alist))))
  4435. (when archive (setq-local org-archive-location archive)))
  4436. ;; Category.
  4437. (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
  4438. (when cat
  4439. (setq-local org-category (intern cat))
  4440. (setq-local org-file-properties
  4441. (org--update-property-plist
  4442. "CATEGORY" cat org-file-properties))))
  4443. ;; Columns.
  4444. (let ((column (cdr (assq 'columns alist))))
  4445. (when column (setq-local org-columns-default-format column)))
  4446. ;; Constants.
  4447. (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
  4448. ;; Link abbreviations.
  4449. (let ((links (cdr (assq 'link alist))))
  4450. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  4451. ;; Priorities.
  4452. (let ((priorities (cdr (assq 'priorities alist))))
  4453. (when priorities
  4454. (setq-local org-highest-priority (nth 0 priorities))
  4455. (setq-local org-lowest-priority (nth 1 priorities))
  4456. (setq-local org-default-priority (nth 2 priorities))))
  4457. ;; Scripts.
  4458. (let ((scripts (assq 'scripts alist)))
  4459. (when scripts
  4460. (setq-local org-use-sub-superscripts (cdr scripts))))
  4461. ;; TODO keywords.
  4462. (setq-local org-todo-kwd-alist nil)
  4463. (setq-local org-todo-key-alist nil)
  4464. (setq-local org-todo-key-trigger nil)
  4465. (setq-local org-todo-keywords-1 nil)
  4466. (setq-local org-done-keywords nil)
  4467. (setq-local org-todo-heads nil)
  4468. (setq-local org-todo-sets nil)
  4469. (setq-local org-todo-log-states nil)
  4470. (let ((todo-sequences
  4471. (or (nreverse (cdr (assq 'todo alist)))
  4472. (let ((d (default-value 'org-todo-keywords)))
  4473. (if (not (stringp (car d))) d
  4474. ;; XXX: Backward compatibility code.
  4475. (list (cons org-todo-interpretation d)))))))
  4476. (dolist (sequence todo-sequences)
  4477. (let* ((sequence (or (run-hook-with-args-until-success
  4478. 'org-todo-setup-filter-hook sequence)
  4479. sequence))
  4480. (sequence-type (car sequence))
  4481. (keywords (cdr sequence))
  4482. (sep (member "|" keywords))
  4483. names alist)
  4484. (dolist (k (remove "|" keywords))
  4485. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  4486. k)
  4487. (error "Invalid TODO keyword %s" k))
  4488. (let ((name (match-string 1 k))
  4489. (key (match-string 2 k))
  4490. (log (org-extract-log-state-settings k)))
  4491. (push name names)
  4492. (push (cons name (and key (string-to-char key))) alist)
  4493. (when log (push log org-todo-log-states))))
  4494. (let* ((names (nreverse names))
  4495. (done (if sep (org-remove-keyword-keys (cdr sep))
  4496. (last names)))
  4497. (head (car names))
  4498. (tail (list sequence-type head (car done) (org-last done))))
  4499. (add-to-list 'org-todo-heads head 'append)
  4500. (push names org-todo-sets)
  4501. (setq org-done-keywords (append org-done-keywords done nil))
  4502. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  4503. (setq org-todo-key-alist
  4504. (append org-todo-key-alist
  4505. (and alist
  4506. (append '((:startgroup))
  4507. (nreverse alist)
  4508. '((:endgroup))))))
  4509. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  4510. (setq org-todo-sets (nreverse org-todo-sets)
  4511. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  4512. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  4513. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  4514. ;; Compute the regular expressions and other local variables.
  4515. ;; Using `org-outline-regexp-bol' would complicate them much,
  4516. ;; because of the fixed white space at the end of that string.
  4517. (unless org-done-keywords
  4518. (setq org-done-keywords
  4519. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  4520. (setq org-not-done-keywords
  4521. (org-delete-all org-done-keywords
  4522. (copy-sequence org-todo-keywords-1))
  4523. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  4524. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  4525. org-not-done-heading-regexp
  4526. (format org-heading-keyword-regexp-format org-not-done-regexp)
  4527. org-todo-line-regexp
  4528. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  4529. org-complex-heading-regexp
  4530. (concat "^\\(\\*+\\)"
  4531. "\\(?: +" org-todo-regexp "\\)?"
  4532. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4533. "\\(?: +\\(.*?\\)\\)??"
  4534. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  4535. "[ \t]*$")
  4536. org-complex-heading-regexp-format
  4537. (concat "^\\(\\*+\\)"
  4538. "\\(?: +" org-todo-regexp "\\)?"
  4539. "\\(?: +\\(\\[#.\\]\\)\\)?"
  4540. "\\(?: +"
  4541. ;; Stats cookies can be stuck to body.
  4542. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  4543. "\\(%s\\)"
  4544. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  4545. "\\)"
  4546. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  4547. "[ \t]*$")
  4548. org-todo-line-tags-regexp
  4549. (concat "^\\(\\*+\\)"
  4550. "\\(?: +" org-todo-regexp "\\)?"
  4551. "\\(?: +\\(.*?\\)\\)??"
  4552. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  4553. "[ \t]*$"))
  4554. (org-compute-latex-and-related-regexp)))))
  4555. (defun org--setup-collect-keywords (regexp &optional files alist)
  4556. "Return setup keywords values as an alist.
  4557. REGEXP matches a subset of setup keywords. FILES is a list of
  4558. file names already visited. It is used to avoid circular setup
  4559. files. ALIST, when non-nil, is the alist computed so far.
  4560. Return value contains the following keys: `archive', `category',
  4561. `columns', `constants', `filetags', `link', `priorities',
  4562. `property', `scripts', `startup', `tags' and `todo'."
  4563. (org-with-wide-buffer
  4564. (goto-char (point-min))
  4565. (let ((case-fold-search t))
  4566. (while (re-search-forward regexp nil t)
  4567. (let ((element (org-element-at-point)))
  4568. (when (eq (org-element-type element) 'keyword)
  4569. (let ((key (org-element-property :key element))
  4570. (value (org-element-property :value element)))
  4571. (cond
  4572. ((equal key "ARCHIVE")
  4573. (when (org-string-nw-p value)
  4574. (push (cons 'archive value) alist)))
  4575. ((equal key "CATEGORY") (push (cons 'category value) alist))
  4576. ((equal key "COLUMNS") (push (cons 'columns value) alist))
  4577. ((equal key "CONSTANTS")
  4578. (let* ((constants (assq 'constants alist))
  4579. (store (cdr constants)))
  4580. (dolist (pair (org-split-string value))
  4581. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
  4582. pair)
  4583. (let* ((name (match-string 1 pair))
  4584. (value (match-string 2 pair))
  4585. (old (assoc name store)))
  4586. (if old (setcdr old value)
  4587. (push (cons name value) store)))))
  4588. (if constants (setcdr constants store)
  4589. (push (cons 'constants store) alist))))
  4590. ((equal key "FILETAGS")
  4591. (when (org-string-nw-p value)
  4592. (let ((old (assq 'filetags alist))
  4593. (new (apply #'nconc
  4594. (mapcar (lambda (x) (org-split-string x ":"))
  4595. (org-split-string value)))))
  4596. (if old (setcdr old (append new (cdr old)))
  4597. (push (cons 'filetags new) alist)))))
  4598. ((equal key "LINK")
  4599. (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  4600. (let ((links (assq 'link alist))
  4601. (pair (cons (match-string-no-properties 1 value)
  4602. (match-string-no-properties 2 value))))
  4603. (if links (push pair (cdr links))
  4604. (push (list 'link pair) alist)))))
  4605. ((equal key "OPTIONS")
  4606. (when (and (org-string-nw-p value)
  4607. (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
  4608. (push (cons 'scripts (read (match-string 1 value))) alist)))
  4609. ((equal key "PRIORITIES")
  4610. (push (cons 'priorities
  4611. (let ((prio (org-split-string value)))
  4612. (if (< (length prio) 3) '(?A ?C ?B)
  4613. (mapcar #'string-to-char prio))))
  4614. alist))
  4615. ((equal key "PROPERTY")
  4616. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  4617. (let* ((property (assq 'property alist))
  4618. (value (org--update-property-plist
  4619. (match-string-no-properties 1 value)
  4620. (match-string-no-properties 2 value)
  4621. (cdr property))))
  4622. (if property (setcdr property value)
  4623. (push (cons 'property value) alist)))))
  4624. ((equal key "STARTUP")
  4625. (let ((startup (assq 'startup alist)))
  4626. (if startup
  4627. (setcdr startup
  4628. (append (cdr startup) (org-split-string value)))
  4629. (push (cons 'startup (org-split-string value)) alist))))
  4630. ((equal key "TAGS")
  4631. (let ((tag-cell (assq 'tags alist)))
  4632. (if tag-cell
  4633. (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
  4634. (push (cons 'tags value) alist))))
  4635. ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
  4636. (let ((todo (assq 'todo alist))
  4637. (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
  4638. (org-split-string value))))
  4639. (if todo (push value (cdr todo))
  4640. (push (list 'todo value) alist))))
  4641. ((equal key "SETUPFILE")
  4642. (unless buffer-read-only ; Do not check in Gnus messages.
  4643. (let ((f (and (org-string-nw-p value)
  4644. (expand-file-name
  4645. (org-unbracket-string "\"" "\"" value)))))
  4646. (when (and f (file-readable-p f) (not (member f files)))
  4647. (with-temp-buffer
  4648. (setq default-directory (file-name-directory f))
  4649. (insert-file-contents f)
  4650. (setq alist
  4651. ;; Fake Org mode to benefit from cache
  4652. ;; without recurring needlessly.
  4653. (let ((major-mode 'org-mode))
  4654. (org--setup-collect-keywords
  4655. regexp (cons f files) alist)))))))))))))))
  4656. alist)
  4657. (defun org-tag-string-to-alist (s)
  4658. "Return tag alist associated to string S.
  4659. S is a value for TAGS keyword or produced with
  4660. `org-tag-alist-to-string'. Return value is an alist suitable for
  4661. `org-tag-alist' or `org-tag-persistent-alist'."
  4662. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  4663. (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
  4664. "\\|{.+?}\\)" ; regular expression
  4665. "\\(?:(\\(.\\))\\)?\\'"))
  4666. alist group-flag)
  4667. (dolist (tokens lines (cdr (nreverse alist)))
  4668. (push '(:newline) alist)
  4669. (while tokens
  4670. (let ((token (pop tokens)))
  4671. (pcase token
  4672. ("{"
  4673. (push '(:startgroup) alist)
  4674. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4675. ("}"
  4676. (push '(:endgroup) alist)
  4677. (setq group-flag nil))
  4678. ("["
  4679. (push '(:startgrouptag) alist)
  4680. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  4681. ("]"
  4682. (push '(:endgrouptag) alist)
  4683. (setq group-flag nil))
  4684. (":"
  4685. (push '(:grouptags) alist))
  4686. ((guard (string-match tag-re token))
  4687. (let ((tag (match-string 1 token))
  4688. (key (and (match-beginning 2)
  4689. (string-to-char (match-string 2 token)))))
  4690. ;; Push all tags in groups, no matter if they already
  4691. ;; appear somewhere else in the list.
  4692. (when (or group-flag (not (assoc tag alist)))
  4693. (push (cons tag key) alist))))))))))
  4694. (defun org-tag-alist-to-string (alist &optional skip-key)
  4695. "Return tag string associated to ALIST.
  4696. ALIST is an alist, as defined in `org-tag-alist' or
  4697. `org-tag-persistent-alist', or produced with
  4698. `org-tag-string-to-alist'.
  4699. Return value is a string suitable as a value for \"TAGS\"
  4700. keyword.
  4701. When optional argument SKIP-KEY is non-nil, skip selection keys
  4702. next to tags."
  4703. (mapconcat (lambda (token)
  4704. (pcase token
  4705. (`(:startgroup) "{")
  4706. (`(:endgroup) "}")
  4707. (`(:startgrouptag) "[")
  4708. (`(:endgrouptag) "]")
  4709. (`(:grouptags) ":")
  4710. (`(:newline) "\\n")
  4711. ((and
  4712. (guard (not skip-key))
  4713. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4714. (format "%s(%c)" tag key))
  4715. (`(,(and tag (pred stringp)) . ,_) tag)
  4716. (_ (user-error "Invalid tag token: %S" token))))
  4717. alist
  4718. " "))
  4719. (defun org-tag-alist-to-groups (alist)
  4720. "Return group alist from tag ALIST.
  4721. ALIST is an alist, as defined in `org-tag-alist' or
  4722. `org-tag-persistent-alist', or produced with
  4723. `org-tag-string-to-alist'. Return value is an alist following
  4724. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4725. a string, summarizing TAGS, as a list of strings."
  4726. (let (groups group-status current-group)
  4727. (dolist (token alist (nreverse groups))
  4728. (pcase token
  4729. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4730. (`(,(or :endgroup :endgrouptag))
  4731. (when (eq group-status 'append)
  4732. (push (nreverse current-group) groups))
  4733. (setq group-status nil))
  4734. (`(:grouptags) (setq group-status 'append))
  4735. ((and `(,tag . ,_) (guard group-status))
  4736. (if (eq group-status 'append) (push tag current-group)
  4737. (setq current-group (list tag))))
  4738. (_ nil)))))
  4739. (defun org-file-contents (file &optional noerror)
  4740. "Return the contents of FILE, as a string."
  4741. (if (and file (file-readable-p file))
  4742. (with-temp-buffer
  4743. (insert-file-contents file)
  4744. (buffer-string))
  4745. (funcall (if noerror 'message 'error)
  4746. "Cannot read file \"%s\"%s"
  4747. file
  4748. (let ((from (buffer-file-name (buffer-base-buffer))))
  4749. (if from (concat " (referenced in file \"" from "\")") "")))))
  4750. (defun org-extract-log-state-settings (x)
  4751. "Extract the log state setting from a TODO keyword string.
  4752. This will extract info from a string like \"WAIT(w@/!)\"."
  4753. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4754. (let ((kw (match-string 1 x))
  4755. (log1 (and (match-end 3) (match-string 3 x)))
  4756. (log2 (and (match-end 4) (match-string 4 x))))
  4757. (and (or log1 log2)
  4758. (list kw
  4759. (and log1 (if (equal log1 "!") 'time 'note))
  4760. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4761. (defun org-remove-keyword-keys (list)
  4762. "Remove a pair of parenthesis at the end of each string in LIST."
  4763. (mapcar (lambda (x)
  4764. (if (string-match "(.*)$" x)
  4765. (substring x 0 (match-beginning 0))
  4766. x))
  4767. list))
  4768. (defun org-assign-fast-keys (alist)
  4769. "Assign fast keys to a keyword-key alist.
  4770. Respect keys that are already there."
  4771. (let (new e (alt ?0))
  4772. (while (setq e (pop alist))
  4773. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4774. (cdr e)) ;; Key already assigned.
  4775. (push e new)
  4776. (let ((clist (string-to-list (downcase (car e))))
  4777. (used (append new alist)))
  4778. (when (= (car clist) ?@)
  4779. (pop clist))
  4780. (while (and clist (rassoc (car clist) used))
  4781. (pop clist))
  4782. (unless clist
  4783. (while (rassoc alt used)
  4784. (cl-incf alt)))
  4785. (push (cons (car e) (or (car clist) alt)) new))))
  4786. (nreverse new)))
  4787. ;;; Some variables used in various places
  4788. (defvar org-window-configuration nil
  4789. "Used in various places to store a window configuration.")
  4790. (defvar org-selected-window nil
  4791. "Used in various places to store a window configuration.")
  4792. (defvar org-finish-function nil
  4793. "Function to be called when `C-c C-c' is used.
  4794. This is for getting out of special buffers like capture.")
  4795. (defvar org-last-state)
  4796. ;; Defined somewhere in this file, but used before definition.
  4797. (defvar org-entities) ;; defined in org-entities.el
  4798. (defvar org-struct-menu)
  4799. (defvar org-org-menu)
  4800. (defvar org-tbl-menu)
  4801. ;;;; Define the Org mode
  4802. ;; We use a before-change function to check if a table might need
  4803. ;; an update.
  4804. (defvar org-table-may-need-update t
  4805. "Indicates that a table might need an update.
  4806. This variable is set by `org-before-change-function'.
  4807. `org-table-align' sets it back to nil.")
  4808. (defun org-before-change-function (_beg _end)
  4809. "Every change indicates that a table might need an update."
  4810. (setq org-table-may-need-update t))
  4811. (defvar org-mode-map)
  4812. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4813. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4814. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4815. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4816. (defvar org-table-buffer-is-an nil)
  4817. (defvar bidi-paragraph-direction)
  4818. (defvar buffer-face-mode-face)
  4819. (require 'outline)
  4820. ;; Other stuff we need.
  4821. (require 'time-date)
  4822. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4823. (require 'easymenu)
  4824. (autoload 'easy-menu-add "easymenu")
  4825. (require 'overlay)
  4826. ;; (require 'org-macs) moved higher up in the file before it is first used
  4827. (require 'org-entities)
  4828. ;; (require 'org-compat) moved higher up in the file before it is first used
  4829. (require 'org-faces)
  4830. (require 'org-list)
  4831. (require 'org-pcomplete)
  4832. (require 'org-src)
  4833. (require 'org-footnote)
  4834. (require 'org-macro)
  4835. ;; babel
  4836. (require 'ob)
  4837. ;;;###autoload
  4838. (define-derived-mode org-mode outline-mode "Org"
  4839. "Outline-based notes management and organizer, alias
  4840. \"Carsten's outline-mode for keeping track of everything.\"
  4841. Org mode develops organizational tasks around a NOTES file which
  4842. contains information about projects as plain text. Org mode is
  4843. implemented on top of Outline mode, which is ideal to keep the content
  4844. of large files well structured. It supports ToDo items, deadlines and
  4845. time stamps, which magically appear in the diary listing of the Emacs
  4846. calendar. Tables are easily created with a built-in table editor.
  4847. Plain text URL-like links connect to websites, emails (VM), Usenet
  4848. messages (Gnus), BBDB entries, and any files related to the project.
  4849. For printing and sharing of notes, an Org file (or a part of it)
  4850. can be exported as a structured ASCII or HTML file.
  4851. The following commands are available:
  4852. \\{org-mode-map}"
  4853. ;; Get rid of Outline menus, they are not needed
  4854. ;; Need to do this here because define-derived-mode sets up
  4855. ;; the keymap so late. Still, it is a waste to call this each time
  4856. ;; we switch another buffer into Org mode.
  4857. (define-key org-mode-map [menu-bar headings] 'undefined)
  4858. (define-key org-mode-map [menu-bar hide] 'undefined)
  4859. (define-key org-mode-map [menu-bar show] 'undefined)
  4860. (org-load-modules-maybe)
  4861. (org-install-agenda-files-menu)
  4862. (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
  4863. (add-to-invisibility-spec '(org-cwidth))
  4864. (add-to-invisibility-spec '(org-hide-block . t))
  4865. (setq-local outline-regexp org-outline-regexp)
  4866. (setq-local outline-level 'org-outline-level)
  4867. (setq bidi-paragraph-direction 'left-to-right)
  4868. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4869. (unless org-display-table
  4870. (setq org-display-table (make-display-table)))
  4871. (set-display-table-slot
  4872. org-display-table 4
  4873. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4874. org-ellipsis)))
  4875. (setq buffer-display-table org-display-table))
  4876. (org-set-regexps-and-options)
  4877. (org-set-font-lock-defaults)
  4878. (when (and org-tag-faces (not org-tags-special-faces-re))
  4879. ;; tag faces set outside customize.... force initialization.
  4880. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4881. ;; Calc embedded
  4882. (setq-local calc-embedded-open-mode "# ")
  4883. ;; Modify a few syntax entries
  4884. (modify-syntax-entry ?@ "w")
  4885. (modify-syntax-entry ?\" "\"")
  4886. (modify-syntax-entry ?\\ "_")
  4887. (modify-syntax-entry ?~ "_")
  4888. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4889. ;; Activate before-change-function
  4890. (setq-local org-table-may-need-update t)
  4891. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4892. ;; Check for running clock before killing a buffer
  4893. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4894. ;; Initialize macros templates.
  4895. (org-macro-initialize-templates)
  4896. ;; Initialize radio targets.
  4897. (org-update-radio-target-regexp)
  4898. ;; Indentation.
  4899. (setq-local indent-line-function 'org-indent-line)
  4900. (setq-local indent-region-function 'org-indent-region)
  4901. ;; Filling and auto-filling.
  4902. (org-setup-filling)
  4903. ;; Comments.
  4904. (org-setup-comments-handling)
  4905. ;; Initialize cache.
  4906. (org-element-cache-reset)
  4907. ;; Beginning/end of defun
  4908. (setq-local beginning-of-defun-function 'org-backward-element)
  4909. (setq-local end-of-defun-function
  4910. (lambda ()
  4911. (if (not (org-at-heading-p))
  4912. (org-forward-element)
  4913. (org-forward-element)
  4914. (forward-char -1))))
  4915. ;; Next error for sparse trees
  4916. (setq-local next-error-function 'org-occur-next-match)
  4917. ;; Make sure dependence stuff works reliably, even for users who set it
  4918. ;; too late :-(
  4919. (if org-enforce-todo-dependencies
  4920. (add-hook 'org-blocker-hook
  4921. 'org-block-todo-from-children-or-siblings-or-parent)
  4922. (remove-hook 'org-blocker-hook
  4923. 'org-block-todo-from-children-or-siblings-or-parent))
  4924. (if org-enforce-todo-checkbox-dependencies
  4925. (add-hook 'org-blocker-hook
  4926. 'org-block-todo-from-checkboxes)
  4927. (remove-hook 'org-blocker-hook
  4928. 'org-block-todo-from-checkboxes))
  4929. ;; Align options lines
  4930. (setq-local
  4931. align-mode-rules-list
  4932. '((org-in-buffer-settings
  4933. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4934. (modes . '(org-mode)))))
  4935. ;; Imenu
  4936. (setq-local imenu-create-index-function 'org-imenu-get-tree)
  4937. ;; Make isearch reveal context
  4938. (setq-local outline-isearch-open-invisible-function
  4939. (lambda (&rest _) (org-show-context 'isearch)))
  4940. ;; Setup the pcomplete hooks
  4941. (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
  4942. (setq-local pcomplete-command-name-function 'org-command-at-point)
  4943. (setq-local pcomplete-default-completion-function 'ignore)
  4944. (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
  4945. (setq-local pcomplete-termination-string "")
  4946. (setq-local buffer-face-mode-face 'org-default)
  4947. ;; If empty file that did not turn on Org mode automatically, make
  4948. ;; it to.
  4949. (when (and org-insert-mode-line-in-empty-file
  4950. (called-interactively-p 'any)
  4951. (= (point-min) (point-max)))
  4952. (insert "# -*- mode: org -*-\n\n"))
  4953. (unless org-inhibit-startup
  4954. (org-unmodified
  4955. (when org-startup-with-beamer-mode (org-beamer-mode))
  4956. (when org-startup-align-all-tables
  4957. (org-table-map-tables #'org-table-align t))
  4958. (when org-startup-with-inline-images (org-display-inline-images))
  4959. (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
  4960. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4961. (when org-startup-truncated (setq truncate-lines t))
  4962. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
  4963. (org-refresh-effort-properties)))
  4964. ;; Try to set `org-hide' face correctly.
  4965. (let ((foreground (org-find-invisible-foreground)))
  4966. (when foreground
  4967. (set-face-foreground 'org-hide foreground))))
  4968. ;; Update `customize-package-emacs-version-alist'
  4969. (add-to-list 'customize-package-emacs-version-alist
  4970. '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
  4971. ("7.8.11" . "24.1") ("7.9.4" . "24.3")
  4972. ("8.2.6" . "24.4") ("8.2.10" . "24.5")
  4973. ("9.0" . "26.1")))
  4974. (defvar org-mode-transpose-word-syntax-table
  4975. (let ((st (make-syntax-table text-mode-syntax-table)))
  4976. (dolist (c org-emphasis-alist st)
  4977. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4978. (when (fboundp 'abbrev-table-put)
  4979. (abbrev-table-put org-mode-abbrev-table
  4980. :parents (list text-mode-abbrev-table)))
  4981. (defun org-find-invisible-foreground ()
  4982. (let ((candidates (remove
  4983. "unspecified-bg"
  4984. (nconc
  4985. (list (face-background 'default)
  4986. (face-background 'org-default))
  4987. (mapcar
  4988. (lambda (alist)
  4989. (when (boundp alist)
  4990. (cdr (assq 'background-color (symbol-value alist)))))
  4991. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4992. (list (face-foreground 'org-hide))))))
  4993. (car (remove nil candidates))))
  4994. (defun org-current-time (&optional rounding-minutes past)
  4995. "Current time, possibly rounded to ROUNDING-MINUTES.
  4996. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4997. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4998. the rounding returns a past time."
  4999. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  5000. (car org-time-stamp-rounding-minutes)))
  5001. (time (decode-time)) res)
  5002. (if (< r 1)
  5003. (current-time)
  5004. (setq res
  5005. (apply 'encode-time
  5006. (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
  5007. (nthcdr 2 time))))
  5008. (if (and past (< (float-time (time-subtract (current-time) res)) 0))
  5009. (seconds-to-time (- (float-time res) (* r 60)))
  5010. res))))
  5011. (defun org-today ()
  5012. "Return today date, considering `org-extend-today-until'."
  5013. (time-to-days
  5014. (time-subtract (current-time)
  5015. (list 0 (* 3600 org-extend-today-until) 0))))
  5016. ;;;; Font-Lock stuff, including the activators
  5017. (defvar org-mouse-map (make-sparse-keymap))
  5018. (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
  5019. (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
  5020. (when org-mouse-1-follows-link
  5021. (org-defkey org-mouse-map [follow-link] 'mouse-face))
  5022. (when org-tab-follows-link
  5023. (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
  5024. (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
  5025. (require 'font-lock)
  5026. (defconst org-non-link-chars "]\t\n\r<>")
  5027. (defvar org-link-types-re nil
  5028. "Matches a link that has a url-like prefix like \"http:\"")
  5029. (defvar org-link-re-with-space nil
  5030. "Matches a link with spaces, optional angular brackets around it.")
  5031. (defvar org-link-re-with-space2 nil
  5032. "Matches a link with spaces, optional angular brackets around it.")
  5033. (defvar org-link-re-with-space3 nil
  5034. "Matches a link with spaces, only for internal part in bracket links.")
  5035. (defvar org-angle-link-re nil
  5036. "Matches link with angular brackets, spaces are allowed.")
  5037. (defvar org-plain-link-re nil
  5038. "Matches plain link, without spaces.")
  5039. (defvar org-bracket-link-regexp nil
  5040. "Matches a link in double brackets.")
  5041. (defvar org-bracket-link-analytic-regexp nil
  5042. "Regular expression used to analyze links.
  5043. Here is what the match groups contain after a match:
  5044. 1: http:
  5045. 2: http
  5046. 3: path
  5047. 4: [desc]
  5048. 5: desc")
  5049. (defvar org-bracket-link-analytic-regexp++ nil
  5050. "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
  5051. (defvar org-any-link-re nil
  5052. "Regular expression matching any link.")
  5053. (defconst org-match-sexp-depth 3
  5054. "Number of stacked braces for sub/superscript matching.")
  5055. (defun org-create-multibrace-regexp (left right n)
  5056. "Create a regular expression which will match a balanced sexp.
  5057. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  5058. as single character strings.
  5059. The regexp returned will match the entire expression including the
  5060. delimiters. It will also define a single group which contains the
  5061. match except for the outermost delimiters. The maximum depth of
  5062. stacked delimiters is N. Escaping delimiters is not possible."
  5063. (let* ((nothing (concat "[^" left right "]*?"))
  5064. (or "\\|")
  5065. (re nothing)
  5066. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  5067. (while (> n 1)
  5068. (setq n (1- n)
  5069. re (concat re or next)
  5070. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  5071. (concat left "\\(" re "\\)" right)))
  5072. (defconst org-match-substring-regexp
  5073. (concat
  5074. "\\(\\S-\\)\\([_^]\\)\\("
  5075. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  5076. "\\|"
  5077. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  5078. "\\|"
  5079. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  5080. "The regular expression matching a sub- or superscript.")
  5081. (defconst org-match-substring-with-braces-regexp
  5082. (concat
  5083. "\\(\\S-\\)\\([_^]\\)"
  5084. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  5085. "The regular expression matching a sub- or superscript, forcing braces.")
  5086. (defun org-make-link-regexps ()
  5087. "Update the link regular expressions.
  5088. This should be called after the variable `org-link-parameters' has changed."
  5089. (let ((types-re (regexp-opt (org-link-types) t)))
  5090. (setq org-link-types-re
  5091. (concat "\\`" types-re ":")
  5092. org-link-re-with-space
  5093. (concat "<?" types-re ":"
  5094. "\\([^" org-non-link-chars " ]"
  5095. "[^" org-non-link-chars "]*"
  5096. "[^" org-non-link-chars " ]\\)>?")
  5097. org-link-re-with-space2
  5098. (concat "<?" types-re ":"
  5099. "\\([^" org-non-link-chars " ]"
  5100. "[^\t\n\r]*"
  5101. "[^" org-non-link-chars " ]\\)>?")
  5102. org-link-re-with-space3
  5103. (concat "<?" types-re ":"
  5104. "\\([^" org-non-link-chars " ]"
  5105. "[^\t\n\r]*\\)")
  5106. org-angle-link-re
  5107. (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
  5108. types-re)
  5109. org-plain-link-re
  5110. (concat
  5111. "\\<" types-re ":"
  5112. "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
  5113. ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
  5114. org-bracket-link-regexp
  5115. "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
  5116. org-bracket-link-analytic-regexp
  5117. (concat
  5118. "\\[\\["
  5119. "\\(" types-re ":\\)?"
  5120. "\\([^]]+\\)"
  5121. "\\]"
  5122. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5123. "\\]")
  5124. org-bracket-link-analytic-regexp++
  5125. (concat
  5126. "\\[\\["
  5127. "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
  5128. "\\([^]]+\\)"
  5129. "\\]"
  5130. "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
  5131. "\\]")
  5132. org-any-link-re
  5133. (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
  5134. org-angle-link-re "\\)\\|\\("
  5135. org-plain-link-re "\\)"))))
  5136. (org-make-link-regexps)
  5137. (defvar org-emph-face nil)
  5138. (defun org-do-emphasis-faces (limit)
  5139. "Run through the buffer and emphasize strings."
  5140. (let (rtn a)
  5141. (while (and (not rtn) (re-search-forward org-emph-re limit t))
  5142. (let* ((border (char-after (match-beginning 3)))
  5143. (bre (regexp-quote (char-to-string border))))
  5144. (when (and (not (= border (char-after (match-beginning 4))))
  5145. (not (string-match-p (concat bre ".*" bre)
  5146. (replace-regexp-in-string
  5147. "\n" " "
  5148. (substring (match-string 2) 1 -1)))))
  5149. (setq rtn t)
  5150. (setq a (assoc (match-string 3) org-emphasis-alist))
  5151. (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
  5152. 'face
  5153. (nth 1 a))
  5154. (and (nth 2 a)
  5155. (org-remove-flyspell-overlays-in
  5156. (match-beginning 0) (match-end 0)))
  5157. (add-text-properties (match-beginning 2) (match-end 2)
  5158. '(font-lock-multiline t org-emphasis t))
  5159. (when org-hide-emphasis-markers
  5160. (add-text-properties (match-end 4) (match-beginning 5)
  5161. '(invisible org-link))
  5162. (add-text-properties (match-beginning 3) (match-end 3)
  5163. '(invisible org-link)))))
  5164. (goto-char (1+ (match-beginning 0))))
  5165. rtn))
  5166. (defun org-emphasize (&optional char)
  5167. "Insert or change an emphasis, i.e. a font like bold or italic.
  5168. If there is an active region, change that region to a new emphasis.
  5169. If there is no region, just insert the marker characters and position
  5170. the cursor between them.
  5171. CHAR should be the marker character. If it is a space, it means to
  5172. remove the emphasis of the selected region.
  5173. If CHAR is not given (for example in an interactive call) it will be
  5174. prompted for."
  5175. (interactive)
  5176. (let ((erc org-emphasis-regexp-components)
  5177. (string "") beg end move s)
  5178. (if (org-region-active-p)
  5179. (setq beg (region-beginning)
  5180. end (region-end)
  5181. string (buffer-substring beg end))
  5182. (setq move t))
  5183. (unless char
  5184. (message "Emphasis marker or tag: [%s]"
  5185. (mapconcat #'car org-emphasis-alist ""))
  5186. (setq char (read-char-exclusive)))
  5187. (if (equal char ?\s)
  5188. (setq s ""
  5189. move nil)
  5190. (unless (assoc (char-to-string char) org-emphasis-alist)
  5191. (user-error "No such emphasis marker: \"%c\"" char))
  5192. (setq s (char-to-string char)))
  5193. (while (and (> (length string) 1)
  5194. (equal (substring string 0 1) (substring string -1))
  5195. (assoc (substring string 0 1) org-emphasis-alist))
  5196. (setq string (substring string 1 -1)))
  5197. (setq string (concat s string s))
  5198. (when beg (delete-region beg end))
  5199. (unless (or (bolp)
  5200. (string-match (concat "[" (nth 0 erc) "\n]")
  5201. (char-to-string (char-before (point)))))
  5202. (insert " "))
  5203. (unless (or (eobp)
  5204. (string-match (concat "[" (nth 1 erc) "\n]")
  5205. (char-to-string (char-after (point)))))
  5206. (insert " ") (backward-char 1))
  5207. (insert string)
  5208. (and move (backward-char 1))))
  5209. (defconst org-nonsticky-props
  5210. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  5211. (defsubst org-rear-nonsticky-at (pos)
  5212. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  5213. (defun org-activate-links (limit)
  5214. "Add link properties to links.
  5215. This includes angle, plain, and bracket links."
  5216. (catch :exit
  5217. (while (re-search-forward org-any-link-re limit t)
  5218. (let* ((start (match-beginning 0))
  5219. (end (match-end 0))
  5220. (style (cond ((eq ?< (char-after start)) 'angle)
  5221. ((eq ?\[ (char-after (1+ start))) 'bracket)
  5222. (t 'plain))))
  5223. (when (and (memq style org-highlight-links)
  5224. ;; Do not confuse plain links with tags.
  5225. (not (and (eq style 'plain)
  5226. (let ((face (get-text-property
  5227. (max (1- start) (point-min)) 'face)))
  5228. (if (consp face) (memq 'org-tag face)
  5229. (eq 'org-tag face))))))
  5230. (let* ((link-object (save-excursion
  5231. (goto-char start)
  5232. (save-match-data (org-element-link-parser))))
  5233. (link (org-element-property :raw-link link-object))
  5234. (type (org-element-property :type link-object))
  5235. (path (org-element-property :path link-object))
  5236. (properties ;for link's visible part
  5237. (list
  5238. 'face (pcase (org-link-get-parameter type :face)
  5239. ((and (pred functionp) face) (funcall face path))
  5240. ((and (pred facep) face) face)
  5241. ((and (pred consp) face) face) ;anonymous
  5242. (_ 'org-link))
  5243. 'mouse-face (or (org-link-get-parameter type :mouse-face)
  5244. 'highlight)
  5245. 'keymap (or (org-link-get-parameter type :keymap)
  5246. org-mouse-map)
  5247. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  5248. ((and (pred stringp) echo) echo)
  5249. ((and (pred functionp) echo) echo)
  5250. (_ (concat "LINK: " link)))
  5251. 'htmlize-link (pcase (org-link-get-parameter type
  5252. :htmlize-link)
  5253. ((and (pred functionp) f) (funcall f))
  5254. (_ `(:uri ,link)))
  5255. 'font-lock-multiline t)))
  5256. (org-remove-flyspell-overlays-in start end)
  5257. (org-rear-nonsticky-at end)
  5258. (if (not (eq 'bracket style))
  5259. (add-text-properties start end properties)
  5260. ;; Handle invisible parts in bracket links.
  5261. (remove-text-properties start end '(invisible nil))
  5262. (let ((hidden
  5263. (append `(invisible
  5264. ,(or (org-link-get-parameter type :display)
  5265. 'org-link))
  5266. properties))
  5267. (visible-start (or (match-beginning 4) (match-beginning 2)))
  5268. (visible-end (or (match-end 4) (match-end 2))))
  5269. (add-text-properties start visible-start hidden)
  5270. (add-text-properties visible-start visible-end properties)
  5271. (add-text-properties visible-end end hidden)
  5272. (org-rear-nonsticky-at visible-start)
  5273. (org-rear-nonsticky-at visible-end)))
  5274. (let ((f (org-link-get-parameter type :activate-func)))
  5275. (when (functionp f)
  5276. (funcall f start end path (eq style 'bracket))))
  5277. (throw :exit t))))) ;signal success
  5278. nil))
  5279. (defun org-activate-code (limit)
  5280. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  5281. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5282. (remove-text-properties (match-beginning 0) (match-end 0)
  5283. '(display t invisible t intangible t))
  5284. t))
  5285. (defcustom org-src-fontify-natively t
  5286. "When non-nil, fontify code in code blocks.
  5287. See also the `org-block' face."
  5288. :type 'boolean
  5289. :version "24.4"
  5290. :package-version '(Org . "8.3")
  5291. :group 'org-appearance
  5292. :group 'org-babel)
  5293. (defcustom org-allow-promoting-top-level-subtree nil
  5294. "When non-nil, allow promoting a top level subtree.
  5295. The leading star of the top level headline will be replaced
  5296. by a #."
  5297. :type 'boolean
  5298. :version "24.1"
  5299. :group 'org-appearance)
  5300. (defun org-fontify-meta-lines-and-blocks (limit)
  5301. (condition-case nil
  5302. (org-fontify-meta-lines-and-blocks-1 limit)
  5303. (error (message "org-mode fontification error in %S at %d"
  5304. (current-buffer)
  5305. (line-number-at-pos)))))
  5306. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  5307. "Fontify #+ lines and blocks."
  5308. (let ((case-fold-search t))
  5309. (when (re-search-forward
  5310. "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
  5311. limit t)
  5312. (let ((beg (match-beginning 0))
  5313. (block-start (match-end 0))
  5314. (block-end nil)
  5315. (lang (match-string 7))
  5316. (beg1 (line-beginning-position 2))
  5317. (dc1 (downcase (match-string 2)))
  5318. (dc3 (downcase (match-string 3)))
  5319. end end1 quoting block-type)
  5320. (cond
  5321. ((and (match-end 4) (equal dc3 "+begin"))
  5322. ;; Truly a block
  5323. (setq block-type (downcase (match-string 5))
  5324. quoting (member block-type org-protecting-blocks))
  5325. (when (re-search-forward
  5326. (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
  5327. nil t) ;; on purpose, we look further than LIMIT
  5328. (setq end (min (point-max) (match-end 0))
  5329. end1 (min (point-max) (1- (match-beginning 0))))
  5330. (setq block-end (match-beginning 0))
  5331. (when quoting
  5332. (org-remove-flyspell-overlays-in beg1 end1)
  5333. (remove-text-properties beg end
  5334. '(display t invisible t intangible t)))
  5335. (add-text-properties
  5336. beg end '(font-lock-fontified t font-lock-multiline t))
  5337. (add-text-properties beg beg1 '(face org-meta-line))
  5338. (org-remove-flyspell-overlays-in beg beg1)
  5339. (add-text-properties ; For end_src
  5340. end1 (min (point-max) (1+ end)) '(face org-meta-line))
  5341. (org-remove-flyspell-overlays-in end1 end)
  5342. (cond
  5343. ((and lang (not (string= lang "")) org-src-fontify-natively)
  5344. (org-src-font-lock-fontify-block lang block-start block-end)
  5345. (add-text-properties beg1 block-end '(src-block t)))
  5346. (quoting
  5347. (add-text-properties beg1 (min (point-max) (1+ end1))
  5348. (list 'face
  5349. (list :inherit
  5350. (let ((face-name
  5351. (intern (format "org-block-%s" lang))))
  5352. (append (and (facep face-name) (list face-name))
  5353. '(org-block))))))) ; end of source block
  5354. ((not org-fontify-quote-and-verse-blocks))
  5355. ((string= block-type "quote")
  5356. (add-face-text-property
  5357. beg1 (min (point-max) (1+ end1)) 'org-quote t))
  5358. ((string= block-type "verse")
  5359. (add-face-text-property
  5360. beg1 (min (point-max) (1+ end1)) 'org-verse t)))
  5361. (add-text-properties beg beg1 '(face org-block-begin-line))
  5362. (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
  5363. '(face org-block-end-line))
  5364. t))
  5365. ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
  5366. (org-remove-flyspell-overlays-in
  5367. (match-beginning 0)
  5368. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  5369. (add-text-properties
  5370. beg (match-end 3)
  5371. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  5372. '(font-lock-fontified t invisible t)
  5373. '(font-lock-fontified t face org-document-info-keyword)))
  5374. (add-text-properties
  5375. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  5376. (if (string-equal dc1 "+title:")
  5377. '(font-lock-fontified t face org-document-title)
  5378. '(font-lock-fontified t face org-document-info))))
  5379. ((string-prefix-p "+caption" dc1)
  5380. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  5381. (remove-text-properties (match-beginning 0) (match-end 0)
  5382. '(display t invisible t intangible t))
  5383. ;; Handle short captions.
  5384. (save-excursion
  5385. (beginning-of-line)
  5386. (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
  5387. (add-text-properties (line-beginning-position) (match-end 1)
  5388. '(font-lock-fontified t face org-meta-line))
  5389. (add-text-properties (match-end 0) (line-end-position)
  5390. '(font-lock-fontified t face org-block))
  5391. t)
  5392. ((member dc3 '(" " ""))
  5393. (org-remove-flyspell-overlays-in beg (match-end 0))
  5394. (add-text-properties
  5395. beg (match-end 0)
  5396. '(font-lock-fontified t face font-lock-comment-face)))
  5397. (t ;; just any other in-buffer setting, but not indented
  5398. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5399. (remove-text-properties (match-beginning 0) (match-end 0)
  5400. '(display t invisible t intangible t))
  5401. (add-text-properties beg (match-end 0)
  5402. '(font-lock-fontified t face org-meta-line))
  5403. t))))))
  5404. (defun org-fontify-drawers (limit)
  5405. "Fontify drawers."
  5406. (when (re-search-forward org-drawer-regexp limit t)
  5407. (add-text-properties
  5408. (match-beginning 0) (match-end 0)
  5409. '(font-lock-fontified t face org-special-keyword))
  5410. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5411. t))
  5412. (defun org-fontify-macros (limit)
  5413. "Fontify macros."
  5414. (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
  5415. (add-text-properties
  5416. (match-beginning 0) (match-end 0)
  5417. '(font-lock-fontified t face org-macro))
  5418. (when org-hide-macro-markers
  5419. (add-text-properties (match-end 2) (match-beginning 2)
  5420. '(invisible t))
  5421. (add-text-properties (match-beginning 1) (match-end 1)
  5422. '(invisible t)))
  5423. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5424. t))
  5425. (defun org-activate-footnote-links (limit)
  5426. "Add text properties for footnotes."
  5427. (let ((fn (org-footnote-next-reference-or-definition limit)))
  5428. (when fn
  5429. (let* ((beg (nth 1 fn))
  5430. (end (nth 2 fn))
  5431. (label (car fn))
  5432. (referencep (/= (line-beginning-position) beg)))
  5433. (when (and referencep (nth 3 fn))
  5434. (save-excursion
  5435. (goto-char beg)
  5436. (search-forward (or label "fn:"))
  5437. (org-remove-flyspell-overlays-in beg (match-end 0))))
  5438. (add-text-properties beg end
  5439. (list 'mouse-face 'highlight
  5440. 'keymap org-mouse-map
  5441. 'help-echo
  5442. (if referencep "Footnote reference"
  5443. "Footnote definition")
  5444. 'font-lock-fontified t
  5445. 'font-lock-multiline t
  5446. 'face 'org-footnote))))))
  5447. (defun org-activate-dates (limit)
  5448. "Add text properties for dates."
  5449. (when (and (re-search-forward org-tsr-regexp-both limit t)
  5450. (not (equal (char-before (match-beginning 0)) 91)))
  5451. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  5452. (add-text-properties (match-beginning 0) (match-end 0)
  5453. (list 'mouse-face 'highlight
  5454. 'keymap org-mouse-map))
  5455. (org-rear-nonsticky-at (match-end 0))
  5456. (when org-display-custom-times
  5457. ;; If it's a date range, activate custom time for second date.
  5458. (when (match-end 3)
  5459. (org-display-custom-time (match-beginning 3) (match-end 3)))
  5460. (org-display-custom-time (match-beginning 1) (match-end 1)))
  5461. t))
  5462. (defvar-local org-target-link-regexp nil
  5463. "Regular expression matching radio targets in plain text.")
  5464. (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
  5465. (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
  5466. border border border))
  5467. "Regular expression matching a link target.")
  5468. (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
  5469. "Regular expression matching a radio target.")
  5470. (defconst org-any-target-regexp
  5471. (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
  5472. "Regular expression matching any target.")
  5473. (defun org-activate-target-links (limit)
  5474. "Add text properties for target matches."
  5475. (when org-target-link-regexp
  5476. (let ((case-fold-search t))
  5477. (when (re-search-forward org-target-link-regexp limit t)
  5478. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5479. (add-text-properties (match-beginning 1) (match-end 1)
  5480. (list 'mouse-face 'highlight
  5481. 'keymap org-mouse-map
  5482. 'help-echo "Radio target link"
  5483. 'org-linked-text t))
  5484. (org-rear-nonsticky-at (match-end 1))
  5485. t))))
  5486. (defun org-update-radio-target-regexp ()
  5487. "Find all radio targets in this file and update the regular expression.
  5488. Also refresh fontification if needed."
  5489. (interactive)
  5490. (let ((old-regexp org-target-link-regexp)
  5491. (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
  5492. (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
  5493. (targets
  5494. (org-with-wide-buffer
  5495. (goto-char (point-min))
  5496. (let (rtn)
  5497. (while (re-search-forward org-radio-target-regexp nil t)
  5498. ;; Make sure point is really within the object.
  5499. (backward-char)
  5500. (let ((obj (org-element-context)))
  5501. (when (eq (org-element-type obj) 'radio-target)
  5502. (cl-pushnew (org-element-property :value obj) rtn
  5503. :test #'equal))))
  5504. rtn))))
  5505. (setq org-target-link-regexp
  5506. (and targets
  5507. (concat before-re
  5508. (mapconcat
  5509. (lambda (x)
  5510. (replace-regexp-in-string
  5511. " +" "\\s-+" (regexp-quote x) t t))
  5512. targets
  5513. "\\|")
  5514. after-re)))
  5515. (unless (equal old-regexp org-target-link-regexp)
  5516. ;; Clean-up cache.
  5517. (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
  5518. ((not org-target-link-regexp) old-regexp)
  5519. (t
  5520. (concat before-re
  5521. (mapconcat
  5522. (lambda (re)
  5523. (substring re (length before-re)
  5524. (- (length after-re))))
  5525. (list old-regexp org-target-link-regexp)
  5526. "\\|")
  5527. after-re)))))
  5528. (org-with-wide-buffer
  5529. (goto-char (point-min))
  5530. (while (re-search-forward regexp nil t)
  5531. (org-element-cache-refresh (match-beginning 1)))))
  5532. ;; Re fontify buffer.
  5533. (when (memq 'radio org-highlight-links)
  5534. (org-restart-font-lock)))))
  5535. (defun org-hide-wide-columns (limit)
  5536. (let (s e)
  5537. (setq s (text-property-any (point) (or limit (point-max))
  5538. 'org-cwidth t))
  5539. (when s
  5540. (setq e (next-single-property-change s 'org-cwidth))
  5541. (add-text-properties s e '(invisible org-cwidth))
  5542. (goto-char e)
  5543. t)))
  5544. (defvar org-latex-and-related-regexp nil
  5545. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  5546. (defun org-compute-latex-and-related-regexp ()
  5547. "Compute regular expression for LaTeX, entities and sub/superscript.
  5548. Result depends on variable `org-highlight-latex-and-related'."
  5549. (setq-local
  5550. org-latex-and-related-regexp
  5551. (let* ((re-sub
  5552. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  5553. ((eq org-use-sub-superscripts '{})
  5554. (list org-match-substring-with-braces-regexp))
  5555. (org-use-sub-superscripts (list org-match-substring-regexp))))
  5556. (re-latex
  5557. (when (memq 'latex org-highlight-latex-and-related)
  5558. (let ((matchers (plist-get org-format-latex-options :matchers)))
  5559. (delq nil
  5560. (mapcar (lambda (x)
  5561. (and (member (car x) matchers) (nth 1 x)))
  5562. org-latex-regexps)))))
  5563. (re-entities
  5564. (when (memq 'entities org-highlight-latex-and-related)
  5565. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
  5566. (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
  5567. (defun org-do-latex-and-related (limit)
  5568. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  5569. LIMIT bounds the search for syntax to highlight. Stop at first
  5570. highlighted object, if any. Return t if some highlighting was
  5571. done, nil otherwise."
  5572. (when (org-string-nw-p org-latex-and-related-regexp)
  5573. (catch 'found
  5574. (while (re-search-forward org-latex-and-related-regexp limit t)
  5575. (unless
  5576. (cl-some
  5577. (lambda (f)
  5578. (memq f '(org-code org-verbatim underline org-special-keyword)))
  5579. (save-excursion
  5580. (goto-char (1+ (match-beginning 0)))
  5581. (face-at-point nil t)))
  5582. (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
  5583. '(?_ ?^))
  5584. 1
  5585. 0)))
  5586. (font-lock-prepend-text-property
  5587. (+ offset (match-beginning 0)) (match-end 0)
  5588. 'face 'org-latex-and-related)
  5589. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  5590. '(font-lock-multiline t)))
  5591. (throw 'found t)))
  5592. nil)))
  5593. (defun org-restart-font-lock ()
  5594. "Restart `font-lock-mode', to force refontification."
  5595. (when (and (boundp 'font-lock-mode) font-lock-mode)
  5596. (font-lock-mode -1)
  5597. (font-lock-mode 1)))
  5598. (defun org-activate-tags (limit)
  5599. (when (re-search-forward
  5600. "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
  5601. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  5602. (add-text-properties (match-beginning 1) (match-end 1)
  5603. (list 'mouse-face 'highlight
  5604. 'keymap org-mouse-map))
  5605. (org-rear-nonsticky-at (match-end 1))
  5606. t))
  5607. (defun org-outline-level ()
  5608. "Compute the outline level of the heading at point.
  5609. If this is called at a normal headline, the level is the number
  5610. of stars. Use `org-reduced-level' to remove the effect of
  5611. `org-odd-levels'. Unlike to `org-current-level', this function
  5612. takes into consideration inlinetasks."
  5613. (org-with-wide-buffer
  5614. (end-of-line)
  5615. (if (re-search-backward org-outline-regexp-bol nil t)
  5616. (1- (- (match-end 0) (match-beginning 0)))
  5617. 0)))
  5618. (defvar org-font-lock-keywords nil)
  5619. (defsubst org-re-property (property &optional literal allow-null value)
  5620. "Return a regexp matching a PROPERTY line.
  5621. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  5622. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  5623. non-nil, match properties even without a value.
  5624. Match group 3 is set to the value when it exists. If there is no
  5625. value and ALLOW-NULL is non-nil, it is set to the empty string.
  5626. With optional argument VALUE, match only property lines with
  5627. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  5628. unless LITERAL is non-nil."
  5629. (concat
  5630. "^\\(?4:[ \t]*\\)"
  5631. (format "\\(?1::\\(?2:%s\\):\\)"
  5632. (if literal property (regexp-quote property)))
  5633. (cond (value
  5634. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  5635. (if literal value (regexp-quote value))))
  5636. (allow-null
  5637. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  5638. (t
  5639. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  5640. (defconst org-property-re
  5641. (org-re-property "\\S-+" 'literal t)
  5642. "Regular expression matching a property line.
  5643. There are four matching groups:
  5644. 1: :PROPKEY: including the leading and trailing colon,
  5645. 2: PROPKEY without the leading and trailing colon,
  5646. 3: PROPVAL without leading or trailing spaces,
  5647. 4: the indentation of the current line,
  5648. 5: trailing whitespace.")
  5649. (defvar org-font-lock-hook nil
  5650. "Functions to be called for special font lock stuff.")
  5651. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  5652. (defvar org-font-lock-set-keywords-hook nil
  5653. "Functions that can manipulate `org-font-lock-extra-keywords'.
  5654. This is called after `org-font-lock-extra-keywords' is defined, but before
  5655. it is installed to be used by font lock. This can be useful if something
  5656. needs to be inserted at a specific position in the font-lock sequence.")
  5657. (defun org-font-lock-hook (limit)
  5658. "Run `org-font-lock-hook' within LIMIT."
  5659. (run-hook-with-args 'org-font-lock-hook limit))
  5660. (defun org-set-font-lock-defaults ()
  5661. "Set font lock defaults for the current buffer."
  5662. (let* ((em org-fontify-emphasized-text)
  5663. (lk org-highlight-links)
  5664. (org-font-lock-extra-keywords
  5665. (list
  5666. ;; Call the hook
  5667. '(org-font-lock-hook)
  5668. ;; Headlines
  5669. `(,(if org-fontify-whole-heading-line
  5670. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  5671. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  5672. (1 (org-get-level-face 1))
  5673. (2 (org-get-level-face 2))
  5674. (3 (org-get-level-face 3)))
  5675. ;; Table lines
  5676. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  5677. (1 'org-table t))
  5678. ;; Table internals
  5679. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5680. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5681. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5682. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5683. ;; Drawers
  5684. '(org-fontify-drawers)
  5685. ;; Properties
  5686. (list org-property-re
  5687. '(1 'org-special-keyword t)
  5688. '(3 'org-property-value t))
  5689. ;; Link related fontification.
  5690. '(org-activate-links)
  5691. (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
  5692. (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
  5693. (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
  5694. (when (memq 'footnote lk) '(org-activate-footnote-links))
  5695. ;; Targets.
  5696. (list org-any-target-regexp '(0 'org-target t))
  5697. ;; Diary sexps.
  5698. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5699. ;; Macro
  5700. '(org-fontify-macros)
  5701. '(org-hide-wide-columns (0 nil append))
  5702. ;; TODO keyword
  5703. (list (format org-heading-keyword-regexp-format
  5704. org-todo-regexp)
  5705. '(2 (org-get-todo-face 2) t))
  5706. ;; DONE
  5707. (if org-fontify-done-headline
  5708. (list (format org-heading-keyword-regexp-format
  5709. (concat
  5710. "\\(?:"
  5711. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5712. "\\)"))
  5713. '(2 'org-headline-done t))
  5714. nil)
  5715. ;; Priorities
  5716. '(org-font-lock-add-priority-faces)
  5717. ;; Tags
  5718. '(org-font-lock-add-tag-faces)
  5719. ;; Tags groups
  5720. (when (and org-group-tags org-tag-groups-alist)
  5721. (list (concat org-outline-regexp-bol ".+\\(:"
  5722. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5723. ":\\).*$")
  5724. '(1 'org-tag-group prepend)))
  5725. ;; Special keywords
  5726. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5727. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5728. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5729. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5730. ;; Emphasis
  5731. (when em '(org-do-emphasis-faces))
  5732. ;; Checkboxes
  5733. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5734. 1 'org-checkbox prepend)
  5735. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5736. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5737. (0 (org-get-checkbox-statistics-face) t)))
  5738. ;; Description list items
  5739. '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5740. 1 'org-list-dt prepend)
  5741. ;; ARCHIVEd headings
  5742. (list (concat
  5743. org-outline-regexp-bol
  5744. "\\(.*:" org-archive-tag ":.*\\)")
  5745. '(1 'org-archived prepend))
  5746. ;; Specials
  5747. '(org-do-latex-and-related)
  5748. '(org-fontify-entities)
  5749. '(org-raise-scripts)
  5750. ;; Code
  5751. '(org-activate-code (1 'org-code t))
  5752. ;; COMMENT
  5753. (list (format
  5754. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5755. org-todo-regexp
  5756. org-comment-string)
  5757. '(9 'org-special-keyword t))
  5758. ;; Blocks and meta lines
  5759. '(org-fontify-meta-lines-and-blocks))))
  5760. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5761. (run-hooks 'org-font-lock-set-keywords-hook)
  5762. ;; Now set the full font-lock-keywords
  5763. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5764. (setq-local font-lock-defaults
  5765. '(org-font-lock-keywords t nil nil backward-paragraph))
  5766. (kill-local-variable 'font-lock-keywords)
  5767. nil))
  5768. (defun org-toggle-pretty-entities ()
  5769. "Toggle the composition display of entities as UTF8 characters."
  5770. (interactive)
  5771. (setq-local org-pretty-entities (not org-pretty-entities))
  5772. (org-restart-font-lock)
  5773. (if org-pretty-entities
  5774. (message "Entities are now displayed as UTF8 characters")
  5775. (save-restriction
  5776. (widen)
  5777. (decompose-region (point-min) (point-max))
  5778. (message "Entities are now displayed as plain text"))))
  5779. (defvar-local org-custom-properties-overlays nil
  5780. "List of overlays used for custom properties.")
  5781. (defun org-toggle-custom-properties-visibility ()
  5782. "Display or hide properties in `org-custom-properties'."
  5783. (interactive)
  5784. (if org-custom-properties-overlays
  5785. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5786. (setq org-custom-properties-overlays nil))
  5787. (when org-custom-properties
  5788. (org-with-wide-buffer
  5789. (goto-char (point-min))
  5790. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5791. (while (re-search-forward regexp nil t)
  5792. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5793. (when (and end (< (point) end))
  5794. ;; Hide first custom property in current drawer.
  5795. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5796. (overlay-put o 'invisible t)
  5797. (overlay-put o 'org-custom-property t)
  5798. (push o org-custom-properties-overlays))
  5799. ;; Hide additional custom properties in the same drawer.
  5800. (while (re-search-forward regexp end t)
  5801. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5802. (overlay-put o 'invisible t)
  5803. (overlay-put o 'org-custom-property t)
  5804. (push o org-custom-properties-overlays)))))
  5805. ;; Each entry is limited to a single property drawer.
  5806. (outline-next-heading)))))))
  5807. (defun org-fontify-entities (limit)
  5808. "Find an entity to fontify."
  5809. (let (ee)
  5810. (when org-pretty-entities
  5811. (catch 'match
  5812. ;; "\_ "-family is left out on purpose. Only the first one,
  5813. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5814. ;; confusing when adding a second white space character.
  5815. (while (re-search-forward
  5816. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5817. limit t)
  5818. (when (and (not (org-at-comment-p))
  5819. (setq ee (org-entity-get (match-string 1)))
  5820. (= (length (nth 6 ee)) 1))
  5821. (let* ((end (if (equal (match-string 2) "{}")
  5822. (match-end 2)
  5823. (match-end 1))))
  5824. (add-text-properties
  5825. (match-beginning 0) end
  5826. (list 'font-lock-fontified t))
  5827. (compose-region (match-beginning 0) end
  5828. (nth 6 ee) nil)
  5829. (backward-char 1)
  5830. (throw 'match t))))
  5831. nil))))
  5832. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5833. "Fontify string S like in Org mode."
  5834. (with-temp-buffer
  5835. (insert s)
  5836. (let ((org-odd-levels-only odd-levels))
  5837. (org-mode)
  5838. (org-font-lock-ensure)
  5839. (buffer-string))))
  5840. (defvar org-m nil)
  5841. (defvar org-l nil)
  5842. (defvar org-f nil)
  5843. (defun org-get-level-face (n)
  5844. "Get the right face for match N in font-lock matching of headlines."
  5845. (setq org-l (- (match-end 2) (match-beginning 1) 1))
  5846. (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
  5847. (if org-cycle-level-faces
  5848. (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
  5849. (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
  5850. (cond
  5851. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5852. ((eq n 2) org-f)
  5853. (t (unless org-level-color-stars-only org-f))))
  5854. (defun org-face-from-face-or-color (context inherit face-or-color)
  5855. "Create a face list that inherits INHERIT, but sets the foreground color.
  5856. When FACE-OR-COLOR is not a string, just return it."
  5857. (if (stringp face-or-color)
  5858. (list :inherit inherit
  5859. (cdr (assoc context org-faces-easy-properties))
  5860. face-or-color)
  5861. face-or-color))
  5862. (defun org-get-todo-face (kwd)
  5863. "Get the right face for a TODO keyword KWD.
  5864. If KWD is a number, get the corresponding match group."
  5865. (when (numberp kwd) (setq kwd (match-string kwd)))
  5866. (or (org-face-from-face-or-color
  5867. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5868. (and (member kwd org-done-keywords) 'org-done)
  5869. 'org-todo))
  5870. (defun org-get-priority-face (priority)
  5871. "Get the right face for PRIORITY.
  5872. PRIORITY is a character."
  5873. (or (org-face-from-face-or-color
  5874. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5875. 'org-priority))
  5876. (defun org-get-tag-face (tag)
  5877. "Get the right face for TAG.
  5878. If TAG is a number, get the corresponding match group."
  5879. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5880. (or (org-face-from-face-or-color
  5881. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5882. 'org-tag)))
  5883. (defun org-font-lock-add-priority-faces (limit)
  5884. "Add the special priority faces."
  5885. (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
  5886. (add-text-properties
  5887. (match-beginning 1) (match-end 1)
  5888. (list 'face (org-get-priority-face (string-to-char (match-string 2)))
  5889. 'font-lock-fontified t))))
  5890. (defun org-font-lock-add-tag-faces (limit)
  5891. "Add the special tag faces."
  5892. (when (and org-tag-faces org-tags-special-faces-re)
  5893. (while (re-search-forward org-tags-special-faces-re limit t)
  5894. (add-text-properties (match-beginning 1) (match-end 1)
  5895. (list 'face (org-get-tag-face 1)
  5896. 'font-lock-fontified t))
  5897. (backward-char 1))))
  5898. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5899. "Remove fontification and activation overlays from links."
  5900. (font-lock-default-unfontify-region beg end)
  5901. (let* ((buffer-undo-list t)
  5902. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5903. (inhibit-modification-hooks t)
  5904. deactivate-mark buffer-file-name buffer-file-truename)
  5905. (decompose-region beg end)
  5906. (remove-text-properties beg end
  5907. '(mouse-face t keymap t org-linked-text t
  5908. invisible t intangible t
  5909. org-emphasis t))
  5910. (org-remove-font-lock-display-properties beg end)))
  5911. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5912. ((raise 0.3) (height 0.7))
  5913. ((raise -0.5))
  5914. ((raise 0.5)))
  5915. "Display properties for showing superscripts and subscripts.")
  5916. (defun org-remove-font-lock-display-properties (beg end)
  5917. "Remove specific display properties that have been added by font lock.
  5918. The will remove the raise properties that are used to show superscripts
  5919. and subscripts."
  5920. (let (next prop)
  5921. (while (< beg end)
  5922. (setq next (next-single-property-change beg 'display nil end)
  5923. prop (get-text-property beg 'display))
  5924. (when (member prop org-script-display)
  5925. (put-text-property beg next 'display nil))
  5926. (setq beg next))))
  5927. (defun org-raise-scripts (limit)
  5928. "Add raise properties to sub/superscripts."
  5929. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5930. (re-search-forward
  5931. (if (eq org-use-sub-superscripts t)
  5932. org-match-substring-regexp
  5933. org-match-substring-with-braces-regexp)
  5934. limit t))
  5935. (let* ((pos (point)) table-p comment-p
  5936. (mpos (match-beginning 3))
  5937. (emph-p (get-text-property mpos 'org-emphasis))
  5938. (link-p (get-text-property mpos 'mouse-face))
  5939. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5940. (goto-char (point-at-bol))
  5941. (setq table-p (looking-at-p org-table-dataline-regexp)
  5942. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5943. (goto-char pos)
  5944. ;; Handle a_b^c
  5945. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5946. (unless (or comment-p emph-p link-p keyw-p)
  5947. (put-text-property (match-beginning 3) (match-end 0)
  5948. 'display
  5949. (if (equal (char-after (match-beginning 2)) ?^)
  5950. (nth (if table-p 3 1) org-script-display)
  5951. (nth (if table-p 2 0) org-script-display)))
  5952. (add-text-properties (match-beginning 2) (match-end 2)
  5953. (list 'invisible t
  5954. 'org-dwidth t 'org-dwidth-n 1))
  5955. (if (and (eq (char-after (match-beginning 3)) ?{)
  5956. (eq (char-before (match-end 3)) ?}))
  5957. (progn
  5958. (add-text-properties
  5959. (match-beginning 3) (1+ (match-beginning 3))
  5960. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
  5961. (add-text-properties
  5962. (1- (match-end 3)) (match-end 3)
  5963. (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
  5964. t)))
  5965. ;;;; Visibility cycling, including org-goto and indirect buffer
  5966. ;;; Cycling
  5967. (defvar-local org-cycle-global-status nil)
  5968. (put 'org-cycle-global-status 'org-state t)
  5969. (defvar-local org-cycle-subtree-status nil)
  5970. (put 'org-cycle-subtree-status 'org-state t)
  5971. (defvar org-inlinetask-min-level)
  5972. (defun org-unlogged-message (&rest args)
  5973. "Display a message, but avoid logging it in the *Messages* buffer."
  5974. (let ((message-log-max nil))
  5975. (apply 'message args)))
  5976. ;;;###autoload
  5977. (defun org-cycle (&optional arg)
  5978. "TAB-action and visibility cycling for Org mode.
  5979. This is the command invoked in Org mode by the `TAB' key. Its main
  5980. purpose is outline visibility cycling, but it also invokes other actions
  5981. in special contexts.
  5982. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5983. the entire
  5984. buffer through 3 states (global cycling)
  5985. 1. OVERVIEW: Show only top-level headlines.
  5986. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5987. 3. SHOW ALL: Show everything.
  5988. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5989. switch to the startup visibility,
  5990. determined by the variable `org-startup-folded', and by any VISIBILITY
  5991. properties in the buffer.
  5992. With a `\\[universal-argument] \\[universal-argument] \
  5993. \\[universal-argument]' prefix argument, show the entire buffer, including
  5994. any drawers.
  5995. When inside a table, re-align the table and move to the next field.
  5996. When point is at the beginning of a headline, rotate the subtree started
  5997. by this line through 3 different states (local cycling)
  5998. 1. FOLDED: Only the main headline is shown.
  5999. 2. CHILDREN: The main headline and the direct children are shown.
  6000. From this state, you can move to one of the children
  6001. and zoom in further.
  6002. 3. SUBTREE: Show the entire subtree, including body text.
  6003. If there is no subtree, switch directly from CHILDREN to FOLDED.
  6004. When point is at the beginning of an empty headline and the variable
  6005. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  6006. of the headline by demoting and promoting it to likely levels. This
  6007. speeds up creation document structure by pressing `TAB' once or several
  6008. times right after creating a new headline.
  6009. When there is a numeric prefix, go up to a heading with level ARG, do
  6010. a `show-subtree' and return to the previous cursor position. If ARG
  6011. is negative, go up that many levels.
  6012. When point is not at the beginning of a headline, execute the global
  6013. binding for `TAB', which is re-indenting the line. See the option
  6014. `org-cycle-emulate-tab' for details.
  6015. As a special case, if point is at the beginning of the buffer and there is
  6016. no headline in line 1, this function will act as if called with prefix arg
  6017. \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
  6018. prefix arg, but only
  6019. if the variable `org-cycle-global-at-bob' is t."
  6020. (interactive "P")
  6021. (org-load-modules-maybe)
  6022. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  6023. (and org-cycle-level-after-item/entry-creation
  6024. (or (org-cycle-level)
  6025. (org-cycle-item-indentation))))
  6026. (let* ((limit-level
  6027. (or org-cycle-max-level
  6028. (and (boundp 'org-inlinetask-min-level)
  6029. org-inlinetask-min-level
  6030. (1- org-inlinetask-min-level))))
  6031. (nstars (and limit-level
  6032. (if org-odd-levels-only
  6033. (and limit-level (1- (* limit-level 2)))
  6034. limit-level)))
  6035. (org-outline-regexp
  6036. (if (not (derived-mode-p 'org-mode))
  6037. outline-regexp
  6038. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
  6039. (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
  6040. (not (looking-at org-outline-regexp))))
  6041. (org-cycle-hook
  6042. (if bob-special
  6043. (delq 'org-optimize-window-after-visibility-change
  6044. (copy-sequence org-cycle-hook))
  6045. org-cycle-hook))
  6046. (pos (point)))
  6047. (cond
  6048. ((equal arg '(16))
  6049. (setq last-command 'dummy)
  6050. (org-set-startup-visibility)
  6051. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  6052. ((equal arg '(64))
  6053. (outline-show-all)
  6054. (org-unlogged-message "Entire buffer visible, including drawers"))
  6055. ((equal arg '(4)) (org-cycle-internal-global))
  6056. ;; Try hiding block at point.
  6057. ((org-hide-block-toggle-maybe))
  6058. ;; Try cdlatex TAB completion
  6059. ((org-try-cdlatex-tab))
  6060. ;; Table: enter it or move to the next field.
  6061. ((org-at-table-p 'any)
  6062. (if (org-at-table.el-p)
  6063. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  6064. Use `\\[org-edit-special]' to edit table.el tables"))
  6065. (if arg (org-table-edit-field t)
  6066. (org-table-justify-field-maybe)
  6067. (call-interactively 'org-table-next-field))))
  6068. ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
  6069. ;; Global cycling: delegate to `org-cycle-internal-global'.
  6070. (bob-special (org-cycle-internal-global))
  6071. ;; Drawers: delegate to `org-flag-drawer'.
  6072. ((save-excursion
  6073. (beginning-of-line 1)
  6074. (looking-at org-drawer-regexp))
  6075. (org-flag-drawer ; toggle block visibility
  6076. (not (get-char-property (match-end 0) 'invisible))))
  6077. ;; Show-subtree, ARG levels up from here.
  6078. ((integerp arg)
  6079. (save-excursion
  6080. (org-back-to-heading)
  6081. (outline-up-heading (if (< arg 0) (- arg)
  6082. (- (funcall outline-level) arg)))
  6083. (org-show-subtree)))
  6084. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  6085. ((and (featurep 'org-inlinetask)
  6086. (org-inlinetask-at-task-p)
  6087. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6088. (org-inlinetask-toggle-visibility))
  6089. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  6090. ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
  6091. (save-excursion (move-beginning-of-line 1)
  6092. (looking-at org-outline-regexp)))
  6093. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  6094. (org-cycle-internal-local))
  6095. ;; From there: TAB emulation and template completion.
  6096. (buffer-read-only (org-back-to-heading))
  6097. ((run-hook-with-args-until-success
  6098. 'org-tab-after-check-for-cycling-hook))
  6099. ((org-try-structure-completion))
  6100. ((run-hook-with-args-until-success
  6101. 'org-tab-before-tab-emulation-hook))
  6102. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  6103. (or (not (bolp))
  6104. (not (looking-at org-outline-regexp))))
  6105. (call-interactively (global-key-binding "\t")))
  6106. ((if (and (memq org-cycle-emulate-tab '(white whitestart))
  6107. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  6108. (or (and (eq org-cycle-emulate-tab 'white)
  6109. (= (match-end 0) (point-at-eol)))
  6110. (and (eq org-cycle-emulate-tab 'whitestart)
  6111. (>= (match-end 0) pos))))
  6112. t
  6113. (eq org-cycle-emulate-tab t))
  6114. (call-interactively (global-key-binding "\t")))
  6115. (t (save-excursion
  6116. (org-back-to-heading)
  6117. (org-cycle)))))))
  6118. (defun org-cycle-internal-global ()
  6119. "Do the global cycling action."
  6120. ;; Hack to avoid display of messages for .org attachments in Gnus
  6121. (let ((ga (string-match "\\*fontification" (buffer-name))))
  6122. (cond
  6123. ((and (eq last-command this-command)
  6124. (eq org-cycle-global-status 'overview))
  6125. ;; We just created the overview - now do table of contents
  6126. ;; This can be slow in very large buffers, so indicate action
  6127. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  6128. (unless ga (org-unlogged-message "CONTENTS..."))
  6129. (org-content)
  6130. (unless ga (org-unlogged-message "CONTENTS...done"))
  6131. (setq org-cycle-global-status 'contents)
  6132. (run-hook-with-args 'org-cycle-hook 'contents))
  6133. ((and (eq last-command this-command)
  6134. (eq org-cycle-global-status 'contents))
  6135. ;; We just showed the table of contents - now show everything
  6136. (run-hook-with-args 'org-pre-cycle-hook 'all)
  6137. (outline-show-all)
  6138. (unless ga (org-unlogged-message "SHOW ALL"))
  6139. (setq org-cycle-global-status 'all)
  6140. (run-hook-with-args 'org-cycle-hook 'all))
  6141. (t
  6142. ;; Default action: go to overview
  6143. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  6144. (org-overview)
  6145. (unless ga (org-unlogged-message "OVERVIEW"))
  6146. (setq org-cycle-global-status 'overview)
  6147. (run-hook-with-args 'org-cycle-hook 'overview)))))
  6148. (defvar org-called-with-limited-levels nil
  6149. "Non-nil when `org-with-limited-levels' is currently active.")
  6150. (defun org-invisible-p (&optional pos)
  6151. "Non-nil if the character after POS is invisible.
  6152. If POS is nil, use `point' instead."
  6153. (get-char-property (or pos (point)) 'invisible))
  6154. (defun org-cycle-internal-local ()
  6155. "Do the local cycling action."
  6156. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  6157. ;; First, determine end of headline (EOH), end of subtree or item
  6158. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  6159. (save-excursion
  6160. (if (org-at-item-p)
  6161. (progn
  6162. (beginning-of-line)
  6163. (setq struct (org-list-struct))
  6164. (setq eoh (point-at-eol))
  6165. (setq eos (org-list-get-item-end-before-blank (point) struct))
  6166. (setq has-children (org-list-has-child-p (point) struct)))
  6167. (org-back-to-heading)
  6168. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  6169. (setq eos (save-excursion (org-end-of-subtree t t)
  6170. (when (bolp) (backward-char)) (point)))
  6171. (setq has-children
  6172. (or (save-excursion
  6173. (let ((level (funcall outline-level)))
  6174. (outline-next-heading)
  6175. (and (org-at-heading-p t)
  6176. (> (funcall outline-level) level))))
  6177. (save-excursion
  6178. (org-list-search-forward (org-item-beginning-re) eos t)))))
  6179. ;; Determine end invisible part of buffer (EOL)
  6180. (beginning-of-line 2)
  6181. (while (and (not (eobp)) ;This is like `next-line'.
  6182. (get-char-property (1- (point)) 'invisible))
  6183. (goto-char (next-single-char-property-change (point) 'invisible))
  6184. (and (eolp) (beginning-of-line 2)))
  6185. (setq eol (point)))
  6186. ;; Find out what to do next and set `this-command'
  6187. (cond
  6188. ((= eos eoh)
  6189. ;; Nothing is hidden behind this heading
  6190. (unless (org-before-first-heading-p)
  6191. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  6192. (org-unlogged-message "EMPTY ENTRY")
  6193. (setq org-cycle-subtree-status nil)
  6194. (save-excursion
  6195. (goto-char eos)
  6196. (outline-next-heading)
  6197. (when (org-invisible-p) (org-flag-heading nil))))
  6198. ((and (or (>= eol eos)
  6199. (not (string-match "\\S-" (buffer-substring eol eos))))
  6200. (or has-children
  6201. (not (setq children-skipped
  6202. org-cycle-skip-children-state-if-no-children))))
  6203. ;; Entire subtree is hidden in one line: children view
  6204. (unless (org-before-first-heading-p)
  6205. (run-hook-with-args 'org-pre-cycle-hook 'children))
  6206. (if (org-at-item-p)
  6207. (org-list-set-item-visibility (point-at-bol) struct 'children)
  6208. (org-show-entry)
  6209. (org-with-limited-levels (org-show-children))
  6210. ;; FIXME: This slows down the func way too much.
  6211. ;; How keep drawers hidden in subtree anyway?
  6212. ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
  6213. ;; (org-cycle-hide-drawers 'subtree))
  6214. ;; Fold every list in subtree to top-level items.
  6215. (when (eq org-cycle-include-plain-lists 'integrate)
  6216. (save-excursion
  6217. (org-back-to-heading)
  6218. (while (org-list-search-forward (org-item-beginning-re) eos t)
  6219. (beginning-of-line 1)
  6220. (let* ((struct (org-list-struct))
  6221. (prevs (org-list-prevs-alist struct))
  6222. (end (org-list-get-bottom-point struct)))
  6223. (dolist (e (org-list-get-all-items (point) struct prevs))
  6224. (org-list-set-item-visibility e struct 'folded))
  6225. (goto-char (if (< end eos) end eos)))))))
  6226. (org-unlogged-message "CHILDREN")
  6227. (save-excursion
  6228. (goto-char eos)
  6229. (outline-next-heading)
  6230. (when (org-invisible-p) (org-flag-heading nil)))
  6231. (setq org-cycle-subtree-status 'children)
  6232. (unless (org-before-first-heading-p)
  6233. (run-hook-with-args 'org-cycle-hook 'children)))
  6234. ((or children-skipped
  6235. (and (eq last-command this-command)
  6236. (eq org-cycle-subtree-status 'children)))
  6237. ;; We just showed the children, or no children are there,
  6238. ;; now show everything.
  6239. (unless (org-before-first-heading-p)
  6240. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  6241. (outline-flag-region eoh eos nil)
  6242. (org-unlogged-message
  6243. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  6244. (setq org-cycle-subtree-status 'subtree)
  6245. (unless (org-before-first-heading-p)
  6246. (run-hook-with-args 'org-cycle-hook 'subtree)))
  6247. (t
  6248. ;; Default action: hide the subtree.
  6249. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  6250. (outline-flag-region eoh eos t)
  6251. (org-unlogged-message "FOLDED")
  6252. (setq org-cycle-subtree-status 'folded)
  6253. (unless (org-before-first-heading-p)
  6254. (run-hook-with-args 'org-cycle-hook 'folded))))))
  6255. ;;;###autoload
  6256. (defun org-global-cycle (&optional arg)
  6257. "Cycle the global visibility. For details see `org-cycle'.
  6258. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  6259. With a numeric prefix, show all headlines up to that level."
  6260. (interactive "P")
  6261. (let ((org-cycle-include-plain-lists
  6262. (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
  6263. (cond
  6264. ((integerp arg)
  6265. (outline-show-all)
  6266. (outline-hide-sublevels arg)
  6267. (setq org-cycle-global-status 'contents))
  6268. ((equal arg '(4))
  6269. (org-set-startup-visibility)
  6270. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  6271. (t
  6272. (org-cycle '(4))))))
  6273. (defun org-set-startup-visibility ()
  6274. "Set the visibility required by startup options and properties."
  6275. (cond
  6276. ((eq org-startup-folded t)
  6277. (org-overview))
  6278. ((eq org-startup-folded 'content)
  6279. (org-content))
  6280. ((or (eq org-startup-folded 'showeverything)
  6281. (eq org-startup-folded nil))
  6282. (outline-show-all)))
  6283. (unless (eq org-startup-folded 'showeverything)
  6284. (when org-hide-block-startup (org-hide-block-all))
  6285. (org-set-visibility-according-to-property 'no-cleanup)
  6286. (org-cycle-hide-archived-subtrees 'all)
  6287. (org-cycle-hide-drawers 'all)
  6288. (org-cycle-show-empty-lines t)))
  6289. (defun org-set-visibility-according-to-property (&optional no-cleanup)
  6290. "Switch subtree visibilities according to :VISIBILITY: property."
  6291. (interactive)
  6292. (org-with-wide-buffer
  6293. (goto-char (point-min))
  6294. (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
  6295. (if (not (org-at-property-p)) (outline-next-heading)
  6296. (let ((state (match-string 3)))
  6297. (save-excursion
  6298. (org-back-to-heading t)
  6299. (outline-hide-subtree)
  6300. (org-reveal)
  6301. (cond
  6302. ((equal state "folded")
  6303. (outline-hide-subtree))
  6304. ((equal state "children")
  6305. (org-show-hidden-entry)
  6306. (org-show-children))
  6307. ((equal state "content")
  6308. (save-excursion
  6309. (save-restriction
  6310. (org-narrow-to-subtree)
  6311. (org-content))))
  6312. ((member state '("all" "showall"))
  6313. (outline-show-subtree)))))))
  6314. (unless no-cleanup
  6315. (org-cycle-hide-archived-subtrees 'all)
  6316. (org-cycle-hide-drawers 'all)
  6317. (org-cycle-show-empty-lines 'all))))
  6318. ;; This function uses outline-regexp instead of the more fundamental
  6319. ;; org-outline-regexp so that org-cycle-global works outside of Org
  6320. ;; buffers, where outline-regexp is needed.
  6321. (defun org-overview ()
  6322. "Switch to overview mode, showing only top-level headlines.
  6323. This shows all headlines with a level equal or greater than the level
  6324. of the first headline in the buffer. This is important, because if the
  6325. first headline is not level one, then (hide-sublevels 1) gives confusing
  6326. results."
  6327. (interactive)
  6328. (save-excursion
  6329. (let ((level
  6330. (save-excursion
  6331. (goto-char (point-min))
  6332. (when (re-search-forward (concat "^" outline-regexp) nil t)
  6333. (goto-char (match-beginning 0))
  6334. (funcall outline-level)))))
  6335. (and level (outline-hide-sublevels level)))))
  6336. (defun org-content (&optional arg)
  6337. "Show all headlines in the buffer, like a table of contents.
  6338. With numerical argument N, show content up to level N."
  6339. (interactive "P")
  6340. (org-overview)
  6341. (save-excursion
  6342. ;; Visit all headings and show their offspring
  6343. (and (integerp arg) (org-overview))
  6344. (goto-char (point-max))
  6345. (catch 'exit
  6346. (while (and (progn (condition-case nil
  6347. (outline-previous-visible-heading 1)
  6348. (error (goto-char (point-min))))
  6349. t)
  6350. (looking-at org-outline-regexp))
  6351. (if (integerp arg)
  6352. (org-show-children (1- arg))
  6353. (outline-show-branches))
  6354. (when (bobp) (throw 'exit nil))))))
  6355. (defun org-optimize-window-after-visibility-change (state)
  6356. "Adjust the window after a change in outline visibility.
  6357. This function is the default value of the hook `org-cycle-hook'."
  6358. (when (get-buffer-window (current-buffer))
  6359. (cond
  6360. ((eq state 'content) nil)
  6361. ((eq state 'all) nil)
  6362. ((eq state 'folded) nil)
  6363. ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
  6364. ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
  6365. (defun org-remove-empty-overlays-at (pos)
  6366. "Remove outline overlays that do not contain non-white stuff."
  6367. (dolist (o (overlays-at pos))
  6368. (and (eq 'outline (overlay-get o 'invisible))
  6369. (not (string-match "\\S-" (buffer-substring (overlay-start o)
  6370. (overlay-end o))))
  6371. (delete-overlay o))))
  6372. (defun org-clean-visibility-after-subtree-move ()
  6373. "Fix visibility issues after moving a subtree."
  6374. ;; First, find a reasonable region to look at:
  6375. ;; Start two siblings above, end three below
  6376. (let* ((beg (save-excursion
  6377. (and (org-get-last-sibling)
  6378. (org-get-last-sibling))
  6379. (point)))
  6380. (end (save-excursion
  6381. (and (org-get-next-sibling)
  6382. (org-get-next-sibling)
  6383. (org-get-next-sibling))
  6384. (if (org-at-heading-p)
  6385. (point-at-eol)
  6386. (point))))
  6387. (level (looking-at "\\*+"))
  6388. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6389. (save-excursion
  6390. (save-restriction
  6391. (narrow-to-region beg end)
  6392. (when re
  6393. ;; Properly fold already folded siblings
  6394. (goto-char (point-min))
  6395. (while (re-search-forward re nil t)
  6396. (when (and (not (org-invisible-p))
  6397. (save-excursion
  6398. (goto-char (point-at-eol)) (org-invisible-p)))
  6399. (outline-hide-entry))))
  6400. (org-cycle-show-empty-lines 'overview)
  6401. (org-cycle-hide-drawers 'overview)))))
  6402. (defun org-cycle-show-empty-lines (state)
  6403. "Show empty lines above all visible headlines.
  6404. The region to be covered depends on STATE when called through
  6405. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6406. entire buffer covered. Note that an empty line is only shown if there
  6407. are at least `org-cycle-separator-lines' empty lines before the headline."
  6408. (when (/= org-cycle-separator-lines 0)
  6409. (save-excursion
  6410. (let* ((n (abs org-cycle-separator-lines))
  6411. (re (cond
  6412. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6413. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6414. (t (let ((ns (number-to-string (- n 2))))
  6415. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6416. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6417. beg end)
  6418. (cond
  6419. ((memq state '(overview contents t))
  6420. (setq beg (point-min) end (point-max)))
  6421. ((memq state '(children folded))
  6422. (setq beg (point)
  6423. end (progn (org-end-of-subtree t t)
  6424. (line-beginning-position 2)))))
  6425. (when beg
  6426. (goto-char beg)
  6427. (while (re-search-forward re end t)
  6428. (unless (get-char-property (match-end 1) 'invisible)
  6429. (let ((e (match-end 1))
  6430. (b (if (>= org-cycle-separator-lines 0)
  6431. (match-beginning 1)
  6432. (save-excursion
  6433. (goto-char (match-beginning 0))
  6434. (skip-chars-backward " \t\n")
  6435. (line-end-position)))))
  6436. (outline-flag-region b e nil))))))))
  6437. ;; Never hide empty lines at the end of the file.
  6438. (save-excursion
  6439. (goto-char (point-max))
  6440. (outline-previous-heading)
  6441. (outline-end-of-heading)
  6442. (when (and (looking-at "[ \t\n]+")
  6443. (= (match-end 0) (point-max)))
  6444. (outline-flag-region (point) (match-end 0) nil))))
  6445. (defun org-show-empty-lines-in-parent ()
  6446. "Move to the parent and re-show empty lines before visible headlines."
  6447. (save-excursion
  6448. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  6449. (org-cycle-show-empty-lines context))))
  6450. (defun org-files-list ()
  6451. "Return `org-agenda-files' list, plus all open Org files.
  6452. This is useful for operations that need to scan all of a user's
  6453. open and agenda-wise Org files."
  6454. (let ((files (mapcar 'expand-file-name (org-agenda-files))))
  6455. (dolist (buf (buffer-list))
  6456. (with-current-buffer buf
  6457. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  6458. (cl-pushnew (expand-file-name (buffer-file-name)) files))))
  6459. files))
  6460. (defsubst org-entry-beginning-position ()
  6461. "Return the beginning position of the current entry."
  6462. (save-excursion (org-back-to-heading t) (point)))
  6463. (defsubst org-entry-end-position ()
  6464. "Return the end position of the current entry."
  6465. (save-excursion (outline-next-heading) (point)))
  6466. (defun org-cycle-hide-drawers (state &optional exceptions)
  6467. "Re-hide all drawers after a visibility state change.
  6468. STATE should be one of the symbols listed in the docstring of
  6469. `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
  6470. a list of strings specifying which drawers should not be hidden."
  6471. (when (and (derived-mode-p 'org-mode)
  6472. (not (memq state '(overview folded contents))))
  6473. (save-excursion
  6474. (let* ((globalp (eq state 'all))
  6475. (beg (if globalp (point-min) (point)))
  6476. (end (if globalp (point-max)
  6477. (if (eq state 'children)
  6478. (save-excursion (outline-next-heading) (point))
  6479. (org-end-of-subtree t)))))
  6480. (goto-char beg)
  6481. (while (re-search-forward org-drawer-regexp (max end (point)) t)
  6482. (unless (member-ignore-case (match-string 1) exceptions)
  6483. (let ((drawer (org-element-at-point)))
  6484. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6485. (org-flag-drawer t drawer)
  6486. ;; Make sure to skip drawer entirely or we might flag
  6487. ;; it another time when matching its ending line with
  6488. ;; `org-drawer-regexp'.
  6489. (goto-char (org-element-property :end drawer))))))))))
  6490. (defun org-flag-drawer (flag &optional element)
  6491. "When FLAG is non-nil, hide the drawer we are at.
  6492. Otherwise make it visible. When optional argument ELEMENT is
  6493. a parsed drawer, as returned by `org-element-at-point', hide or
  6494. show that drawer instead."
  6495. (let ((drawer (or element
  6496. (and (save-excursion
  6497. (beginning-of-line)
  6498. (looking-at-p org-drawer-regexp))
  6499. (org-element-at-point)))))
  6500. (when (memq (org-element-type drawer) '(drawer property-drawer))
  6501. (let ((post (org-element-property :post-affiliated drawer)))
  6502. (save-excursion
  6503. (outline-flag-region
  6504. (progn (goto-char post) (line-end-position))
  6505. (progn (goto-char (org-element-property :end drawer))
  6506. (skip-chars-backward " \r\t\n")
  6507. (line-end-position))
  6508. flag))
  6509. ;; When the drawer is hidden away, make sure point lies in
  6510. ;; a visible part of the buffer.
  6511. (when (and flag (> (line-beginning-position) post))
  6512. (goto-char post))))))
  6513. (defun org-subtree-end-visible-p ()
  6514. "Is the end of the current subtree visible?"
  6515. (pos-visible-in-window-p
  6516. (save-excursion (org-end-of-subtree t) (point))))
  6517. (defun org-first-headline-recenter ()
  6518. "Move cursor to the first headline and recenter the headline."
  6519. (let ((window (get-buffer-window)))
  6520. (when window
  6521. (goto-char (point-min))
  6522. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  6523. (set-window-start window (line-beginning-position))))))
  6524. ;;; Saving and restoring visibility
  6525. (defun org-outline-overlay-data (&optional use-markers)
  6526. "Return a list of the locations of all outline overlays.
  6527. These are overlays with the `invisible' property value `outline'.
  6528. The return value is a list of cons cells, with start and stop
  6529. positions for each overlay.
  6530. If USE-MARKERS is set, return the positions as markers."
  6531. (let (beg end)
  6532. (org-with-wide-buffer
  6533. (delq nil
  6534. (mapcar (lambda (o)
  6535. (when (eq (overlay-get o 'invisible) 'outline)
  6536. (setq beg (overlay-start o)
  6537. end (overlay-end o))
  6538. (and beg end (> end beg)
  6539. (if use-markers
  6540. (cons (copy-marker beg)
  6541. (copy-marker end t))
  6542. (cons beg end)))))
  6543. (overlays-in (point-min) (point-max)))))))
  6544. (defun org-set-outline-overlay-data (data)
  6545. "Create visibility overlays for all positions in DATA.
  6546. DATA should have been made by `org-outline-overlay-data'."
  6547. (org-with-wide-buffer
  6548. (outline-show-all)
  6549. (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
  6550. ;;; Folding of blocks
  6551. (defvar-local org-hide-block-overlays nil
  6552. "Overlays hiding blocks.")
  6553. (defun org-block-map (function &optional start end)
  6554. "Call FUNCTION at the head of all source blocks in the current buffer.
  6555. Optional arguments START and END can be used to limit the range."
  6556. (let ((start (or start (point-min)))
  6557. (end (or end (point-max))))
  6558. (save-excursion
  6559. (goto-char start)
  6560. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  6561. (save-excursion
  6562. (save-match-data
  6563. (goto-char (match-beginning 0))
  6564. (funcall function)))))))
  6565. (defun org-hide-block-toggle-all ()
  6566. "Toggle the visibility of all blocks in the current buffer."
  6567. (org-block-map 'org-hide-block-toggle))
  6568. (defun org-hide-block-all ()
  6569. "Fold all blocks in the current buffer."
  6570. (interactive)
  6571. (org-show-block-all)
  6572. (org-block-map 'org-hide-block-toggle-maybe))
  6573. (defun org-show-block-all ()
  6574. "Unfold all blocks in the current buffer."
  6575. (interactive)
  6576. (mapc #'delete-overlay org-hide-block-overlays)
  6577. (setq org-hide-block-overlays nil))
  6578. (defun org-hide-block-toggle-maybe ()
  6579. "Toggle visibility of block at point.
  6580. Unlike to `org-hide-block-toggle', this function does not throw
  6581. an error. Return a non-nil value when toggling is successful."
  6582. (interactive)
  6583. (ignore-errors (org-hide-block-toggle)))
  6584. (defun org-hide-block-toggle (&optional force)
  6585. "Toggle the visibility of the current block.
  6586. When optional argument FORCE is `off', make block visible. If it
  6587. is non-nil, hide it unconditionally. Throw an error when not at
  6588. a block. Return a non-nil value when toggling is successful."
  6589. (interactive)
  6590. (let ((element (org-element-at-point)))
  6591. (unless (memq (org-element-type element)
  6592. '(center-block comment-block dynamic-block example-block
  6593. export-block quote-block special-block
  6594. src-block verse-block))
  6595. (user-error "Not at a block"))
  6596. (let* ((start (save-excursion
  6597. (goto-char (org-element-property :post-affiliated element))
  6598. (line-end-position)))
  6599. (end (save-excursion
  6600. (goto-char (org-element-property :end element))
  6601. (skip-chars-backward " \r\t\n")
  6602. (line-end-position)))
  6603. (overlays (overlays-at start)))
  6604. (cond
  6605. ;; Do nothing when not before or at the block opening line or
  6606. ;; at the block closing line.
  6607. ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
  6608. ((and (not (eq force 'off))
  6609. (not (memq t (mapcar
  6610. (lambda (o)
  6611. (eq (overlay-get o 'invisible) 'org-hide-block))
  6612. overlays))))
  6613. (let ((ov (make-overlay start end)))
  6614. (overlay-put ov 'invisible 'org-hide-block)
  6615. ;; Make the block accessible to `isearch'.
  6616. (overlay-put
  6617. ov 'isearch-open-invisible
  6618. (lambda (ov)
  6619. (when (memq ov org-hide-block-overlays)
  6620. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6621. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6622. (delete-overlay ov))))
  6623. (push ov org-hide-block-overlays)
  6624. ;; When the block is hidden away, make sure point is left in
  6625. ;; a visible part of the buffer.
  6626. (when (> (line-beginning-position) start)
  6627. (goto-char start)
  6628. (beginning-of-line))
  6629. ;; Signal successful toggling.
  6630. t))
  6631. ((or (not force) (eq force 'off))
  6632. (dolist (ov overlays t)
  6633. (when (memq ov org-hide-block-overlays)
  6634. (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
  6635. (when (eq (overlay-get ov 'invisible) 'org-hide-block)
  6636. (delete-overlay ov))))))))
  6637. ;; Remove overlays when changing major mode
  6638. (add-hook 'org-mode-hook
  6639. (lambda () (add-hook 'change-major-mode-hook
  6640. 'org-show-block-all 'append 'local)))
  6641. ;;; Org-goto
  6642. (defvar org-goto-window-configuration nil)
  6643. (defvar org-goto-marker nil)
  6644. (defvar org-goto-map)
  6645. (defun org-goto-map ()
  6646. "Set the keymap `org-goto'."
  6647. (setq org-goto-map
  6648. (let ((map (make-sparse-keymap)))
  6649. (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
  6650. mouse-drag-region universal-argument org-occur)))
  6651. (dolist (cmd cmds)
  6652. (substitute-key-definition cmd cmd map global-map)))
  6653. (suppress-keymap map)
  6654. (org-defkey map "\C-m" 'org-goto-ret)
  6655. (org-defkey map [(return)] 'org-goto-ret)
  6656. (org-defkey map [(left)] 'org-goto-left)
  6657. (org-defkey map [(right)] 'org-goto-right)
  6658. (org-defkey map [(control ?g)] 'org-goto-quit)
  6659. (org-defkey map "\C-i" 'org-cycle)
  6660. (org-defkey map [(tab)] 'org-cycle)
  6661. (org-defkey map [(down)] 'outline-next-visible-heading)
  6662. (org-defkey map [(up)] 'outline-previous-visible-heading)
  6663. (if org-goto-auto-isearch
  6664. (if (fboundp 'define-key-after)
  6665. (define-key-after map [t] 'org-goto-local-auto-isearch)
  6666. nil)
  6667. (org-defkey map "q" 'org-goto-quit)
  6668. (org-defkey map "n" 'outline-next-visible-heading)
  6669. (org-defkey map "p" 'outline-previous-visible-heading)
  6670. (org-defkey map "f" 'outline-forward-same-level)
  6671. (org-defkey map "b" 'outline-backward-same-level)
  6672. (org-defkey map "u" 'outline-up-heading))
  6673. (org-defkey map "/" 'org-occur)
  6674. (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
  6675. (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
  6676. (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
  6677. (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
  6678. (org-defkey map "\C-c\C-u" 'outline-up-heading)
  6679. map)))
  6680. (defconst org-goto-help
  6681. "Browse buffer copy, to find location or copy text.%s
  6682. RET=jump to location C-g=quit and return to previous location
  6683. \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
  6684. (defvar org-goto-start-pos) ; dynamically scoped parameter
  6685. (defun org-goto (&optional alternative-interface)
  6686. "Look up a different location in the current file, keeping current visibility.
  6687. When you want look-up or go to a different location in a
  6688. document, the fastest way is often to fold the entire buffer and
  6689. then dive into the tree. This method has the disadvantage, that
  6690. the previous location will be folded, which may not be what you
  6691. want.
  6692. This command works around this by showing a copy of the current
  6693. buffer in an indirect buffer, in overview mode. You can dive
  6694. into the tree in that copy, use org-occur and incremental search
  6695. to find a location. When pressing RET or `Q', the command
  6696. returns to the original buffer in which the visibility is still
  6697. unchanged. After RET it will also jump to the location selected
  6698. in the indirect buffer and expose the headline hierarchy above.
  6699. With a prefix argument, use the alternative interface: e.g., if
  6700. `org-goto-interface' is `outline' use `outline-path-completion'."
  6701. (interactive "P")
  6702. (org-goto-map)
  6703. (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
  6704. (org-refile-use-outline-path t)
  6705. (org-refile-target-verify-function nil)
  6706. (interface
  6707. (if (not alternative-interface)
  6708. org-goto-interface
  6709. (if (eq org-goto-interface 'outline)
  6710. 'outline-path-completion
  6711. 'outline)))
  6712. (org-goto-start-pos (point))
  6713. (selected-point
  6714. (if (eq interface 'outline)
  6715. (car (org-get-location (current-buffer) org-goto-help))
  6716. (let ((pa (org-refile-get-location "Goto")))
  6717. (org-refile-check-position pa)
  6718. (nth 3 pa)))))
  6719. (if selected-point
  6720. (progn
  6721. (org-mark-ring-push org-goto-start-pos)
  6722. (goto-char selected-point)
  6723. (when (or (org-invisible-p) (org-invisible-p2))
  6724. (org-show-context 'org-goto)))
  6725. (message "Quit"))))
  6726. (defvar org-goto-selected-point nil) ; dynamically scoped parameter
  6727. (defvar org-goto-exit-command nil) ; dynamically scoped parameter
  6728. (defvar org-goto-local-auto-isearch-map) ; defined below
  6729. (defun org-get-location (_buf help)
  6730. "Let the user select a location in current buffer.
  6731. This function uses a recursive edit. It returns the selected position
  6732. or nil."
  6733. (org-no-popups
  6734. (let ((isearch-mode-map org-goto-local-auto-isearch-map)
  6735. (isearch-hide-immediately nil)
  6736. (isearch-search-fun-function
  6737. (lambda () 'org-goto-local-search-headings))
  6738. (org-goto-selected-point org-goto-exit-command))
  6739. (save-excursion
  6740. (save-window-excursion
  6741. (delete-other-windows)
  6742. (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
  6743. (pop-to-buffer-same-window
  6744. (condition-case nil
  6745. (make-indirect-buffer (current-buffer) "*org-goto*")
  6746. (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
  6747. (with-output-to-temp-buffer "*Org Help*"
  6748. (princ (format help (if org-goto-auto-isearch
  6749. " Just type for auto-isearch."
  6750. " n/p/f/b/u to navigate, q to quit."))))
  6751. (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
  6752. (setq buffer-read-only nil)
  6753. (let ((org-startup-truncated t)
  6754. (org-startup-folded nil)
  6755. (org-startup-align-all-tables nil))
  6756. (org-mode)
  6757. (org-overview))
  6758. (setq buffer-read-only t)
  6759. (if (and (boundp 'org-goto-start-pos)
  6760. (integer-or-marker-p org-goto-start-pos))
  6761. (progn (goto-char org-goto-start-pos)
  6762. (when (org-invisible-p)
  6763. (org-show-set-visibility 'lineage)))
  6764. (goto-char (point-min)))
  6765. (let (org-special-ctrl-a/e) (org-beginning-of-line))
  6766. (message "Select location and press RET")
  6767. (use-local-map org-goto-map)
  6768. (recursive-edit)))
  6769. (kill-buffer "*org-goto*")
  6770. (cons org-goto-selected-point org-goto-exit-command))))
  6771. (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
  6772. (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
  6773. ;; `isearch-other-control-char' was removed in Emacs 24.4.
  6774. (if (fboundp 'isearch-other-control-char)
  6775. (progn
  6776. (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
  6777. (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
  6778. (define-key org-goto-local-auto-isearch-map "\C-i" nil)
  6779. (define-key org-goto-local-auto-isearch-map "\C-m" nil)
  6780. (define-key org-goto-local-auto-isearch-map [return] nil))
  6781. (defun org-goto-local-search-headings (string bound noerror)
  6782. "Search and make sure that any matches are in headlines."
  6783. (catch 'return
  6784. (while (if isearch-forward
  6785. (search-forward string bound noerror)
  6786. (search-backward string bound noerror))
  6787. (when (save-match-data
  6788. (and (save-excursion
  6789. (beginning-of-line)
  6790. (looking-at org-complex-heading-regexp))
  6791. (or (not (match-beginning 5))
  6792. (< (point) (match-beginning 5)))))
  6793. (throw 'return (point))))))
  6794. (defun org-goto-local-auto-isearch ()
  6795. "Start isearch."
  6796. (interactive)
  6797. (goto-char (point-min))
  6798. (let ((keys (this-command-keys)))
  6799. (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
  6800. (isearch-mode t)
  6801. (isearch-process-search-char (string-to-char keys)))))
  6802. (defun org-goto-ret (&optional _arg)
  6803. "Finish `org-goto' by going to the new location."
  6804. (interactive "P")
  6805. (setq org-goto-selected-point (point))
  6806. (setq org-goto-exit-command 'return)
  6807. (throw 'exit nil))
  6808. (defun org-goto-left ()
  6809. "Finish `org-goto' by going to the new location."
  6810. (interactive)
  6811. (if (org-at-heading-p)
  6812. (progn
  6813. (beginning-of-line 1)
  6814. (setq org-goto-selected-point (point)
  6815. org-goto-exit-command 'left)
  6816. (throw 'exit nil))
  6817. (user-error "Not on a heading")))
  6818. (defun org-goto-right ()
  6819. "Finish `org-goto' by going to the new location."
  6820. (interactive)
  6821. (if (org-at-heading-p)
  6822. (progn
  6823. (setq org-goto-selected-point (point)
  6824. org-goto-exit-command 'right)
  6825. (throw 'exit nil))
  6826. (user-error "Not on a heading")))
  6827. (defun org-goto-quit ()
  6828. "Finish `org-goto' without cursor motion."
  6829. (interactive)
  6830. (setq org-goto-selected-point nil)
  6831. (setq org-goto-exit-command 'quit)
  6832. (throw 'exit nil))
  6833. ;;; Indirect buffer display of subtrees
  6834. (defvar org-indirect-dedicated-frame nil
  6835. "This is the frame being used for indirect tree display.")
  6836. (defvar org-last-indirect-buffer nil)
  6837. (defun org-tree-to-indirect-buffer (&optional arg)
  6838. "Create indirect buffer and narrow it to current subtree.
  6839. With a numerical prefix ARG, go up to this level and then take that tree.
  6840. If ARG is negative, go up that many levels.
  6841. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6842. indirect buffer previously made with this command, to avoid proliferation of
  6843. indirect buffers. However, when you call the command with a \
  6844. `\\[universal-argument]' prefix, or
  6845. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6846. so that you can work with several indirect buffers at the same time. If
  6847. `org-indirect-buffer-display' is `dedicated-frame', the \
  6848. `\\[universal-argument]' prefix also
  6849. requests that a new frame be made for the new buffer, so that the dedicated
  6850. frame is not changed."
  6851. (interactive "P")
  6852. (let ((cbuf (current-buffer))
  6853. (cwin (selected-window))
  6854. (pos (point))
  6855. beg end level heading ibuf)
  6856. (save-excursion
  6857. (org-back-to-heading t)
  6858. (when (numberp arg)
  6859. (setq level (org-outline-level))
  6860. (when (< arg 0) (setq arg (+ level arg)))
  6861. (while (> (setq level (org-outline-level)) arg)
  6862. (org-up-heading-safe)))
  6863. (setq beg (point)
  6864. heading (org-get-heading 'no-tags))
  6865. (org-end-of-subtree t t)
  6866. (when (org-at-heading-p) (backward-char 1))
  6867. (setq end (point)))
  6868. (when (and (buffer-live-p org-last-indirect-buffer)
  6869. (not (eq org-indirect-buffer-display 'new-frame))
  6870. (not arg))
  6871. (kill-buffer org-last-indirect-buffer))
  6872. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6873. org-last-indirect-buffer ibuf)
  6874. (cond
  6875. ((or (eq org-indirect-buffer-display 'new-frame)
  6876. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6877. (select-frame (make-frame))
  6878. (delete-other-windows)
  6879. (pop-to-buffer-same-window ibuf)
  6880. (org-set-frame-title heading))
  6881. ((eq org-indirect-buffer-display 'dedicated-frame)
  6882. (raise-frame
  6883. (select-frame (or (and org-indirect-dedicated-frame
  6884. (frame-live-p org-indirect-dedicated-frame)
  6885. org-indirect-dedicated-frame)
  6886. (setq org-indirect-dedicated-frame (make-frame)))))
  6887. (delete-other-windows)
  6888. (pop-to-buffer-same-window ibuf)
  6889. (org-set-frame-title (concat "Indirect: " heading)))
  6890. ((eq org-indirect-buffer-display 'current-window)
  6891. (pop-to-buffer-same-window ibuf))
  6892. ((eq org-indirect-buffer-display 'other-window)
  6893. (pop-to-buffer ibuf))
  6894. (t (error "Invalid value")))
  6895. (narrow-to-region beg end)
  6896. (outline-show-all)
  6897. (goto-char pos)
  6898. (run-hook-with-args 'org-cycle-hook 'all)
  6899. (and (window-live-p cwin) (select-window cwin))))
  6900. (defun org-get-indirect-buffer (&optional buffer heading)
  6901. (setq buffer (or buffer (current-buffer)))
  6902. (let ((n 1) (base (buffer-name buffer)) bname)
  6903. (while (buffer-live-p
  6904. (get-buffer
  6905. (setq bname
  6906. (concat base "-"
  6907. (if heading (concat heading "-" (number-to-string n))
  6908. (number-to-string n))))))
  6909. (setq n (1+ n)))
  6910. (condition-case nil
  6911. (make-indirect-buffer buffer bname 'clone)
  6912. (error (make-indirect-buffer buffer bname)))))
  6913. (defun org-set-frame-title (title)
  6914. "Set the title of the current frame to the string TITLE."
  6915. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6916. ;;;; Structure editing
  6917. ;;; Inserting headlines
  6918. (defun org--line-empty-p (n)
  6919. "Is the Nth next line empty?
  6920. Counts the current line as N = 1 and the previous line as N = 0;
  6921. see `beginning-of-line'."
  6922. (save-excursion
  6923. (and (not (bobp))
  6924. (or (beginning-of-line n) t)
  6925. (save-match-data
  6926. (looking-at "[ \t]*$")))))
  6927. (defun org-previous-line-empty-p ()
  6928. "Is the previous line a blank line?
  6929. When NEXT is non-nil, check the next line instead."
  6930. (org--line-empty-p 0))
  6931. (defun org-next-line-empty-p ()
  6932. "Is the previous line a blank line?
  6933. When NEXT is non-nil, check the next line instead."
  6934. (org--line-empty-p 2))
  6935. (defun org-insert-heading (&optional arg invisible-ok top)
  6936. "Insert a new heading or an item with the same depth at point.
  6937. If point is at the beginning of a heading or a list item, insert
  6938. a new heading or a new item above the current one. When at the
  6939. beginning of a regular line of text, turn it into a heading.
  6940. If point is in the middle of a line, split it and create a new
  6941. headline/item with the text in the current line after point (see
  6942. `org-M-RET-may-split-line' on how to modify this behavior). As
  6943. a special case, on a headline, splitting can only happen on the
  6944. title itself. E.g., this excludes breaking stars or tags.
  6945. With a `\\[universal-argument]' prefix, set \
  6946. `org-insert-heading-respect-content' to
  6947. a non-nil value for the duration of the command. This forces the
  6948. insertion of a heading after the current subtree, independently
  6949. on the location of point.
  6950. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6951. insert the heading at the end of the tree
  6952. above the current heading. For example, if point is within a
  6953. 2nd-level heading, then it will insert a 2nd-level heading at
  6954. the end of the 1st-level parent subtree.
  6955. When INVISIBLE-OK is set, stop at invisible headlines when going
  6956. back. This is important for non-interactive uses of the
  6957. command.
  6958. When optional argument TOP is non-nil, insert a level 1 heading,
  6959. unconditionally."
  6960. (interactive "P")
  6961. (let ((itemp (and (not top) (org-in-item-p)))
  6962. (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
  6963. (respect-content (or org-insert-heading-respect-content
  6964. (equal arg '(4))))
  6965. (initial-content ""))
  6966. (cond
  6967. ((or (= (buffer-size) 0)
  6968. (and (not (save-excursion
  6969. (and (ignore-errors (org-back-to-heading invisible-ok))
  6970. (org-at-heading-p))))
  6971. (or arg (not itemp))))
  6972. ;; At beginning of buffer or so high up that only a heading
  6973. ;; makes sense.
  6974. (cond ((and (bolp) (not respect-content)) (insert "* "))
  6975. ((not respect-content)
  6976. (unless may-split (end-of-line))
  6977. (insert "\n* "))
  6978. ((re-search-forward org-outline-regexp-bol nil t)
  6979. (beginning-of-line)
  6980. (insert "* \n")
  6981. (backward-char))
  6982. (t (goto-char (point-max))
  6983. (insert "\n* ")))
  6984. (run-hooks 'org-insert-heading-hook))
  6985. ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
  6986. (t
  6987. ;; Maybe move at the end of the subtree
  6988. (when (equal arg '(16))
  6989. (org-up-heading-safe)
  6990. (org-end-of-subtree t))
  6991. ;; Insert a heading
  6992. (save-restriction
  6993. (widen)
  6994. (let* ((level nil)
  6995. (on-heading (org-at-heading-p))
  6996. (empty-line-p (if on-heading
  6997. (org-previous-line-empty-p)
  6998. ;; We will decide later
  6999. nil))
  7000. ;; Get a level string to fall back on.
  7001. (fix-level
  7002. (if (org-before-first-heading-p) "*"
  7003. (save-excursion
  7004. (org-back-to-heading t)
  7005. (when (org-previous-line-empty-p) (setq empty-line-p t))
  7006. (looking-at org-outline-regexp)
  7007. (make-string (1- (length (match-string 0))) ?*))))
  7008. (stars
  7009. (save-excursion
  7010. (condition-case nil
  7011. (if top "* "
  7012. (org-back-to-heading invisible-ok)
  7013. (when (and (not on-heading)
  7014. (featurep 'org-inlinetask)
  7015. (integerp org-inlinetask-min-level)
  7016. (>= (length (match-string 0))
  7017. org-inlinetask-min-level))
  7018. ;; Find a heading level before the inline
  7019. ;; task.
  7020. (while (and (setq level (org-up-heading-safe))
  7021. (>= level org-inlinetask-min-level)))
  7022. (if (org-at-heading-p)
  7023. (org-back-to-heading invisible-ok)
  7024. (error "This should not happen")))
  7025. (unless (and (save-excursion
  7026. (save-match-data
  7027. (org-backward-heading-same-level
  7028. 1 invisible-ok))
  7029. (= (point) (match-beginning 0)))
  7030. (not (org-next-line-empty-p)))
  7031. (setq empty-line-p (or empty-line-p
  7032. (org-previous-line-empty-p))))
  7033. (match-string 0))
  7034. (error (or fix-level "* ")))))
  7035. (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
  7036. (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
  7037. ;; If we insert after content, move there and clean up
  7038. ;; whitespace.
  7039. (when respect-content
  7040. (if (not (org-before-first-heading-p))
  7041. (org-end-of-subtree nil t)
  7042. (re-search-forward org-outline-regexp-bol)
  7043. (beginning-of-line 0))
  7044. (skip-chars-backward " \r\t\n")
  7045. (and (not (looking-back "^\\*+" (line-beginning-position)))
  7046. (looking-at "[ \t]+") (replace-match ""))
  7047. (unless (eobp) (forward-char 1))
  7048. (when (looking-at "^\\*")
  7049. (unless (bobp) (backward-char 1))
  7050. (insert "\n")))
  7051. ;; If we are splitting, grab the text that should be moved
  7052. ;; to the new headline.
  7053. (when may-split
  7054. (if (org-at-heading-p)
  7055. ;; This is a heading: split intelligently (keeping
  7056. ;; tags).
  7057. (let ((pos (point)))
  7058. (beginning-of-line)
  7059. (let ((case-fold-search nil))
  7060. (unless (looking-at org-complex-heading-regexp)
  7061. (error "This should not happen")))
  7062. (when (and (match-beginning 4)
  7063. (> pos (match-beginning 4))
  7064. (< pos (match-end 4)))
  7065. (setq initial-content (buffer-substring pos (match-end 4)))
  7066. (goto-char pos)
  7067. (delete-region (point) (match-end 4))
  7068. (if (looking-at "[ \t]*$")
  7069. (replace-match "")
  7070. (insert (make-string (length initial-content) ?\s)))
  7071. (setq initial-content (org-trim initial-content)))
  7072. (goto-char pos))
  7073. ;; A normal line.
  7074. (setq initial-content
  7075. (org-trim
  7076. (delete-and-extract-region (point) (line-end-position))))))
  7077. ;; If we are at the beginning of the line, insert before it.
  7078. ;; Otherwise, after it.
  7079. (cond
  7080. ((and (bolp) (looking-at "[ \t]*$")))
  7081. ((bolp) (save-excursion (insert "\n")))
  7082. (t (end-of-line)
  7083. (insert "\n")))
  7084. ;; Insert the new heading
  7085. (insert stars)
  7086. (just-one-space)
  7087. (insert initial-content)
  7088. (unless (and blank (org-previous-line-empty-p))
  7089. (org-N-empty-lines-before-current (if blank 1 0)))
  7090. ;; Adjust visibility, which may be messed up if we removed
  7091. ;; blank lines while previous entry was hidden.
  7092. (let ((bol (line-beginning-position)))
  7093. (dolist (o (overlays-at (1- bol)))
  7094. (when (and (eq (overlay-get o 'invisible) 'outline)
  7095. (eq (overlay-end o) bol))
  7096. (move-overlay o (overlay-start o) (1- bol)))))
  7097. (run-hooks 'org-insert-heading-hook)))))))
  7098. (defun org-N-empty-lines-before-current (N)
  7099. "Make the number of empty lines before current exactly N.
  7100. So this will delete or add empty lines."
  7101. (save-excursion
  7102. (beginning-of-line)
  7103. (let ((p (point)))
  7104. (skip-chars-backward " \r\t\n")
  7105. (unless (bolp) (forward-line))
  7106. (delete-region (point) p))
  7107. (when (> N 0) (insert (make-string N ?\n)))))
  7108. (defun org-get-heading (&optional no-tags no-todo)
  7109. "Return the heading of the current entry, without the stars.
  7110. When NO-TAGS is non-nil, don't include tags.
  7111. When NO-TODO is non-nil, don't include TODO keywords."
  7112. (save-excursion
  7113. (org-back-to-heading t)
  7114. (let ((case-fold-search nil))
  7115. (cond
  7116. ((and no-tags no-todo)
  7117. (looking-at org-complex-heading-regexp)
  7118. ;; Return value has to be a string, but match group 4 is
  7119. ;; optional.
  7120. (or (match-string 4) ""))
  7121. (no-tags
  7122. (looking-at (concat org-outline-regexp
  7123. "\\(.*?\\)"
  7124. "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
  7125. (match-string 1))
  7126. (no-todo
  7127. (looking-at org-todo-line-regexp)
  7128. (match-string 3))
  7129. (t (looking-at org-heading-regexp)
  7130. (match-string 2))))))
  7131. (defvar orgstruct-mode) ; defined below
  7132. (defun org-heading-components ()
  7133. "Return the components of the current heading.
  7134. This is a list with the following elements:
  7135. - the level as an integer
  7136. - the reduced level, different if `org-odd-levels-only' is set.
  7137. - the TODO keyword, or nil
  7138. - the priority character, like ?A, or nil if no priority is given
  7139. - the headline text itself, or the tags string if no headline text
  7140. - the tags string, or nil."
  7141. (save-excursion
  7142. (org-back-to-heading t)
  7143. (when (let (case-fold-search)
  7144. (looking-at
  7145. (if orgstruct-mode
  7146. org-heading-regexp
  7147. org-complex-heading-regexp)))
  7148. (if orgstruct-mode
  7149. (list (length (match-string 1))
  7150. (org-reduced-level (length (match-string 1)))
  7151. nil
  7152. nil
  7153. (match-string 2)
  7154. nil)
  7155. (list (length (match-string 1))
  7156. (org-reduced-level (length (match-string 1)))
  7157. (match-string-no-properties 2)
  7158. (and (match-end 3) (aref (match-string 3) 2))
  7159. (match-string-no-properties 4)
  7160. (match-string-no-properties 5))))))
  7161. (defun org-get-entry ()
  7162. "Get the entry text, after heading, entire subtree."
  7163. (save-excursion
  7164. (org-back-to-heading t)
  7165. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  7166. (defun org-edit-headline (&optional heading)
  7167. "Edit the current headline.
  7168. Set it to HEADING when provided."
  7169. (interactive)
  7170. (org-with-wide-buffer
  7171. (org-back-to-heading t)
  7172. (let ((case-fold-search nil))
  7173. (when (looking-at org-complex-heading-regexp)
  7174. (let* ((old (match-string-no-properties 4))
  7175. (new (save-match-data
  7176. (org-trim (or heading (read-string "Edit: " old))))))
  7177. (unless (equal old new)
  7178. (if old (replace-match new t t nil 4)
  7179. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  7180. (insert " " new))
  7181. (org-set-tags nil t)
  7182. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  7183. (defun org-insert-heading-after-current ()
  7184. "Insert a new heading with same level as current, after current subtree."
  7185. (interactive)
  7186. (org-back-to-heading)
  7187. (org-insert-heading)
  7188. (org-move-subtree-down)
  7189. (end-of-line 1))
  7190. (defun org-insert-heading-respect-content (&optional invisible-ok)
  7191. "Insert heading with `org-insert-heading-respect-content' set to t."
  7192. (interactive)
  7193. (org-insert-heading '(4) invisible-ok))
  7194. (defun org-insert-todo-heading-respect-content (&optional force-state)
  7195. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  7196. (interactive)
  7197. (org-insert-todo-heading force-state '(4)))
  7198. (defun org-insert-todo-heading (arg &optional force-heading)
  7199. "Insert a new heading with the same level and TODO state as current heading.
  7200. If the heading has no TODO state, or if the state is DONE, use
  7201. the first state (TODO by default). Also with one prefix arg,
  7202. force first state. With two prefix args, force inserting at the
  7203. end of the parent subtree.
  7204. When called at a plain list item, insert a new item with an
  7205. unchecked check box."
  7206. (interactive "P")
  7207. (when (or force-heading (not (org-insert-item 'checkbox)))
  7208. (org-insert-heading (or (and (equal arg '(16)) '(16))
  7209. force-heading))
  7210. (save-excursion
  7211. (org-back-to-heading)
  7212. (outline-previous-heading)
  7213. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  7214. (let* ((new-mark-x
  7215. (if (or (equal arg '(4))
  7216. (not (match-beginning 2))
  7217. (member (match-string 2) org-done-keywords))
  7218. (car org-todo-keywords-1)
  7219. (match-string 2)))
  7220. (new-mark
  7221. (or
  7222. (run-hook-with-args-until-success
  7223. 'org-todo-get-default-hook new-mark-x nil)
  7224. new-mark-x)))
  7225. (beginning-of-line 1)
  7226. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  7227. (if org-treat-insert-todo-heading-as-state-change
  7228. (org-todo new-mark)
  7229. (insert new-mark " "))))
  7230. (when org-provide-todo-statistics
  7231. (org-update-parent-todo-statistics))))
  7232. (defun org-insert-subheading (arg)
  7233. "Insert a new subheading and demote it.
  7234. Works for outline headings and for plain lists alike."
  7235. (interactive "P")
  7236. (org-insert-heading arg)
  7237. (cond
  7238. ((org-at-heading-p) (org-do-demote))
  7239. ((org-at-item-p) (org-indent-item))))
  7240. (defun org-insert-todo-subheading (arg)
  7241. "Insert a new subheading with TODO keyword or checkbox and demote it.
  7242. Works for outline headings and for plain lists alike."
  7243. (interactive "P")
  7244. (org-insert-todo-heading arg)
  7245. (cond
  7246. ((org-at-heading-p) (org-do-demote))
  7247. ((org-at-item-p) (org-indent-item))))
  7248. ;;; Promotion and Demotion
  7249. (defvar org-after-demote-entry-hook nil
  7250. "Hook run after an entry has been demoted.
  7251. The cursor will be at the beginning of the entry.
  7252. When a subtree is being demoted, the hook will be called for each node.")
  7253. (defvar org-after-promote-entry-hook nil
  7254. "Hook run after an entry has been promoted.
  7255. The cursor will be at the beginning of the entry.
  7256. When a subtree is being promoted, the hook will be called for each node.")
  7257. (defun org-promote-subtree ()
  7258. "Promote the entire subtree.
  7259. See also `org-promote'."
  7260. (interactive)
  7261. (save-excursion
  7262. (org-with-limited-levels (org-map-tree 'org-promote)))
  7263. (org-fix-position-after-promote))
  7264. (defun org-demote-subtree ()
  7265. "Demote the entire subtree.
  7266. See `org-demote' and `org-promote'."
  7267. (interactive)
  7268. (save-excursion
  7269. (org-with-limited-levels (org-map-tree 'org-demote)))
  7270. (org-fix-position-after-promote))
  7271. (defun org-do-promote ()
  7272. "Promote the current heading higher up the tree.
  7273. If the region is active in `transient-mark-mode', promote all
  7274. headings in the region."
  7275. (interactive)
  7276. (save-excursion
  7277. (if (org-region-active-p)
  7278. (org-map-region 'org-promote (region-beginning) (region-end))
  7279. (org-promote)))
  7280. (org-fix-position-after-promote))
  7281. (defun org-do-demote ()
  7282. "Demote the current heading lower down the tree.
  7283. If the region is active in `transient-mark-mode', demote all
  7284. headings in the region."
  7285. (interactive)
  7286. (save-excursion
  7287. (if (org-region-active-p)
  7288. (org-map-region 'org-demote (region-beginning) (region-end))
  7289. (org-demote)))
  7290. (org-fix-position-after-promote))
  7291. (defun org-fix-position-after-promote ()
  7292. "Fix cursor position and indentation after demoting/promoting."
  7293. (let ((pos (point)))
  7294. (when (save-excursion
  7295. (beginning-of-line)
  7296. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  7297. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  7298. (cond ((eobp) (insert " "))
  7299. ((eolp) (insert " "))
  7300. ((equal (char-after) ?\s) (forward-char 1))))))
  7301. (defun org-current-level ()
  7302. "Return the level of the current entry, or nil if before the first headline.
  7303. The level is the number of stars at the beginning of the
  7304. headline. Use `org-reduced-level' to remove the effect of
  7305. `org-odd-levels'. Unlike to `org-outline-level', this function
  7306. ignores inlinetasks."
  7307. (let ((level (org-with-limited-levels (org-outline-level))))
  7308. (and (> level 0) level)))
  7309. (defun org-get-previous-line-level ()
  7310. "Return the outline depth of the last headline before the current line.
  7311. Returns 0 for the first headline in the buffer, and nil if before the
  7312. first headline."
  7313. (and (org-current-level)
  7314. (or (and (/= (line-beginning-position) (point-min))
  7315. (save-excursion (beginning-of-line 0) (org-current-level)))
  7316. 0)))
  7317. (defun org-reduced-level (l)
  7318. "Compute the effective level of a heading.
  7319. This takes into account the setting of `org-odd-levels-only'."
  7320. (cond
  7321. ((zerop l) 0)
  7322. (org-odd-levels-only (1+ (floor (/ l 2))))
  7323. (t l)))
  7324. (defun org-level-increment ()
  7325. "Return the number of stars that will be added or removed at a
  7326. time to headlines when structure editing, based on the value of
  7327. `org-odd-levels-only'."
  7328. (if org-odd-levels-only 2 1))
  7329. (defun org-get-valid-level (level &optional change)
  7330. "Rectify a level change under the influence of `org-odd-levels-only'
  7331. LEVEL is a current level, CHANGE is by how much the level should be
  7332. modified. Even if CHANGE is nil, LEVEL may be returned modified because
  7333. even level numbers will become the next higher odd number."
  7334. (if org-odd-levels-only
  7335. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  7336. ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
  7337. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  7338. (max 1 (+ level (or change 0)))))
  7339. (defun org-promote ()
  7340. "Promote the current heading higher up the tree."
  7341. (org-with-wide-buffer
  7342. (org-back-to-heading t)
  7343. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7344. after-change-functions))
  7345. (level (save-match-data (funcall outline-level)))
  7346. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  7347. (diff (abs (- level (length up-head) -1))))
  7348. (cond
  7349. ((and (= level 1) org-allow-promoting-top-level-subtree)
  7350. (replace-match "# " nil t))
  7351. ((= level 1)
  7352. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  7353. (t (replace-match up-head nil t)))
  7354. (unless (= level 1)
  7355. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7356. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  7357. (run-hooks 'org-after-promote-entry-hook))))
  7358. (defun org-demote ()
  7359. "Demote the current heading lower down the tree."
  7360. (org-with-wide-buffer
  7361. (org-back-to-heading t)
  7362. (let* ((after-change-functions (remq 'flyspell-after-change-function
  7363. after-change-functions))
  7364. (level (save-match-data (funcall outline-level)))
  7365. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  7366. (diff (abs (- level (length down-head) -1))))
  7367. (replace-match down-head nil t)
  7368. (when org-auto-align-tags (org-set-tags nil 'ignore-column))
  7369. (when org-adapt-indentation (org-fixup-indentation diff))
  7370. (run-hooks 'org-after-demote-entry-hook))))
  7371. (defun org-cycle-level ()
  7372. "Cycle the level of an empty headline through possible states.
  7373. This goes first to child, then to parent, level, then up the hierarchy.
  7374. After top level, it switches back to sibling level."
  7375. (interactive)
  7376. (let ((org-adapt-indentation nil))
  7377. (when (org-point-at-end-of-empty-headline)
  7378. (setq this-command 'org-cycle-level) ; Only needed for caching
  7379. (let ((cur-level (org-current-level))
  7380. (prev-level (org-get-previous-line-level)))
  7381. (cond
  7382. ;; If first headline in file, promote to top-level.
  7383. ((= prev-level 0)
  7384. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7385. do (org-do-promote)))
  7386. ;; If same level as prev, demote one.
  7387. ((= prev-level cur-level)
  7388. (org-do-demote))
  7389. ;; If parent is top-level, promote to top level if not already.
  7390. ((= prev-level 1)
  7391. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  7392. do (org-do-promote)))
  7393. ;; If top-level, return to prev-level.
  7394. ((= cur-level 1)
  7395. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  7396. do (org-do-demote)))
  7397. ;; If less than prev-level, promote one.
  7398. ((< cur-level prev-level)
  7399. (org-do-promote))
  7400. ;; If deeper than prev-level, promote until higher than
  7401. ;; prev-level.
  7402. ((> cur-level prev-level)
  7403. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  7404. do (org-do-promote))))
  7405. t))))
  7406. (defun org-map-tree (fun)
  7407. "Call FUN for every heading underneath the current one."
  7408. (org-back-to-heading t)
  7409. (let ((level (funcall outline-level)))
  7410. (save-excursion
  7411. (funcall fun)
  7412. (while (and (progn
  7413. (outline-next-heading)
  7414. (> (funcall outline-level) level))
  7415. (not (eobp)))
  7416. (funcall fun)))))
  7417. (defun org-map-region (fun beg end)
  7418. "Call FUN for every heading between BEG and END."
  7419. (let ((org-ignore-region t))
  7420. (save-excursion
  7421. (setq end (copy-marker end))
  7422. (goto-char beg)
  7423. (when (and (re-search-forward org-outline-regexp-bol nil t)
  7424. (< (point) end))
  7425. (funcall fun))
  7426. (while (and (progn
  7427. (outline-next-heading)
  7428. (< (point) end))
  7429. (not (eobp)))
  7430. (funcall fun)))))
  7431. (defun org-fixup-indentation (diff)
  7432. "Change the indentation in the current entry by DIFF.
  7433. DIFF is an integer. Indentation is done according to the
  7434. following rules:
  7435. - Planning information and property drawers are always indented
  7436. according to the new level of the headline;
  7437. - Footnote definitions and their contents are ignored;
  7438. - Inlinetasks' boundaries are not shifted;
  7439. - Empty lines are ignored;
  7440. - Other lines' indentation are shifted by DIFF columns, unless
  7441. it would introduce a structural change in the document, in
  7442. which case no shifting is done at all.
  7443. Assume point is at a heading or an inlinetask beginning."
  7444. (org-with-wide-buffer
  7445. (narrow-to-region (line-beginning-position)
  7446. (save-excursion
  7447. (if (org-with-limited-levels (org-at-heading-p))
  7448. (org-with-limited-levels (outline-next-heading))
  7449. (org-inlinetask-goto-end))
  7450. (point)))
  7451. (forward-line)
  7452. ;; Indent properly planning info and property drawer.
  7453. (when (looking-at-p org-planning-line-re)
  7454. (org-indent-line)
  7455. (forward-line))
  7456. (when (looking-at org-property-drawer-re)
  7457. (goto-char (match-end 0))
  7458. (forward-line)
  7459. (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
  7460. (catch 'no-shift
  7461. (when (zerop diff) (throw 'no-shift nil))
  7462. ;; If DIFF is negative, first check if a shift is possible at all
  7463. ;; (e.g., it doesn't break structure). This can only happen if
  7464. ;; some contents are not properly indented.
  7465. (let ((case-fold-search t))
  7466. (when (< diff 0)
  7467. (let ((diff (- diff))
  7468. (forbidden-re (concat org-outline-regexp
  7469. "\\|"
  7470. (substring org-footnote-definition-re 1))))
  7471. (save-excursion
  7472. (while (not (eobp))
  7473. (cond
  7474. ((looking-at-p "[ \t]*$") (forward-line))
  7475. ((and (looking-at-p org-footnote-definition-re)
  7476. (let ((e (org-element-at-point)))
  7477. (and (eq (org-element-type e) 'footnote-definition)
  7478. (goto-char (org-element-property :end e))))))
  7479. ((looking-at-p org-outline-regexp) (forward-line))
  7480. ;; Give up if shifting would move before column 0 or
  7481. ;; if it would introduce a headline or a footnote
  7482. ;; definition.
  7483. (t
  7484. (skip-chars-forward " \t")
  7485. (let ((ind (current-column)))
  7486. (when (or (< ind diff)
  7487. (and (= ind diff) (looking-at-p forbidden-re)))
  7488. (throw 'no-shift nil)))
  7489. ;; Ignore contents of example blocks and source
  7490. ;; blocks if their indentation is meant to be
  7491. ;; preserved. Jump to block's closing line.
  7492. (beginning-of-line)
  7493. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7494. (let ((e (org-element-at-point)))
  7495. (and (memq (org-element-type e)
  7496. '(example-block src-block))
  7497. (or org-src-preserve-indentation
  7498. (org-element-property :preserve-indent e))
  7499. (goto-char (org-element-property :end e))
  7500. (progn (skip-chars-backward " \r\t\n")
  7501. (beginning-of-line)
  7502. t))))
  7503. (forward-line))))))))
  7504. ;; Shift lines but footnote definitions, inlinetasks boundaries
  7505. ;; by DIFF. Also skip contents of source or example blocks
  7506. ;; when indentation is meant to be preserved.
  7507. (while (not (eobp))
  7508. (cond
  7509. ((and (looking-at-p org-footnote-definition-re)
  7510. (let ((e (org-element-at-point)))
  7511. (and (eq (org-element-type e) 'footnote-definition)
  7512. (goto-char (org-element-property :end e))))))
  7513. ((looking-at-p org-outline-regexp) (forward-line))
  7514. ((looking-at-p "[ \t]*$") (forward-line))
  7515. (t
  7516. (indent-line-to (+ (org-get-indentation) diff))
  7517. (beginning-of-line)
  7518. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  7519. (let ((e (org-element-at-point)))
  7520. (and (memq (org-element-type e)
  7521. '(example-block src-block))
  7522. (or org-src-preserve-indentation
  7523. (org-element-property :preserve-indent e))
  7524. (goto-char (org-element-property :end e))
  7525. (progn (skip-chars-backward " \r\t\n")
  7526. (beginning-of-line)
  7527. t))))
  7528. (forward-line)))))))))
  7529. (defun org-convert-to-odd-levels ()
  7530. "Convert an Org file with all levels allowed to one with odd levels.
  7531. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  7532. level 5 etc."
  7533. (interactive)
  7534. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  7535. (let ((outline-level 'org-outline-level)
  7536. (org-odd-levels-only nil) n)
  7537. (save-excursion
  7538. (goto-char (point-min))
  7539. (while (re-search-forward "^\\*\\*+ " nil t)
  7540. (setq n (- (length (match-string 0)) 2))
  7541. (while (>= (setq n (1- n)) 0)
  7542. (org-demote))
  7543. (end-of-line 1))))))
  7544. (defun org-convert-to-oddeven-levels ()
  7545. "Convert an Org file with only odd levels to one with odd/even levels.
  7546. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  7547. file contains a section with an even level, conversion would
  7548. destroy the structure of the file. An error is signaled in this
  7549. case."
  7550. (interactive)
  7551. (goto-char (point-min))
  7552. ;; First check if there are no even levels
  7553. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  7554. (org-show-set-visibility 'canonical)
  7555. (error "Not all levels are odd in this file. Conversion not possible"))
  7556. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  7557. (let ((outline-regexp org-outline-regexp)
  7558. (outline-level 'org-outline-level)
  7559. (org-odd-levels-only nil) n)
  7560. (save-excursion
  7561. (goto-char (point-min))
  7562. (while (re-search-forward "^\\*\\*+ " nil t)
  7563. (setq n (/ (1- (length (match-string 0))) 2))
  7564. (while (>= (setq n (1- n)) 0)
  7565. (org-promote))
  7566. (end-of-line 1))))))
  7567. (defun org-tr-level (n)
  7568. "Make N odd if required."
  7569. (if org-odd-levels-only (1+ (/ n 2)) n))
  7570. ;;; Vertical tree motion, cutting and pasting of subtrees
  7571. (defun org-move-subtree-up (&optional arg)
  7572. "Move the current subtree up past ARG headlines of the same level."
  7573. (interactive "p")
  7574. (org-move-subtree-down (- (prefix-numeric-value arg))))
  7575. (defun org-move-subtree-down (&optional arg)
  7576. "Move the current subtree down past ARG headlines of the same level."
  7577. (interactive "p")
  7578. (setq arg (prefix-numeric-value arg))
  7579. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  7580. 'org-get-last-sibling))
  7581. (ins-point (make-marker))
  7582. (cnt (abs arg))
  7583. (col (current-column))
  7584. beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
  7585. ;; Select the tree
  7586. (org-back-to-heading)
  7587. (setq beg0 (point))
  7588. (save-excursion
  7589. (setq ne-beg (org-back-over-empty-lines))
  7590. (setq beg (point)))
  7591. (save-match-data
  7592. (save-excursion (outline-end-of-heading)
  7593. (setq folded (org-invisible-p)))
  7594. (progn (org-end-of-subtree nil t)
  7595. (unless (eobp) (backward-char))))
  7596. (outline-next-heading)
  7597. (setq ne-end (org-back-over-empty-lines))
  7598. (setq end (point))
  7599. (goto-char beg0)
  7600. (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
  7601. ;; include less whitespace
  7602. (save-excursion
  7603. (goto-char beg)
  7604. (forward-line (- ne-beg ne-end))
  7605. (setq beg (point))))
  7606. ;; Find insertion point, with error handling
  7607. (while (> cnt 0)
  7608. (or (and (funcall movfunc) (looking-at org-outline-regexp))
  7609. (progn (goto-char beg0)
  7610. (user-error "Cannot move past superior level or buffer limit")))
  7611. (setq cnt (1- cnt)))
  7612. (when (> arg 0)
  7613. ;; Moving forward - still need to move over subtree
  7614. (org-end-of-subtree t t)
  7615. (save-excursion
  7616. (org-back-over-empty-lines)
  7617. (or (bolp) (newline))))
  7618. (setq ne-ins (org-back-over-empty-lines))
  7619. (move-marker ins-point (point))
  7620. (setq txt (buffer-substring beg end))
  7621. (org-save-markers-in-region beg end)
  7622. (delete-region beg end)
  7623. (org-remove-empty-overlays-at beg)
  7624. (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
  7625. (or (bobp) (outline-flag-region (1- (point)) (point) nil))
  7626. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  7627. (let ((bbb (point)))
  7628. (insert-before-markers txt)
  7629. (org-reinstall-markers-in-region bbb)
  7630. (move-marker ins-point bbb))
  7631. (or (bolp) (insert "\n"))
  7632. (setq ins-end (point))
  7633. (goto-char ins-point)
  7634. (org-skip-whitespace)
  7635. (when (and (< arg 0)
  7636. (org-first-sibling-p)
  7637. (> ne-ins ne-beg))
  7638. ;; Move whitespace back to beginning
  7639. (save-excursion
  7640. (goto-char ins-end)
  7641. (let ((kill-whole-line t))
  7642. (kill-line (- ne-ins ne-beg)) (point)))
  7643. (insert (make-string (- ne-ins ne-beg) ?\n)))
  7644. (move-marker ins-point nil)
  7645. (if folded
  7646. (outline-hide-subtree)
  7647. (org-show-entry)
  7648. (org-show-children)
  7649. (org-cycle-hide-drawers 'children))
  7650. (org-clean-visibility-after-subtree-move)
  7651. ;; move back to the initial column we were at
  7652. (move-to-column col)))
  7653. (defvar org-subtree-clip ""
  7654. "Clipboard for cut and paste of subtrees.
  7655. This is actually only a copy of the kill, because we use the normal kill
  7656. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  7657. (defvar org-subtree-clip-folded nil
  7658. "Was the last copied subtree folded?
  7659. This is used to fold the tree back after pasting.")
  7660. (defun org-cut-subtree (&optional n)
  7661. "Cut the current subtree into the clipboard.
  7662. With prefix arg N, cut this many sequential subtrees.
  7663. This is a short-hand for marking the subtree and then cutting it."
  7664. (interactive "p")
  7665. (org-copy-subtree n 'cut))
  7666. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  7667. "Copy the current subtree it in the clipboard.
  7668. With prefix arg N, copy this many sequential subtrees.
  7669. This is a short-hand for marking the subtree and then copying it.
  7670. If CUT is non-nil, actually cut the subtree.
  7671. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  7672. of some markers in the region, even if CUT is non-nil. This is
  7673. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  7674. (interactive "p")
  7675. (let (beg end folded (beg0 (point)))
  7676. (if (called-interactively-p 'any)
  7677. (org-back-to-heading nil) ; take what looks like a subtree
  7678. (org-back-to-heading t)) ; take what is really there
  7679. (setq beg (point))
  7680. (skip-chars-forward " \t\r\n")
  7681. (save-match-data
  7682. (if nosubtrees
  7683. (outline-next-heading)
  7684. (save-excursion (outline-end-of-heading)
  7685. (setq folded (org-invisible-p)))
  7686. (ignore-errors (org-forward-heading-same-level (1- n) t))
  7687. (org-end-of-subtree t t)))
  7688. ;; Include the end of an inlinetask
  7689. (when (and (featurep 'org-inlinetask)
  7690. (looking-at-p (concat (org-inlinetask-outline-regexp)
  7691. "END[ \t]*$")))
  7692. (end-of-line))
  7693. (setq end (point))
  7694. (goto-char beg0)
  7695. (when (> end beg)
  7696. (setq org-subtree-clip-folded folded)
  7697. (when (or cut force-store-markers)
  7698. (org-save-markers-in-region beg end))
  7699. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  7700. (setq org-subtree-clip (current-kill 0))
  7701. (message "%s: Subtree(s) with %d characters"
  7702. (if cut "Cut" "Copied")
  7703. (length org-subtree-clip)))))
  7704. (defun org-paste-subtree (&optional level tree for-yank remove)
  7705. "Paste the clipboard as a subtree, with modification of headline level.
  7706. The entire subtree is promoted or demoted in order to match a new headline
  7707. level.
  7708. If the cursor is at the beginning of a headline, the same level as
  7709. that headline is used to paste the tree.
  7710. If not, the new level is derived from the *visible* headings
  7711. before and after the insertion point, and taken to be the inferior headline
  7712. level of the two. So if the previous visible heading is level 3 and the
  7713. next is level 4 (or vice versa), level 4 will be used for insertion.
  7714. This makes sure that the subtree remains an independent subtree and does
  7715. not swallow low level entries.
  7716. You can also force a different level, either by using a numeric prefix
  7717. argument, or by inserting the heading marker by hand. For example, if the
  7718. cursor is after \"*****\", then the tree will be shifted to level 5.
  7719. If optional TREE is given, use this text instead of the kill ring.
  7720. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  7721. move back over whitespace before inserting, and move point to the end of
  7722. the inserted text when done.
  7723. When REMOVE is non-nil, remove the subtree from the clipboard."
  7724. (interactive "P")
  7725. (setq tree (or tree (and kill-ring (current-kill 0))))
  7726. (unless (org-kill-is-subtree-p tree)
  7727. (user-error "%s"
  7728. (substitute-command-keys
  7729. "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
  7730. (org-with-limited-levels
  7731. (let* ((visp (not (org-invisible-p)))
  7732. (txt tree)
  7733. (^re_ "\\(\\*+\\)[ \t]*")
  7734. (old-level (if (string-match org-outline-regexp-bol txt)
  7735. (- (match-end 0) (match-beginning 0) 1)
  7736. -1))
  7737. (force-level (cond (level (prefix-numeric-value level))
  7738. ((and (looking-at "[ \t]*$")
  7739. (string-match
  7740. "^\\*+$" (buffer-substring
  7741. (point-at-bol) (point))))
  7742. (- (match-end 0) (match-beginning 0)))
  7743. ((and (bolp)
  7744. (looking-at org-outline-regexp))
  7745. (- (match-end 0) (point) 1))))
  7746. (previous-level (save-excursion
  7747. (condition-case nil
  7748. (progn
  7749. (outline-previous-visible-heading 1)
  7750. (if (looking-at ^re_)
  7751. (- (match-end 0) (match-beginning 0) 1)
  7752. 1))
  7753. (error 1))))
  7754. (next-level (save-excursion
  7755. (condition-case nil
  7756. (progn
  7757. (or (looking-at org-outline-regexp)
  7758. (outline-next-visible-heading 1))
  7759. (if (looking-at ^re_)
  7760. (- (match-end 0) (match-beginning 0) 1)
  7761. 1))
  7762. (error 1))))
  7763. (new-level (or force-level (max previous-level next-level)))
  7764. (shift (if (or (= old-level -1)
  7765. (= new-level -1)
  7766. (= old-level new-level))
  7767. 0
  7768. (- new-level old-level)))
  7769. (delta (if (> shift 0) -1 1))
  7770. (func (if (> shift 0) 'org-demote 'org-promote))
  7771. (org-odd-levels-only nil)
  7772. beg end newend)
  7773. ;; Remove the forced level indicator
  7774. (when force-level
  7775. (delete-region (point-at-bol) (point)))
  7776. ;; Paste
  7777. (beginning-of-line (if (bolp) 1 2))
  7778. (setq beg (point))
  7779. (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  7780. (insert-before-markers txt)
  7781. (unless (string-suffix-p "\n" txt) (insert "\n"))
  7782. (setq newend (point))
  7783. (org-reinstall-markers-in-region beg)
  7784. (setq end (point))
  7785. (goto-char beg)
  7786. (skip-chars-forward " \t\n\r")
  7787. (setq beg (point))
  7788. (when (and (org-invisible-p) visp)
  7789. (save-excursion (outline-show-heading)))
  7790. ;; Shift if necessary
  7791. (unless (= shift 0)
  7792. (save-restriction
  7793. (narrow-to-region beg end)
  7794. (while (not (= shift 0))
  7795. (org-map-region func (point-min) (point-max))
  7796. (setq shift (+ delta shift)))
  7797. (goto-char (point-min))
  7798. (setq newend (point-max))))
  7799. (when (or (called-interactively-p 'interactive) for-yank)
  7800. (message "Clipboard pasted as level %d subtree" new-level))
  7801. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  7802. kill-ring
  7803. (eq org-subtree-clip (current-kill 0))
  7804. org-subtree-clip-folded)
  7805. ;; The tree was folded before it was killed/copied
  7806. (outline-hide-subtree))
  7807. (and for-yank (goto-char newend))
  7808. (and remove (setq kill-ring (cdr kill-ring))))))
  7809. (defun org-kill-is-subtree-p (&optional txt)
  7810. "Check if the current kill is an outline subtree, or a set of trees.
  7811. Returns nil if kill does not start with a headline, or if the first
  7812. headline level is not the largest headline level in the tree.
  7813. So this will actually accept several entries of equal levels as well,
  7814. which is OK for `org-paste-subtree'.
  7815. If optional TXT is given, check this string instead of the current kill."
  7816. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7817. (re (org-get-limited-outline-regexp))
  7818. (^re (concat "^" re))
  7819. (start-level (and kill
  7820. (string-match
  7821. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7822. kill)
  7823. (- (match-end 2) (match-beginning 2) 1)))
  7824. (start (1+ (or (match-beginning 2) -1))))
  7825. (if (not start-level)
  7826. (progn
  7827. nil) ;; does not even start with a heading
  7828. (catch 'exit
  7829. (while (setq start (string-match ^re kill (1+ start)))
  7830. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7831. (throw 'exit nil)))
  7832. t))))
  7833. (defvar org-markers-to-move nil
  7834. "Markers that should be moved with a cut-and-paste operation.
  7835. Those markers are stored together with their positions relative to
  7836. the start of the region.")
  7837. (defun org-save-markers-in-region (beg end)
  7838. "Check markers in region.
  7839. If these markers are between BEG and END, record their position relative
  7840. to BEG, so that after moving the block of text, we can put the markers back
  7841. into place.
  7842. This function gets called just before an entry or tree gets cut from the
  7843. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7844. called immediately, to move the markers with the entries."
  7845. (setq org-markers-to-move nil)
  7846. (when (featurep 'org-clock)
  7847. (org-clock-save-markers-for-cut-and-paste beg end))
  7848. (when (featurep 'org-agenda)
  7849. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7850. (defun org-check-and-save-marker (marker beg end)
  7851. "Check if MARKER is between BEG and END.
  7852. If yes, remember the marker and the distance to BEG."
  7853. (when (and (marker-buffer marker)
  7854. (equal (marker-buffer marker) (current-buffer))
  7855. (>= marker beg) (< marker end))
  7856. (push (cons marker (- marker beg)) org-markers-to-move)))
  7857. (defun org-reinstall-markers-in-region (beg)
  7858. "Move all remembered markers to their position relative to BEG."
  7859. (dolist (x org-markers-to-move)
  7860. (move-marker (car x) (+ beg (cdr x))))
  7861. (setq org-markers-to-move nil))
  7862. (defun org-narrow-to-subtree ()
  7863. "Narrow buffer to the current subtree."
  7864. (interactive)
  7865. (save-excursion
  7866. (save-match-data
  7867. (org-with-limited-levels
  7868. (narrow-to-region
  7869. (progn (org-back-to-heading t) (point))
  7870. (progn (org-end-of-subtree t t)
  7871. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7872. (point)))))))
  7873. (defun org-narrow-to-block ()
  7874. "Narrow buffer to the current block."
  7875. (interactive)
  7876. (let* ((case-fold-search t)
  7877. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7878. "^[ \t]*#\\+end_.*")))
  7879. (if blockp
  7880. (narrow-to-region (car blockp) (cdr blockp))
  7881. (user-error "Not in a block"))))
  7882. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7883. "Clone the task (subtree) at point N times.
  7884. The clones will be inserted as siblings.
  7885. In interactive use, the user will be prompted for the number of
  7886. clones to be produced. If the entry has a timestamp, the user
  7887. will also be prompted for a time shift, which may be a repeater
  7888. as used in time stamps, for example `+3d'. To disable this,
  7889. you can call the function with a universal prefix argument.
  7890. When a valid repeater is given and the entry contains any time
  7891. stamps, the clones will become a sequence in time, with time
  7892. stamps in the subtree shifted for each clone produced. If SHIFT
  7893. is nil or the empty string, time stamps will be left alone. The
  7894. ID property of the original subtree is removed.
  7895. In each clone, all the CLOCK entries will be removed. This
  7896. prevents Org from considering that the clocked times overlap.
  7897. If the original subtree did contain time stamps with a repeater,
  7898. the following will happen:
  7899. - the repeater will be removed in each clone
  7900. - an additional clone will be produced, with the current, unshifted
  7901. date(s) in the entry.
  7902. - the original entry will be placed *after* all the clones, with
  7903. repeater intact.
  7904. - the start days in the repeater in the original entry will be shifted
  7905. to past the last clone.
  7906. In this way you can spell out a number of instances of a repeating task,
  7907. and still retain the repeater to cover future instances of the task.
  7908. As described above, N+1 clones are produced when the original
  7909. subtree has a repeater. Setting N to 0, then, can be used to
  7910. remove the repeater from a subtree and create a shifted clone
  7911. with the original repeater."
  7912. (interactive "nNumber of clones to produce: ")
  7913. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7914. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7915. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7916. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7917. (shift
  7918. (or shift
  7919. (if (and (not (equal current-prefix-arg '(4)))
  7920. (save-excursion
  7921. (goto-char beg)
  7922. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7923. (read-from-minibuffer
  7924. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7925. ""))) ;No time shift
  7926. (doshift
  7927. (and (org-string-nw-p shift)
  7928. (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
  7929. shift)
  7930. (user-error "Invalid shift specification %s" shift)))))
  7931. (goto-char end-of-tree)
  7932. (unless (bolp) (insert "\n"))
  7933. (let* ((end (point))
  7934. (template (buffer-substring beg end))
  7935. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7936. (shift-what (pcase (and doshift (match-string 2 shift))
  7937. (`nil nil)
  7938. ("d" 'day)
  7939. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7940. ("m" 'month)
  7941. ("y" 'year)
  7942. (_ (error "Unsupported time unit"))))
  7943. (nmin 1)
  7944. (nmax n)
  7945. (n-no-remove -1)
  7946. (idprop (org-entry-get nil "ID")))
  7947. (when (and doshift
  7948. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7949. template))
  7950. (delete-region beg end)
  7951. (setq end beg)
  7952. (setq nmin 0)
  7953. (setq nmax (1+ nmax))
  7954. (setq n-no-remove nmax))
  7955. (goto-char end)
  7956. (cl-loop for n from nmin to nmax do
  7957. (insert
  7958. ;; Prepare clone.
  7959. (with-temp-buffer
  7960. (insert template)
  7961. (org-mode)
  7962. (goto-char (point-min))
  7963. (org-show-subtree)
  7964. (and idprop (if org-clone-delete-id
  7965. (org-entry-delete nil "ID")
  7966. (org-id-get-create t)))
  7967. (unless (= n 0)
  7968. (while (re-search-forward org-clock-line-re nil t)
  7969. (delete-region (line-beginning-position)
  7970. (line-beginning-position 2)))
  7971. (goto-char (point-min))
  7972. (while (re-search-forward org-drawer-regexp nil t)
  7973. (org-remove-empty-drawer-at (point))))
  7974. (goto-char (point-min))
  7975. (when doshift
  7976. (while (re-search-forward org-ts-regexp-both nil t)
  7977. (org-timestamp-change (* n shift-n) shift-what))
  7978. (unless (= n n-no-remove)
  7979. (goto-char (point-min))
  7980. (while (re-search-forward org-ts-regexp nil t)
  7981. (save-excursion
  7982. (goto-char (match-beginning 0))
  7983. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7984. (delete-region (match-beginning 1) (match-end 1)))))))
  7985. (buffer-string)))))
  7986. (goto-char beg)))
  7987. ;;; Outline Sorting
  7988. (defun org-sort (with-case)
  7989. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7990. Optional argument WITH-CASE means sort case-sensitively."
  7991. (interactive "P")
  7992. (cond
  7993. ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
  7994. ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
  7995. (t
  7996. (org-call-with-arg 'org-sort-entries with-case))))
  7997. (defun org-sort-remove-invisible (s)
  7998. "Remove invisible links from string S."
  7999. (remove-text-properties 0 (length s) org-rm-props s)
  8000. (while (string-match org-bracket-link-regexp s)
  8001. (setq s (replace-match (if (match-end 2)
  8002. (match-string 3 s)
  8003. (match-string 1 s))
  8004. t t s)))
  8005. (let ((st (format " %s " s)))
  8006. (while (string-match org-emph-re st)
  8007. (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
  8008. (setq s (substring st 1 -1)))
  8009. s)
  8010. (defvar org-priority-regexp) ; defined later in the file
  8011. (defvar org-after-sorting-entries-or-items-hook nil
  8012. "Hook that is run after a bunch of entries or items have been sorted.
  8013. When children are sorted, the cursor is in the parent line when this
  8014. hook gets called. When a region or a plain list is sorted, the cursor
  8015. will be in the first entry of the sorted region/list.")
  8016. (defun org-sort-entries
  8017. (&optional with-case sorting-type getkey-func compare-func property
  8018. interactive?)
  8019. "Sort entries on a certain level of an outline tree.
  8020. If there is an active region, the entries in the region are sorted.
  8021. Else, if the cursor is before the first entry, sort the top-level items.
  8022. Else, the children of the entry at point are sorted.
  8023. Sorting can be alphabetically, numerically, by date/time as given by
  8024. a time stamp, by a property, by priority order, or by a custom function.
  8025. The command prompts for the sorting type unless it has been given to the
  8026. function through the SORTING-TYPE argument, which needs to be a character,
  8027. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  8028. the precise meaning of each character:
  8029. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  8030. c By creation time, which is assumed to be the first inactive time stamp
  8031. at the beginning of a line.
  8032. d By deadline date/time.
  8033. k By clocking time.
  8034. n Numerically, by converting the beginning of the entry/item to a number.
  8035. o By order of TODO keywords.
  8036. p By priority according to the cookie.
  8037. r By the value of a property.
  8038. s By scheduled date/time.
  8039. t By date/time, either the first active time stamp in the entry, or, if
  8040. none exist, by the first inactive one.
  8041. Capital letters will reverse the sort order.
  8042. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  8043. called with point at the beginning of the record. It must return a
  8044. value that is compatible with COMPARE-FUNC, the function used to
  8045. compare entries.
  8046. Comparing entries ignores case by default. However, with an optional argument
  8047. WITH-CASE, the sorting considers case as well.
  8048. Sorting is done against the visible part of the headlines, it ignores hidden
  8049. links.
  8050. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  8051. A non-nil value for INTERACTIVE? is used to signal that this
  8052. function is being called interactively."
  8053. (interactive (list current-prefix-arg nil nil nil nil t))
  8054. (let ((case-func (if with-case 'identity 'downcase))
  8055. start beg end stars re re2
  8056. txt what tmp)
  8057. ;; Find beginning and end of region to sort
  8058. (cond
  8059. ((org-region-active-p)
  8060. ;; we will sort the region
  8061. (setq end (region-end)
  8062. what "region")
  8063. (goto-char (region-beginning))
  8064. (unless (org-at-heading-p) (outline-next-heading))
  8065. (setq start (point)))
  8066. ((or (org-at-heading-p)
  8067. (ignore-errors (progn (org-back-to-heading) t)))
  8068. ;; we will sort the children of the current headline
  8069. (org-back-to-heading)
  8070. (setq start (point)
  8071. end (progn (org-end-of-subtree t t)
  8072. (or (bolp) (insert "\n"))
  8073. (when (>= (org-back-over-empty-lines) 1)
  8074. (forward-line 1))
  8075. (point))
  8076. what "children")
  8077. (goto-char start)
  8078. (outline-show-subtree)
  8079. (outline-next-heading))
  8080. (t
  8081. ;; we will sort the top-level entries in this file
  8082. (goto-char (point-min))
  8083. (or (org-at-heading-p) (outline-next-heading))
  8084. (setq start (point))
  8085. (goto-char (point-max))
  8086. (beginning-of-line 1)
  8087. (when (looking-at ".*?\\S-")
  8088. ;; File ends in a non-white line
  8089. (end-of-line 1)
  8090. (insert "\n"))
  8091. (setq end (point-max))
  8092. (setq what "top-level")
  8093. (goto-char start)
  8094. (outline-show-all)))
  8095. (setq beg (point))
  8096. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  8097. (looking-at "\\(\\*+\\)")
  8098. (setq stars (match-string 1)
  8099. re (concat "^" (regexp-quote stars) " +")
  8100. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  8101. txt (buffer-substring beg end))
  8102. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  8103. (when (and (not (equal stars "*")) (string-match re2 txt))
  8104. (user-error "Region to sort contains a level above the first entry"))
  8105. (unless sorting-type
  8106. (message
  8107. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  8108. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  8109. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  8110. what)
  8111. (setq sorting-type (read-char-exclusive)))
  8112. (unless getkey-func
  8113. (and (= (downcase sorting-type) ?f)
  8114. (setq getkey-func
  8115. (or (and interactive?
  8116. (org-read-function
  8117. "Function for extracting keys: "))
  8118. (error "Missing key extractor")))))
  8119. (and (= (downcase sorting-type) ?r)
  8120. (not property)
  8121. (setq property
  8122. (completing-read "Property: "
  8123. (mapcar #'list (org-buffer-property-keys t))
  8124. nil t)))
  8125. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  8126. (message "Sorting entries...")
  8127. (save-restriction
  8128. (narrow-to-region start end)
  8129. (let ((restore-clock?
  8130. ;; The clock marker is lost when using `sort-subr'; mark
  8131. ;; the clock with temporary `:org-clock-marker-backup'
  8132. ;; text property.
  8133. (when (and (eq (org-clocking-buffer) (current-buffer))
  8134. (<= start (marker-position org-clock-marker))
  8135. (>= end (marker-position org-clock-marker)))
  8136. (org-with-silent-modifications
  8137. (put-text-property (1- org-clock-marker) org-clock-marker
  8138. :org-clock-marker-backup t))
  8139. t))
  8140. (dcst (downcase sorting-type))
  8141. (case-fold-search nil)
  8142. (now (current-time)))
  8143. (sort-subr
  8144. (/= dcst sorting-type)
  8145. ;; This function moves to the beginning character of the "record" to
  8146. ;; be sorted.
  8147. (lambda nil
  8148. (if (re-search-forward re nil t)
  8149. (goto-char (match-beginning 0))
  8150. (goto-char (point-max))))
  8151. ;; This function moves to the last character of the "record" being
  8152. ;; sorted.
  8153. (lambda nil
  8154. (save-match-data
  8155. (condition-case nil
  8156. (outline-forward-same-level 1)
  8157. (error
  8158. (goto-char (point-max))))))
  8159. ;; This function returns the value that gets sorted against.
  8160. (lambda nil
  8161. (cond
  8162. ((= dcst ?n)
  8163. (if (looking-at org-complex-heading-regexp)
  8164. (string-to-number (org-sort-remove-invisible (match-string 4)))
  8165. nil))
  8166. ((= dcst ?a)
  8167. (if (looking-at org-complex-heading-regexp)
  8168. (funcall case-func (org-sort-remove-invisible (match-string 4)))
  8169. nil))
  8170. ((= dcst ?k)
  8171. (or (get-text-property (point) :org-clock-minutes) 0))
  8172. ((= dcst ?t)
  8173. (let ((end (save-excursion (outline-next-heading) (point))))
  8174. (if (or (re-search-forward org-ts-regexp end t)
  8175. (re-search-forward org-ts-regexp-both end t))
  8176. (org-time-string-to-seconds (match-string 0))
  8177. (float-time now))))
  8178. ((= dcst ?c)
  8179. (let ((end (save-excursion (outline-next-heading) (point))))
  8180. (if (re-search-forward
  8181. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  8182. end t)
  8183. (org-time-string-to-seconds (match-string 0))
  8184. (float-time now))))
  8185. ((= dcst ?s)
  8186. (let ((end (save-excursion (outline-next-heading) (point))))
  8187. (if (re-search-forward org-scheduled-time-regexp end t)
  8188. (org-time-string-to-seconds (match-string 1))
  8189. (float-time now))))
  8190. ((= dcst ?d)
  8191. (let ((end (save-excursion (outline-next-heading) (point))))
  8192. (if (re-search-forward org-deadline-time-regexp end t)
  8193. (org-time-string-to-seconds (match-string 1))
  8194. (float-time now))))
  8195. ((= dcst ?p)
  8196. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  8197. (string-to-char (match-string 2))
  8198. org-default-priority))
  8199. ((= dcst ?r)
  8200. (or (org-entry-get nil property) ""))
  8201. ((= dcst ?o)
  8202. (when (looking-at org-complex-heading-regexp)
  8203. (let* ((m (match-string 2))
  8204. (s (if (member m org-done-keywords) '- '+)))
  8205. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  8206. ((= dcst ?f)
  8207. (if getkey-func
  8208. (progn
  8209. (setq tmp (funcall getkey-func))
  8210. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  8211. tmp)
  8212. (error "Invalid key function `%s'" getkey-func)))
  8213. (t (error "Invalid sorting type `%c'" sorting-type))))
  8214. nil
  8215. (cond
  8216. ((= dcst ?a) 'string<)
  8217. ((= dcst ?f)
  8218. (or compare-func
  8219. (and interactive?
  8220. (org-read-function
  8221. (concat "Function for comparing keys "
  8222. "(empty for default `sort-subr' predicate): ")
  8223. 'allow-empty))))
  8224. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
  8225. (when restore-clock?
  8226. (move-marker org-clock-marker
  8227. (1+ (next-single-property-change
  8228. start :org-clock-marker-backup)))
  8229. (remove-text-properties (1- org-clock-marker) org-clock-marker
  8230. '(:org-clock-marker-backup t)))))
  8231. (run-hooks 'org-after-sorting-entries-or-items-hook)
  8232. (message "Sorting entries...done")))
  8233. ;;; The orgstruct minor mode
  8234. ;; Define a minor mode which can be used in other modes in order to
  8235. ;; integrate the Org mode structure editing commands.
  8236. ;; This is really a hack, because the Org mode structure commands use
  8237. ;; keys which normally belong to the major mode. Here is how it
  8238. ;; works: The minor mode defines all the keys necessary to operate the
  8239. ;; structure commands, but wraps the commands into a function which
  8240. ;; tests if the cursor is currently at a headline or a plain list
  8241. ;; item. If that is the case, the structure command is used,
  8242. ;; temporarily setting many Org mode variables like regular
  8243. ;; expressions for filling etc. However, when any of those keys is
  8244. ;; used at a different location, function uses `key-binding' to look
  8245. ;; up if the key has an associated command in another currently active
  8246. ;; keymap (minor modes, major mode, global), and executes that
  8247. ;; command. There might be problems if any of the keys is otherwise
  8248. ;; used as a prefix key.
  8249. (defcustom orgstruct-heading-prefix-regexp ""
  8250. "Regexp that matches the custom prefix of Org headlines in
  8251. orgstruct(++)-mode."
  8252. :group 'org
  8253. :version "24.4"
  8254. :package-version '(Org . "8.3")
  8255. :type 'regexp)
  8256. ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
  8257. (defcustom orgstruct-setup-hook nil
  8258. "Hook run after orgstruct-mode-map is filled."
  8259. :group 'org
  8260. :version "24.4"
  8261. :package-version '(Org . "8.0")
  8262. :type 'hook)
  8263. (defvar orgstruct-initialized nil)
  8264. (defvar org-local-vars nil
  8265. "List of local variables, for use by `orgstruct-mode'.")
  8266. ;;;###autoload
  8267. (define-minor-mode orgstruct-mode
  8268. "Toggle the minor mode `orgstruct-mode'.
  8269. This mode is for using Org mode structure commands in other
  8270. modes. The following keys behave as if Org mode were active, if
  8271. the cursor is on a headline, or on a plain list item (both as
  8272. defined by Org mode)."
  8273. nil " OrgStruct" (make-sparse-keymap)
  8274. (funcall (if orgstruct-mode
  8275. 'add-to-invisibility-spec
  8276. 'remove-from-invisibility-spec)
  8277. '(outline . t))
  8278. (when orgstruct-mode
  8279. (org-load-modules-maybe)
  8280. (unless orgstruct-initialized
  8281. (orgstruct-setup)
  8282. (setq orgstruct-initialized t))))
  8283. ;;;###autoload
  8284. (defun turn-on-orgstruct ()
  8285. "Unconditionally turn on `orgstruct-mode'."
  8286. (orgstruct-mode 1))
  8287. (defvar-local orgstruct-is-++ nil
  8288. "Is `orgstruct-mode' in ++ version in the current-buffer?")
  8289. (defvar-local org-fb-vars nil)
  8290. (defun orgstruct++-mode (&optional arg)
  8291. "Toggle `orgstruct-mode', the enhanced version of it.
  8292. In addition to setting orgstruct-mode, this also exports all
  8293. indentation and autofilling variables from Org mode into the
  8294. buffer. It will also recognize item context in multiline items."
  8295. (interactive "P")
  8296. (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
  8297. (if (< arg 1)
  8298. (progn (orgstruct-mode -1)
  8299. (dolist (v org-fb-vars)
  8300. (set (make-local-variable (car v))
  8301. (if (eq (car-safe (cadr v)) 'quote)
  8302. (cl-cadadr v)
  8303. (nth 1 v)))))
  8304. (orgstruct-mode 1)
  8305. (setq org-fb-vars nil)
  8306. (unless org-local-vars
  8307. (setq org-local-vars (org-get-local-variables)))
  8308. (let (var val)
  8309. (dolist (x org-local-vars)
  8310. (when (string-match
  8311. "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
  8312. \\|fill-prefix\\|indent-\\)"
  8313. (symbol-name (car x)))
  8314. (setq var (car x) val (nth 1 x))
  8315. (push (list var `(quote ,(eval var))) org-fb-vars)
  8316. (set (make-local-variable var)
  8317. (if (eq (car-safe val) 'quote) (nth 1 val) val))))
  8318. (setq-local orgstruct-is-++ t))))
  8319. ;;;###autoload
  8320. (defun turn-on-orgstruct++ ()
  8321. "Unconditionally turn on `orgstruct++-mode'."
  8322. (orgstruct++-mode 1))
  8323. (defun orgstruct-error ()
  8324. "Error when there is no default binding for a structure key."
  8325. (interactive)
  8326. (funcall (if (fboundp 'user-error)
  8327. 'user-error
  8328. 'error)
  8329. "This key has no function outside structure elements"))
  8330. (defun orgstruct-setup ()
  8331. "Setup orgstruct keymap."
  8332. (dolist (cell '((org-demote . t)
  8333. (org-metaleft . t)
  8334. (org-metaright . t)
  8335. (org-promote . t)
  8336. (org-shiftmetaleft . t)
  8337. (org-shiftmetaright . t)
  8338. org-backward-element
  8339. org-backward-heading-same-level
  8340. org-ctrl-c-ret
  8341. org-ctrl-c-minus
  8342. org-ctrl-c-star
  8343. org-cycle
  8344. org-force-cycle-archived
  8345. org-forward-heading-same-level
  8346. org-insert-heading
  8347. org-insert-heading-respect-content
  8348. org-kill-note-or-show-branches
  8349. org-mark-subtree
  8350. org-meta-return
  8351. org-metadown
  8352. org-metaup
  8353. org-narrow-to-subtree
  8354. org-promote-subtree
  8355. org-reveal
  8356. org-shiftdown
  8357. org-shiftleft
  8358. org-shiftmetadown
  8359. org-shiftmetaup
  8360. org-shiftright
  8361. org-shifttab
  8362. org-shifttab
  8363. org-shiftup
  8364. org-show-children
  8365. org-show-subtree
  8366. org-sort
  8367. org-up-element
  8368. outline-demote
  8369. outline-next-visible-heading
  8370. outline-previous-visible-heading
  8371. outline-promote
  8372. outline-up-heading))
  8373. (let ((f (or (car-safe cell) cell))
  8374. (disable-when-heading-prefix (cdr-safe cell)))
  8375. (when (fboundp f)
  8376. (let ((new-bindings))
  8377. (dolist (binding (nconc (where-is-internal f org-mode-map)
  8378. (where-is-internal f outline-mode-map)))
  8379. (push binding new-bindings)
  8380. ;; TODO use local-function-key-map
  8381. (dolist (rep '(("<tab>" . "TAB")
  8382. ("<return>" . "RET")
  8383. ("<escape>" . "ESC")
  8384. ("<delete>" . "DEL")))
  8385. (setq binding (read-kbd-macro
  8386. (let ((case-fold-search))
  8387. (replace-regexp-in-string
  8388. (regexp-quote (cdr rep))
  8389. (car rep)
  8390. (key-description binding)))))
  8391. (cl-pushnew binding new-bindings :test 'equal)))
  8392. (dolist (binding new-bindings)
  8393. (let ((key (lookup-key orgstruct-mode-map binding)))
  8394. (when (or (not key) (numberp key))
  8395. (ignore-errors
  8396. (org-defkey orgstruct-mode-map
  8397. binding
  8398. (orgstruct-make-binding
  8399. f binding disable-when-heading-prefix))))))))))
  8400. (run-hooks 'orgstruct-setup-hook))
  8401. (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
  8402. "Create a function for binding in the structure minor mode.
  8403. FUN is the command to call inside a table. KEY is the key that
  8404. should be checked in for a command to execute outside of tables.
  8405. Non-nil `disable-when-heading-prefix' means to disable the command
  8406. if `orgstruct-heading-prefix-regexp' is not empty."
  8407. (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
  8408. (let ((nname name)
  8409. (i 0))
  8410. (while (fboundp (intern nname))
  8411. (setq nname (format "%s-%d" name (setq i (1+ i)))))
  8412. (setq name (intern nname)))
  8413. (eval
  8414. (let ((bindings '((org-heading-regexp
  8415. (concat "^"
  8416. orgstruct-heading-prefix-regexp
  8417. "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
  8418. (org-outline-regexp
  8419. (concat orgstruct-heading-prefix-regexp "\\*+ "))
  8420. (org-outline-regexp-bol
  8421. (concat "^" org-outline-regexp))
  8422. (outline-regexp org-outline-regexp)
  8423. (outline-heading-end-regexp "\n")
  8424. (outline-level 'org-outline-level)
  8425. (outline-heading-alist))))
  8426. `(defun ,name (arg)
  8427. ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
  8428. "Outside of structure, run the binding of `"
  8429. (key-description key) "'."
  8430. (when disable-when-heading-prefix
  8431. (concat
  8432. "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
  8433. "back to the default binding due to limitations of Org's implementation of\n"
  8434. "`" (symbol-name fun) "'.")))
  8435. (interactive "p")
  8436. (let* ((disable
  8437. ,(and disable-when-heading-prefix
  8438. '(not (string= orgstruct-heading-prefix-regexp ""))))
  8439. (fallback
  8440. (or disable
  8441. (not
  8442. (let* ,bindings
  8443. (org-context-p 'headline 'item
  8444. ,(when (memq fun
  8445. '(org-insert-heading
  8446. org-insert-heading-respect-content
  8447. org-meta-return))
  8448. '(when orgstruct-is-++
  8449. 'item-body))))))))
  8450. (if fallback
  8451. (let* ((orgstruct-mode)
  8452. (binding
  8453. (let ((key ,key))
  8454. (catch 'exit
  8455. (dolist
  8456. (rep
  8457. '(nil
  8458. ("<\\([^>]*\\)tab>" . "\\1TAB")
  8459. ("<\\([^>]*\\)return>" . "\\1RET")
  8460. ("<\\([^>]*\\)escape>" . "\\1ESC")
  8461. ("<\\([^>]*\\)delete>" . "\\1DEL"))
  8462. nil)
  8463. (when rep
  8464. (setq key (read-kbd-macro
  8465. (let ((case-fold-search))
  8466. (replace-regexp-in-string
  8467. (car rep)
  8468. (cdr rep)
  8469. (key-description key))))))
  8470. (when (key-binding key)
  8471. (throw 'exit (key-binding key))))))))
  8472. (if (keymapp binding)
  8473. (org-set-transient-map binding)
  8474. (let ((func (or binding
  8475. (unless disable
  8476. 'orgstruct-error))))
  8477. (when func
  8478. (call-interactively func)))))
  8479. (org-run-like-in-org-mode
  8480. (lambda ()
  8481. (interactive)
  8482. (let* ,bindings
  8483. (call-interactively ',fun)))))))))
  8484. name))
  8485. (defun org-contextualize-keys (alist contexts)
  8486. "Return valid elements in ALIST depending on CONTEXTS.
  8487. `org-agenda-custom-commands' or `org-capture-templates' are the
  8488. values used for ALIST, and `org-agenda-custom-commands-contexts'
  8489. or `org-capture-templates-contexts' are the associated contexts
  8490. definitions."
  8491. (let ((contexts
  8492. ;; normalize contexts
  8493. (mapcar
  8494. (lambda(c) (cond ((listp (cadr c))
  8495. (list (car c) (car c) (nth 1 c)))
  8496. ((string= "" (cadr c))
  8497. (list (car c) (car c) (nth 2 c)))
  8498. (t c)))
  8499. contexts))
  8500. (a alist) r s)
  8501. ;; loop over all commands or templates
  8502. (dolist (c a)
  8503. (let (vrules repl)
  8504. (cond
  8505. ((not (assoc (car c) contexts))
  8506. (push c r))
  8507. ((and (assoc (car c) contexts)
  8508. (setq vrules (org-contextualize-validate-key
  8509. (car c) contexts)))
  8510. (mapc (lambda (vr)
  8511. (unless (equal (car vr) (cadr vr))
  8512. (setq repl vr)))
  8513. vrules)
  8514. (if (not repl) (push c r)
  8515. (push (cadr repl) s)
  8516. (push
  8517. (cons (car c)
  8518. (cdr (or (assoc (cadr repl) alist)
  8519. (error "Undefined key `%s' as contextual replacement for `%s'"
  8520. (cadr repl) (car c)))))
  8521. r))))))
  8522. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  8523. (delq
  8524. nil
  8525. (delete-dups
  8526. (mapcar (lambda (x)
  8527. (let ((tpl (car x)))
  8528. (unless (delq
  8529. nil
  8530. (mapcar (lambda (y)
  8531. (equal y tpl))
  8532. s))
  8533. x)))
  8534. (reverse r))))))
  8535. (defun org-contextualize-validate-key (key contexts)
  8536. "Check CONTEXTS for agenda or capture KEY."
  8537. (let (res)
  8538. (dolist (r contexts)
  8539. (dolist (rr (car (last r)))
  8540. (when
  8541. (and (equal key (car r))
  8542. (if (functionp rr) (funcall rr)
  8543. (or (and (eq (car rr) 'in-file)
  8544. (buffer-file-name)
  8545. (string-match (cdr rr) (buffer-file-name)))
  8546. (and (eq (car rr) 'in-mode)
  8547. (string-match (cdr rr) (symbol-name major-mode)))
  8548. (and (eq (car rr) 'in-buffer)
  8549. (string-match (cdr rr) (buffer-name)))
  8550. (when (and (eq (car rr) 'not-in-file)
  8551. (buffer-file-name))
  8552. (not (string-match (cdr rr) (buffer-file-name))))
  8553. (when (eq (car rr) 'not-in-mode)
  8554. (not (string-match (cdr rr) (symbol-name major-mode))))
  8555. (when (eq (car rr) 'not-in-buffer)
  8556. (not (string-match (cdr rr) (buffer-name)))))))
  8557. (push r res))))
  8558. (delete-dups (delq nil res))))
  8559. (defun org-context-p (&rest contexts)
  8560. "Check if local context is any of CONTEXTS.
  8561. Possible values in the list of contexts are `table', `headline', and `item'."
  8562. (let ((pos (point)))
  8563. (goto-char (point-at-bol))
  8564. (prog1 (or (and (memq 'table contexts)
  8565. (looking-at "[ \t]*|"))
  8566. (and (memq 'headline contexts)
  8567. (looking-at org-outline-regexp))
  8568. (and (memq 'item contexts)
  8569. (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
  8570. (and (memq 'item-body contexts)
  8571. (org-in-item-p)))
  8572. (goto-char pos))))
  8573. ;;;###autoload
  8574. (defun org-run-like-in-org-mode (cmd)
  8575. "Run a command, pretending that the current buffer is in Org mode.
  8576. This will temporarily bind local variables that are typically bound in
  8577. Org mode to the values they have in Org mode, and then interactively
  8578. call CMD."
  8579. (org-load-modules-maybe)
  8580. (unless org-local-vars
  8581. (setq org-local-vars (org-get-local-variables)))
  8582. (let (binds)
  8583. (dolist (var org-local-vars)
  8584. (when (or (not (boundp (car var)))
  8585. (eq (symbol-value (car var))
  8586. (default-value (car var))))
  8587. (push (list (car var) `(quote ,(cadr var))) binds)))
  8588. (eval `(let ,binds
  8589. (call-interactively (quote ,cmd))))))
  8590. (defun org-get-category (&optional pos force-refresh)
  8591. "Get the category applying to position POS."
  8592. (save-match-data
  8593. (when force-refresh (org-refresh-category-properties))
  8594. (let ((pos (or pos (point))))
  8595. (or (get-text-property pos 'org-category)
  8596. (progn (org-refresh-category-properties)
  8597. (get-text-property pos 'org-category))))))
  8598. ;;; Refresh properties
  8599. (defun org-refresh-properties (dprop tprop)
  8600. "Refresh buffer text properties.
  8601. DPROP is the drawer property and TPROP is either the
  8602. corresponding text property to set, or an alist with each element
  8603. being a text property (as a symbol) and a function to apply to
  8604. the value of the drawer property."
  8605. (let* ((case-fold-search t)
  8606. (inhibit-read-only t)
  8607. (inherit? (org-property-inherit-p dprop))
  8608. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  8609. (global (and inherit? (org--property-global-value dprop nil))))
  8610. (org-with-silent-modifications
  8611. (org-with-point-at 1
  8612. ;; Set global values (e.g., values defined through
  8613. ;; "#+PROPERTY:" keywords) to the whole buffer.
  8614. (when global (put-text-property (point-min) (point-max) tprop global))
  8615. ;; Set local values.
  8616. (while (re-search-forward property-re nil t)
  8617. (when (org-at-property-p)
  8618. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  8619. (outline-next-heading))))))
  8620. (defun org-refresh-property (tprop p &optional inherit)
  8621. "Refresh the buffer text property TPROP from the drawer property P.
  8622. The refresh happens only for the current headline, or the whole
  8623. sub-tree if optional argument INHERIT is non-nil."
  8624. (unless (org-before-first-heading-p)
  8625. (save-excursion
  8626. (org-back-to-heading t)
  8627. (let ((start (point))
  8628. (end (save-excursion
  8629. (if inherit (org-end-of-subtree t t)
  8630. (or (outline-next-heading) (point-max))))))
  8631. (if (symbolp tprop)
  8632. ;; TPROP is a text property symbol.
  8633. (put-text-property start end tprop p)
  8634. ;; TPROP is an alist with (property . function) elements.
  8635. (pcase-dolist (`(,prop . ,f) tprop)
  8636. (put-text-property start end prop (funcall f p))))))))
  8637. (defun org-refresh-category-properties ()
  8638. "Refresh category text properties in the buffer."
  8639. (let ((case-fold-search t)
  8640. (inhibit-read-only t)
  8641. (default-category
  8642. (cond ((null org-category)
  8643. (if buffer-file-name
  8644. (file-name-sans-extension
  8645. (file-name-nondirectory buffer-file-name))
  8646. "???"))
  8647. ((symbolp org-category) (symbol-name org-category))
  8648. (t org-category))))
  8649. (org-with-silent-modifications
  8650. (org-with-wide-buffer
  8651. ;; Set buffer-wide category. Search last #+CATEGORY keyword.
  8652. ;; This is the default category for the buffer. If none is
  8653. ;; found, fall-back to `org-category' or buffer file name.
  8654. (put-text-property
  8655. (point-min) (point-max)
  8656. 'org-category
  8657. (catch 'buffer-category
  8658. (goto-char (point-max))
  8659. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  8660. (let ((element (org-element-at-point)))
  8661. (when (eq (org-element-type element) 'keyword)
  8662. (throw 'buffer-category
  8663. (org-element-property :value element)))))
  8664. default-category))
  8665. ;; Set sub-tree specific categories.
  8666. (goto-char (point-min))
  8667. (let ((regexp (org-re-property "CATEGORY")))
  8668. (while (re-search-forward regexp nil t)
  8669. (let ((value (match-string-no-properties 3)))
  8670. (when (org-at-property-p)
  8671. (put-text-property
  8672. (save-excursion (org-back-to-heading t) (point))
  8673. (save-excursion (org-end-of-subtree t t) (point))
  8674. 'org-category
  8675. value)))))))))
  8676. (defun org-refresh-stats-properties ()
  8677. "Refresh stats text properties in the buffer."
  8678. (org-with-silent-modifications
  8679. (org-with-point-at 1
  8680. (let ((regexp (concat org-outline-regexp-bol
  8681. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  8682. (while (re-search-forward regexp nil t)
  8683. (let* ((numerator (string-to-number (match-string 1)))
  8684. (denominator (and (match-end 2)
  8685. (string-to-number (match-string 2))))
  8686. (stats (cond ((not denominator) numerator) ;percent
  8687. ((= denominator 0) 0)
  8688. (t (/ (* numerator 100) denominator)))))
  8689. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  8690. 'org-stats stats)))))))
  8691. (defun org-refresh-effort-properties ()
  8692. "Refresh effort properties"
  8693. (org-refresh-properties
  8694. org-effort-property
  8695. '((effort . identity)
  8696. (effort-minutes . org-duration-string-to-minutes))))
  8697. ;;;; Link Stuff
  8698. ;;; Link abbreviations
  8699. (defun org-link-expand-abbrev (link)
  8700. "Apply replacements as defined in `org-link-abbrev-alist'."
  8701. (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
  8702. (let* ((key (match-string 1 link))
  8703. (as (or (assoc key org-link-abbrev-alist-local)
  8704. (assoc key org-link-abbrev-alist)))
  8705. (tag (and (match-end 2) (match-string 3 link)))
  8706. rpl)
  8707. (if (not as)
  8708. link
  8709. (setq rpl (cdr as))
  8710. (cond
  8711. ((symbolp rpl) (funcall rpl tag))
  8712. ((string-match "%(\\([^)]+\\))" rpl)
  8713. (replace-match
  8714. (save-match-data
  8715. (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
  8716. ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
  8717. ((string-match "%h" rpl)
  8718. (replace-match (url-hexify-string (or tag "")) t t rpl))
  8719. (t (concat rpl tag)))))
  8720. link))
  8721. ;;; Storing and inserting links
  8722. (defvar org-insert-link-history nil
  8723. "Minibuffer history for links inserted with `org-insert-link'.")
  8724. (defvar org-stored-links nil
  8725. "Contains the links stored with `org-store-link'.")
  8726. (defvar org-store-link-plist nil
  8727. "Plist with info about the most recently link created with `org-store-link'.")
  8728. (defun org-store-link-functions ()
  8729. "Return a list of functions that are called to create and store a link.
  8730. The functions defined in the :store property of
  8731. `org-link-parameters'.
  8732. Each function will be called in turn until one returns a non-nil
  8733. value. Each function should check if it is responsible for
  8734. creating this link (for example by looking at the major mode).
  8735. If not, it must exit and return nil. If yes, it should return
  8736. a non-nil value after calling `org-store-link-props' with a list
  8737. of properties and values. Special properties are:
  8738. :type The link prefix, like \"http\". This must be given.
  8739. :link The link, like \"http://www.astro.uva.nl/~dominik\".
  8740. This is obligatory as well.
  8741. :description Optional default description for the second pair
  8742. of brackets in an Org mode link. The user can still change
  8743. this when inserting this link into an Org mode buffer.
  8744. In addition to these, any additional properties can be specified
  8745. and then used in capture templates."
  8746. (cl-loop for link in org-link-parameters
  8747. with store-func
  8748. do (setq store-func (org-link-get-parameter (car link) :store))
  8749. if store-func
  8750. collect store-func))
  8751. (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
  8752. (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
  8753. ;;;###autoload
  8754. (defun org-store-link (arg)
  8755. "Store an org-link to the current location.
  8756. \\<org-mode-map>
  8757. This link is added to `org-stored-links' and can later be inserted
  8758. into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
  8759. For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
  8760. A single
  8761. `\\[universal-argument]' negates `org-context-in-file-links' for file links or
  8762. `org-gnus-prefer-web-links' for links to Usenet articles.
  8763. A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
  8764. skipping storing functions that are not
  8765. part of Org core.
  8766. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8767. prefix ARG forces storing a link for each line in the
  8768. active region."
  8769. (interactive "P")
  8770. (org-load-modules-maybe)
  8771. (if (and (equal arg '(64)) (org-region-active-p))
  8772. (save-excursion
  8773. (let ((end (region-end)))
  8774. (goto-char (region-beginning))
  8775. (set-mark (point))
  8776. (while (< (point-at-eol) end)
  8777. (move-end-of-line 1) (activate-mark)
  8778. (let (current-prefix-arg)
  8779. (call-interactively 'org-store-link))
  8780. (move-beginning-of-line 2)
  8781. (set-mark (point)))))
  8782. (setq org-store-link-plist nil)
  8783. (let (link cpltxt desc description search
  8784. txt custom-id agenda-link sfuns sfunsn)
  8785. (cond
  8786. ;; Store a link using an external link type
  8787. ((and (not (equal arg '(16)))
  8788. (setq sfuns
  8789. (delq
  8790. nil (mapcar (lambda (f)
  8791. (let (fs) (if (funcall f) (push f fs))))
  8792. (org-store-link-functions)))
  8793. sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
  8794. (or (and (cdr sfuns)
  8795. (funcall (intern
  8796. (completing-read
  8797. "Which function for creating the link? "
  8798. sfunsn nil t (car sfunsn)))))
  8799. (funcall (caar sfuns)))
  8800. (setq link (plist-get org-store-link-plist :link)
  8801. desc (or (plist-get org-store-link-plist
  8802. :description)
  8803. link))))
  8804. ;; Store a link from a source code buffer.
  8805. ((org-src-edit-buffer-p)
  8806. (let ((coderef-format (org-src-coderef-format)))
  8807. (cond ((save-excursion
  8808. (beginning-of-line)
  8809. (looking-at (org-src-coderef-regexp coderef-format)))
  8810. (setq link (format "(%s)" (match-string-no-properties 3))))
  8811. ((called-interactively-p 'any)
  8812. (let ((label (read-string "Code line label: ")))
  8813. (end-of-line)
  8814. (setq link (format coderef-format label))
  8815. (let ((gc (- 79 (length link))))
  8816. (if (< (current-column) gc)
  8817. (org-move-to-column gc t)
  8818. (insert " ")))
  8819. (insert link)
  8820. (setq link (concat "(" label ")"))
  8821. (setq desc nil)))
  8822. (t (setq link nil)))))
  8823. ;; We are in the agenda, link to referenced location
  8824. ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
  8825. (let ((m (or (get-text-property (point) 'org-hd-marker)
  8826. (get-text-property (point) 'org-marker))))
  8827. (when m
  8828. (org-with-point-at m
  8829. (setq agenda-link
  8830. (if (called-interactively-p 'any)
  8831. (call-interactively 'org-store-link)
  8832. (org-store-link nil)))))))
  8833. ((eq major-mode 'calendar-mode)
  8834. (let ((cd (calendar-cursor-to-date)))
  8835. (setq link
  8836. (format-time-string
  8837. (car org-time-stamp-formats)
  8838. (apply 'encode-time
  8839. (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
  8840. nil nil nil))))
  8841. (org-store-link-props :type "calendar" :date cd)))
  8842. ((eq major-mode 'help-mode)
  8843. (setq link (concat "help:" (save-excursion
  8844. (goto-char (point-min))
  8845. (looking-at "^[^ ]+")
  8846. (match-string 0))))
  8847. (org-store-link-props :type "help"))
  8848. ((eq major-mode 'w3-mode)
  8849. (setq cpltxt (if (and (buffer-name)
  8850. (not (string-match "Untitled" (buffer-name))))
  8851. (buffer-name)
  8852. (url-view-url t))
  8853. link (url-view-url t))
  8854. (org-store-link-props :type "w3" :url (url-view-url t)))
  8855. ((eq major-mode 'image-mode)
  8856. (setq cpltxt (concat "file:"
  8857. (abbreviate-file-name buffer-file-name))
  8858. link cpltxt)
  8859. (org-store-link-props :type "image" :file buffer-file-name))
  8860. ;; In dired, store a link to the file of the current line
  8861. ((derived-mode-p 'dired-mode)
  8862. (let ((file (dired-get-filename nil t)))
  8863. (setq file (if file
  8864. (abbreviate-file-name
  8865. (expand-file-name (dired-get-filename nil t)))
  8866. ;; otherwise, no file so use current directory.
  8867. default-directory))
  8868. (setq cpltxt (concat "file:" file)
  8869. link cpltxt)))
  8870. ((setq search (run-hook-with-args-until-success
  8871. 'org-create-file-search-functions))
  8872. (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
  8873. "::" search))
  8874. (setq cpltxt (or description link)))
  8875. ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
  8876. (org-with-limited-levels
  8877. (setq custom-id (org-entry-get nil "CUSTOM_ID"))
  8878. (cond
  8879. ;; Store a link using the target at point
  8880. ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
  8881. (setq cpltxt
  8882. (concat "file:"
  8883. (abbreviate-file-name
  8884. (buffer-file-name (buffer-base-buffer)))
  8885. "::" (match-string 1))
  8886. link cpltxt))
  8887. ((and (featurep 'org-id)
  8888. (or (eq org-id-link-to-org-use-id t)
  8889. (and (called-interactively-p 'any)
  8890. (or (eq org-id-link-to-org-use-id 'create-if-interactive)
  8891. (and (eq org-id-link-to-org-use-id
  8892. 'create-if-interactive-and-no-custom-id)
  8893. (not custom-id))))
  8894. (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
  8895. ;; Store a link using the ID at point
  8896. (setq link (condition-case nil
  8897. (prog1 (org-id-store-link)
  8898. (setq desc (or (plist-get org-store-link-plist
  8899. :description)
  8900. "")))
  8901. (error
  8902. ;; Probably before first headline, link only to file
  8903. (concat "file:"
  8904. (abbreviate-file-name
  8905. (buffer-file-name (buffer-base-buffer))))))))
  8906. (t
  8907. ;; Just link to current headline
  8908. (setq cpltxt (concat "file:"
  8909. (abbreviate-file-name
  8910. (buffer-file-name (buffer-base-buffer)))))
  8911. ;; Add a context search string
  8912. (when (org-xor org-context-in-file-links
  8913. (equal arg '(4)))
  8914. (let* ((element (org-element-at-point))
  8915. (name (org-element-property :name element)))
  8916. (setq txt (cond
  8917. ((org-at-heading-p) nil)
  8918. (name)
  8919. ((org-region-active-p)
  8920. (buffer-substring (region-beginning) (region-end)))))
  8921. (when (or (null txt) (string-match "\\S-" txt))
  8922. (setq cpltxt
  8923. (concat cpltxt "::"
  8924. (condition-case nil
  8925. (org-make-org-heading-search-string txt)
  8926. (error "")))
  8927. desc (or name
  8928. (nth 4 (ignore-errors (org-heading-components)))
  8929. "NONE")))))
  8930. (when (string-match "::\\'" cpltxt)
  8931. (setq cpltxt (substring cpltxt 0 -2)))
  8932. (setq link cpltxt)))))
  8933. ((buffer-file-name (buffer-base-buffer))
  8934. ;; Just link to this file here.
  8935. (setq cpltxt (concat "file:"
  8936. (abbreviate-file-name
  8937. (buffer-file-name (buffer-base-buffer)))))
  8938. ;; Add a context string.
  8939. (when (org-xor org-context-in-file-links
  8940. (equal arg '(4)))
  8941. (setq txt (if (org-region-active-p)
  8942. (buffer-substring (region-beginning) (region-end))
  8943. (buffer-substring (point-at-bol) (point-at-eol))))
  8944. ;; Only use search option if there is some text.
  8945. (when (string-match "\\S-" txt)
  8946. (setq cpltxt
  8947. (concat cpltxt "::" (org-make-org-heading-search-string txt))
  8948. desc "NONE")))
  8949. (setq link cpltxt))
  8950. ((called-interactively-p 'interactive)
  8951. (user-error "No method for storing a link from this buffer"))
  8952. (t (setq link nil)))
  8953. ;; We're done setting link and desc, clean up
  8954. (when (consp link) (setq cpltxt (car link) link (cdr link)))
  8955. (setq link (or link cpltxt)
  8956. desc (or desc cpltxt))
  8957. (cond ((not desc))
  8958. ((equal desc "NONE") (setq desc nil))
  8959. (t (setq desc
  8960. (replace-regexp-in-string
  8961. org-bracket-link-analytic-regexp
  8962. (lambda (m) (or (match-string 5 m) (match-string 3 m)))
  8963. desc))))
  8964. ;; Return the link
  8965. (if (not (and (or (called-interactively-p 'any)
  8966. executing-kbd-macro)
  8967. link))
  8968. (or agenda-link (and link (org-make-link-string link desc)))
  8969. (push (list link desc) org-stored-links)
  8970. (message "Stored: %s" (or desc link))
  8971. (when custom-id
  8972. (setq link (concat "file:" (abbreviate-file-name
  8973. (buffer-file-name)) "::#" custom-id))
  8974. (push (list link desc) org-stored-links))
  8975. (car org-stored-links)))))
  8976. (defun org-store-link-props (&rest plist)
  8977. "Store link properties, extract names, addresses and dates."
  8978. (let ((x (plist-get plist :from)))
  8979. (when x
  8980. (let ((adr (mail-extract-address-components x)))
  8981. (setq plist (plist-put plist :fromname (car adr)))
  8982. (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
  8983. (let ((x (plist-get plist :to)))
  8984. (when x
  8985. (let ((adr (mail-extract-address-components x)))
  8986. (setq plist (plist-put plist :toname (car adr)))
  8987. (setq plist (plist-put plist :toaddress (nth 1 adr))))))
  8988. (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
  8989. (when x
  8990. (setq plist (plist-put plist :date-timestamp
  8991. (format-time-string
  8992. (org-time-stamp-format t) x)))
  8993. (setq plist (plist-put plist :date-timestamp-inactive
  8994. (format-time-string
  8995. (org-time-stamp-format t t) x)))))
  8996. (let ((from (plist-get plist :from))
  8997. (to (plist-get plist :to)))
  8998. (when (and from to org-from-is-user-regexp)
  8999. (setq plist
  9000. (plist-put plist :fromto
  9001. (if (string-match org-from-is-user-regexp from)
  9002. (concat "to %t")
  9003. (concat "from %f"))))))
  9004. (setq org-store-link-plist plist))
  9005. (defun org-add-link-props (&rest plist)
  9006. "Add these properties to the link property list."
  9007. (let (key value)
  9008. (while plist
  9009. (setq key (pop plist) value (pop plist))
  9010. (setq org-store-link-plist
  9011. (plist-put org-store-link-plist key value)))))
  9012. (defun org-email-link-description (&optional fmt)
  9013. "Return the description part of an email link.
  9014. This takes information from `org-store-link-plist' and formats it
  9015. according to FMT (default from `org-email-link-description-format')."
  9016. (setq fmt (or fmt org-email-link-description-format))
  9017. (let* ((p org-store-link-plist)
  9018. (to (plist-get p :toaddress))
  9019. (from (plist-get p :fromaddress))
  9020. (table
  9021. (list
  9022. (cons "%c" (plist-get p :fromto))
  9023. (cons "%F" (plist-get p :from))
  9024. (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
  9025. (cons "%T" (plist-get p :to))
  9026. (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
  9027. (cons "%s" (plist-get p :subject))
  9028. (cons "%d" (plist-get p :date))
  9029. (cons "%m" (plist-get p :message-id)))))
  9030. (when (string-match "%c" fmt)
  9031. ;; Check if the user wrote this message
  9032. (if (and org-from-is-user-regexp from to
  9033. (save-match-data (string-match org-from-is-user-regexp from)))
  9034. (setq fmt (replace-match "to %t" t t fmt))
  9035. (setq fmt (replace-match "from %f" t t fmt))))
  9036. (org-replace-escapes fmt table)))
  9037. (defun org-make-org-heading-search-string (&optional string)
  9038. "Make search string for the current headline or STRING."
  9039. (let ((s (or string
  9040. (and (derived-mode-p 'org-mode)
  9041. (save-excursion
  9042. (org-back-to-heading t)
  9043. (org-element-property :raw-value (org-element-at-point))))))
  9044. (lines org-context-in-file-links))
  9045. (or string (setq s (concat "*" s))) ; Add * for headlines
  9046. (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
  9047. (when (and string (integerp lines) (> lines 0))
  9048. (let ((slines (org-split-string s "\n")))
  9049. (when (< lines (length slines))
  9050. (setq s (mapconcat
  9051. 'identity
  9052. (reverse (nthcdr (- (length slines) lines)
  9053. (reverse slines))) "\n")))))
  9054. (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
  9055. (defun org-make-link-string (link &optional description)
  9056. "Make a link with brackets, consisting of LINK and DESCRIPTION."
  9057. (unless (org-string-nw-p link) (error "Empty link"))
  9058. (let ((uri (cond ((string-match org-link-types-re link)
  9059. (concat (match-string 1 link)
  9060. (org-link-escape (substring link (match-end 1)))))
  9061. ;; For readability, url-encode internal links only
  9062. ;; when absolutely needed (i.e, when they contain
  9063. ;; square brackets). File links however, are
  9064. ;; encoded since, e.g., spaces are significant.
  9065. ((or (file-name-absolute-p link)
  9066. (string-match-p "\\`\\.\\.?/\\|[][]" link))
  9067. (org-link-escape link))
  9068. (t link)))
  9069. (description
  9070. (and (org-string-nw-p description)
  9071. ;; Remove brackets from description, as they are fatal.
  9072. (replace-regexp-in-string
  9073. "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
  9074. (org-trim description)))))
  9075. (format "[[%s]%s]"
  9076. uri
  9077. (if description (format "[%s]" description) ""))))
  9078. (defconst org-link-escape-chars
  9079. ;;%20 %5B %5D %25
  9080. '(?\s ?\[ ?\] ?%)
  9081. "List of characters that should be escaped in a link when stored to Org.
  9082. This is the list that is used for internal purposes.")
  9083. (defun org-link-escape (text &optional table merge)
  9084. "Return percent escaped representation of TEXT.
  9085. TEXT is a string with the text to escape.
  9086. Optional argument TABLE is a list with characters that should be
  9087. escaped. When nil, `org-link-escape-chars' is used.
  9088. If optional argument MERGE is set, merge TABLE into
  9089. `org-link-escape-chars'."
  9090. (let ((characters-to-encode
  9091. (cond ((null table) org-link-escape-chars)
  9092. (merge (append org-link-escape-chars table))
  9093. (t table))))
  9094. (mapconcat
  9095. (lambda (c)
  9096. (if (or (memq c characters-to-encode)
  9097. (and org-url-hexify-p (or (< c 32) (> c 126))))
  9098. (mapconcat (lambda (e) (format "%%%.2X" e))
  9099. (or (encode-coding-char c 'utf-8)
  9100. (error "Unable to percent escape character: %c" c))
  9101. "")
  9102. (char-to-string c)))
  9103. text "")))
  9104. (defun org-link-unescape (str)
  9105. "Unhex hexified Unicode parts in string STR.
  9106. E.g. `%C3%B6' becomes the german o-Umlaut. This is the
  9107. reciprocal of `org-link-escape', which see."
  9108. (if (org-string-nw-p str)
  9109. (replace-regexp-in-string
  9110. "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
  9111. str))
  9112. (defun org-link-unescape-compound (hex)
  9113. "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
  9114. Note: this function also decodes single byte encodings like
  9115. `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
  9116. (save-match-data
  9117. (let* ((bytes (cdr (split-string hex "%")))
  9118. (ret "")
  9119. (eat 0)
  9120. (sum 0))
  9121. (while bytes
  9122. (let* ((val (string-to-number (pop bytes) 16))
  9123. (shift-xor
  9124. (if (= 0 eat)
  9125. (cond
  9126. ((>= val 252) (cons 6 252))
  9127. ((>= val 248) (cons 5 248))
  9128. ((>= val 240) (cons 4 240))
  9129. ((>= val 224) (cons 3 224))
  9130. ((>= val 192) (cons 2 192))
  9131. (t (cons 0 0)))
  9132. (cons 6 128))))
  9133. (when (>= val 192) (setq eat (car shift-xor)))
  9134. (setq val (logxor val (cdr shift-xor)))
  9135. (setq sum (+ (lsh sum (car shift-xor)) val))
  9136. (when (> eat 0) (setq eat (- eat 1)))
  9137. (cond
  9138. ((= 0 eat) ;multi byte
  9139. (setq ret (concat ret (char-to-string sum)))
  9140. (setq sum 0))
  9141. ((not bytes) ; single byte(s)
  9142. (setq ret (org-link-unescape-single-byte-sequence hex))))))
  9143. ret)))
  9144. (defun org-link-unescape-single-byte-sequence (hex)
  9145. "Unhexify hex-encoded single byte character sequences."
  9146. (mapconcat (lambda (byte)
  9147. (char-to-string (string-to-number byte 16)))
  9148. (cdr (split-string hex "%")) ""))
  9149. (defun org-xor (a b)
  9150. "Exclusive or."
  9151. (if a (not b) b))
  9152. (defun org-fixup-message-id-for-http (s)
  9153. "Replace special characters in a message id, so it can be used in an http query."
  9154. (when (string-match "%" s)
  9155. (setq s (mapconcat (lambda (c)
  9156. (if (eq c ?%)
  9157. "%25"
  9158. (char-to-string c)))
  9159. s "")))
  9160. (while (string-match "<" s)
  9161. (setq s (replace-match "%3C" t t s)))
  9162. (while (string-match ">" s)
  9163. (setq s (replace-match "%3E" t t s)))
  9164. (while (string-match "@" s)
  9165. (setq s (replace-match "%40" t t s)))
  9166. s)
  9167. (defun org-link-prettify (link)
  9168. "Return a human-readable representation of LINK.
  9169. The car of LINK must be a raw link.
  9170. The cdr of LINK must be either a link description or nil."
  9171. (let ((desc (or (cadr link) "<no description>")))
  9172. (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
  9173. "<" (car link) ">")))
  9174. ;;;###autoload
  9175. (defun org-insert-link-global ()
  9176. "Insert a link like Org mode does.
  9177. This command can be called in any mode to insert a link in Org syntax."
  9178. (interactive)
  9179. (org-load-modules-maybe)
  9180. (org-run-like-in-org-mode 'org-insert-link))
  9181. (defun org-insert-all-links (arg &optional pre post)
  9182. "Insert all links in `org-stored-links'.
  9183. When a universal prefix, do not delete the links from `org-stored-links'.
  9184. When `ARG' is a number, insert the last N link(s).
  9185. `PRE' and `POST' are optional arguments to define a string to
  9186. prepend or to append."
  9187. (interactive "P")
  9188. (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
  9189. (links (copy-sequence org-stored-links))
  9190. (pr (or pre "- "))
  9191. (po (or post "\n"))
  9192. (cnt 1) l)
  9193. (if (null org-stored-links)
  9194. (message "No link to insert")
  9195. (while (and (or (listp arg) (>= arg cnt))
  9196. (setq l (if (listp arg)
  9197. (pop links)
  9198. (pop org-stored-links))))
  9199. (setq cnt (1+ cnt))
  9200. (insert pr)
  9201. (org-insert-link nil (car l) (or (cadr l) "<no description>"))
  9202. (insert po)))))
  9203. (defun org-insert-last-stored-link (arg)
  9204. "Insert the last link stored in `org-stored-links'."
  9205. (interactive "p")
  9206. (org-insert-all-links arg "" "\n"))
  9207. (defun org-link-fontify-links-to-this-file ()
  9208. "Fontify links to the current file in `org-stored-links'."
  9209. (let ((f (buffer-file-name)) a b)
  9210. (setq a (mapcar (lambda(l)
  9211. (let ((ll (car l)))
  9212. (when (and (string-match "^file:\\(.+\\)::" ll)
  9213. (equal f (expand-file-name (match-string 1 ll))))
  9214. ll)))
  9215. org-stored-links))
  9216. (when (featurep 'org-id)
  9217. (setq b (mapcar (lambda(l)
  9218. (let ((ll (car l)))
  9219. (when (and (string-match "^id:\\(.+\\)$" ll)
  9220. (equal f (expand-file-name
  9221. (or (org-id-find-id-file
  9222. (match-string 1 ll)) ""))))
  9223. ll)))
  9224. org-stored-links)))
  9225. (mapcar (lambda(l)
  9226. (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
  9227. (delq nil (append a b)))))
  9228. (defvar org--links-history nil)
  9229. (defun org-insert-link (&optional complete-file link-location default-description)
  9230. "Insert a link. At the prompt, enter the link.
  9231. Completion can be used to insert any of the link protocol prefixes in use.
  9232. The history can be used to select a link previously stored with
  9233. `org-store-link'. When the empty string is entered (i.e. if you just
  9234. press `RET' at the prompt), the link defaults to the most recently
  9235. stored link. As `SPC' triggers completion in the minibuffer, you need to
  9236. use `M-SPC' or `C-q SPC' to force the insertion of a space character.
  9237. You will also be prompted for a description, and if one is given, it will
  9238. be displayed in the buffer instead of the link.
  9239. If there is already a link at point, this command will allow you to edit
  9240. link and description parts.
  9241. With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
  9242. file name can be
  9243. selected using completion. The path to the file will be relative to the
  9244. current directory if the file is in the current directory or a subdirectory.
  9245. Otherwise, the link will be the absolute path as completed in the minibuffer
  9246. \(i.e. normally ~/path/to/file). You can configure this behavior using the
  9247. option `org-link-file-path-type'.
  9248. With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
  9249. absolute path even if the file is in
  9250. the current directory or below.
  9251. A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  9252. prefix negates `org-keep-stored-link-after-insertion'.
  9253. If `org-make-link-description-function' is non-nil, this function will be
  9254. called with the link target, and the result will be the default
  9255. link description.
  9256. If the LINK-LOCATION parameter is non-nil, this value will be used as
  9257. the link location instead of reading one interactively.
  9258. If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
  9259. as the default description."
  9260. (interactive "P")
  9261. (let* ((wcf (current-window-configuration))
  9262. (origbuf (current-buffer))
  9263. (region (when (org-region-active-p)
  9264. (buffer-substring (region-beginning) (region-end))))
  9265. (remove (and region (list (region-beginning) (region-end))))
  9266. (desc region)
  9267. (link link-location)
  9268. (abbrevs org-link-abbrev-alist-local)
  9269. entry all-prefixes auto-desc)
  9270. (cond
  9271. (link-location) ; specified by arg, just use it.
  9272. ((org-in-regexp org-bracket-link-regexp 1)
  9273. ;; We do have a link at point, and we are going to edit it.
  9274. (setq remove (list (match-beginning 0) (match-end 0)))
  9275. (setq desc (when (match-end 3) (match-string-no-properties 3)))
  9276. (setq link (read-string "Link: "
  9277. (org-link-unescape
  9278. (match-string-no-properties 1)))))
  9279. ((or (org-in-regexp org-angle-link-re)
  9280. (org-in-regexp org-plain-link-re))
  9281. ;; Convert to bracket link
  9282. (setq remove (list (match-beginning 0) (match-end 0))
  9283. link (read-string "Link: "
  9284. (org-unbracket-string "<" ">" (match-string 0)))))
  9285. ((member complete-file '((4) (16)))
  9286. ;; Completing read for file names.
  9287. (setq link (org-file-complete-link complete-file)))
  9288. (t
  9289. ;; Read link, with completion for stored links.
  9290. (org-link-fontify-links-to-this-file)
  9291. (org-switch-to-buffer-other-window "*Org Links*")
  9292. (with-current-buffer "*Org Links*"
  9293. (erase-buffer)
  9294. (insert "Insert a link.
  9295. Use TAB to complete link prefixes, then RET for type-specific completion support\n")
  9296. (when org-stored-links
  9297. (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
  9298. (insert (mapconcat 'org-link-prettify
  9299. (reverse org-stored-links) "\n")))
  9300. (goto-char (point-min)))
  9301. (let ((cw (selected-window)))
  9302. (select-window (get-buffer-window "*Org Links*" 'visible))
  9303. (with-current-buffer "*Org Links*" (setq truncate-lines t))
  9304. (unless (pos-visible-in-window-p (point-max))
  9305. (org-fit-window-to-buffer))
  9306. (and (window-live-p cw) (select-window cw)))
  9307. (setq all-prefixes (append (mapcar 'car abbrevs)
  9308. (mapcar 'car org-link-abbrev-alist)
  9309. (org-link-types)))
  9310. (unwind-protect
  9311. ;; Fake a link history, containing the stored links.
  9312. (let ((org--links-history
  9313. (append (mapcar #'car org-stored-links)
  9314. org-insert-link-history)))
  9315. (setq link
  9316. (org-completing-read
  9317. "Link: "
  9318. (append
  9319. (mapcar (lambda (x) (concat x ":")) all-prefixes)
  9320. (mapcar #'car org-stored-links))
  9321. nil nil nil
  9322. 'org--links-history
  9323. (caar org-stored-links)))
  9324. (unless (org-string-nw-p link) (user-error "No link selected"))
  9325. (dolist (l org-stored-links)
  9326. (when (equal link (cadr l))
  9327. (setq link (car l))
  9328. (setq auto-desc t)))
  9329. (when (or (member link all-prefixes)
  9330. (and (equal ":" (substring link -1))
  9331. (member (substring link 0 -1) all-prefixes)
  9332. (setq link (substring link 0 -1))))
  9333. (setq link (with-current-buffer origbuf
  9334. (org-link-try-special-completion link)))))
  9335. (set-window-configuration wcf)
  9336. (kill-buffer "*Org Links*"))
  9337. (setq entry (assoc link org-stored-links))
  9338. (or entry (push link org-insert-link-history))
  9339. (setq desc (or desc (nth 1 entry)))))
  9340. (when (funcall (if (equal complete-file '(64)) 'not 'identity)
  9341. (not org-keep-stored-link-after-insertion))
  9342. (setq org-stored-links (delq (assoc link org-stored-links)
  9343. org-stored-links)))
  9344. (when (and (string-match org-plain-link-re link)
  9345. (not (string-match org-ts-regexp link)))
  9346. ;; URL-like link, normalize the use of angular brackets.
  9347. (setq link (org-unbracket-string "<" ">" link)))
  9348. ;; Check if we are linking to the current file with a search
  9349. ;; option If yes, simplify the link by using only the search
  9350. ;; option.
  9351. (when (and buffer-file-name
  9352. (let ((case-fold-search nil))
  9353. (string-match "\\`file:\\(.+?\\)::" link)))
  9354. (let ((path (match-string-no-properties 1 link))
  9355. (search (substring-no-properties link (match-end 0))))
  9356. (save-match-data
  9357. (when (equal (file-truename buffer-file-name) (file-truename path))
  9358. ;; We are linking to this same file, with a search option
  9359. (setq link search)))))
  9360. ;; Check if we can/should use a relative path. If yes, simplify the link
  9361. (let ((case-fold-search nil))
  9362. (when (string-match "\\`\\(file\\|docview\\):" link)
  9363. (let* ((type (match-string-no-properties 0 link))
  9364. (path (substring-no-properties link (match-end 0)))
  9365. (origpath path))
  9366. (cond
  9367. ((or (eq org-link-file-path-type 'absolute)
  9368. (equal complete-file '(16)))
  9369. (setq path (abbreviate-file-name (expand-file-name path))))
  9370. ((eq org-link-file-path-type 'noabbrev)
  9371. (setq path (expand-file-name path)))
  9372. ((eq org-link-file-path-type 'relative)
  9373. (setq path (file-relative-name path)))
  9374. (t
  9375. (save-match-data
  9376. (if (string-match (concat "^" (regexp-quote
  9377. (expand-file-name
  9378. (file-name-as-directory
  9379. default-directory))))
  9380. (expand-file-name path))
  9381. ;; We are linking a file with relative path name.
  9382. (setq path (substring (expand-file-name path)
  9383. (match-end 0)))
  9384. (setq path (abbreviate-file-name (expand-file-name path)))))))
  9385. (setq link (concat type path))
  9386. (when (equal desc origpath)
  9387. (setq desc path)))))
  9388. (if org-make-link-description-function
  9389. (setq desc
  9390. (or (condition-case nil
  9391. (funcall org-make-link-description-function link desc)
  9392. (error (progn (message "Can't get link description from `%s'"
  9393. (symbol-name org-make-link-description-function))
  9394. (sit-for 2) nil)))
  9395. (read-string "Description: " default-description)))
  9396. (if default-description (setq desc default-description)
  9397. (setq desc (or (and auto-desc desc)
  9398. (read-string "Description: " desc)))))
  9399. (unless (string-match "\\S-" desc) (setq desc nil))
  9400. (when remove (apply 'delete-region remove))
  9401. (insert (org-make-link-string link desc))
  9402. ;; Redisplay so as the new link has proper invisible characters.
  9403. (sit-for 0)))
  9404. (defun org-link-try-special-completion (type)
  9405. "If there is completion support for link type TYPE, offer it."
  9406. (let ((fun (org-link-get-parameter type :complete)))
  9407. (if (functionp fun)
  9408. (funcall fun)
  9409. (read-string "Link (no completion support): " (concat type ":")))))
  9410. (defun org-file-complete-link (&optional arg)
  9411. "Create a file link using completion."
  9412. (let ((file (read-file-name "File: "))
  9413. (pwd (file-name-as-directory (expand-file-name ".")))
  9414. (pwd1 (file-name-as-directory (abbreviate-file-name
  9415. (expand-file-name ".")))))
  9416. (cond ((equal arg '(16))
  9417. (concat "file:"
  9418. (abbreviate-file-name (expand-file-name file))))
  9419. ((string-match
  9420. (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
  9421. (concat "file:" (match-string 1 file)))
  9422. ((string-match
  9423. (concat "^" (regexp-quote pwd) "\\(.+\\)")
  9424. (expand-file-name file))
  9425. (concat "file:"
  9426. (match-string 1 (expand-file-name file))))
  9427. (t (concat "file:" file)))))
  9428. (defun org-completing-read (&rest args)
  9429. "Completing-read with SPACE being a normal character."
  9430. (let ((enable-recursive-minibuffers t)
  9431. (minibuffer-local-completion-map
  9432. (copy-keymap minibuffer-local-completion-map)))
  9433. (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
  9434. (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
  9435. (org-defkey minibuffer-local-completion-map (kbd "C-c !")
  9436. 'org-time-stamp-inactive)
  9437. (apply #'completing-read args)))
  9438. ;;; Opening/following a link
  9439. (defvar org-link-search-failed nil)
  9440. (defvar org-open-link-functions nil
  9441. "Hook for functions finding a plain text link.
  9442. These functions must take a single argument, the link content.
  9443. They will be called for links that look like [[link text][description]]
  9444. when LINK TEXT does not have a protocol like \"http:\" and does not look
  9445. like a filename (e.g. \"./blue.png\").
  9446. These functions will be called *before* Org attempts to resolve the
  9447. link by doing text searches in the current buffer - so if you want a
  9448. link \"[[target]]\" to still find \"<<target>>\", your function should
  9449. handle this as a special case.
  9450. When the function does handle the link, it must return a non-nil value.
  9451. If it decides that it is not responsible for this link, it must return
  9452. nil to indicate that that Org can continue with other options like
  9453. exact and fuzzy text search.")
  9454. (defun org-next-link (&optional search-backward)
  9455. "Move forward to the next link.
  9456. If the link is in hidden text, expose it."
  9457. (interactive "P")
  9458. (when (and org-link-search-failed (eq this-command last-command))
  9459. (goto-char (point-min))
  9460. (message "Link search wrapped back to beginning of buffer"))
  9461. (setq org-link-search-failed nil)
  9462. (let* ((pos (point))
  9463. (ct (org-context))
  9464. (a (assq :link ct))
  9465. (srch-fun (if search-backward 're-search-backward 're-search-forward)))
  9466. (cond (a (goto-char (nth (if search-backward 1 2) a)))
  9467. ((looking-at org-any-link-re)
  9468. ;; Don't stay stuck at link without an org-link face
  9469. (forward-char (if search-backward -1 1))))
  9470. (if (funcall srch-fun org-any-link-re nil t)
  9471. (progn
  9472. (goto-char (match-beginning 0))
  9473. (when (org-invisible-p) (org-show-context)))
  9474. (goto-char pos)
  9475. (setq org-link-search-failed t)
  9476. (message "No further link found"))))
  9477. (defun org-previous-link ()
  9478. "Move backward to the previous link.
  9479. If the link is in hidden text, expose it."
  9480. (interactive)
  9481. (funcall 'org-next-link t))
  9482. (defun org-translate-link (s)
  9483. "Translate a link string if a translation function has been defined."
  9484. (with-temp-buffer
  9485. (insert (org-trim s))
  9486. (org-trim (org-element-interpret-data (org-element-context)))))
  9487. (defun org-translate-link-from-planner (type path)
  9488. "Translate a link from Emacs Planner syntax so that Org can follow it.
  9489. This is still an experimental function, your mileage may vary."
  9490. (cond
  9491. ((member type '("http" "https" "news" "ftp"))
  9492. ;; standard Internet links are the same.
  9493. nil)
  9494. ((and (equal type "irc") (string-match "^//" path))
  9495. ;; Planner has two / at the beginning of an irc link, we have 1.
  9496. ;; We should have zero, actually....
  9497. (setq path (substring path 1)))
  9498. ((and (equal type "lisp") (string-match "^/" path))
  9499. ;; Planner has a slash, we do not.
  9500. (setq type "elisp" path (substring path 1)))
  9501. ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
  9502. ;; A typical message link. Planner has the id after the final slash,
  9503. ;; we separate it with a hash mark
  9504. (setq path (concat (match-string 1 path) "#"
  9505. (org-unbracket-string "<" ">" (match-string 2 path))))))
  9506. (cons type path))
  9507. (defun org-find-file-at-mouse (ev)
  9508. "Open file link or URL at mouse."
  9509. (interactive "e")
  9510. (mouse-set-point ev)
  9511. (org-open-at-point 'in-emacs))
  9512. (defun org-open-at-mouse (ev)
  9513. "Open file link or URL at mouse.
  9514. See the docstring of `org-open-file' for details."
  9515. (interactive "e")
  9516. (mouse-set-point ev)
  9517. (when (eq major-mode 'org-agenda-mode)
  9518. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  9519. (org-open-at-point))
  9520. (defvar org-window-config-before-follow-link nil
  9521. "The window configuration before following a link.
  9522. This is saved in case the need arises to restore it.")
  9523. ;;;###autoload
  9524. (defun org-open-at-point-global ()
  9525. "Follow a link or time-stamp like Org mode does.
  9526. This command can be called in any mode to follow an external link
  9527. or a time-stamp that has Org mode syntax. Its behavior is
  9528. undefined when called on internal links (e.g., fuzzy links).
  9529. Raise an error when there is nothing to follow. "
  9530. (interactive)
  9531. (cond ((org-in-regexp org-any-link-re)
  9532. (org-open-link-from-string (match-string-no-properties 0)))
  9533. ((or (org-in-regexp org-ts-regexp-both nil t)
  9534. (org-in-regexp org-tsr-regexp-both nil t))
  9535. (org-follow-timestamp-link))
  9536. (t (user-error "No link found"))))
  9537. ;;;###autoload
  9538. (defun org-open-link-from-string (s &optional arg reference-buffer)
  9539. "Open a link in the string S, as if it was in Org mode."
  9540. (interactive "sLink: \nP")
  9541. (let ((reference-buffer (or reference-buffer (current-buffer))))
  9542. (with-temp-buffer
  9543. (let ((org-inhibit-startup (not reference-buffer)))
  9544. (org-mode)
  9545. (insert s)
  9546. (goto-char (point-min))
  9547. (when reference-buffer
  9548. (setq org-link-abbrev-alist-local
  9549. (with-current-buffer reference-buffer
  9550. org-link-abbrev-alist-local)))
  9551. (org-open-at-point arg reference-buffer)))))
  9552. (defvar org-open-at-point-functions nil
  9553. "Hook that is run when following a link at point.
  9554. Functions in this hook must return t if they identify and follow
  9555. a link at point. If they don't find anything interesting at point,
  9556. they must return nil.")
  9557. (defvar org-link-search-inhibit-query nil)
  9558. (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
  9559. (defun org--open-doi-link (path)
  9560. "Open a \"doi\" type link.
  9561. PATH is a the path to search for, as a string."
  9562. (browse-url (url-encode-url (concat org-doi-server-url path))))
  9563. (defun org--open-elisp-link (path)
  9564. "Open a \"elisp\" type link.
  9565. PATH is the sexp to evaluate, as a string."
  9566. (let ((cmd path))
  9567. (if (or (and (org-string-nw-p
  9568. org-confirm-elisp-link-not-regexp)
  9569. (string-match-p org-confirm-elisp-link-not-regexp cmd))
  9570. (not org-confirm-elisp-link-function)
  9571. (funcall org-confirm-elisp-link-function
  9572. (format "Execute \"%s\" as elisp? "
  9573. (org-add-props cmd nil 'face 'org-warning))))
  9574. (message "%s => %s" cmd
  9575. (if (eq (string-to-char cmd) ?\()
  9576. (eval (read cmd))
  9577. (call-interactively (read cmd))))
  9578. (user-error "Abort"))))
  9579. (defun org--open-help-link (path)
  9580. "Open a \"help\" type link.
  9581. PATH is a symbol name, as a string."
  9582. (pcase (intern path)
  9583. ((and (pred fboundp) variable) (describe-function variable))
  9584. ((and (pred boundp) function) (describe-variable function))
  9585. (name (user-error "Unknown function or variable: %s" name))))
  9586. (defun org--open-shell-link (path)
  9587. "Open a \"shell\" type link.
  9588. PATH is the command to execute, as a string."
  9589. (let ((buf (generate-new-buffer "*Org Shell Output*"))
  9590. (cmd path))
  9591. (if (or (and (org-string-nw-p
  9592. org-confirm-shell-link-not-regexp)
  9593. (string-match
  9594. org-confirm-shell-link-not-regexp cmd))
  9595. (not org-confirm-shell-link-function)
  9596. (funcall org-confirm-shell-link-function
  9597. (format "Execute \"%s\" in shell? "
  9598. (org-add-props cmd nil
  9599. 'face 'org-warning))))
  9600. (progn
  9601. (message "Executing %s" cmd)
  9602. (shell-command cmd buf)
  9603. (when (featurep 'midnight)
  9604. (setq clean-buffer-list-kill-buffer-names
  9605. (cons (buffer-name buf)
  9606. clean-buffer-list-kill-buffer-names))))
  9607. (user-error "Abort"))))
  9608. (defun org-open-at-point (&optional arg reference-buffer)
  9609. "Open link, timestamp, footnote or tags at point.
  9610. When point is on a link, follow it. Normally, files will be
  9611. opened by an appropriate application. If the optional prefix
  9612. argument ARG is non-nil, Emacs will visit the file. With
  9613. a double prefix argument, try to open outside of Emacs, in the
  9614. application the system uses for this file type.
  9615. When point is on a timestamp, open the agenda at the day
  9616. specified.
  9617. When point is a footnote definition, move to the first reference
  9618. found. If it is on a reference, move to the associated
  9619. definition.
  9620. When point is on a headline, display a list of every link in the
  9621. entry, so it is possible to pick one, or all, of them. If point
  9622. is on a tag, call `org-tags-view' instead.
  9623. When optional argument REFERENCE-BUFFER is non-nil, it should
  9624. specify a buffer from where the link search should happen. This
  9625. is used internally by `org-open-link-from-string'.
  9626. On top of syntactically correct links, this function will also
  9627. try to open links and time-stamps in comments, example
  9628. blocks... i.e., whenever point is on something looking like
  9629. a timestamp or a link."
  9630. (interactive "P")
  9631. ;; On a code block, open block's results.
  9632. (unless (call-interactively 'org-babel-open-src-block-result)
  9633. (org-load-modules-maybe)
  9634. (setq org-window-config-before-follow-link (current-window-configuration))
  9635. (org-remove-occur-highlights nil nil t)
  9636. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  9637. (let* ((context
  9638. ;; Only consider supported types, even if they are not
  9639. ;; the closest one.
  9640. (org-element-lineage
  9641. (org-element-context)
  9642. '(clock footnote-definition footnote-reference headline
  9643. inlinetask link timestamp)
  9644. t))
  9645. (type (org-element-type context))
  9646. (value (org-element-property :value context)))
  9647. (cond
  9648. ;; On a headline or an inlinetask, but not on a timestamp,
  9649. ;; a link, a footnote reference.
  9650. ((memq type '(headline inlinetask))
  9651. (org-match-line org-complex-heading-regexp)
  9652. (if (and (match-beginning 5)
  9653. (>= (point) (match-beginning 5))
  9654. (< (point) (match-end 5)))
  9655. ;; On tags.
  9656. (org-tags-view arg (substring (match-string 5) 0 -1))
  9657. ;; Not on tags.
  9658. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  9659. (`(nil . ,_)
  9660. (require 'org-attach)
  9661. (org-attach-reveal 'if-exists))
  9662. (`(,links . ,links-end)
  9663. (dolist (link (if (stringp links) (list links) links))
  9664. (search-forward link nil links-end)
  9665. (goto-char (match-beginning 0))
  9666. (org-open-at-point))))))
  9667. ;; On a footnote reference or at definition's label.
  9668. ((or (eq type 'footnote-reference)
  9669. (and (eq type 'footnote-definition)
  9670. (save-excursion
  9671. ;; Do not validate action when point is on the
  9672. ;; spaces right after the footnote label, in
  9673. ;; order to be on par with behaviour on links.
  9674. (skip-chars-forward " \t")
  9675. (let ((begin
  9676. (org-element-property :contents-begin context)))
  9677. (if begin (< (point) begin)
  9678. (= (org-element-property :post-affiliated context)
  9679. (line-beginning-position)))))))
  9680. (org-footnote-action))
  9681. ;; No valid context. Ignore catch-all types like `headline'.
  9682. ;; If point is on something looking like a link or
  9683. ;; a time-stamp, try opening it. It may be useful in
  9684. ;; comments, example blocks...
  9685. ((memq type '(footnote-definition headline inlinetask nil))
  9686. (call-interactively #'org-open-at-point-global))
  9687. ;; On a clock line, make sure point is on the timestamp
  9688. ;; before opening it.
  9689. ((and (eq type 'clock)
  9690. value
  9691. (>= (point) (org-element-property :begin value))
  9692. (<= (point) (org-element-property :end value)))
  9693. (org-follow-timestamp-link))
  9694. ;; Do nothing on white spaces after an object.
  9695. ((>= (point)
  9696. (save-excursion
  9697. (goto-char (org-element-property :end context))
  9698. (skip-chars-backward " \t")
  9699. (point)))
  9700. (user-error "No link found"))
  9701. ((eq type 'timestamp) (org-follow-timestamp-link))
  9702. ((eq type 'link)
  9703. ;; When link is located within the description of another
  9704. ;; link (e.g., an inline image), always open the parent
  9705. ;; link.
  9706. (let* ((link (let ((up (org-element-property :parent context)))
  9707. (if (eq (org-element-type up) 'link) up context)))
  9708. (type (org-element-property :type link))
  9709. (path (org-link-unescape (org-element-property :path link))))
  9710. ;; Switch back to REFERENCE-BUFFER needed when called in
  9711. ;; a temporary buffer through `org-open-link-from-string'.
  9712. (with-current-buffer (or reference-buffer (current-buffer))
  9713. (cond
  9714. ((equal type "file")
  9715. (if (string-match "[*?{]" (file-name-nondirectory path))
  9716. (dired path)
  9717. ;; Look into `org-link-parameters' in order to find
  9718. ;; a DEDICATED-FUNCTION to open file. The function
  9719. ;; will be applied on raw link instead of parsed
  9720. ;; link due to the limitation in `org-add-link-type'
  9721. ;; ("open" function called with a single argument).
  9722. ;; If no such function is found, fallback to
  9723. ;; `org-open-file'.
  9724. (let* ((option (org-element-property :search-option link))
  9725. (app (org-element-property :application link))
  9726. (dedicated-function
  9727. (org-link-get-parameter
  9728. (if app (concat type "+" app) type)
  9729. :follow)))
  9730. (if dedicated-function
  9731. (funcall dedicated-function
  9732. (concat path
  9733. (and option (concat "::" option))))
  9734. (apply #'org-open-file
  9735. path
  9736. (cond (arg)
  9737. ((equal app "emacs") 'emacs)
  9738. ((equal app "sys") 'system))
  9739. (cond ((not option) nil)
  9740. ((string-match-p "\\`[0-9]+\\'" option)
  9741. (list (string-to-number option)))
  9742. (t (list nil
  9743. (org-link-unescape option)))))))))
  9744. ((functionp (org-link-get-parameter type :follow))
  9745. (funcall (org-link-get-parameter type :follow) path))
  9746. ((member type '("coderef" "custom-id" "fuzzy" "radio"))
  9747. (unless (run-hook-with-args-until-success
  9748. 'org-open-link-functions path)
  9749. (if (not arg) (org-mark-ring-push)
  9750. (switch-to-buffer-other-window
  9751. (org-get-buffer-for-internal-link (current-buffer))))
  9752. (let ((destination
  9753. (org-with-wide-buffer
  9754. (if (equal type "radio")
  9755. (org-search-radio-target
  9756. (org-element-property :path link))
  9757. (org-link-search
  9758. (if (member type '("custom-id" "coderef"))
  9759. (org-element-property :raw-link link)
  9760. path)
  9761. ;; Prevent fuzzy links from matching
  9762. ;; themselves.
  9763. (and (equal type "fuzzy")
  9764. (+ 2 (org-element-property :begin link)))))
  9765. (point))))
  9766. (unless (and (<= (point-min) destination)
  9767. (>= (point-max) destination))
  9768. (widen))
  9769. (goto-char destination))))
  9770. (t (browse-url-at-point))))))
  9771. (t (user-error "No link found")))))
  9772. (run-hook-with-args 'org-follow-link-hook)))
  9773. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  9774. "Offer links in the current entry and return the selected link.
  9775. If there is only one link, return it.
  9776. If NTH is an integer, return the NTH link found.
  9777. If ZERO is a string, check also this string for a link, and if
  9778. there is one, return it."
  9779. (with-current-buffer buffer
  9780. (org-with-wide-buffer
  9781. (goto-char marker)
  9782. (let ((cnt ?0)
  9783. have-zero end links link c)
  9784. (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
  9785. (push (match-string 0 zero) links)
  9786. (setq cnt (1- cnt) have-zero t))
  9787. (save-excursion
  9788. (org-back-to-heading t)
  9789. (setq end (save-excursion (outline-next-heading) (point)))
  9790. (while (re-search-forward org-any-link-re end t)
  9791. (push (match-string 0) links))
  9792. (setq links (org-uniquify (reverse links))))
  9793. (cond
  9794. ((null links)
  9795. (message "No links"))
  9796. ((equal (length links) 1)
  9797. (setq link (car links)))
  9798. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  9799. (setq link (nth (if have-zero nth (1- nth)) links)))
  9800. (t ; we have to select a link
  9801. (save-excursion
  9802. (save-window-excursion
  9803. (delete-other-windows)
  9804. (with-output-to-temp-buffer "*Select Link*"
  9805. (dolist (l links)
  9806. (cond
  9807. ((not (string-match org-bracket-link-regexp l))
  9808. (princ (format "[%c] %s\n" (cl-incf cnt)
  9809. (org-unbracket-string "<" ">" l))))
  9810. ((match-end 3)
  9811. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  9812. (match-string 3 l) (match-string 1 l))))
  9813. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  9814. (match-string 1 l)))))))
  9815. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  9816. (message "Select link to open, RET to open all:")
  9817. (setq c (read-char-exclusive))
  9818. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  9819. (when (equal c ?q) (user-error "Abort"))
  9820. (if (equal c ?\C-m)
  9821. (setq link links)
  9822. (setq nth (- c ?0))
  9823. (when have-zero (setq nth (1+ nth)))
  9824. (unless (and (integerp nth) (>= (length links) nth))
  9825. (user-error "Invalid link selection"))
  9826. (setq link (nth (1- nth) links)))))
  9827. (cons link end)))))
  9828. ;; TODO: These functions are deprecated since `org-open-at-point'
  9829. ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
  9830. (defun org-open-file-with-system (path)
  9831. "Open file at PATH using the system way of opening it."
  9832. (org-open-file path 'system))
  9833. (defun org-open-file-with-emacs (path)
  9834. "Open file at PATH in Emacs."
  9835. (org-open-file path 'emacs))
  9836. ;;; File search
  9837. (defvar org-create-file-search-functions nil
  9838. "List of functions to construct the right search string for a file link.
  9839. These functions are called in turn with point at the location to
  9840. which the link should point.
  9841. A function in the hook should first test if it would like to
  9842. handle this file type, for example by checking the `major-mode'
  9843. or the file extension. If it decides not to handle this file, it
  9844. should just return nil to give other functions a chance. If it
  9845. does handle the file, it must return the search string to be used
  9846. when following the link. The search string will be part of the
  9847. file link, given after a double colon, and `org-open-at-point'
  9848. will automatically search for it. If special measures must be
  9849. taken to make the search successful, another function should be
  9850. added to the companion hook `org-execute-file-search-functions',
  9851. which see.
  9852. A function in this hook may also use `setq' to set the variable
  9853. `description' to provide a suggestion for the descriptive text to
  9854. be used for this link when it gets inserted into an Org buffer
  9855. with \\[org-insert-link].")
  9856. (defvar org-execute-file-search-functions nil
  9857. "List of functions to execute a file search triggered by a link.
  9858. Functions added to this hook must accept a single argument, the
  9859. search string that was part of the file link, the part after the
  9860. double colon. The function must first check if it would like to
  9861. handle this search, for example by checking the `major-mode' or
  9862. the file extension. If it decides not to handle this search, it
  9863. should just return nil to give other functions a chance. If it
  9864. does handle the search, it must return a non-nil value to keep
  9865. other functions from trying.
  9866. Each function can access the current prefix argument through the
  9867. variable `current-prefix-arg'. Note that a single prefix is used
  9868. to force opening a link in Emacs, so it may be good to only use a
  9869. numeric or double prefix to guide the search function.
  9870. In case this is needed, a function in this hook can also restore
  9871. the window configuration before `org-open-at-point' was called using:
  9872. (set-window-configuration org-window-config-before-follow-link)")
  9873. (defun org-search-radio-target (target)
  9874. "Search a radio target matching TARGET in current buffer.
  9875. White spaces are not significant."
  9876. (let ((re (format "<<<%s>>>"
  9877. (mapconcat #'regexp-quote
  9878. (org-split-string target "[ \t\n]+")
  9879. "[ \t]+\\(?:\n[ \t]*\\)?")))
  9880. (origin (point)))
  9881. (goto-char (point-min))
  9882. (catch :radio-match
  9883. (while (re-search-forward re nil t)
  9884. (backward-char)
  9885. (let ((object (org-element-context)))
  9886. (when (eq (org-element-type object) 'radio-target)
  9887. (goto-char (org-element-property :begin object))
  9888. (org-show-context 'link-search)
  9889. (throw :radio-match nil))))
  9890. (goto-char origin)
  9891. (user-error "No match for radio target: %s" target))))
  9892. (defun org-link-search (s &optional avoid-pos stealth)
  9893. "Search for a search string S.
  9894. If S starts with \"#\", it triggers a custom ID search.
  9895. If S is enclosed within parenthesis, it initiates a coderef
  9896. search.
  9897. If S is surrounded by forward slashes, it is interpreted as
  9898. a regular expression. In Org mode files, this will create an
  9899. `org-occur' sparse tree. In ordinary files, `occur' will be used
  9900. to list matches. If the current buffer is in `dired-mode', grep
  9901. will be used to search in all files.
  9902. When AVOID-POS is given, ignore matches near that position.
  9903. When optional argument STEALTH is non-nil, do not modify
  9904. visibility around point, thus ignoring `org-show-context-detail'
  9905. variable.
  9906. Search is case-insensitive and ignores white spaces. Return type
  9907. of matched result, which is either `dedicated' or `fuzzy'."
  9908. (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
  9909. (let* ((case-fold-search t)
  9910. (origin (point))
  9911. (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
  9912. (starred (eq (string-to-char normalized) ?*))
  9913. (words (split-string (if starred (substring s 1) s)))
  9914. (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
  9915. (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
  9916. type)
  9917. (cond
  9918. ;; Check if there are any special search functions.
  9919. ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
  9920. ((eq (string-to-char s) ?#)
  9921. ;; Look for a custom ID S if S starts with "#".
  9922. (let* ((id (substring normalized 1))
  9923. (match (org-find-property "CUSTOM_ID" id)))
  9924. (if match (progn (goto-char match) (setf type 'dedicated))
  9925. (error "No match for custom ID: %s" id))))
  9926. ((string-match "\\`(\\(.*\\))\\'" normalized)
  9927. ;; Look for coderef targets if S is enclosed within parenthesis.
  9928. (let ((coderef (match-string-no-properties 1 normalized))
  9929. (re (substring s-single-re 1 -1)))
  9930. (goto-char (point-min))
  9931. (catch :coderef-match
  9932. (while (re-search-forward re nil t)
  9933. (let ((element (org-element-at-point)))
  9934. (when (and (memq (org-element-type element)
  9935. '(example-block src-block))
  9936. ;; Build proper regexp according to current
  9937. ;; block's label format.
  9938. (let ((label-fmt
  9939. (regexp-quote
  9940. (or (org-element-property :label-fmt element)
  9941. org-coderef-label-format))))
  9942. (save-excursion
  9943. (beginning-of-line)
  9944. (looking-at (format ".*?\\(%s\\)[ \t]*$"
  9945. (format label-fmt coderef))))))
  9946. (setq type 'dedicated)
  9947. (goto-char (match-beginning 1))
  9948. (throw :coderef-match nil))))
  9949. (goto-char origin)
  9950. (error "No match for coderef: %s" coderef))))
  9951. ((string-match "\\`/\\(.*\\)/\\'" normalized)
  9952. ;; Look for a regular expression.
  9953. (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
  9954. (match-string 1 s)))
  9955. ;; From here, we handle fuzzy links.
  9956. ;;
  9957. ;; Look for targets, only if not in a headline search.
  9958. ((and (not starred)
  9959. (let ((target (format "<<%s>>" s-multi-re)))
  9960. (catch :target-match
  9961. (goto-char (point-min))
  9962. (while (re-search-forward target nil t)
  9963. (backward-char)
  9964. (let ((context (org-element-context)))
  9965. (when (eq (org-element-type context) 'target)
  9966. (setq type 'dedicated)
  9967. (goto-char (org-element-property :begin context))
  9968. (throw :target-match t))))
  9969. nil))))
  9970. ;; Look for elements named after S, only if not in a headline
  9971. ;; search.
  9972. ((and (not starred)
  9973. (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
  9974. (catch :name-match
  9975. (goto-char (point-min))
  9976. (while (re-search-forward name nil t)
  9977. (let ((element (org-element-at-point)))
  9978. (when (equal words
  9979. (split-string
  9980. (org-element-property :name element)))
  9981. (setq type 'dedicated)
  9982. (beginning-of-line)
  9983. (throw :name-match t))))
  9984. nil))))
  9985. ;; Regular text search. Prefer headlines in Org mode buffers.
  9986. ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
  9987. ;; statistics cookies and tags.
  9988. ((and (derived-mode-p 'org-mode)
  9989. (let ((title-re
  9990. (format "%s.*\\(?:%s[ \t]\\)?.*%s"
  9991. org-outline-regexp-bol
  9992. org-comment-string
  9993. (mapconcat #'regexp-quote words ".+")))
  9994. (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
  9995. (comment-re (format "\\`%s[ \t]+" org-comment-string)))
  9996. (goto-char (point-min))
  9997. (catch :found
  9998. (while (re-search-forward title-re nil t)
  9999. (when (equal words
  10000. (split-string
  10001. (replace-regexp-in-string
  10002. cookie-re ""
  10003. (replace-regexp-in-string
  10004. comment-re "" (org-get-heading t t)))))
  10005. (throw :found t)))
  10006. nil)))
  10007. (beginning-of-line)
  10008. (setq type 'dedicated))
  10009. ;; Offer to create non-existent headline depending on
  10010. ;; `org-link-search-must-match-exact-headline'.
  10011. ((and (derived-mode-p 'org-mode)
  10012. (not org-link-search-inhibit-query)
  10013. (eq org-link-search-must-match-exact-headline 'query-to-create)
  10014. (yes-or-no-p "No match - create this as a new heading? "))
  10015. (goto-char (point-max))
  10016. (unless (bolp) (newline))
  10017. (org-insert-heading nil t t)
  10018. (insert s "\n")
  10019. (beginning-of-line 0))
  10020. ;; Only headlines are looked after. No need to process
  10021. ;; further: throw an error.
  10022. ((and (derived-mode-p 'org-mode)
  10023. (or starred org-link-search-must-match-exact-headline))
  10024. (goto-char origin)
  10025. (error "No match for fuzzy expression: %s" normalized))
  10026. ;; Regular text search.
  10027. ((catch :fuzzy-match
  10028. (goto-char (point-min))
  10029. (while (re-search-forward s-multi-re nil t)
  10030. ;; Skip match if it contains AVOID-POS or it is included in
  10031. ;; a link with a description but outside the description.
  10032. (unless (or (and avoid-pos
  10033. (<= (match-beginning 0) avoid-pos)
  10034. (> (match-end 0) avoid-pos))
  10035. (and (save-match-data
  10036. (org-in-regexp org-bracket-link-regexp))
  10037. (match-beginning 3)
  10038. (or (> (match-beginning 3) (point))
  10039. (<= (match-end 3) (point)))
  10040. (org-element-lineage
  10041. (save-match-data (org-element-context))
  10042. '(link) t)))
  10043. (goto-char (match-beginning 0))
  10044. (setq type 'fuzzy)
  10045. (throw :fuzzy-match t)))
  10046. nil))
  10047. ;; All failed. Throw an error.
  10048. (t (goto-char origin)
  10049. (error "No match for fuzzy expression: %s" normalized)))
  10050. ;; Disclose surroundings of match, if appropriate.
  10051. (when (and (derived-mode-p 'org-mode) (not stealth))
  10052. (org-show-context 'link-search))
  10053. type))
  10054. (defun org-get-buffer-for-internal-link (buffer)
  10055. "Return a buffer to be used for displaying the link target of internal links."
  10056. (cond
  10057. ((not org-display-internal-link-with-indirect-buffer)
  10058. buffer)
  10059. ((string-suffix-p "(Clone)" (buffer-name buffer))
  10060. (message "Buffer is already a clone, not making another one")
  10061. ;; we also do not modify visibility in this case
  10062. buffer)
  10063. (t ; make a new indirect buffer for displaying the link
  10064. (let* ((bn (buffer-name buffer))
  10065. (ibn (concat bn "(Clone)"))
  10066. (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
  10067. (with-current-buffer ib (org-overview))
  10068. ib))))
  10069. (defun org-do-occur (regexp &optional cleanup)
  10070. "Call the Emacs command `occur'.
  10071. If CLEANUP is non-nil, remove the printout of the regular expression
  10072. in the *Occur* buffer. This is useful if the regex is long and not useful
  10073. to read."
  10074. (occur regexp)
  10075. (when cleanup
  10076. (let ((cwin (selected-window)) win beg end)
  10077. (when (setq win (get-buffer-window "*Occur*"))
  10078. (select-window win))
  10079. (goto-char (point-min))
  10080. (when (re-search-forward "match[a-z]+" nil t)
  10081. (setq beg (match-end 0))
  10082. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  10083. (setq end (1- (match-beginning 0)))))
  10084. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  10085. (goto-char (point-min))
  10086. (select-window cwin))))
  10087. ;;; The mark ring for links jumps
  10088. (defvar org-mark-ring nil
  10089. "Mark ring for positions before jumps in Org mode.")
  10090. (defvar org-mark-ring-last-goto nil
  10091. "Last position in the mark ring used to go back.")
  10092. ;; Fill and close the ring
  10093. (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
  10094. (dotimes (_ org-mark-ring-length)
  10095. (push (make-marker) org-mark-ring))
  10096. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  10097. org-mark-ring)
  10098. (defun org-mark-ring-push (&optional pos buffer)
  10099. "Put the current position or POS into the mark ring and rotate it."
  10100. (interactive)
  10101. (setq pos (or pos (point)))
  10102. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  10103. (move-marker (car org-mark-ring)
  10104. (or pos (point))
  10105. (or buffer (current-buffer)))
  10106. (message "%s"
  10107. (substitute-command-keys
  10108. "Position saved to mark ring, go back with \
  10109. `\\[org-mark-ring-goto]'.")))
  10110. (defun org-mark-ring-goto (&optional n)
  10111. "Jump to the previous position in the mark ring.
  10112. With prefix arg N, jump back that many stored positions. When
  10113. called several times in succession, walk through the entire ring.
  10114. Org mode commands jumping to a different position in the current file,
  10115. or to another Org file, automatically push the old position onto the ring."
  10116. (interactive "p")
  10117. (let (p m)
  10118. (if (eq last-command this-command)
  10119. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  10120. (setq p org-mark-ring))
  10121. (setq org-mark-ring-last-goto p)
  10122. (setq m (car p))
  10123. (pop-to-buffer-same-window (marker-buffer m))
  10124. (goto-char m)
  10125. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  10126. (defun org-add-angle-brackets (s)
  10127. (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
  10128. (unless (equal (substring s -1) ">") (setq s (concat s ">")))
  10129. s)
  10130. ;;; Following specific links
  10131. (defvar org-agenda-buffer-tmp-name)
  10132. (defvar org-agenda-start-on-weekday)
  10133. (defun org-follow-timestamp-link ()
  10134. "Open an agenda view for the time-stamp date/range at point."
  10135. (cond
  10136. ((org-at-date-range-p t)
  10137. (let ((org-agenda-start-on-weekday)
  10138. (t1 (match-string 1))
  10139. (t2 (match-string 2)) tt1 tt2)
  10140. (setq tt1 (time-to-days (org-time-string-to-time t1))
  10141. tt2 (time-to-days (org-time-string-to-time t2)))
  10142. (let ((org-agenda-buffer-tmp-name
  10143. (format "*Org Agenda(a:%s)"
  10144. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  10145. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  10146. ((org-at-timestamp-p t)
  10147. (let ((org-agenda-buffer-tmp-name
  10148. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  10149. (org-agenda-list nil (time-to-days (org-time-string-to-time
  10150. (substring (match-string 1) 0 10)))
  10151. 1)))
  10152. (t (error "This should not happen"))))
  10153. ;;; Following file links
  10154. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  10155. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  10156. (declare-function mailcap-mime-info
  10157. "mailcap" (string &optional request no-decode))
  10158. (defvar org-wait nil)
  10159. (defun org-open-file (path &optional in-emacs line search)
  10160. "Open the file at PATH.
  10161. First, this expands any special file name abbreviations. Then the
  10162. configuration variable `org-file-apps' is checked if it contains an
  10163. entry for this file type, and if yes, the corresponding command is launched.
  10164. If no application is found, Emacs simply visits the file.
  10165. With optional prefix argument IN-EMACS, Emacs will visit the file.
  10166. With a double \\[universal-argument] \\[universal-argument] \
  10167. prefix arg, Org tries to avoid opening in Emacs
  10168. and to use an external application to visit the file.
  10169. Optional LINE specifies a line to go to, optional SEARCH a string
  10170. to search for. If LINE or SEARCH is given, the file will be
  10171. opened in Emacs, unless an entry from org-file-apps that makes
  10172. use of groups in a regexp matches.
  10173. If you want to change the way frames are used when following a
  10174. link, please customize `org-link-frame-setup'.
  10175. If the file does not exist, an error is thrown."
  10176. (let* ((file (if (equal path "")
  10177. buffer-file-name
  10178. (substitute-in-file-name (expand-file-name path))))
  10179. (file-apps (append org-file-apps (org-default-apps)))
  10180. (apps (cl-remove-if
  10181. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10182. (apps-dlink (cl-remove-if-not
  10183. 'org-file-apps-entry-match-against-dlink-p file-apps))
  10184. (remp (and (assq 'remote apps) (org-file-remote-p file)))
  10185. (dirp (unless remp (file-directory-p file)))
  10186. (file (if (and dirp org-open-directory-means-index-dot-org)
  10187. (concat (file-name-as-directory file) "index.org")
  10188. file))
  10189. (a-m-a-p (assq 'auto-mode apps))
  10190. (dfile (downcase file))
  10191. ;; Reconstruct the original link from the PATH, LINE and
  10192. ;; SEARCH args.
  10193. (link (cond (line (concat file "::" (number-to-string line)))
  10194. (search (concat file "::" search))
  10195. (t file)))
  10196. (dlink (downcase link))
  10197. (old-buffer (current-buffer))
  10198. (old-pos (point))
  10199. (old-mode major-mode)
  10200. (ext
  10201. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  10202. (match-string 1 dfile)))
  10203. cmd link-match-data)
  10204. (cond
  10205. ((member in-emacs '((16) system))
  10206. (setq cmd (cdr (assq 'system apps))))
  10207. (in-emacs (setq cmd 'emacs))
  10208. (t
  10209. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  10210. (and dirp (cdr (assq 'directory apps)))
  10211. ;; First, try matching against apps-dlink if we
  10212. ;; get a match here, store the match data for
  10213. ;; later.
  10214. (let ((match (assoc-default dlink apps-dlink
  10215. 'string-match)))
  10216. (if match
  10217. (progn (setq link-match-data (match-data))
  10218. match)
  10219. (progn (setq in-emacs (or in-emacs line search))
  10220. nil))) ; if we have no match in apps-dlink,
  10221. ; always open the file in emacs if line or search
  10222. ; is given (for backwards compatibility)
  10223. (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
  10224. 'string-match)
  10225. (cdr (assoc ext apps))
  10226. (cdr (assq t apps))))))
  10227. (when (eq cmd 'system)
  10228. (setq cmd (cdr (assq 'system apps))))
  10229. (when (eq cmd 'default)
  10230. (setq cmd (cdr (assoc t apps))))
  10231. (when (eq cmd 'mailcap)
  10232. (require 'mailcap)
  10233. (mailcap-parse-mailcaps)
  10234. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  10235. (command (mailcap-mime-info mime-type)))
  10236. (if (stringp command)
  10237. (setq cmd command)
  10238. (setq cmd 'emacs))))
  10239. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  10240. (not (file-exists-p file))
  10241. (not org-open-non-existing-files))
  10242. (user-error "No such file: %s" file))
  10243. (cond
  10244. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  10245. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  10246. (while (string-match "['\"]%s['\"]" cmd)
  10247. (setq cmd (replace-match "%s" t t cmd)))
  10248. (setq cmd (replace-regexp-in-string
  10249. "%s"
  10250. (shell-quote-argument (convert-standard-filename file))
  10251. cmd
  10252. nil t))
  10253. ;; Replace "%1", "%2" etc. in command with group matches from regex
  10254. (save-match-data
  10255. (let ((match-index 1)
  10256. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  10257. (set-match-data link-match-data)
  10258. (while (<= match-index number-of-groups)
  10259. (let ((regex (concat "%" (number-to-string match-index)))
  10260. (replace-with (match-string match-index dlink)))
  10261. (while (string-match regex cmd)
  10262. (setq cmd (replace-match replace-with t t cmd))))
  10263. (setq match-index (+ match-index 1)))))
  10264. (save-window-excursion
  10265. (message "Running %s...done" cmd)
  10266. (start-process-shell-command cmd nil cmd)
  10267. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  10268. ((or (stringp cmd)
  10269. (eq cmd 'emacs))
  10270. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  10271. (widen)
  10272. (cond (line (org-goto-line line)
  10273. (when (derived-mode-p 'org-mode) (org-reveal)))
  10274. (search (org-link-search search))))
  10275. ((functionp cmd)
  10276. (save-match-data
  10277. (set-match-data link-match-data)
  10278. (condition-case nil
  10279. (funcall cmd file link)
  10280. ;; FIXME: Remove this check when most default installations
  10281. ;; of Emacs have at least Org 9.0.
  10282. ((debug wrong-number-of-arguments wrong-type-argument
  10283. invalid-function)
  10284. (user-error "Please see Org News for version 9.0 about \
  10285. `org-file-apps'--Lisp error: %S" cmd)))))
  10286. ((consp cmd)
  10287. ;; FIXME: Remove this check when most default installations of
  10288. ;; Emacs have at least Org 9.0.
  10289. ;; Heads-up instead of silently fall back to
  10290. ;; `org-link-frame-setup' for an old usage of `org-file-apps'
  10291. ;; with sexp instead of a function for `cmd'.
  10292. (user-error "Please see Org News for version 9.0 about \
  10293. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  10294. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  10295. (and (derived-mode-p 'org-mode)
  10296. (eq old-mode 'org-mode)
  10297. (or (not (eq old-buffer (current-buffer)))
  10298. (not (eq old-pos (point))))
  10299. (org-mark-ring-push old-pos old-buffer))))
  10300. (defun org-file-apps-entry-match-against-dlink-p (entry)
  10301. "This function returns non-nil if `entry' uses a regular
  10302. expression which should be matched against the whole link by
  10303. org-open-file.
  10304. It assumes that is the case when the entry uses a regular
  10305. expression which has at least one grouping construct and the
  10306. action is either a lisp form or a command string containing
  10307. `%1', i.e. using at least one subexpression match as a
  10308. parameter."
  10309. (let ((selector (car entry))
  10310. (action (cdr entry)))
  10311. (if (stringp selector)
  10312. (and (> (regexp-opt-depth selector) 0)
  10313. (or (and (stringp action)
  10314. (string-match "%[0-9]" action))
  10315. (consp action)))
  10316. nil)))
  10317. (defun org-default-apps ()
  10318. "Return the default applications for this operating system."
  10319. (cond
  10320. ((eq system-type 'darwin)
  10321. org-file-apps-defaults-macosx)
  10322. ((eq system-type 'windows-nt)
  10323. org-file-apps-defaults-windowsnt)
  10324. (t org-file-apps-defaults-gnu)))
  10325. (defun org-apps-regexp-alist (list &optional add-auto-mode)
  10326. "Convert extensions to regular expressions in the cars of LIST.
  10327. Also, weed out any non-string entries, because the return value is used
  10328. only for regexp matching.
  10329. When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
  10330. point to the symbol `emacs', indicating that the file should
  10331. be opened in Emacs."
  10332. (append
  10333. (delq nil
  10334. (mapcar (lambda (x)
  10335. (unless (not (stringp (car x)))
  10336. (if (string-match "\\W" (car x))
  10337. x
  10338. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  10339. list))
  10340. (when add-auto-mode
  10341. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  10342. (defvar ange-ftp-name-format)
  10343. (defun org-file-remote-p (file)
  10344. "Test whether FILE specifies a location on a remote system.
  10345. Return non-nil if the location is indeed remote.
  10346. For example, the filename \"/user@host:/foo\" specifies a location
  10347. on the system \"/user@host:\"."
  10348. (cond ((fboundp 'file-remote-p)
  10349. (file-remote-p file))
  10350. ((fboundp 'tramp-handle-file-remote-p)
  10351. (tramp-handle-file-remote-p file))
  10352. ((and (boundp 'ange-ftp-name-format)
  10353. (string-match (car ange-ftp-name-format) file))
  10354. t)))
  10355. ;;;; Refiling
  10356. (defun org-get-org-file ()
  10357. "Read a filename, with default directory `org-directory'."
  10358. (let ((default (or org-default-notes-file remember-data-file)))
  10359. (read-file-name (format "File name [%s]: " default)
  10360. (file-name-as-directory org-directory)
  10361. default)))
  10362. (defun org-notes-order-reversed-p ()
  10363. "Check if the current file should receive notes in reversed order."
  10364. (cond
  10365. ((not org-reverse-note-order) nil)
  10366. ((eq t org-reverse-note-order) t)
  10367. ((not (listp org-reverse-note-order)) nil)
  10368. (t (catch 'exit
  10369. (dolist (entry org-reverse-note-order)
  10370. (when (string-match (car entry) buffer-file-name)
  10371. (throw 'exit (cdr entry))))))))
  10372. (defvar org-refile-target-table nil
  10373. "The list of refile targets, created by `org-refile'.")
  10374. (defvar org-agenda-new-buffers nil
  10375. "Buffers created to visit agenda files.")
  10376. (defvar org-refile-cache nil
  10377. "Cache for refile targets.")
  10378. (defvar org-refile-markers nil
  10379. "All the markers used for caching refile locations.")
  10380. (defun org-refile-marker (pos)
  10381. "Get a new refile marker, but only if caching is in use."
  10382. (if (not org-refile-use-cache)
  10383. pos
  10384. (let ((m (make-marker)))
  10385. (move-marker m pos)
  10386. (push m org-refile-markers)
  10387. m)))
  10388. (defun org-refile-cache-clear ()
  10389. "Clear the refile cache and disable all the markers."
  10390. (dolist (m org-refile-markers) (move-marker m nil))
  10391. (setq org-refile-markers nil)
  10392. (setq org-refile-cache nil)
  10393. (message "Refile cache has been cleared"))
  10394. (defun org-refile-cache-check-set (set)
  10395. "Check if all the markers in the cache still have live buffers."
  10396. (let (marker)
  10397. (catch 'exit
  10398. (while (and set (setq marker (nth 3 (pop set))))
  10399. ;; If `org-refile-use-outline-path' is 'file, marker may be nil
  10400. (when (and marker (null (marker-buffer marker)))
  10401. (message "Please regenerate the refile cache with `C-0 C-c C-w'")
  10402. (sit-for 3)
  10403. (throw 'exit nil)))
  10404. t)))
  10405. (defun org-refile-cache-put (set &rest identifiers)
  10406. "Push the refile targets SET into the cache, under IDENTIFIERS."
  10407. (let* ((key (sha1 (prin1-to-string identifiers)))
  10408. (entry (assoc key org-refile-cache)))
  10409. (if entry
  10410. (setcdr entry set)
  10411. (push (cons key set) org-refile-cache))))
  10412. (defun org-refile-cache-get (&rest identifiers)
  10413. "Retrieve the cached value for refile targets given by IDENTIFIERS."
  10414. (cond
  10415. ((not org-refile-cache) nil)
  10416. ((not org-refile-use-cache) (org-refile-cache-clear) nil)
  10417. (t
  10418. (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
  10419. org-refile-cache))))
  10420. (and set (org-refile-cache-check-set set) set)))))
  10421. (defvar org-outline-path-cache nil
  10422. "Alist between buffer positions and outline paths.
  10423. It value is an alist (POSITION . PATH) where POSITION is the
  10424. buffer position at the beginning of an entry and PATH is a list
  10425. of strings describing the outline path for that entry, in reverse
  10426. order.")
  10427. (defun org-refile-get-targets (&optional default-buffer)
  10428. "Produce a table with refile targets."
  10429. (let ((case-fold-search nil)
  10430. ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
  10431. (entries (or org-refile-targets '((nil . (:level . 1)))))
  10432. targets tgs files desc descre)
  10433. (message "Getting targets...")
  10434. (with-current-buffer (or default-buffer (current-buffer))
  10435. (dolist (entry entries)
  10436. (setq files (car entry) desc (cdr entry))
  10437. (cond
  10438. ((null files) (setq files (list (current-buffer))))
  10439. ((eq files 'org-agenda-files)
  10440. (setq files (org-agenda-files 'unrestricted)))
  10441. ((and (symbolp files) (fboundp files))
  10442. (setq files (funcall files)))
  10443. ((and (symbolp files) (boundp files))
  10444. (setq files (symbol-value files))))
  10445. (when (stringp files) (setq files (list files)))
  10446. (cond
  10447. ((eq (car desc) :tag)
  10448. (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
  10449. ((eq (car desc) :todo)
  10450. (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
  10451. ((eq (car desc) :regexp)
  10452. (setq descre (cdr desc)))
  10453. ((eq (car desc) :level)
  10454. (setq descre (concat "^\\*\\{" (number-to-string
  10455. (if org-odd-levels-only
  10456. (1- (* 2 (cdr desc)))
  10457. (cdr desc)))
  10458. "\\}[ \t]")))
  10459. ((eq (car desc) :maxlevel)
  10460. (setq descre (concat "^\\*\\{1," (number-to-string
  10461. (if org-odd-levels-only
  10462. (1- (* 2 (cdr desc)))
  10463. (cdr desc)))
  10464. "\\}[ \t]")))
  10465. (t (error "Bad refiling target description %s" desc)))
  10466. (dolist (f files)
  10467. (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
  10468. (or
  10469. (setq tgs (org-refile-cache-get (buffer-file-name) descre))
  10470. (progn
  10471. (when (bufferp f)
  10472. (setq f (buffer-file-name (buffer-base-buffer f))))
  10473. (setq f (and f (expand-file-name f)))
  10474. (when (eq org-refile-use-outline-path 'file)
  10475. (push (list (file-name-nondirectory f) f nil nil) tgs))
  10476. (org-with-wide-buffer
  10477. (goto-char (point-min))
  10478. (setq org-outline-path-cache nil)
  10479. (while (re-search-forward descre nil t)
  10480. (beginning-of-line)
  10481. (let ((case-fold-search nil))
  10482. (looking-at org-complex-heading-regexp))
  10483. (let ((begin (point))
  10484. (heading (match-string-no-properties 4)))
  10485. (unless (or (and
  10486. org-refile-target-verify-function
  10487. (not
  10488. (funcall org-refile-target-verify-function)))
  10489. (not heading))
  10490. (let ((re (format org-complex-heading-regexp-format
  10491. (regexp-quote heading)))
  10492. (target
  10493. (if (not org-refile-use-outline-path) heading
  10494. (mapconcat
  10495. #'org-protect-slash
  10496. (append
  10497. (pcase org-refile-use-outline-path
  10498. (`file (list (file-name-nondirectory
  10499. (buffer-file-name
  10500. (buffer-base-buffer)))))
  10501. (`full-file-path
  10502. (list (buffer-file-name
  10503. (buffer-base-buffer))))
  10504. (_ nil))
  10505. (org-get-outline-path t t))
  10506. "/"))))
  10507. (push (list target f re (org-refile-marker (point)))
  10508. tgs)))
  10509. (when (= (point) begin)
  10510. ;; Verification function has not moved point.
  10511. (end-of-line)))))))
  10512. (when org-refile-use-cache
  10513. (org-refile-cache-put tgs (buffer-file-name) descre))
  10514. (setq targets (append tgs targets))))))
  10515. (message "Getting targets...done")
  10516. (delete-dups (nreverse targets))))
  10517. (defun org-protect-slash (s)
  10518. (replace-regexp-in-string "/" "\\/" s nil t))
  10519. (defun org--get-outline-path-1 (&optional use-cache)
  10520. "Return outline path to current headline.
  10521. Outline path is a list of strings, in reverse order. When
  10522. optional argument USE-CACHE is non-nil, make use of a cache. See
  10523. `org-get-outline-path' for details.
  10524. Assume buffer is widened and point is on a headline."
  10525. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  10526. (let ((p (point))
  10527. (heading (let ((case-fold-search nil))
  10528. (looking-at org-complex-heading-regexp)
  10529. (if (not (match-end 4)) ""
  10530. ;; Remove statistics cookies.
  10531. (org-trim
  10532. (org-link-display-format
  10533. (replace-regexp-in-string
  10534. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  10535. (match-string-no-properties 4))))))))
  10536. (if (org-up-heading-safe)
  10537. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  10538. (when use-cache
  10539. (push (cons p path) org-outline-path-cache))
  10540. path)
  10541. ;; This is a new root node. Since we assume we are moving
  10542. ;; forward, we can drop previous cache so as to limit number
  10543. ;; of associations there.
  10544. (let ((path (list heading)))
  10545. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  10546. path)))))
  10547. (defun org-get-outline-path (&optional with-self use-cache)
  10548. "Return the outline path to the current entry.
  10549. An outline path is a list of ancestors for current headline, as
  10550. a list of strings. Statistics cookies are removed and links are
  10551. replaced with their description, if any, or their path otherwise.
  10552. When optional argument WITH-SELF is non-nil, the path also
  10553. includes the current headline.
  10554. When optional argument USE-CACHE is non-nil, cache outline paths
  10555. between calls to this function so as to avoid backtracking. This
  10556. argument is useful when planning to find more than one outline
  10557. path in the same document. In that case, there are two
  10558. conditions to satisfy:
  10559. - `org-outline-path-cache' is set to nil before starting the
  10560. process;
  10561. - outline paths are computed by increasing buffer positions."
  10562. (org-with-wide-buffer
  10563. (and (or (and with-self (org-back-to-heading t))
  10564. (org-up-heading-safe))
  10565. (reverse (org--get-outline-path-1 use-cache)))))
  10566. (defun org-format-outline-path (path &optional width prefix separator)
  10567. "Format the outline path PATH for display.
  10568. WIDTH is the maximum number of characters that is available.
  10569. PREFIX is a prefix to be included in the returned string,
  10570. such as the file name.
  10571. SEPARATOR is inserted between the different parts of the path,
  10572. the default is \"/\"."
  10573. (setq width (or width 79))
  10574. (setq path (delq nil path))
  10575. (unless (> width 0)
  10576. (user-error "Argument `width' must be positive"))
  10577. (setq separator (or separator "/"))
  10578. (let* ((org-odd-levels-only nil)
  10579. (fpath (concat
  10580. prefix (and prefix path separator)
  10581. (mapconcat
  10582. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  10583. (cl-loop for head in path
  10584. for n from 0
  10585. collect (org-add-props
  10586. head nil 'face
  10587. (nth (% n org-n-level-faces) org-level-faces)))
  10588. separator))))
  10589. (when (> (length fpath) width)
  10590. (if (< width 7)
  10591. ;; It's unlikely that `width' will be this small, but don't
  10592. ;; waste characters by adding ".." if it is.
  10593. (setq fpath (substring fpath 0 width))
  10594. (setf (substring fpath (- width 2)) "..")))
  10595. fpath))
  10596. (defun org-display-outline-path (&optional file current separator just-return-string)
  10597. "Display the current outline path in the echo area.
  10598. If FILE is non-nil, prepend the output with the file name.
  10599. If CURRENT is non-nil, append the current heading to the output.
  10600. SEPARATOR is passed through to `org-format-outline-path'. It separates
  10601. the different parts of the path and defaults to \"/\".
  10602. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  10603. (interactive "P")
  10604. (let* (case-fold-search
  10605. (bfn (buffer-file-name (buffer-base-buffer)))
  10606. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  10607. res)
  10608. (when current (setq path (append path
  10609. (save-excursion
  10610. (org-back-to-heading t)
  10611. (when (looking-at org-complex-heading-regexp)
  10612. (list (match-string 4)))))))
  10613. (setq res
  10614. (org-format-outline-path
  10615. path
  10616. (1- (frame-width))
  10617. (and file bfn (concat (file-name-nondirectory bfn) separator))
  10618. separator))
  10619. (if just-return-string
  10620. (org-no-properties res)
  10621. (org-unlogged-message "%s" res))))
  10622. (defvar org-refile-history nil
  10623. "History for refiling operations.")
  10624. (defvar org-after-refile-insert-hook nil
  10625. "Hook run after `org-refile' has inserted its stuff at the new location.
  10626. Note that this is still *before* the stuff will be removed from
  10627. the *old* location.")
  10628. (defvar org-capture-last-stored-marker)
  10629. (defvar org-refile-keep nil
  10630. "Non-nil means `org-refile' will copy instead of refile.")
  10631. (defun org-copy ()
  10632. "Like `org-refile', but copy."
  10633. (interactive)
  10634. (let ((org-refile-keep t))
  10635. (funcall 'org-refile nil nil nil "Copy")))
  10636. (defun org-refile (&optional arg default-buffer rfloc msg)
  10637. "Move the entry or entries at point to another heading.
  10638. The list of target headings is compiled using the information in
  10639. `org-refile-targets', which see.
  10640. At the target location, the entry is filed as a subitem of the
  10641. target heading. Depending on `org-reverse-note-order', the new
  10642. subitem will either be the first or the last subitem.
  10643. If there is an active region, all entries in that region will be
  10644. refiled. However, the region must fulfill the requirement that
  10645. the first heading sets the top-level of the moved text.
  10646. With a `\\[universal-argument]' ARG, the command will only visit the target \
  10647. location
  10648. and not actually move anything.
  10649. With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
  10650. location where the last
  10651. refiling operation has put the subtree.
  10652. With a numeric prefix argument of `2', refile to the running clock.
  10653. With a numeric prefix argument of `3', emulate `org-refile-keep'
  10654. being set to t and copy to the target location, don't move it.
  10655. Beware that keeping refiled entries may result in duplicated ID
  10656. properties.
  10657. RFLOC can be a refile location obtained in a different way.
  10658. MSG is a string to replace \"Refile\" in the default prompt with
  10659. another verb. E.g. `org-copy' sets this parameter to \"Copy\".
  10660. See also `org-refile-use-outline-path'.
  10661. If you are using target caching (see `org-refile-use-cache'), you
  10662. have to clear the target cache in order to find new targets.
  10663. This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
  10664. prefix argument (`C-u C-u C-u C-c C-w')."
  10665. (interactive "P")
  10666. (if (member arg '(0 (64)))
  10667. (org-refile-cache-clear)
  10668. (let* ((actionmsg (cond (msg msg)
  10669. ((equal arg 3) "Refile (and keep)")
  10670. (t "Refile")))
  10671. (regionp (org-region-active-p))
  10672. (region-start (and regionp (region-beginning)))
  10673. (region-end (and regionp (region-end)))
  10674. (org-refile-keep (if (equal arg 3) t org-refile-keep))
  10675. pos it nbuf file level reversed)
  10676. (setq last-command nil)
  10677. (when regionp
  10678. (goto-char region-start)
  10679. (or (bolp) (goto-char (point-at-bol)))
  10680. (setq region-start (point))
  10681. (unless (or (org-kill-is-subtree-p
  10682. (buffer-substring region-start region-end))
  10683. (prog1 org-refile-active-region-within-subtree
  10684. (let ((s (point-at-eol)))
  10685. (org-toggle-heading)
  10686. (setq region-end (+ (- (point-at-eol) s) region-end)))))
  10687. (user-error "The region is not a (sequence of) subtree(s)")))
  10688. (if (equal arg '(16))
  10689. (org-refile-goto-last-stored)
  10690. (when (or
  10691. (and (equal arg 2)
  10692. org-clock-hd-marker (marker-buffer org-clock-hd-marker)
  10693. (prog1
  10694. (setq it (list (or org-clock-heading "running clock")
  10695. (buffer-file-name
  10696. (marker-buffer org-clock-hd-marker))
  10697. ""
  10698. (marker-position org-clock-hd-marker)))
  10699. (setq arg nil)))
  10700. (setq it
  10701. (or rfloc
  10702. (let (heading-text)
  10703. (save-excursion
  10704. (unless (and arg (listp arg))
  10705. (org-back-to-heading t)
  10706. (setq heading-text
  10707. (replace-regexp-in-string
  10708. org-bracket-link-regexp
  10709. "\\3"
  10710. (or (nth 4 (org-heading-components))
  10711. ""))))
  10712. (org-refile-get-location
  10713. (cond ((and arg (listp arg)) "Goto")
  10714. (regionp (concat actionmsg " region to"))
  10715. (t (concat actionmsg " subtree \""
  10716. heading-text "\" to")))
  10717. default-buffer
  10718. (and (not (equal '(4) arg))
  10719. org-refile-allow-creating-parent-nodes)))))))
  10720. (setq file (nth 1 it)
  10721. pos (nth 3 it))
  10722. (when (and (not arg)
  10723. pos
  10724. (equal (buffer-file-name) file)
  10725. (if regionp
  10726. (and (>= pos region-start)
  10727. (<= pos region-end))
  10728. (and (>= pos (point))
  10729. (< pos (save-excursion
  10730. (org-end-of-subtree t t))))))
  10731. (error "Cannot refile to position inside the tree or region"))
  10732. (setq nbuf (or (find-buffer-visiting file)
  10733. (find-file-noselect file)))
  10734. (if (and arg (not (equal arg 3)))
  10735. (progn
  10736. (pop-to-buffer-same-window nbuf)
  10737. (goto-char (cond (pos)
  10738. ((org-notes-order-reversed-p) (point-min))
  10739. (t (point-max))))
  10740. (org-show-context 'org-goto))
  10741. (if regionp
  10742. (progn
  10743. (org-kill-new (buffer-substring region-start region-end))
  10744. (org-save-markers-in-region region-start region-end))
  10745. (org-copy-subtree 1 nil t))
  10746. (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
  10747. (find-file-noselect file)))
  10748. (setq reversed (org-notes-order-reversed-p))
  10749. (org-with-wide-buffer
  10750. (if pos
  10751. (progn
  10752. (goto-char pos)
  10753. (looking-at org-outline-regexp)
  10754. (setq level (org-get-valid-level (funcall outline-level) 1))
  10755. (goto-char
  10756. (if reversed
  10757. (or (outline-next-heading) (point-max))
  10758. (or (save-excursion (org-get-next-sibling))
  10759. (org-end-of-subtree t t)
  10760. (point-max)))))
  10761. (setq level 1)
  10762. (if (not reversed)
  10763. (goto-char (point-max))
  10764. (goto-char (point-min))
  10765. (or (outline-next-heading) (goto-char (point-max)))))
  10766. (unless (bolp) (newline))
  10767. (org-paste-subtree level nil nil t)
  10768. (when org-log-refile
  10769. (org-add-log-setup 'refile nil nil org-log-refile)
  10770. (unless (eq org-log-refile 'note)
  10771. (save-excursion (org-add-log-note))))
  10772. (and org-auto-align-tags
  10773. (let ((org-loop-over-headlines-in-active-region nil))
  10774. (org-set-tags nil t)))
  10775. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10776. :last-refile)))
  10777. (when bookmark-name
  10778. (with-demoted-errors
  10779. (bookmark-set bookmark-name))))
  10780. ;; If we are refiling for capture, make sure that the
  10781. ;; last-capture pointers point here
  10782. (when (bound-and-true-p org-capture-is-refiling)
  10783. (let ((bookmark-name (plist-get org-bookmark-names-plist
  10784. :last-capture-marker)))
  10785. (when bookmark-name
  10786. (with-demoted-errors
  10787. (bookmark-set bookmark-name))))
  10788. (move-marker org-capture-last-stored-marker (point)))
  10789. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10790. (run-hooks 'org-after-refile-insert-hook)))
  10791. (unless org-refile-keep
  10792. (if regionp
  10793. (delete-region (point) (+ (point) (- region-end region-start)))
  10794. (delete-region
  10795. (and (org-back-to-heading t) (point))
  10796. (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
  10797. (when (featurep 'org-inlinetask)
  10798. (org-inlinetask-remove-END-maybe))
  10799. (setq org-markers-to-move nil)
  10800. (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
  10801. (defun org-refile-goto-last-stored ()
  10802. "Go to the location where the last refile was stored."
  10803. (interactive)
  10804. (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
  10805. (message "This is the location of the last refile"))
  10806. (defun org-refile--get-location (refloc tbl)
  10807. "When user refile to REFLOC, find the associated target in TBL.
  10808. Also check `org-refile-target-table'."
  10809. (car (delq
  10810. nil
  10811. (mapcar
  10812. (lambda (r) (or (assoc r tbl)
  10813. (assoc r org-refile-target-table)))
  10814. (list (replace-regexp-in-string "/$" "" refloc)
  10815. (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
  10816. (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
  10817. "Prompt the user for a refile location, using PROMPT.
  10818. PROMPT should not be suffixed with a colon and a space, because
  10819. this function appends the default value from
  10820. `org-refile-history' automatically, if that is not empty."
  10821. (let ((org-refile-targets org-refile-targets)
  10822. (org-refile-use-outline-path org-refile-use-outline-path))
  10823. (setq org-refile-target-table (org-refile-get-targets default-buffer)))
  10824. (unless org-refile-target-table
  10825. (user-error "No refile targets"))
  10826. (let* ((cbuf (current-buffer))
  10827. (cfn (buffer-file-name (buffer-base-buffer cbuf)))
  10828. (cfunc (if (and org-refile-use-outline-path
  10829. org-outline-path-complete-in-steps)
  10830. #'org-olpath-completing-read
  10831. #'completing-read))
  10832. (extra (if org-refile-use-outline-path "/" ""))
  10833. (cbnex (concat (buffer-name) extra))
  10834. (filename (and cfn (expand-file-name cfn)))
  10835. (tbl (mapcar
  10836. (lambda (x)
  10837. (if (and (not (member org-refile-use-outline-path
  10838. '(file full-file-path)))
  10839. (not (equal filename (nth 1 x))))
  10840. (cons (concat (car x) extra " ("
  10841. (file-name-nondirectory (nth 1 x)) ")")
  10842. (cdr x))
  10843. (cons (concat (car x) extra) (cdr x))))
  10844. org-refile-target-table))
  10845. (completion-ignore-case t)
  10846. cdef
  10847. (prompt (concat prompt
  10848. (or (and (car org-refile-history)
  10849. (concat " (default " (car org-refile-history) ")"))
  10850. (and (assoc cbnex tbl) (setq cdef cbnex)
  10851. (concat " (default " cbnex ")"))) ": "))
  10852. pa answ parent-target child parent old-hist)
  10853. (setq old-hist org-refile-history)
  10854. (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
  10855. nil 'org-refile-history (or cdef (car org-refile-history))))
  10856. (if (setq pa (org-refile--get-location answ tbl))
  10857. (progn
  10858. (org-refile-check-position pa)
  10859. (when (or (not org-refile-history)
  10860. (not (eq old-hist org-refile-history))
  10861. (not (equal (car pa) (car org-refile-history))))
  10862. (setq org-refile-history
  10863. (cons (car pa) (if (assoc (car org-refile-history) tbl)
  10864. org-refile-history
  10865. (cdr org-refile-history))))
  10866. (when (equal (car org-refile-history) (nth 1 org-refile-history))
  10867. (pop org-refile-history)))
  10868. pa)
  10869. (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
  10870. (progn
  10871. (setq parent (match-string 1 answ)
  10872. child (match-string 2 answ))
  10873. (setq parent-target (org-refile--get-location parent tbl))
  10874. (when (and parent-target
  10875. (or (eq new-nodes t)
  10876. (and (eq new-nodes 'confirm)
  10877. (y-or-n-p (format "Create new node \"%s\"? "
  10878. child)))))
  10879. (org-refile-new-child parent-target child)))
  10880. (user-error "Invalid target location")))))
  10881. (declare-function org-string-nw-p "org-macs" (s))
  10882. (defun org-refile-check-position (refile-pointer)
  10883. "Check if the refile pointer matches the headline to which it points."
  10884. (let* ((file (nth 1 refile-pointer))
  10885. (re (nth 2 refile-pointer))
  10886. (pos (nth 3 refile-pointer))
  10887. buffer)
  10888. (if (and (not (markerp pos)) (not file))
  10889. (user-error "Please indicate a target file in the refile path")
  10890. (when (org-string-nw-p re)
  10891. (setq buffer (if (markerp pos)
  10892. (marker-buffer pos)
  10893. (or (find-buffer-visiting file)
  10894. (find-file-noselect file))))
  10895. (with-current-buffer buffer
  10896. (org-with-wide-buffer
  10897. (goto-char pos)
  10898. (beginning-of-line 1)
  10899. (unless (looking-at-p re)
  10900. (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
  10901. (defun org-refile-new-child (parent-target child)
  10902. "Use refile target PARENT-TARGET to add new CHILD below it."
  10903. (unless parent-target
  10904. (error "Cannot find parent for new node"))
  10905. (let ((file (nth 1 parent-target))
  10906. (pos (nth 3 parent-target))
  10907. level)
  10908. (with-current-buffer (or (find-buffer-visiting file)
  10909. (find-file-noselect file))
  10910. (org-with-wide-buffer
  10911. (if pos
  10912. (goto-char pos)
  10913. (goto-char (point-max))
  10914. (unless (bolp) (newline)))
  10915. (when (looking-at org-outline-regexp)
  10916. (setq level (funcall outline-level))
  10917. (org-end-of-subtree t t))
  10918. (org-back-over-empty-lines)
  10919. (insert "\n" (make-string
  10920. (if pos (org-get-valid-level level 1) 1) ?*)
  10921. " " child "\n")
  10922. (beginning-of-line 0)
  10923. (list (concat (car parent-target) "/" child) file "" (point))))))
  10924. (defun org-olpath-completing-read (prompt collection &rest args)
  10925. "Read an outline path like a file name."
  10926. (let ((thetable collection))
  10927. (apply #'completing-read
  10928. prompt
  10929. (lambda (string predicate &optional flag)
  10930. (cond
  10931. ((eq flag nil) (try-completion string thetable))
  10932. ((eq flag t)
  10933. (let ((l (length string)))
  10934. (mapcar (lambda (x)
  10935. (let ((r (substring x l))
  10936. (f (if (string-match " ([^)]*)$" x)
  10937. (match-string 0 x)
  10938. "")))
  10939. (if (string-match "/" r)
  10940. (concat string (substring r 0 (match-end 0)) f)
  10941. x)))
  10942. (all-completions string thetable predicate))))
  10943. ;; Exact match?
  10944. ((eq flag 'lambda) (assoc string thetable))))
  10945. args)))
  10946. ;;;; Dynamic blocks
  10947. (defun org-find-dblock (name)
  10948. "Find the first dynamic block with name NAME in the buffer.
  10949. If not found, stay at current position and return nil."
  10950. (let ((case-fold-search t) pos)
  10951. (save-excursion
  10952. (goto-char (point-min))
  10953. (setq pos (and (re-search-forward
  10954. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  10955. (match-beginning 0))))
  10956. (when pos (goto-char pos))
  10957. pos))
  10958. (defun org-create-dblock (plist)
  10959. "Create a dynamic block section, with parameters taken from PLIST.
  10960. PLIST must contain a :name entry which is used as the name of the block."
  10961. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  10962. (end-of-line 1)
  10963. (newline))
  10964. (let ((col (current-column))
  10965. (name (plist-get plist :name)))
  10966. (insert "#+BEGIN: " name)
  10967. (while plist
  10968. (if (eq (car plist) :name)
  10969. (setq plist (cddr plist))
  10970. (insert " " (prin1-to-string (pop plist)))))
  10971. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  10972. (beginning-of-line -2)))
  10973. (defun org-prepare-dblock ()
  10974. "Prepare dynamic block for refresh.
  10975. This empties the block, puts the cursor at the insert position and returns
  10976. the property list including an extra property :name with the block name."
  10977. (unless (looking-at org-dblock-start-re)
  10978. (user-error "Not at a dynamic block"))
  10979. (let* ((begdel (1+ (match-end 0)))
  10980. (name (org-no-properties (match-string 1)))
  10981. (params (append (list :name name)
  10982. (read (concat "(" (match-string 3) ")")))))
  10983. (save-excursion
  10984. (beginning-of-line 1)
  10985. (skip-chars-forward " \t")
  10986. (setq params (plist-put params :indentation-column (current-column))))
  10987. (unless (re-search-forward org-dblock-end-re nil t)
  10988. (error "Dynamic block not terminated"))
  10989. (setq params
  10990. (append params
  10991. (list :content (buffer-substring
  10992. begdel (match-beginning 0)))))
  10993. (delete-region begdel (match-beginning 0))
  10994. (goto-char begdel)
  10995. (open-line 1)
  10996. params))
  10997. (defun org-map-dblocks (&optional command)
  10998. "Apply COMMAND to all dynamic blocks in the current buffer.
  10999. If COMMAND is not given, use `org-update-dblock'."
  11000. (let ((cmd (or command 'org-update-dblock)))
  11001. (save-excursion
  11002. (goto-char (point-min))
  11003. (while (re-search-forward org-dblock-start-re nil t)
  11004. (goto-char (match-beginning 0))
  11005. (save-excursion
  11006. (condition-case nil
  11007. (funcall cmd)
  11008. (error (message "Error during update of dynamic block"))))
  11009. (unless (re-search-forward org-dblock-end-re nil t)
  11010. (error "Dynamic block not terminated"))))))
  11011. (defun org-dblock-update (&optional arg)
  11012. "User command for updating dynamic blocks.
  11013. Update the dynamic block at point. With prefix ARG, update all dynamic
  11014. blocks in the buffer."
  11015. (interactive "P")
  11016. (if arg
  11017. (org-update-all-dblocks)
  11018. (or (looking-at org-dblock-start-re)
  11019. (org-beginning-of-dblock))
  11020. (org-update-dblock)))
  11021. (defun org-update-dblock ()
  11022. "Update the dynamic block at point.
  11023. This means to empty the block, parse for parameters and then call
  11024. the correct writing function."
  11025. (interactive)
  11026. (save-excursion
  11027. (let* ((win (selected-window))
  11028. (pos (point))
  11029. (line (org-current-line))
  11030. (params (org-prepare-dblock))
  11031. (name (plist-get params :name))
  11032. (indent (plist-get params :indentation-column))
  11033. (cmd (intern (concat "org-dblock-write:" name))))
  11034. (message "Updating dynamic block `%s' at line %d..." name line)
  11035. (funcall cmd params)
  11036. (message "Updating dynamic block `%s' at line %d...done" name line)
  11037. (goto-char pos)
  11038. (when (and indent (> indent 0))
  11039. (setq indent (make-string indent ?\ ))
  11040. (save-excursion
  11041. (select-window win)
  11042. (org-beginning-of-dblock)
  11043. (forward-line 1)
  11044. (while (not (looking-at org-dblock-end-re))
  11045. (insert indent)
  11046. (beginning-of-line 2))
  11047. (when (looking-at org-dblock-end-re)
  11048. (and (looking-at "[ \t]+")
  11049. (replace-match ""))
  11050. (insert indent)))))))
  11051. (defun org-beginning-of-dblock ()
  11052. "Find the beginning of the dynamic block at point.
  11053. Error if there is no such block at point."
  11054. (let ((pos (point))
  11055. beg)
  11056. (end-of-line 1)
  11057. (if (and (re-search-backward org-dblock-start-re nil t)
  11058. (setq beg (match-beginning 0))
  11059. (re-search-forward org-dblock-end-re nil t)
  11060. (> (match-end 0) pos))
  11061. (goto-char beg)
  11062. (goto-char pos)
  11063. (error "Not in a dynamic block"))))
  11064. (defun org-update-all-dblocks ()
  11065. "Update all dynamic blocks in the buffer.
  11066. This function can be used in a hook."
  11067. (interactive)
  11068. (when (derived-mode-p 'org-mode)
  11069. (org-map-dblocks 'org-update-dblock)))
  11070. ;;;; Completion
  11071. (declare-function org-export-backend-options "ox" (cl-x) t)
  11072. (defun org-get-export-keywords ()
  11073. "Return a list of all currently understood export keywords.
  11074. Export keywords include options, block names, attributes and
  11075. keywords relative to each registered export back-end."
  11076. (let (keywords)
  11077. (dolist (backend
  11078. (bound-and-true-p org-export-registered-backends)
  11079. (delq nil keywords))
  11080. ;; Back-end name (for keywords, like #+LATEX:)
  11081. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  11082. (dolist (option-entry (org-export-backend-options backend))
  11083. ;; Back-end options.
  11084. (push (nth 1 option-entry) keywords)))))
  11085. (defconst org-options-keywords
  11086. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  11087. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  11088. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  11089. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  11090. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  11091. (defcustom org-structure-template-alist
  11092. '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
  11093. ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
  11094. ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
  11095. ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
  11096. ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
  11097. ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
  11098. ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
  11099. ("L" "#+LaTeX: ")
  11100. ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
  11101. ("H" "#+HTML: ")
  11102. ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
  11103. ("A" "#+ASCII: ")
  11104. ("i" "#+INDEX: ?")
  11105. ("I" "#+INCLUDE: %file ?"))
  11106. "Structure completion elements.
  11107. This is a list of abbreviation keys and values. The value gets inserted
  11108. if you type `<' followed by the key and then press the completion key,
  11109. usually `TAB'. %file will be replaced by a file name after prompting
  11110. for the file using completion. The cursor will be placed at the position
  11111. of the `?' in the template.
  11112. There are two templates for each key, the first uses the original Org syntax,
  11113. the second uses Emacs Muse-like syntax tags. These Muse-like tags become
  11114. the default when the /org-mtags.el/ module has been loaded. See also the
  11115. variable `org-mtags-prefer-muse-templates'."
  11116. :group 'org-completion
  11117. :type '(repeat
  11118. (list
  11119. (string :tag "Key")
  11120. (string :tag "Template")))
  11121. :version "26.1"
  11122. :package-version '(Org . "8.3"))
  11123. (defun org-try-structure-completion ()
  11124. "Try to complete a structure template before point.
  11125. This looks for strings like \"<e\" on an otherwise empty line and
  11126. expands them."
  11127. (let ((l (buffer-substring (point-at-bol) (point)))
  11128. a)
  11129. (when (and (looking-at "[ \t]*$")
  11130. (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
  11131. (setq a (assoc (match-string 1 l) org-structure-template-alist)))
  11132. (org-complete-expand-structure-template (+ -1 (point-at-bol)
  11133. (match-beginning 1)) a)
  11134. t)))
  11135. (defun org-complete-expand-structure-template (start cell)
  11136. "Expand a structure template."
  11137. (let ((rpl (nth 1 cell))
  11138. (ind ""))
  11139. (delete-region start (point))
  11140. (when (string-match "\\`[ \t]*#\\+" rpl)
  11141. (cond
  11142. ((bolp))
  11143. ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
  11144. (setq ind (buffer-substring (point-at-bol) (point))))
  11145. (t (newline))))
  11146. (setq start (point))
  11147. (when (string-match "%file" rpl)
  11148. (setq rpl (replace-match
  11149. (concat
  11150. "\""
  11151. (save-match-data
  11152. (abbreviate-file-name (read-file-name "Include file: ")))
  11153. "\"")
  11154. t t rpl)))
  11155. (setq rpl (mapconcat 'identity (split-string rpl "\n")
  11156. (concat "\n" ind)))
  11157. (insert rpl)
  11158. (when (re-search-backward "\\?" start t) (delete-char 1))))
  11159. ;;;; TODO, DEADLINE, Comments
  11160. (defun org-toggle-comment ()
  11161. "Change the COMMENT state of an entry."
  11162. (interactive)
  11163. (save-excursion
  11164. (org-back-to-heading)
  11165. (let ((case-fold-search nil))
  11166. (looking-at org-complex-heading-regexp))
  11167. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  11168. (skip-chars-forward " \t")
  11169. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  11170. (if (org-in-commented-heading-p t)
  11171. (delete-region (point)
  11172. (progn (search-forward " " (line-end-position) 'move)
  11173. (skip-chars-forward " \t")
  11174. (point)))
  11175. (insert org-comment-string)
  11176. (unless (eolp) (insert " ")))))
  11177. (defvar org-last-todo-state-is-todo nil
  11178. "This is non-nil when the last TODO state change led to a TODO state.
  11179. If the last change removed the TODO tag or switched to DONE, then
  11180. this is nil.")
  11181. (defvar org-setting-tags nil) ; dynamically skipped
  11182. (defvar org-todo-setup-filter-hook nil
  11183. "Hook for functions that pre-filter todo specs.
  11184. Each function takes a todo spec and returns either nil or the spec
  11185. transformed into canonical form." )
  11186. (defvar org-todo-get-default-hook nil
  11187. "Hook for functions that get a default item for todo.
  11188. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  11189. nil or a string to be used for the todo mark." )
  11190. (defvar org-agenda-headline-snapshot-before-repeat)
  11191. (defun org-current-effective-time ()
  11192. "Return current time adjusted for `org-extend-today-until' variable."
  11193. (let* ((ct (org-current-time))
  11194. (dct (decode-time ct))
  11195. (ct1
  11196. (cond
  11197. (org-use-last-clock-out-time-as-effective-time
  11198. (or (org-clock-get-last-clock-out-time) ct))
  11199. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  11200. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  11201. (t ct))))
  11202. ct1))
  11203. (defun org-todo-yesterday (&optional arg)
  11204. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  11205. (interactive "P")
  11206. (if (eq major-mode 'org-agenda-mode)
  11207. (apply 'org-agenda-todo-yesterday arg)
  11208. (let* ((org-use-effective-time t)
  11209. (hour (nth 2 (decode-time (org-current-time))))
  11210. (org-extend-today-until (1+ hour)))
  11211. (org-todo arg))))
  11212. (defvar org-block-entry-blocking ""
  11213. "First entry preventing the TODO state change.")
  11214. (defun org-cancel-repeater ()
  11215. "Cancel a repeater by setting its numeric value to zero."
  11216. (interactive)
  11217. (save-excursion
  11218. (org-back-to-heading t)
  11219. (let ((bound1 (point))
  11220. (bound0 (save-excursion (outline-next-heading) (point))))
  11221. (when (and (re-search-forward
  11222. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  11223. org-deadline-time-regexp "\\)\\|\\("
  11224. org-ts-regexp "\\)")
  11225. bound0 t)
  11226. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  11227. bound1 t))
  11228. (replace-match "0" t nil nil 1)))))
  11229. (defvar org-state)
  11230. (defvar org-blocked-by-checkboxes)
  11231. (defun org-todo (&optional arg)
  11232. "Change the TODO state of an item.
  11233. The state of an item is given by a keyword at the start of the heading,
  11234. like
  11235. *** TODO Write paper
  11236. *** DONE Call mom
  11237. The different keywords are specified in the variable `org-todo-keywords'.
  11238. By default the available states are \"TODO\" and \"DONE\". So, for this
  11239. example: when the item starts with TODO, it is changed to DONE.
  11240. When it starts with DONE, the DONE is removed. And when neither TODO nor
  11241. DONE are present, add TODO at the beginning of the heading.
  11242. With `\\[universal-argument]' prefix ARG, use completion to determine the new \
  11243. state.
  11244. With numeric prefix ARG, switch to that state.
  11245. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  11246. next set of TODO \
  11247. keywords (nextset).
  11248. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  11249. prefix, circumvent any state blocking.
  11250. With a numeric prefix arg of 0, inhibit note taking for the change.
  11251. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  11252. When called through ELisp, arg is also interpreted in the following way:
  11253. `none' -> empty state
  11254. \"\" -> switch to empty state
  11255. `done' -> switch to DONE
  11256. `nextset' -> switch to the next set of keywords
  11257. `previousset' -> switch to the previous set of keywords
  11258. \"WAITING\" -> switch to the specified keyword, but only if it
  11259. really is a member of `org-todo-keywords'."
  11260. (interactive "P")
  11261. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11262. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11263. 'region-start-level 'region))
  11264. org-loop-over-headlines-in-active-region)
  11265. (org-map-entries
  11266. `(org-todo ,arg)
  11267. org-loop-over-headlines-in-active-region
  11268. cl (when (org-invisible-p) (org-end-of-subtree nil t))))
  11269. (when (equal arg '(16)) (setq arg 'nextset))
  11270. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  11271. (let ((org-blocker-hook org-blocker-hook)
  11272. commentp
  11273. case-fold-search)
  11274. (when (equal arg '(64))
  11275. (setq arg nil org-blocker-hook nil))
  11276. (when (and org-blocker-hook
  11277. (or org-inhibit-blocking
  11278. (org-entry-get nil "NOBLOCKING")))
  11279. (setq org-blocker-hook nil))
  11280. (save-excursion
  11281. (catch 'exit
  11282. (org-back-to-heading t)
  11283. (when (org-in-commented-heading-p t)
  11284. (org-toggle-comment)
  11285. (setq commentp t))
  11286. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  11287. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  11288. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  11289. (let* ((match-data (match-data))
  11290. (startpos (point-at-bol))
  11291. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  11292. (org-log-done org-log-done)
  11293. (org-log-repeat org-log-repeat)
  11294. (org-todo-log-states org-todo-log-states)
  11295. (org-inhibit-logging
  11296. (if (equal arg 0)
  11297. (progn (setq arg nil) 'note) org-inhibit-logging))
  11298. (this (match-string 1))
  11299. (hl-pos (match-beginning 0))
  11300. (head (org-get-todo-sequence-head this))
  11301. (ass (assoc head org-todo-kwd-alist))
  11302. (interpret (nth 1 ass))
  11303. (done-word (nth 3 ass))
  11304. (final-done-word (nth 4 ass))
  11305. (org-last-state (or this ""))
  11306. (completion-ignore-case t)
  11307. (member (member this org-todo-keywords-1))
  11308. (tail (cdr member))
  11309. (org-state (cond
  11310. ((and org-todo-key-trigger
  11311. (or (and (equal arg '(4))
  11312. (eq org-use-fast-todo-selection 'prefix))
  11313. (and (not arg) org-use-fast-todo-selection
  11314. (not (eq org-use-fast-todo-selection
  11315. 'prefix)))))
  11316. ;; Use fast selection.
  11317. (org-fast-todo-selection))
  11318. ((and (equal arg '(4))
  11319. (or (not org-use-fast-todo-selection)
  11320. (not org-todo-key-trigger)))
  11321. ;; Read a state with completion.
  11322. (completing-read
  11323. "State: " (mapcar #'list org-todo-keywords-1)
  11324. nil t))
  11325. ((eq arg 'right)
  11326. (if this
  11327. (if tail (car tail) nil)
  11328. (car org-todo-keywords-1)))
  11329. ((eq arg 'left)
  11330. (unless (equal member org-todo-keywords-1)
  11331. (if this
  11332. (nth (- (length org-todo-keywords-1)
  11333. (length tail) 2)
  11334. org-todo-keywords-1)
  11335. (org-last org-todo-keywords-1))))
  11336. ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
  11337. (setq arg nil))) ;hack to fall back to cycling
  11338. (arg
  11339. ;; User or caller requests a specific state.
  11340. (cond
  11341. ((equal arg "") nil)
  11342. ((eq arg 'none) nil)
  11343. ((eq arg 'done) (or done-word (car org-done-keywords)))
  11344. ((eq arg 'nextset)
  11345. (or (car (cdr (member head org-todo-heads)))
  11346. (car org-todo-heads)))
  11347. ((eq arg 'previousset)
  11348. (let ((org-todo-heads (reverse org-todo-heads)))
  11349. (or (car (cdr (member head org-todo-heads)))
  11350. (car org-todo-heads))))
  11351. ((car (member arg org-todo-keywords-1)))
  11352. ((stringp arg)
  11353. (user-error "State `%s' not valid in this file" arg))
  11354. ((nth (1- (prefix-numeric-value arg))
  11355. org-todo-keywords-1))))
  11356. ((null member) (or head (car org-todo-keywords-1)))
  11357. ((equal this final-done-word) nil) ;-> make empty
  11358. ((null tail) nil) ;-> first entry
  11359. ((memq interpret '(type priority))
  11360. (if (eq this-command last-command)
  11361. (car tail)
  11362. (if (> (length tail) 0)
  11363. (or done-word (car org-done-keywords))
  11364. nil)))
  11365. (t
  11366. (car tail))))
  11367. (org-state (or
  11368. (run-hook-with-args-until-success
  11369. 'org-todo-get-default-hook org-state org-last-state)
  11370. org-state))
  11371. (next (if org-state (concat " " org-state " ") " "))
  11372. (change-plist (list :type 'todo-state-change :from this :to org-state
  11373. :position startpos))
  11374. dolog now-done-p)
  11375. (when org-blocker-hook
  11376. (let (org-blocked-by-checkboxes block-reason)
  11377. (setq org-last-todo-state-is-todo
  11378. (not (member this org-done-keywords)))
  11379. (unless (save-excursion
  11380. (save-match-data
  11381. (org-with-wide-buffer
  11382. (run-hook-with-args-until-failure
  11383. 'org-blocker-hook change-plist))))
  11384. (setq block-reason (if org-blocked-by-checkboxes
  11385. "contained checkboxes"
  11386. (format "\"%s\"" org-block-entry-blocking)))
  11387. (if (called-interactively-p 'interactive)
  11388. (user-error "TODO state change from %s to %s blocked (by %s)"
  11389. this org-state block-reason)
  11390. ;; Fail silently.
  11391. (message "TODO state change from %s to %s blocked (by %s)"
  11392. this org-state block-reason)
  11393. (throw 'exit nil)))))
  11394. (store-match-data match-data)
  11395. (replace-match next t t)
  11396. (cond ((equal this org-state)
  11397. (message "TODO state was already %s" (org-trim next)))
  11398. ((not (pos-visible-in-window-p hl-pos))
  11399. (message "TODO state changed to %s" (org-trim next))))
  11400. (unless head
  11401. (setq head (org-get-todo-sequence-head org-state)
  11402. ass (assoc head org-todo-kwd-alist)
  11403. interpret (nth 1 ass)
  11404. done-word (nth 3 ass)
  11405. final-done-word (nth 4 ass)))
  11406. (when (memq arg '(nextset previousset))
  11407. (message "Keyword-Set %d/%d: %s"
  11408. (- (length org-todo-sets) -1
  11409. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  11410. (length org-todo-sets)
  11411. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  11412. (setq org-last-todo-state-is-todo
  11413. (not (member org-state org-done-keywords)))
  11414. (setq now-done-p (and (member org-state org-done-keywords)
  11415. (not (member this org-done-keywords))))
  11416. (and logging (org-local-logging logging))
  11417. (when (and (or org-todo-log-states org-log-done)
  11418. (not (eq org-inhibit-logging t))
  11419. (not (memq arg '(nextset previousset))))
  11420. ;; We need to look at recording a time and note.
  11421. (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
  11422. (nth 2 (assoc this org-todo-log-states))))
  11423. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  11424. (setq dolog 'time))
  11425. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  11426. (and org-state
  11427. (member org-state org-not-done-keywords)
  11428. (not (member this org-not-done-keywords))))
  11429. ;; This is now a todo state and was not one before
  11430. ;; If there was a CLOSED time stamp, get rid of it.
  11431. (org-add-planning-info nil nil 'closed))
  11432. (when (and now-done-p org-log-done)
  11433. ;; It is now done, and it was not done before.
  11434. (org-add-planning-info 'closed (org-current-effective-time))
  11435. (when (and (not dolog) (eq 'note org-log-done))
  11436. (org-add-log-setup 'done org-state this 'note)))
  11437. (when (and org-state dolog)
  11438. ;; This is a non-nil state, and we need to log it.
  11439. (org-add-log-setup 'state org-state this dolog)))
  11440. ;; Fixup tag positioning.
  11441. (org-todo-trigger-tag-changes org-state)
  11442. (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
  11443. (when org-provide-todo-statistics
  11444. (org-update-parent-todo-statistics))
  11445. (run-hooks 'org-after-todo-state-change-hook)
  11446. (when (and arg (not (member org-state org-done-keywords)))
  11447. (setq head (org-get-todo-sequence-head org-state)))
  11448. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  11449. ;; Do we need to trigger a repeat?
  11450. (when now-done-p
  11451. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  11452. ;; This is for the agenda, take a snapshot of the headline.
  11453. (save-match-data
  11454. (setq org-agenda-headline-snapshot-before-repeat
  11455. (org-get-heading))))
  11456. (org-auto-repeat-maybe org-state))
  11457. ;; Fixup cursor location if close to the keyword.
  11458. (when (and (outline-on-heading-p)
  11459. (not (bolp))
  11460. (save-excursion (beginning-of-line 1)
  11461. (looking-at org-todo-line-regexp))
  11462. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  11463. (goto-char (or (match-end 2) (match-end 1)))
  11464. (and (looking-at " ") (just-one-space)))
  11465. (when org-trigger-hook
  11466. (save-excursion
  11467. (run-hook-with-args 'org-trigger-hook change-plist)))
  11468. (when commentp (org-toggle-comment))))))))
  11469. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  11470. "Block turning an entry into a TODO, using the hierarchy.
  11471. This checks whether the current task should be blocked from state
  11472. changes. Such blocking occurs when:
  11473. 1. The task has children which are not all in a completed state.
  11474. 2. A task has a parent with the property :ORDERED:, and there
  11475. are siblings prior to the current task with incomplete
  11476. status.
  11477. 3. The parent of the task is blocked because it has siblings that should
  11478. be done first, or is child of a block grandparent TODO entry."
  11479. (if (not org-enforce-todo-dependencies)
  11480. t ; if locally turned off don't block
  11481. (catch 'dont-block
  11482. ;; If this is not a todo state change, or if this entry is already DONE,
  11483. ;; do not block
  11484. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11485. (member (plist-get change-plist :from)
  11486. (cons 'done org-done-keywords))
  11487. (member (plist-get change-plist :to)
  11488. (cons 'todo org-not-done-keywords))
  11489. (not (plist-get change-plist :to)))
  11490. (throw 'dont-block t))
  11491. ;; If this task has children, and any are undone, it's blocked
  11492. (save-excursion
  11493. (org-back-to-heading t)
  11494. (let ((this-level (funcall outline-level)))
  11495. (outline-next-heading)
  11496. (let ((child-level (funcall outline-level)))
  11497. (while (and (not (eobp))
  11498. (> child-level this-level))
  11499. ;; this todo has children, check whether they are all
  11500. ;; completed
  11501. (when (and (not (org-entry-is-done-p))
  11502. (org-entry-is-todo-p))
  11503. (setq org-block-entry-blocking (org-get-heading))
  11504. (throw 'dont-block nil))
  11505. (outline-next-heading)
  11506. (setq child-level (funcall outline-level))))))
  11507. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  11508. ;; any previous siblings are undone, it's blocked
  11509. (save-excursion
  11510. (org-back-to-heading t)
  11511. (let* ((pos (point))
  11512. (parent-pos (and (org-up-heading-safe) (point)))
  11513. (case-fold-search nil))
  11514. (unless parent-pos (throw 'dont-block t)) ; no parent
  11515. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11516. (forward-line 1)
  11517. (re-search-forward org-not-done-heading-regexp pos t))
  11518. (setq org-block-entry-blocking (match-string 0))
  11519. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  11520. ;; Search further up the hierarchy, to see if an ancestor is blocked
  11521. (while t
  11522. (goto-char parent-pos)
  11523. (unless (looking-at org-not-done-heading-regexp)
  11524. (throw 'dont-block t)) ; do not block, parent is not a TODO
  11525. (setq pos (point))
  11526. (setq parent-pos (and (org-up-heading-safe) (point)))
  11527. (unless parent-pos (throw 'dont-block t)) ; no parent
  11528. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  11529. (forward-line 1)
  11530. (re-search-forward org-not-done-heading-regexp pos t)
  11531. (setq org-block-entry-blocking (org-get-heading)))
  11532. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  11533. (defcustom org-track-ordered-property-with-tag nil
  11534. "Should the ORDERED property also be shown as a tag?
  11535. The ORDERED property decides if an entry should require subtasks to be
  11536. completed in sequence. Since a property is not very visible, setting
  11537. this option means that toggling the ORDERED property with the command
  11538. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  11539. not relevant for the behavior, but it makes things more visible.
  11540. Note that toggling the tag with tags commands will not change the property
  11541. and therefore not influence behavior!
  11542. This can be t, meaning the tag ORDERED should be used, It can also be a
  11543. string to select a different tag for this task."
  11544. :group 'org-todo
  11545. :type '(choice
  11546. (const :tag "No tracking" nil)
  11547. (const :tag "Track with ORDERED tag" t)
  11548. (string :tag "Use other tag")))
  11549. (defun org-toggle-ordered-property ()
  11550. "Toggle the ORDERED property of the current entry.
  11551. For better visibility, you can track the value of this property with a tag.
  11552. See variable `org-track-ordered-property-with-tag'."
  11553. (interactive)
  11554. (let* ((t1 org-track-ordered-property-with-tag)
  11555. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  11556. (save-excursion
  11557. (org-back-to-heading)
  11558. (if (org-entry-get nil "ORDERED")
  11559. (progn
  11560. (org-delete-property "ORDERED")
  11561. (and tag (org-toggle-tag tag 'off))
  11562. (message "Subtasks can be completed in arbitrary order"))
  11563. (org-entry-put nil "ORDERED" "t")
  11564. (and tag (org-toggle-tag tag 'on))
  11565. (message "Subtasks must be completed in sequence")))))
  11566. (defun org-block-todo-from-checkboxes (change-plist)
  11567. "Block turning an entry into a TODO, using checkboxes.
  11568. This checks whether the current task should be blocked from state
  11569. changes because there are unchecked boxes in this entry."
  11570. (if (not org-enforce-todo-checkbox-dependencies)
  11571. t ; if locally turned off don't block
  11572. (catch 'dont-block
  11573. ;; If this is not a todo state change, or if this entry is already DONE,
  11574. ;; do not block
  11575. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  11576. (member (plist-get change-plist :from)
  11577. (cons 'done org-done-keywords))
  11578. (member (plist-get change-plist :to)
  11579. (cons 'todo org-not-done-keywords))
  11580. (not (plist-get change-plist :to)))
  11581. (throw 'dont-block t))
  11582. ;; If this task has checkboxes that are not checked, it's blocked
  11583. (save-excursion
  11584. (org-back-to-heading t)
  11585. (let ((beg (point)) end)
  11586. (outline-next-heading)
  11587. (setq end (point))
  11588. (goto-char beg)
  11589. (when (org-list-search-forward
  11590. (concat (org-item-beginning-re)
  11591. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  11592. "\\[[- ]\\]")
  11593. end t)
  11594. (when (boundp 'org-blocked-by-checkboxes)
  11595. (setq org-blocked-by-checkboxes t))
  11596. (throw 'dont-block nil))))
  11597. t))) ; do not block
  11598. (defun org-entry-blocked-p ()
  11599. "Non-nil if entry at point is blocked."
  11600. (and (not (org-entry-get nil "NOBLOCKING"))
  11601. (member (org-entry-get nil "TODO") org-not-done-keywords)
  11602. (not (run-hook-with-args-until-failure
  11603. 'org-blocker-hook
  11604. (list :type 'todo-state-change
  11605. :position (point)
  11606. :from 'todo
  11607. :to 'done)))))
  11608. (defun org-update-statistics-cookies (all)
  11609. "Update the statistics cookie, either from TODO or from checkboxes.
  11610. This should be called with the cursor in a line with a statistics
  11611. cookie. When called with a \\[universal-argument] prefix, update
  11612. all statistics cookies in the buffer."
  11613. (interactive "P")
  11614. (if all
  11615. (progn
  11616. (org-update-checkbox-count 'all)
  11617. (org-map-entries 'org-update-parent-todo-statistics))
  11618. (if (not (org-at-heading-p))
  11619. (org-update-checkbox-count)
  11620. (let ((pos (point-marker))
  11621. end l1 l2)
  11622. (ignore-errors (org-back-to-heading t))
  11623. (if (not (org-at-heading-p))
  11624. (org-update-checkbox-count)
  11625. (setq l1 (org-outline-level))
  11626. (setq end (save-excursion
  11627. (outline-next-heading)
  11628. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  11629. (point)))
  11630. (if (and (save-excursion
  11631. (re-search-forward
  11632. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  11633. (not (save-excursion (re-search-forward
  11634. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  11635. (org-update-checkbox-count)
  11636. (if (and l2 (> l2 l1))
  11637. (progn
  11638. (goto-char end)
  11639. (org-update-parent-todo-statistics))
  11640. (goto-char pos)
  11641. (beginning-of-line 1)
  11642. (while (re-search-forward
  11643. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  11644. (point-at-eol) t)
  11645. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  11646. (goto-char pos)
  11647. (move-marker pos nil)))))
  11648. (defvar org-entry-property-inherited-from) ;; defined below
  11649. (defun org-update-parent-todo-statistics ()
  11650. "Update any statistics cookie in the parent of the current headline.
  11651. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  11652. the entire subtree and this will travel up the hierarchy and update
  11653. statistics everywhere."
  11654. (let* ((prop (save-excursion (org-up-heading-safe)
  11655. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  11656. (recursive (or (not org-hierarchical-todo-statistics)
  11657. (and prop (string-match "\\<recursive\\>" prop))))
  11658. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  11659. 0))
  11660. (first t)
  11661. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  11662. level ltoggle l1 new ndel
  11663. (cnt-all 0) (cnt-done 0) is-percent kwd
  11664. checkbox-beg cookie-present)
  11665. (catch 'exit
  11666. (save-excursion
  11667. (beginning-of-line 1)
  11668. (setq ltoggle (funcall outline-level))
  11669. ;; Three situations are to consider:
  11670. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  11671. ;; to the top-level ancestor on the headline;
  11672. ;; 2. If parent has "recursive" property, repeat up to the
  11673. ;; headline setting that property, taking inheritance into
  11674. ;; account;
  11675. ;; 3. Else, move up to direct parent and proceed only once.
  11676. (while (and (setq level (org-up-heading-safe))
  11677. (or recursive first)
  11678. (>= (point) lim))
  11679. (setq first nil cookie-present nil)
  11680. (unless (and level
  11681. (not (string-match
  11682. "\\<checkbox\\>"
  11683. (downcase (or (org-entry-get nil "COOKIE_DATA")
  11684. "")))))
  11685. (throw 'exit nil))
  11686. (while (re-search-forward box-re (point-at-eol) t)
  11687. (setq cnt-all 0 cnt-done 0 cookie-present t)
  11688. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  11689. (save-match-data
  11690. (unless (outline-next-heading) (throw 'exit nil))
  11691. (while (and (looking-at org-complex-heading-regexp)
  11692. (> (setq l1 (length (match-string 1))) level))
  11693. (setq kwd (and (or recursive (= l1 ltoggle))
  11694. (match-string 2)))
  11695. (if (or (eq org-provide-todo-statistics 'all-headlines)
  11696. (and (eq org-provide-todo-statistics t)
  11697. (or (member kwd org-done-keywords)))
  11698. (and (listp org-provide-todo-statistics)
  11699. (stringp (car org-provide-todo-statistics))
  11700. (or (member kwd org-provide-todo-statistics)
  11701. (member kwd org-done-keywords)))
  11702. (and (listp org-provide-todo-statistics)
  11703. (listp (car org-provide-todo-statistics))
  11704. (or (member kwd (car org-provide-todo-statistics))
  11705. (and (member kwd org-done-keywords)
  11706. (member kwd (cadr org-provide-todo-statistics))))))
  11707. (setq cnt-all (1+ cnt-all))
  11708. (and (eq org-provide-todo-statistics t)
  11709. kwd
  11710. (setq cnt-all (1+ cnt-all))))
  11711. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  11712. (member kwd org-done-keywords))
  11713. (and (listp org-provide-todo-statistics)
  11714. (listp (car org-provide-todo-statistics))
  11715. (member kwd org-done-keywords)
  11716. (member kwd (cadr org-provide-todo-statistics)))
  11717. (and (listp org-provide-todo-statistics)
  11718. (stringp (car org-provide-todo-statistics))
  11719. (member kwd org-done-keywords)))
  11720. (setq cnt-done (1+ cnt-done)))
  11721. (outline-next-heading)))
  11722. (setq new
  11723. (if is-percent
  11724. (format "[%d%%]" (floor (* 100.0 cnt-done)
  11725. (max 1 cnt-all)))
  11726. (format "[%d/%d]" cnt-done cnt-all))
  11727. ndel (- (match-end 0) checkbox-beg))
  11728. (goto-char checkbox-beg)
  11729. (insert new)
  11730. (delete-region (point) (+ (point) ndel))
  11731. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  11732. (when cookie-present
  11733. (run-hook-with-args 'org-after-todo-statistics-hook
  11734. cnt-done (- cnt-all cnt-done))))))
  11735. (run-hooks 'org-todo-statistics-hook)))
  11736. (defvar org-after-todo-statistics-hook nil
  11737. "Hook that is called after a TODO statistics cookie has been updated.
  11738. Each function is called with two arguments: the number of not-done entries
  11739. and the number of done entries.
  11740. For example, the following function, when added to this hook, will switch
  11741. an entry to DONE when all children are done, and back to TODO when new
  11742. entries are set to a TODO status. Note that this hook is only called
  11743. when there is a statistics cookie in the headline!
  11744. (defun org-summary-todo (n-done n-not-done)
  11745. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  11746. (let (org-log-done org-log-states) ; turn off logging
  11747. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
  11748. ")
  11749. (defvar org-todo-statistics-hook nil
  11750. "Hook that is run whenever Org thinks TODO statistics should be updated.
  11751. This hook runs even if there is no statistics cookie present, in which case
  11752. `org-after-todo-statistics-hook' would not run.")
  11753. (defun org-todo-trigger-tag-changes (state)
  11754. "Apply the changes defined in `org-todo-state-tags-triggers'."
  11755. (let ((l org-todo-state-tags-triggers)
  11756. changes)
  11757. (when (or (not state) (equal state ""))
  11758. (setq changes (append changes (cdr (assoc "" l)))))
  11759. (when (and (stringp state) (> (length state) 0))
  11760. (setq changes (append changes (cdr (assoc state l)))))
  11761. (when (member state org-not-done-keywords)
  11762. (setq changes (append changes (cdr (assq 'todo l)))))
  11763. (when (member state org-done-keywords)
  11764. (setq changes (append changes (cdr (assq 'done l)))))
  11765. (dolist (c changes)
  11766. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  11767. (defun org-local-logging (value)
  11768. "Get logging settings from a property VALUE."
  11769. ;; Directly set the variables, they are already local.
  11770. (setq org-log-done nil
  11771. org-log-repeat nil
  11772. org-todo-log-states nil)
  11773. (dolist (w (org-split-string value))
  11774. (let (a)
  11775. (cond
  11776. ((setq a (assoc w org-startup-options))
  11777. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  11778. (set (nth 1 a) (nth 2 a))))
  11779. ((setq a (org-extract-log-state-settings w))
  11780. (and (member (car a) org-todo-keywords-1)
  11781. (push a org-todo-log-states)))))))
  11782. (defun org-get-todo-sequence-head (kwd)
  11783. "Return the head of the TODO sequence to which KWD belongs.
  11784. If KWD is not set, check if there is a text property remembering the
  11785. right sequence."
  11786. (let (p)
  11787. (cond
  11788. ((not kwd)
  11789. (or (get-text-property (point-at-bol) 'org-todo-head)
  11790. (progn
  11791. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  11792. nil (point-at-eol)))
  11793. (get-text-property p 'org-todo-head))))
  11794. ((not (member kwd org-todo-keywords-1))
  11795. (car org-todo-keywords-1))
  11796. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  11797. (defun org-fast-todo-selection ()
  11798. "Fast TODO keyword selection with single keys.
  11799. Returns the new TODO keyword, or nil if no state change should occur."
  11800. (let* ((fulltable org-todo-key-alist)
  11801. (done-keywords org-done-keywords) ;; needed for the faces.
  11802. (maxlen (apply 'max (mapcar
  11803. (lambda (x)
  11804. (if (stringp (car x)) (string-width (car x)) 0))
  11805. fulltable)))
  11806. (expert nil)
  11807. (fwidth (+ maxlen 3 1 3))
  11808. (ncol (/ (- (window-width) 4) fwidth))
  11809. tg cnt e c tbl
  11810. groups ingroup)
  11811. (save-excursion
  11812. (save-window-excursion
  11813. (if expert
  11814. (set-buffer (get-buffer-create " *Org todo*"))
  11815. (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
  11816. (erase-buffer)
  11817. (setq-local org-done-keywords done-keywords)
  11818. (setq tbl fulltable cnt 0)
  11819. (while (setq e (pop tbl))
  11820. (cond
  11821. ((equal e '(:startgroup))
  11822. (push '() groups) (setq ingroup t)
  11823. (unless (= cnt 0)
  11824. (setq cnt 0)
  11825. (insert "\n"))
  11826. (insert "{ "))
  11827. ((equal e '(:endgroup))
  11828. (setq ingroup nil cnt 0)
  11829. (insert "}\n"))
  11830. ((equal e '(:newline))
  11831. (unless (= cnt 0)
  11832. (setq cnt 0)
  11833. (insert "\n")
  11834. (setq e (car tbl))
  11835. (while (equal (car tbl) '(:newline))
  11836. (insert "\n")
  11837. (setq tbl (cdr tbl)))))
  11838. (t
  11839. (setq tg (car e) c (cdr e))
  11840. (when ingroup (push tg (car groups)))
  11841. (setq tg (org-add-props tg nil 'face
  11842. (org-get-todo-face tg)))
  11843. (when (and (= cnt 0) (not ingroup)) (insert " "))
  11844. (insert "[" c "] " tg (make-string
  11845. (- fwidth 4 (length tg)) ?\ ))
  11846. (when (= (setq cnt (1+ cnt)) ncol)
  11847. (insert "\n")
  11848. (when ingroup (insert " "))
  11849. (setq cnt 0)))))
  11850. (insert "\n")
  11851. (goto-char (point-min))
  11852. (unless expert (org-fit-window-to-buffer))
  11853. (message "[a-z..]:Set [SPC]:clear")
  11854. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11855. (cond
  11856. ((or (= c ?\C-g)
  11857. (and (= c ?q) (not (rassoc c fulltable))))
  11858. (setq quit-flag t))
  11859. ((= c ?\ ) nil)
  11860. ((setq e (rassoc c fulltable) tg (car e))
  11861. tg)
  11862. (t (setq quit-flag t)))))))
  11863. (defun org-entry-is-todo-p ()
  11864. (member (org-get-todo-state) org-not-done-keywords))
  11865. (defun org-entry-is-done-p ()
  11866. (member (org-get-todo-state) org-done-keywords))
  11867. (defun org-get-todo-state ()
  11868. "Return the TODO keyword of the current subtree."
  11869. (save-excursion
  11870. (org-back-to-heading t)
  11871. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  11872. (match-end 2)
  11873. (match-string 2))))
  11874. (defun org-at-date-range-p (&optional inactive-ok)
  11875. "Non-nil if point is inside a date range.
  11876. When optional argument INACTIVE-OK is non-nil, also consider
  11877. inactive time ranges.
  11878. When this function returns a non-nil value, match data is set
  11879. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  11880. on INACTIVE-OK."
  11881. (interactive)
  11882. (save-excursion
  11883. (catch 'exit
  11884. (let ((pos (point)))
  11885. (skip-chars-backward "^[<\r\n")
  11886. (skip-chars-backward "<[")
  11887. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11888. (>= (match-end 0) pos)
  11889. (throw 'exit t))
  11890. (skip-chars-backward "^<[\r\n")
  11891. (skip-chars-backward "<[")
  11892. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  11893. (>= (match-end 0) pos)
  11894. (throw 'exit t)))
  11895. nil)))
  11896. (defun org-get-repeat (&optional tagline)
  11897. "Check if there is a deadline/schedule with repeater in this entry."
  11898. (save-match-data
  11899. (save-excursion
  11900. (org-back-to-heading t)
  11901. (and (re-search-forward (if tagline
  11902. (concat tagline "\\s-*" org-repeat-re)
  11903. org-repeat-re)
  11904. (org-entry-end-position) t)
  11905. (match-string-no-properties 1)))))
  11906. (defvar org-last-changed-timestamp)
  11907. (defvar org-last-inserted-timestamp)
  11908. (defvar org-log-post-message)
  11909. (defvar org-log-note-purpose)
  11910. (defvar org-log-note-how nil)
  11911. (defvar org-log-note-extra)
  11912. (defun org-auto-repeat-maybe (done-word)
  11913. "Check if the current headline contains a repeated time-stamp.
  11914. If yes, set TODO state back to what it was and change the base date
  11915. of repeating deadline/scheduled time stamps to new date.
  11916. This function is run automatically after each state change to a DONE state."
  11917. (let* ((repeat (org-get-repeat))
  11918. (aa (assoc org-last-state org-todo-kwd-alist))
  11919. (interpret (nth 1 aa))
  11920. (head (nth 2 aa))
  11921. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  11922. (msg "Entry repeats: ")
  11923. (org-log-done nil)
  11924. (org-todo-log-states nil))
  11925. (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
  11926. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  11927. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  11928. org-todo-repeat-to-state)))
  11929. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  11930. to-state)
  11931. ((eq interpret 'type) org-last-state)
  11932. (head)
  11933. (t 'none))))
  11934. (when (or org-log-repeat (org-entry-get nil "CLOCK"))
  11935. (org-entry-put nil "LAST_REPEAT" (format-time-string
  11936. (org-time-stamp-format t t))))
  11937. (when org-log-repeat
  11938. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  11939. (memq 'org-add-log-note post-command-hook))
  11940. ;; We are already setup for some record.
  11941. (when (eq org-log-repeat 'note)
  11942. ;; Make sure we take a note, not only a time stamp.
  11943. (setq org-log-note-how 'note))
  11944. ;; Set up for taking a record.
  11945. (org-add-log-setup 'state
  11946. (or done-word (car org-done-keywords))
  11947. org-last-state
  11948. org-log-repeat)))
  11949. (org-back-to-heading t)
  11950. (org-add-planning-info nil nil 'closed)
  11951. (let ((end (save-excursion (outline-next-heading) (point)))
  11952. (planning-re (regexp-opt
  11953. (list org-scheduled-string org-deadline-string))))
  11954. (while (re-search-forward org-ts-regexp end t)
  11955. (let* ((ts (match-string 0))
  11956. (planning? (org-at-planning-p))
  11957. (type (if (not planning?) "Plain:"
  11958. (save-excursion
  11959. (re-search-backward
  11960. planning-re (line-beginning-position) t)
  11961. (match-string 0)))))
  11962. (cond
  11963. ;; Ignore fake time-stamps (e.g., within comments).
  11964. ((and (not planning?)
  11965. (not (org-at-property-p))
  11966. (not (eq 'timestamp
  11967. (org-element-type (save-excursion
  11968. (backward-char)
  11969. (org-element-context)))))))
  11970. ;; Time-stamps without a repeater are usually skipped.
  11971. ;; However, a SCHEDULED time-stamp without one is
  11972. ;; removed, as it is considered as no longer relevant.
  11973. ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  11974. (when (equal type org-scheduled-string)
  11975. (org-remove-timestamp-with-keyword type)))
  11976. (t
  11977. (let ((n (string-to-number (match-string 2 ts)))
  11978. (what (match-string 3 ts)))
  11979. (when (equal what "w") (setq n (* n 7) what "d"))
  11980. (when (and (equal what "h")
  11981. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  11982. ts)))
  11983. (user-error
  11984. "Cannot repeat in Repeat in %d hour(s) because no hour \
  11985. has been set"
  11986. n))
  11987. ;; Preparation, see if we need to modify the start
  11988. ;; date for the change.
  11989. (when (match-end 1)
  11990. (let ((time (save-match-data (org-time-string-to-time ts))))
  11991. (cond
  11992. ((equal (match-string 1 ts) ".")
  11993. ;; Shift starting date to today
  11994. (org-timestamp-change
  11995. (- (org-today) (time-to-days time))
  11996. 'day))
  11997. ((equal (match-string 1 ts) "+")
  11998. (let ((nshiftmax 10)
  11999. (nshift 0))
  12000. (while (or (= nshift 0)
  12001. (not (time-less-p (current-time) time)))
  12002. (when (= (cl-incf nshift) nshiftmax)
  12003. (or (y-or-n-p
  12004. (format "%d repeater intervals were not \
  12005. enough to shift date past today. Continue? "
  12006. nshift))
  12007. (user-error "Abort")))
  12008. (org-timestamp-change n (cdr (assoc what whata)))
  12009. (org-at-timestamp-p t)
  12010. (setq ts (match-string 1))
  12011. (setq time
  12012. (save-match-data
  12013. (org-time-string-to-time ts)))))
  12014. (org-timestamp-change (- n) (cdr (assoc what whata)))
  12015. ;; Rematch, so that we have everything in place
  12016. ;; for the real shift.
  12017. (org-at-timestamp-p t)
  12018. (setq ts (match-string 1))
  12019. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  12020. ts)))))
  12021. (save-excursion
  12022. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  12023. (setq msg
  12024. (concat
  12025. msg type " " org-last-changed-timestamp " "))))))))
  12026. (setq org-log-post-message msg)
  12027. (message "%s" msg))))
  12028. (defun org-show-todo-tree (arg)
  12029. "Make a compact tree which shows all headlines marked with TODO.
  12030. The tree will show the lines where the regexp matches, and all higher
  12031. headlines above the match.
  12032. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  12033. With a numeric prefix N, construct a sparse tree for the Nth element
  12034. of `org-todo-keywords-1'."
  12035. (interactive "P")
  12036. (let ((case-fold-search nil)
  12037. (kwd-re
  12038. (cond ((null arg) org-not-done-regexp)
  12039. ((equal arg '(4))
  12040. (let ((kwd
  12041. (completing-read "Keyword (or KWD1|KWD2|...): "
  12042. (mapcar #'list org-todo-keywords-1))))
  12043. (concat "\\("
  12044. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  12045. "\\)\\>")))
  12046. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  12047. (regexp-quote (nth (1- (prefix-numeric-value arg))
  12048. org-todo-keywords-1)))
  12049. (t (user-error "Invalid prefix argument: %s" arg)))))
  12050. (message "%d TODO entries found"
  12051. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  12052. (defun org--deadline-or-schedule (arg type time)
  12053. "Insert DEADLINE or SCHEDULE information in current entry.
  12054. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  12055. `org-schedule' for information about ARG and TIME arguments."
  12056. (let* ((deadline? (eq type 'deadline))
  12057. (keyword (if deadline? org-deadline-string org-scheduled-string))
  12058. (log (if deadline? org-log-redeadline org-log-reschedule))
  12059. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  12060. (old-date-time (and old-date (org-time-string-to-time old-date)))
  12061. ;; Save repeater cookie from either TIME or current scheduled
  12062. ;; time stamp. We are going to insert it back at the end of
  12063. ;; the process.
  12064. (repeater (or (and (org-string-nw-p time)
  12065. ;; We use `org-repeat-re' because we need
  12066. ;; to tell the difference between a real
  12067. ;; repeater and a time delta, e.g. "+2d".
  12068. (string-match org-repeat-re time)
  12069. (match-string 1 time))
  12070. (and (org-string-nw-p old-date)
  12071. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  12072. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  12073. old-date)
  12074. (match-string 1 old-date)))))
  12075. (pcase arg
  12076. (`(4)
  12077. (when (and old-date log)
  12078. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  12079. nil old-date log))
  12080. (org-remove-timestamp-with-keyword keyword)
  12081. (message (if deadline? "Item no longer has a deadline."
  12082. "Item is no longer scheduled.")))
  12083. (`(16)
  12084. (save-excursion
  12085. (org-back-to-heading t)
  12086. (let ((regexp (if deadline? org-deadline-time-regexp
  12087. org-scheduled-time-regexp)))
  12088. (if (not (re-search-forward regexp (line-end-position 2) t))
  12089. (user-error (if deadline? "No deadline information to update"
  12090. "No scheduled information to update"))
  12091. (let* ((rpl0 (match-string 1))
  12092. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  12093. (msg (if deadline? "Warn starting from" "Delay until")))
  12094. (replace-match
  12095. (concat keyword
  12096. " <" rpl
  12097. (format " -%dd"
  12098. (abs (- (time-to-days
  12099. (save-match-data
  12100. (org-read-date
  12101. nil t nil msg old-date-time)))
  12102. (time-to-days old-date-time))))
  12103. ">") t t))))))
  12104. (_
  12105. (org-add-planning-info type time 'closed)
  12106. (when (and old-date
  12107. log
  12108. (not (equal old-date org-last-inserted-timestamp)))
  12109. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  12110. org-last-inserted-timestamp
  12111. old-date
  12112. log))
  12113. (when repeater
  12114. (save-excursion
  12115. (org-back-to-heading t)
  12116. (when (re-search-forward
  12117. (concat keyword " " org-last-inserted-timestamp)
  12118. (line-end-position 2)
  12119. t)
  12120. (goto-char (1- (match-end 0)))
  12121. (insert " " repeater)
  12122. (setq org-last-inserted-timestamp
  12123. (concat (substring org-last-inserted-timestamp 0 -1)
  12124. " " repeater
  12125. (substring org-last-inserted-timestamp -1))))))
  12126. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  12127. org-last-inserted-timestamp)))))
  12128. (defun org-deadline (arg &optional time)
  12129. "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
  12130. With one universal prefix argument, remove any deadline from the item.
  12131. With two universal prefix arguments, prompt for a warning delay.
  12132. With argument TIME, set the deadline at the corresponding date. TIME
  12133. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12134. (interactive "P")
  12135. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12136. (org-map-entries
  12137. (lambda () (org--deadline-or-schedule arg 'deadline time))
  12138. nil
  12139. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12140. 'region-start-level
  12141. 'region)
  12142. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  12143. (org--deadline-or-schedule arg 'deadline time)))
  12144. (defun org-schedule (arg &optional time)
  12145. "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
  12146. With one universal prefix argument, remove any scheduling date from the item.
  12147. With two universal prefix arguments, prompt for a delay cookie.
  12148. With argument TIME, scheduled at the corresponding date. TIME can
  12149. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  12150. (interactive "P")
  12151. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  12152. (org-map-entries
  12153. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  12154. nil
  12155. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  12156. 'region-start-level
  12157. 'region)
  12158. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  12159. (org--deadline-or-schedule arg 'scheduled time)))
  12160. (defun org-get-scheduled-time (pom &optional inherit)
  12161. "Get the scheduled time as a time tuple, of a format suitable
  12162. for calling org-schedule with, or if there is no scheduling,
  12163. returns nil."
  12164. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  12165. (when time
  12166. (apply 'encode-time (org-parse-time-string time)))))
  12167. (defun org-get-deadline-time (pom &optional inherit)
  12168. "Get the deadline as a time tuple, of a format suitable for
  12169. calling org-deadline with, or if there is no scheduling, returns
  12170. nil."
  12171. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  12172. (when time
  12173. (apply 'encode-time (org-parse-time-string time)))))
  12174. (defun org-remove-timestamp-with-keyword (keyword)
  12175. "Remove all time stamps with KEYWORD in the current entry."
  12176. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  12177. beg)
  12178. (save-excursion
  12179. (org-back-to-heading t)
  12180. (setq beg (point))
  12181. (outline-next-heading)
  12182. (while (re-search-backward re beg t)
  12183. (replace-match "")
  12184. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  12185. (equal (char-before) ?\ ))
  12186. (backward-delete-char 1)
  12187. (when (string-match "^[ \t]*$" (buffer-substring
  12188. (point-at-bol) (point-at-eol)))
  12189. (delete-region (point-at-bol)
  12190. (min (point-max) (1+ (point-at-eol))))))))))
  12191. (defvar org-time-was-given) ; dynamically scoped parameter
  12192. (defvar org-end-time-was-given) ; dynamically scoped parameter
  12193. (defun org-at-planning-p ()
  12194. "Non-nil when point is on a planning info line."
  12195. ;; This is as accurate and faster than `org-element-at-point' since
  12196. ;; planning info location is fixed in the section.
  12197. (org-with-wide-buffer
  12198. (beginning-of-line)
  12199. (and (looking-at-p org-planning-line-re)
  12200. (eq (point)
  12201. (ignore-errors
  12202. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  12203. (org-back-to-heading t)
  12204. (org-with-limited-levels (org-back-to-heading t)))
  12205. (line-beginning-position 2))))))
  12206. (defun org-add-planning-info (what &optional time &rest remove)
  12207. "Insert new timestamp with keyword in the planning line.
  12208. WHAT indicates what kind of time stamp to add. It is a symbol
  12209. among `closed', `deadline', `scheduled' and nil. TIME indicates
  12210. the time to use. If none is given, the user is prompted for
  12211. a date. REMOVE indicates what kind of entries to remove. An old
  12212. WHAT entry will also be removed."
  12213. (let (org-time-was-given org-end-time-was-given default-time default-input)
  12214. (catch 'exit
  12215. (when (and (memq what '(scheduled deadline))
  12216. (or (not time)
  12217. (and (stringp time)
  12218. (string-match "^[-+]+[0-9]" time))))
  12219. ;; Try to get a default date/time from existing timestamp
  12220. (save-excursion
  12221. (org-back-to-heading t)
  12222. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  12223. (when (re-search-forward (if (eq what 'scheduled)
  12224. org-scheduled-time-regexp
  12225. org-deadline-time-regexp)
  12226. end t)
  12227. (setq ts (match-string 1)
  12228. default-time (apply 'encode-time (org-parse-time-string ts))
  12229. default-input (and ts (org-get-compact-tod ts)))))))
  12230. (when what
  12231. (setq time
  12232. (if (stringp time)
  12233. ;; This is a string (relative or absolute), set
  12234. ;; proper date.
  12235. (apply #'encode-time
  12236. (org-read-date-analyze
  12237. time default-time (decode-time default-time)))
  12238. ;; If necessary, get the time from the user
  12239. (or time (org-read-date nil 'to-time nil nil
  12240. default-time default-input)))))
  12241. (org-with-wide-buffer
  12242. (org-back-to-heading t)
  12243. (forward-line)
  12244. (unless (bolp) (insert "\n"))
  12245. (cond ((looking-at-p org-planning-line-re)
  12246. ;; Move to current indentation.
  12247. (skip-chars-forward " \t")
  12248. ;; Check if we have to remove something.
  12249. (dolist (type (if what (cons what remove) remove))
  12250. (save-excursion
  12251. (when (re-search-forward
  12252. (cl-case type
  12253. (closed org-closed-time-regexp)
  12254. (deadline org-deadline-time-regexp)
  12255. (scheduled org-scheduled-time-regexp)
  12256. (otherwise
  12257. (error "Invalid planning type: %s" type)))
  12258. (line-end-position) t)
  12259. ;; Delete until next keyword or end of line.
  12260. (delete-region
  12261. (match-beginning 0)
  12262. (if (re-search-forward org-keyword-time-not-clock-regexp
  12263. (line-end-position)
  12264. t)
  12265. (match-beginning 0)
  12266. (line-end-position))))))
  12267. ;; If there is nothing more to add and no more keyword
  12268. ;; is left, remove the line completely.
  12269. (if (and (looking-at-p "[ \t]*$") (not what))
  12270. (delete-region (line-beginning-position)
  12271. (line-beginning-position 2))
  12272. ;; If we removed last keyword, do not leave trailing
  12273. ;; white space at the end of line.
  12274. (let ((p (point)))
  12275. (save-excursion
  12276. (end-of-line)
  12277. (unless (= (skip-chars-backward " \t" p) 0)
  12278. (delete-region (point) (line-end-position)))))))
  12279. ((not what) (throw 'exit nil)) ; Nothing to do.
  12280. (t (insert-before-markers "\n")
  12281. (backward-char 1)
  12282. (when org-adapt-indentation
  12283. (indent-to-column (1+ (org-outline-level))))))
  12284. (when what
  12285. ;; Insert planning keyword.
  12286. (insert (cl-case what
  12287. (closed org-closed-string)
  12288. (deadline org-deadline-string)
  12289. (scheduled org-scheduled-string)
  12290. (otherwise (error "Invalid planning type: %s" what)))
  12291. " ")
  12292. ;; Insert associated timestamp.
  12293. (let ((ts (org-insert-time-stamp
  12294. time
  12295. (or org-time-was-given
  12296. (and (eq what 'closed) org-log-done-with-time))
  12297. (eq what 'closed)
  12298. nil nil (list org-end-time-was-given))))
  12299. (unless (eolp) (insert " "))
  12300. ts))))))
  12301. (defvar org-log-note-marker (make-marker)
  12302. "Marker pointing at the entry where the note is to be inserted.")
  12303. (defvar org-log-note-purpose nil)
  12304. (defvar org-log-note-state nil)
  12305. (defvar org-log-note-previous-state nil)
  12306. (defvar org-log-note-extra nil)
  12307. (defvar org-log-note-window-configuration nil)
  12308. (defvar org-log-note-return-to (make-marker))
  12309. (defvar org-log-note-effective-time nil
  12310. "Remembered current time so that dynamically scoped
  12311. `org-extend-today-until' affects timestamps in state change log")
  12312. (defvar org-log-post-message nil
  12313. "Message to be displayed after a log note has been stored.
  12314. The auto-repeater uses this.")
  12315. (defun org-add-note ()
  12316. "Add a note to the current entry.
  12317. This is done in the same way as adding a state change note."
  12318. (interactive)
  12319. (org-add-log-setup 'note))
  12320. (defun org-log-beginning (&optional create)
  12321. "Return expected start of log notes in current entry.
  12322. When optional argument CREATE is non-nil, the function creates
  12323. a drawer to store notes, if necessary. Returned position ignores
  12324. narrowing."
  12325. (org-with-wide-buffer
  12326. (let ((drawer (org-log-into-drawer)))
  12327. (cond
  12328. (drawer
  12329. (org-end-of-meta-data)
  12330. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  12331. (end (if (org-at-heading-p) (point)
  12332. (save-excursion (outline-next-heading) (point))))
  12333. (case-fold-search t))
  12334. (catch 'exit
  12335. ;; Try to find existing drawer.
  12336. (while (re-search-forward regexp end t)
  12337. (let ((element (org-element-at-point)))
  12338. (when (eq (org-element-type element) 'drawer)
  12339. (let ((cend (org-element-property :contents-end element)))
  12340. (when (and (not org-log-states-order-reversed) cend)
  12341. (goto-char cend)))
  12342. (throw 'exit nil))))
  12343. ;; No drawer found. Create one, if permitted.
  12344. (when create
  12345. (unless (bolp) (insert "\n"))
  12346. (let ((beg (point)))
  12347. (insert ":" drawer ":\n:END:\n")
  12348. (org-indent-region beg (point)))
  12349. (end-of-line -1)))))
  12350. (t
  12351. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  12352. (skip-chars-forward " \t\n")
  12353. (beginning-of-line)
  12354. (unless org-log-states-order-reversed
  12355. (org-skip-over-state-notes)
  12356. (skip-chars-backward " \t\n")
  12357. (forward-line)))))
  12358. (if (bolp) (point) (line-beginning-position 2))))
  12359. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  12360. "Set up the post command hook to take a note.
  12361. If this is about to TODO state change, the new state is expected in STATE.
  12362. HOW is an indicator what kind of note should be created.
  12363. EXTRA is additional text that will be inserted into the notes buffer."
  12364. (move-marker org-log-note-marker (point))
  12365. (setq org-log-note-purpose purpose
  12366. org-log-note-state state
  12367. org-log-note-previous-state prev-state
  12368. org-log-note-how how
  12369. org-log-note-extra extra
  12370. org-log-note-effective-time (org-current-effective-time))
  12371. (add-hook 'post-command-hook 'org-add-log-note 'append))
  12372. (defun org-skip-over-state-notes ()
  12373. "Skip past the list of State notes in an entry."
  12374. (when (ignore-errors (goto-char (org-in-item-p)))
  12375. (let* ((struct (org-list-struct))
  12376. (prevs (org-list-prevs-alist struct))
  12377. (regexp
  12378. (concat "[ \t]*- +"
  12379. (replace-regexp-in-string
  12380. " +" " +"
  12381. (org-replace-escapes
  12382. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  12383. `(("%d" . ,org-ts-regexp-inactive)
  12384. ("%D" . ,org-ts-regexp)
  12385. ("%s" . "\"\\S-+\"")
  12386. ("%S" . "\"\\S-+\"")
  12387. ("%t" . ,org-ts-regexp-inactive)
  12388. ("%T" . ,org-ts-regexp)
  12389. ("%u" . ".*?")
  12390. ("%U" . ".*?")))))))
  12391. (while (looking-at-p regexp)
  12392. (goto-char (or (org-list-get-next-item (point) struct prevs)
  12393. (org-list-get-item-end (point) struct)))))))
  12394. (defun org-add-log-note (&optional _purpose)
  12395. "Pop up a window for taking a note, and add this note later."
  12396. (remove-hook 'post-command-hook 'org-add-log-note)
  12397. (setq org-log-note-window-configuration (current-window-configuration))
  12398. (delete-other-windows)
  12399. (move-marker org-log-note-return-to (point))
  12400. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  12401. (goto-char org-log-note-marker)
  12402. (org-switch-to-buffer-other-window "*Org Note*")
  12403. (erase-buffer)
  12404. (if (memq org-log-note-how '(time state))
  12405. (org-store-log-note)
  12406. (let ((org-inhibit-startup t)) (org-mode))
  12407. (insert (format "# Insert note for %s.
  12408. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  12409. (cond
  12410. ((eq org-log-note-purpose 'clock-out) "stopped clock")
  12411. ((eq org-log-note-purpose 'done) "closed todo item")
  12412. ((eq org-log-note-purpose 'state)
  12413. (format "state change from \"%s\" to \"%s\""
  12414. (or org-log-note-previous-state "")
  12415. (or org-log-note-state "")))
  12416. ((eq org-log-note-purpose 'reschedule)
  12417. "rescheduling")
  12418. ((eq org-log-note-purpose 'delschedule)
  12419. "no longer scheduled")
  12420. ((eq org-log-note-purpose 'redeadline)
  12421. "changing deadline")
  12422. ((eq org-log-note-purpose 'deldeadline)
  12423. "removing deadline")
  12424. ((eq org-log-note-purpose 'refile)
  12425. "refiling")
  12426. ((eq org-log-note-purpose 'note)
  12427. "this entry")
  12428. (t (error "This should not happen")))))
  12429. (when org-log-note-extra (insert org-log-note-extra))
  12430. (setq-local org-finish-function 'org-store-log-note)
  12431. (run-hooks 'org-log-buffer-setup-hook)))
  12432. (defvar org-note-abort nil) ; dynamically scoped
  12433. (defun org-store-log-note ()
  12434. "Finish taking a log note, and insert it to where it belongs."
  12435. (let ((txt (prog1 (buffer-string)
  12436. (kill-buffer)))
  12437. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  12438. lines)
  12439. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  12440. (setq txt (replace-match "" t t txt)))
  12441. (when (string-match "\\s-+\\'" txt)
  12442. (setq txt (replace-match "" t t txt)))
  12443. (setq lines (org-split-string txt "\n"))
  12444. (when (org-string-nw-p note)
  12445. (setq note
  12446. (org-replace-escapes
  12447. note
  12448. (list (cons "%u" (user-login-name))
  12449. (cons "%U" user-full-name)
  12450. (cons "%t" (format-time-string
  12451. (org-time-stamp-format 'long 'inactive)
  12452. org-log-note-effective-time))
  12453. (cons "%T" (format-time-string
  12454. (org-time-stamp-format 'long nil)
  12455. org-log-note-effective-time))
  12456. (cons "%d" (format-time-string
  12457. (org-time-stamp-format nil 'inactive)
  12458. org-log-note-effective-time))
  12459. (cons "%D" (format-time-string
  12460. (org-time-stamp-format nil nil)
  12461. org-log-note-effective-time))
  12462. (cons "%s" (cond
  12463. ((not org-log-note-state) "")
  12464. ((string-match-p org-ts-regexp
  12465. org-log-note-state)
  12466. (format "\"[%s]\""
  12467. (substring org-log-note-state 1 -1)))
  12468. (t (format "\"%s\"" org-log-note-state))))
  12469. (cons "%S"
  12470. (cond
  12471. ((not org-log-note-previous-state) "")
  12472. ((string-match-p org-ts-regexp
  12473. org-log-note-previous-state)
  12474. (format "\"[%s]\""
  12475. (substring
  12476. org-log-note-previous-state 1 -1)))
  12477. (t (format "\"%s\""
  12478. org-log-note-previous-state)))))))
  12479. (when lines (setq note (concat note " \\\\")))
  12480. (push note lines))
  12481. (when (and lines (not org-note-abort))
  12482. (with-current-buffer (marker-buffer org-log-note-marker)
  12483. (org-with-wide-buffer
  12484. ;; Find location for the new note.
  12485. (goto-char org-log-note-marker)
  12486. (set-marker org-log-note-marker nil)
  12487. ;; Note associated to a clock is to be located right after
  12488. ;; the clock. Do not move point.
  12489. (unless (eq org-log-note-purpose 'clock-out)
  12490. (goto-char (org-log-beginning t)))
  12491. ;; Make sure point is at the beginning of an empty line.
  12492. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  12493. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  12494. ;; In an existing list, add a new item at the top level.
  12495. ;; Otherwise, indent line like a regular one.
  12496. (let ((itemp (org-in-item-p)))
  12497. (if itemp
  12498. (indent-line-to
  12499. (let ((struct (save-excursion
  12500. (goto-char itemp) (org-list-struct))))
  12501. (org-list-get-ind (org-list-get-top-point struct) struct)))
  12502. (org-indent-line)))
  12503. (insert (org-list-bullet-string "-") (pop lines))
  12504. (let ((ind (org-list-item-body-column (line-beginning-position))))
  12505. (dolist (line lines)
  12506. (insert "\n")
  12507. (indent-line-to ind)
  12508. (insert line)))
  12509. (message "Note stored")
  12510. (org-back-to-heading t)
  12511. (org-cycle-hide-drawers 'children))
  12512. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  12513. ;; from within `org-add-log-note' because `buffer-undo-list'
  12514. ;; is then modified outside of `org-with-remote-undo'.
  12515. (when (eq this-command 'org-agenda-todo)
  12516. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  12517. ;; Don't add undo information when called from `org-agenda-todo'.
  12518. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  12519. (set-window-configuration org-log-note-window-configuration)
  12520. (with-current-buffer (marker-buffer org-log-note-return-to)
  12521. (goto-char org-log-note-return-to))
  12522. (move-marker org-log-note-return-to nil)
  12523. (when org-log-post-message (message "%s" org-log-post-message))))
  12524. (defun org-remove-empty-drawer-at (pos)
  12525. "Remove an empty drawer at position POS.
  12526. POS may also be a marker."
  12527. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  12528. (org-with-wide-buffer
  12529. (goto-char pos)
  12530. (let ((drawer (org-element-at-point)))
  12531. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  12532. (not (org-element-property :contents-begin drawer)))
  12533. (delete-region (org-element-property :begin drawer)
  12534. (progn (goto-char (org-element-property :end drawer))
  12535. (skip-chars-backward " \r\t\n")
  12536. (forward-line)
  12537. (point))))))))
  12538. (defvar org-ts-type nil)
  12539. (defun org-sparse-tree (&optional arg type)
  12540. "Create a sparse tree, prompt for the details.
  12541. This command can create sparse trees. You first need to select the type
  12542. of match used to create the tree:
  12543. t Show all TODO entries.
  12544. T Show entries with a specific TODO keyword.
  12545. m Show entries selected by a tags/property match.
  12546. p Enter a property name and its value (both with completion on existing
  12547. names/values) and show entries with that property.
  12548. r Show entries matching a regular expression (`/' can be used as well).
  12549. b Show deadlines and scheduled items before a date.
  12550. a Show deadlines and scheduled items after a date.
  12551. d Show deadlines due within `org-deadline-warning-days'.
  12552. D Show deadlines and scheduled items between a date range."
  12553. (interactive "P")
  12554. (setq type (or type org-sparse-tree-default-date-type))
  12555. (setq org-ts-type type)
  12556. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  12557. \[d]eadlines [b]efore-date [a]fter-date [D]ates range
  12558. \[c]ycle through date types: %s"
  12559. (cl-case type
  12560. (all "all timestamps")
  12561. (scheduled "only scheduled")
  12562. (deadline "only deadline")
  12563. (active "only active timestamps")
  12564. (inactive "only inactive timestamps")
  12565. (closed "with a closed time-stamp")
  12566. (otherwise "scheduled/deadline")))
  12567. (let ((answer (read-char-exclusive)))
  12568. (cl-case answer
  12569. (?c
  12570. (org-sparse-tree
  12571. arg
  12572. (cadr
  12573. (memq type '(nil all scheduled deadline active inactive closed)))))
  12574. (?d (call-interactively 'org-check-deadlines))
  12575. (?b (call-interactively 'org-check-before-date))
  12576. (?a (call-interactively 'org-check-after-date))
  12577. (?D (call-interactively 'org-check-dates-range))
  12578. (?t (call-interactively 'org-show-todo-tree))
  12579. (?T (org-show-todo-tree '(4)))
  12580. (?m (call-interactively 'org-match-sparse-tree))
  12581. ((?p ?P)
  12582. (let* ((kwd (completing-read
  12583. "Property: " (mapcar #'list (org-buffer-property-keys))))
  12584. (value (completing-read
  12585. "Value: " (mapcar #'list (org-property-values kwd)))))
  12586. (unless (string-match "\\`{.*}\\'" value)
  12587. (setq value (concat "\"" value "\"")))
  12588. (org-match-sparse-tree arg (concat kwd "=" value))))
  12589. ((?r ?R ?/) (call-interactively 'org-occur))
  12590. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  12591. (defvar-local org-occur-highlights nil
  12592. "List of overlays used for occur matches.")
  12593. (defvar-local org-occur-parameters nil
  12594. "Parameters of the active org-occur calls.
  12595. This is a list, each call to org-occur pushes as cons cell,
  12596. containing the regular expression and the callback, onto the list.
  12597. The list can contain several entries if `org-occur' has been called
  12598. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  12599. will only contain one set of parameters. When the highlights are
  12600. removed (for example with `C-c C-c', or with the next edit (depending
  12601. on `org-remove-highlights-with-change'), this variable is emptied
  12602. as well.")
  12603. (defun org-occur (regexp &optional keep-previous callback)
  12604. "Make a compact tree which shows all matches of REGEXP.
  12605. The tree will show the lines where the regexp matches, and any other context
  12606. defined in `org-show-context-detail', which see.
  12607. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  12608. done by a previous call to `org-occur' will be kept, to allow stacking of
  12609. calls to this command.
  12610. Optional argument CALLBACK can be a function of no argument. In this case,
  12611. it is called with point at the end of the match, match data being set
  12612. accordingly. Current match is shown only if the return value is non-nil.
  12613. The function must neither move point nor alter narrowing."
  12614. (interactive "sRegexp: \nP")
  12615. (when (equal regexp "")
  12616. (user-error "Regexp cannot be empty"))
  12617. (unless keep-previous
  12618. (org-remove-occur-highlights nil nil t))
  12619. (push (cons regexp callback) org-occur-parameters)
  12620. (let ((cnt 0))
  12621. (save-excursion
  12622. (goto-char (point-min))
  12623. (when (or (not keep-previous) ; do not want to keep
  12624. (not org-occur-highlights)) ; no previous matches
  12625. ;; hide everything
  12626. (org-overview))
  12627. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  12628. (isearch-no-upper-case-p regexp t)
  12629. org-occur-case-fold-search)))
  12630. (while (re-search-forward regexp nil t)
  12631. (when (or (not callback)
  12632. (save-match-data (funcall callback)))
  12633. (setq cnt (1+ cnt))
  12634. (when org-highlight-sparse-tree-matches
  12635. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  12636. (org-show-context 'occur-tree)))))
  12637. (when org-remove-highlights-with-change
  12638. (add-hook 'before-change-functions 'org-remove-occur-highlights
  12639. nil 'local))
  12640. (unless org-sparse-tree-open-archived-trees
  12641. (org-hide-archived-subtrees (point-min) (point-max)))
  12642. (run-hooks 'org-occur-hook)
  12643. (when (called-interactively-p 'interactive)
  12644. (message "%d match(es) for regexp %s" cnt regexp))
  12645. cnt))
  12646. (defun org-occur-next-match (&optional n _reset)
  12647. "Function for `next-error-function' to find sparse tree matches.
  12648. N is the number of matches to move, when negative move backwards.
  12649. This function always goes back to the starting point when no
  12650. match is found."
  12651. (let* ((limit (if (< n 0) (point-min) (point-max)))
  12652. (search-func (if (< n 0)
  12653. 'previous-single-char-property-change
  12654. 'next-single-char-property-change))
  12655. (n (abs n))
  12656. (pos (point))
  12657. p1)
  12658. (catch 'exit
  12659. (while (setq p1 (funcall search-func (point) 'org-type))
  12660. (when (equal p1 limit)
  12661. (goto-char pos)
  12662. (user-error "No more matches"))
  12663. (when (equal (get-char-property p1 'org-type) 'org-occur)
  12664. (setq n (1- n))
  12665. (when (= n 0)
  12666. (goto-char p1)
  12667. (throw 'exit (point))))
  12668. (goto-char p1))
  12669. (goto-char p1)
  12670. (user-error "No more matches"))))
  12671. (defun org-show-context (&optional key)
  12672. "Make sure point and context are visible.
  12673. Optional argument KEY, when non-nil, is a symbol. See
  12674. `org-show-context-detail' for allowed values and how much is to
  12675. be shown."
  12676. (org-show-set-visibility
  12677. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  12678. ((cdr (assq key org-show-context-detail)))
  12679. (t (cdr (assq 'default org-show-context-detail))))))
  12680. (defun org-show-set-visibility (detail)
  12681. "Set visibility around point according to DETAIL.
  12682. DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
  12683. `tree', `canonical' or t. See `org-show-context-detail' for more
  12684. information."
  12685. ;; Show current heading and possibly its entry, following headline
  12686. ;; or all children.
  12687. (if (and (org-at-heading-p) (not (eq detail 'local)))
  12688. (org-flag-heading nil)
  12689. (org-show-entry)
  12690. ;; If point is hidden within a drawer or a block, make sure to
  12691. ;; expose it.
  12692. (dolist (o (overlays-at (point)))
  12693. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  12694. (delete-overlay o)))
  12695. (unless (org-before-first-heading-p)
  12696. (org-with-limited-levels
  12697. (cl-case detail
  12698. ((tree canonical t) (org-show-children))
  12699. ((nil minimal ancestors))
  12700. (t (save-excursion
  12701. (outline-next-heading)
  12702. (org-flag-heading nil)))))))
  12703. ;; Show all siblings.
  12704. (when (eq detail 'lineage) (org-show-siblings))
  12705. ;; Show ancestors, possibly with their children.
  12706. (when (memq detail '(ancestors lineage tree canonical t))
  12707. (save-excursion
  12708. (while (org-up-heading-safe)
  12709. (org-flag-heading nil)
  12710. (when (memq detail '(canonical t)) (org-show-entry))
  12711. (when (memq detail '(tree canonical t)) (org-show-children))))))
  12712. (defvar org-reveal-start-hook nil
  12713. "Hook run before revealing a location.")
  12714. (defun org-reveal (&optional siblings)
  12715. "Show current entry, hierarchy above it, and the following headline.
  12716. This can be used to show a consistent set of context around
  12717. locations exposed with `org-show-context'.
  12718. With optional argument SIBLINGS, on each level of the hierarchy all
  12719. siblings are shown. This repairs the tree structure to what it would
  12720. look like when opened with hierarchical calls to `org-cycle'.
  12721. With a \\[universal-argument] \\[universal-argument] prefix, \
  12722. go to the parent and show the entire tree."
  12723. (interactive "P")
  12724. (run-hooks 'org-reveal-start-hook)
  12725. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  12726. ((equal siblings '(16))
  12727. (save-excursion
  12728. (when (org-up-heading-safe)
  12729. (org-show-subtree)
  12730. (run-hook-with-args 'org-cycle-hook 'subtree))))
  12731. (t (org-show-set-visibility 'lineage))))
  12732. (defun org-highlight-new-match (beg end)
  12733. "Highlight from BEG to END and mark the highlight is an occur headline."
  12734. (let ((ov (make-overlay beg end)))
  12735. (overlay-put ov 'face 'secondary-selection)
  12736. (overlay-put ov 'org-type 'org-occur)
  12737. (push ov org-occur-highlights)))
  12738. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  12739. "Remove the occur highlights from the buffer.
  12740. BEG and END are ignored. If NOREMOVE is nil, remove this function
  12741. from the `before-change-functions' in the current buffer."
  12742. (interactive)
  12743. (unless org-inhibit-highlight-removal
  12744. (mapc #'delete-overlay org-occur-highlights)
  12745. (setq org-occur-highlights nil)
  12746. (setq org-occur-parameters nil)
  12747. (unless noremove
  12748. (remove-hook 'before-change-functions
  12749. 'org-remove-occur-highlights 'local))))
  12750. ;;;; Priorities
  12751. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
  12752. "Regular expression matching the priority indicator.")
  12753. (defvar org-remove-priority-next-time nil)
  12754. (defun org-priority-up ()
  12755. "Increase the priority of the current item."
  12756. (interactive)
  12757. (org-priority 'up))
  12758. (defun org-priority-down ()
  12759. "Decrease the priority of the current item."
  12760. (interactive)
  12761. (org-priority 'down))
  12762. (defun org-priority (&optional action _show)
  12763. "Change the priority of an item.
  12764. ACTION can be `set', `up', `down', or a character."
  12765. (interactive "P")
  12766. (if (equal action '(4))
  12767. (org-show-priority)
  12768. (unless org-enable-priority-commands
  12769. (user-error "Priority commands are disabled"))
  12770. (setq action (or action 'set))
  12771. (let (current new news have remove)
  12772. (save-excursion
  12773. (org-back-to-heading t)
  12774. (when (looking-at org-priority-regexp)
  12775. (setq current (string-to-char (match-string 2))
  12776. have t))
  12777. (cond
  12778. ((eq action 'remove)
  12779. (setq remove t new ?\ ))
  12780. ((or (eq action 'set)
  12781. (integerp action))
  12782. (if (not (eq action 'set))
  12783. (setq new action)
  12784. (message "Priority %c-%c, SPC to remove: "
  12785. org-highest-priority org-lowest-priority)
  12786. (save-match-data
  12787. (setq new (read-char-exclusive))))
  12788. (when (and (= (upcase org-highest-priority) org-highest-priority)
  12789. (= (upcase org-lowest-priority) org-lowest-priority))
  12790. (setq new (upcase new)))
  12791. (cond ((equal new ?\ ) (setq remove t))
  12792. ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
  12793. (user-error "Priority must be between `%c' and `%c'"
  12794. org-highest-priority org-lowest-priority))))
  12795. ((eq action 'up)
  12796. (setq new (if have
  12797. (1- current) ; normal cycling
  12798. ;; last priority was empty
  12799. (if (eq last-command this-command)
  12800. org-lowest-priority ; wrap around empty to lowest
  12801. ;; default
  12802. (if org-priority-start-cycle-with-default
  12803. org-default-priority
  12804. (1- org-default-priority))))))
  12805. ((eq action 'down)
  12806. (setq new (if have
  12807. (1+ current) ; normal cycling
  12808. ;; last priority was empty
  12809. (if (eq last-command this-command)
  12810. org-highest-priority ; wrap around empty to highest
  12811. ;; default
  12812. (if org-priority-start-cycle-with-default
  12813. org-default-priority
  12814. (1+ org-default-priority))))))
  12815. (t (user-error "Invalid action")))
  12816. (when (or (< (upcase new) org-highest-priority)
  12817. (> (upcase new) org-lowest-priority))
  12818. (if (and (memq action '(up down))
  12819. (not have) (not (eq last-command this-command)))
  12820. ;; `new' is from default priority
  12821. (error
  12822. "The default can not be set, see `org-default-priority' why")
  12823. ;; normal cycling: `new' is beyond highest/lowest priority
  12824. ;; and is wrapped around to the empty priority
  12825. (setq remove t)))
  12826. (setq news (format "%c" new))
  12827. (if have
  12828. (if remove
  12829. (replace-match "" t t nil 1)
  12830. (replace-match news t t nil 2))
  12831. (if remove
  12832. (user-error "No priority cookie found in line")
  12833. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  12834. (if (match-end 2)
  12835. (progn
  12836. (goto-char (match-end 2))
  12837. (insert " [#" news "]"))
  12838. (goto-char (match-beginning 3))
  12839. (insert "[#" news "] "))))
  12840. (org-set-tags nil 'align))
  12841. (if remove
  12842. (message "Priority removed")
  12843. (message "Priority of current item set to %s" news)))))
  12844. (defun org-show-priority ()
  12845. "Show the priority of the current item.
  12846. This priority is composed of the main priority given with the [#A] cookies,
  12847. and by additional input from the age of a schedules or deadline entry."
  12848. (interactive)
  12849. (let ((pri (if (eq major-mode 'org-agenda-mode)
  12850. (org-get-at-bol 'priority)
  12851. (save-excursion
  12852. (save-match-data
  12853. (beginning-of-line)
  12854. (and (looking-at org-heading-regexp)
  12855. (org-get-priority (match-string 0))))))))
  12856. (message "Priority is %d" (if pri pri -1000))))
  12857. (defun org-get-priority (s)
  12858. "Find priority cookie and return priority."
  12859. (save-match-data
  12860. (if (functionp org-get-priority-function)
  12861. (funcall org-get-priority-function)
  12862. (if (not (string-match org-priority-regexp s))
  12863. (* 1000 (- org-lowest-priority org-default-priority))
  12864. (* 1000 (- org-lowest-priority
  12865. (string-to-char (match-string 2 s))))))))
  12866. ;;;; Tags
  12867. (defvar org-agenda-archives-mode)
  12868. (defvar org-map-continue-from nil
  12869. "Position from where mapping should continue.
  12870. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  12871. (defvar org-scanner-tags nil
  12872. "The current tag list while the tags scanner is running.")
  12873. (defvar org-trust-scanner-tags nil
  12874. "Should `org-get-tags-at' use the tags for the scanner.
  12875. This is for internal dynamical scoping only.
  12876. When this is non-nil, the function `org-get-tags-at' will return the value
  12877. of `org-scanner-tags' instead of building the list by itself. This
  12878. can lead to large speed-ups when the tags scanner is used in a file with
  12879. many entries, and when the list of tags is retrieved, for example to
  12880. obtain a list of properties. Building the tags list for each entry in such
  12881. a file becomes an N^2 operation - but with this variable set, it scales
  12882. as N.")
  12883. (defvar org--matcher-tags-todo-only nil)
  12884. (defun org-scan-tags (action matcher todo-only &optional start-level)
  12885. "Scan headline tags with inheritance and produce output ACTION.
  12886. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  12887. or `agenda' to produce an entry list for an agenda view. It can also be
  12888. a Lisp form or a function that should be called at each matched headline, in
  12889. this case the return value is a list of all return values from these calls.
  12890. MATCHER is a function accepting three arguments, returning
  12891. a non-nil value whenever a given set of tags qualifies a headline
  12892. for inclusion. See `org-make-tags-matcher' for more information.
  12893. As a special case, it can also be set to t (respectively nil) in
  12894. order to match all (respectively none) headline.
  12895. When TODO-ONLY is non-nil, only lines with a not-done TODO
  12896. keyword are included in the output.
  12897. START-LEVEL can be a string with asterisks, reducing the scope to
  12898. headlines matching this string."
  12899. (require 'org-agenda)
  12900. (let* ((re (concat "^"
  12901. (if start-level
  12902. ;; Get the correct level to match
  12903. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  12904. org-outline-regexp)
  12905. " *\\(\\<\\("
  12906. (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
  12907. "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  12908. (props (list 'face 'default
  12909. 'done-face 'org-agenda-done
  12910. 'undone-face 'default
  12911. 'mouse-face 'highlight
  12912. 'org-not-done-regexp org-not-done-regexp
  12913. 'org-todo-regexp org-todo-regexp
  12914. 'org-complex-heading-regexp org-complex-heading-regexp
  12915. 'help-echo
  12916. (format "mouse-2 or RET jump to org file %s"
  12917. (abbreviate-file-name
  12918. (or (buffer-file-name (buffer-base-buffer))
  12919. (buffer-name (buffer-base-buffer)))))))
  12920. (org-map-continue-from nil)
  12921. lspos tags tags-list
  12922. (tags-alist (list (cons 0 org-file-tags)))
  12923. (llast 0) rtn rtn1 level category i txt
  12924. todo marker entry priority
  12925. ts-date ts-date-type ts-date-pair)
  12926. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  12927. (setq action (list 'lambda nil action)))
  12928. (save-excursion
  12929. (goto-char (point-min))
  12930. (when (eq action 'sparse-tree)
  12931. (org-overview)
  12932. (org-remove-occur-highlights))
  12933. (while (let (case-fold-search)
  12934. (re-search-forward re nil t))
  12935. (setq org-map-continue-from nil)
  12936. (catch :skip
  12937. (setq todo
  12938. ;; TODO: is the 1-2 difference a bug?
  12939. (when (match-end 1) (match-string-no-properties 2))
  12940. tags (when (match-end 4) (match-string-no-properties 4)))
  12941. (goto-char (setq lspos (match-beginning 0)))
  12942. (setq level (org-reduced-level (org-outline-level))
  12943. category (org-get-category))
  12944. (when (eq action 'agenda)
  12945. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  12946. ts-date (car ts-date-pair)
  12947. ts-date-type (cdr ts-date-pair)))
  12948. (setq i llast llast level)
  12949. ;; remove tag lists from same and sublevels
  12950. (while (>= i level)
  12951. (when (setq entry (assoc i tags-alist))
  12952. (setq tags-alist (delete entry tags-alist)))
  12953. (setq i (1- i)))
  12954. ;; add the next tags
  12955. (when tags
  12956. (setq tags (org-split-string tags ":")
  12957. tags-alist
  12958. (cons (cons level tags) tags-alist)))
  12959. ;; compile tags for current headline
  12960. (setq tags-list
  12961. (if org-use-tag-inheritance
  12962. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  12963. tags)
  12964. org-scanner-tags tags-list)
  12965. (when org-use-tag-inheritance
  12966. (setcdr (car tags-alist)
  12967. (mapcar (lambda (x)
  12968. (setq x (copy-sequence x))
  12969. (org-add-prop-inherited x))
  12970. (cdar tags-alist))))
  12971. (when (and tags org-use-tag-inheritance
  12972. (or (not (eq t org-use-tag-inheritance))
  12973. org-tags-exclude-from-inheritance))
  12974. ;; Selective inheritance, remove uninherited ones.
  12975. (setcdr (car tags-alist)
  12976. (org-remove-uninherited-tags (cdar tags-alist))))
  12977. (when (and
  12978. ;; eval matcher only when the todo condition is OK
  12979. (and (or (not todo-only) (member todo org-not-done-keywords))
  12980. (if (functionp matcher)
  12981. (let ((case-fold-search t) (org-trust-scanner-tags t))
  12982. (funcall matcher todo tags-list level))
  12983. matcher))
  12984. ;; Call the skipper, but return t if it does not
  12985. ;; skip, so that the `and' form continues evaluating.
  12986. (progn
  12987. (unless (eq action 'sparse-tree) (org-agenda-skip))
  12988. t)
  12989. ;; Check if timestamps are deselecting this entry
  12990. (or (not todo-only)
  12991. (and (member todo org-not-done-keywords)
  12992. (or (not org-agenda-tags-todo-honor-ignore-options)
  12993. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  12994. ;; select this headline
  12995. (cond
  12996. ((eq action 'sparse-tree)
  12997. (and org-highlight-sparse-tree-matches
  12998. (org-get-heading) (match-end 0)
  12999. (org-highlight-new-match
  13000. (match-beginning 1) (match-end 1)))
  13001. (org-show-context 'tags-tree))
  13002. ((eq action 'agenda)
  13003. (setq txt (org-agenda-format-item
  13004. ""
  13005. (concat
  13006. (if (eq org-tags-match-list-sublevels 'indented)
  13007. (make-string (1- level) ?.) "")
  13008. (org-get-heading))
  13009. (make-string level ?\s)
  13010. category
  13011. tags-list)
  13012. priority (org-get-priority txt))
  13013. (goto-char lspos)
  13014. (setq marker (org-agenda-new-marker))
  13015. (org-add-props txt props
  13016. 'org-marker marker 'org-hd-marker marker 'org-category category
  13017. 'todo-state todo
  13018. 'ts-date ts-date
  13019. 'priority priority
  13020. 'type (concat "tagsmatch" ts-date-type))
  13021. (push txt rtn))
  13022. ((functionp action)
  13023. (setq org-map-continue-from nil)
  13024. (save-excursion
  13025. (setq rtn1 (funcall action))
  13026. (push rtn1 rtn)))
  13027. (t (user-error "Invalid action")))
  13028. ;; if we are to skip sublevels, jump to end of subtree
  13029. (unless org-tags-match-list-sublevels
  13030. (org-end-of-subtree t)
  13031. (backward-char 1))))
  13032. ;; Get the correct position from where to continue
  13033. (if org-map-continue-from
  13034. (goto-char org-map-continue-from)
  13035. (and (= (point) lspos) (end-of-line 1)))))
  13036. (when (and (eq action 'sparse-tree)
  13037. (not org-sparse-tree-open-archived-trees))
  13038. (org-hide-archived-subtrees (point-min) (point-max)))
  13039. (nreverse rtn)))
  13040. (defun org-remove-uninherited-tags (tags)
  13041. "Remove all tags that are not inherited from the list TAGS."
  13042. (cond
  13043. ((eq org-use-tag-inheritance t)
  13044. (if org-tags-exclude-from-inheritance
  13045. (org-delete-all org-tags-exclude-from-inheritance tags)
  13046. tags))
  13047. ((not org-use-tag-inheritance) nil)
  13048. ((stringp org-use-tag-inheritance)
  13049. (delq nil (mapcar
  13050. (lambda (x)
  13051. (if (and (string-match org-use-tag-inheritance x)
  13052. (not (member x org-tags-exclude-from-inheritance)))
  13053. x nil))
  13054. tags)))
  13055. ((listp org-use-tag-inheritance)
  13056. (delq nil (mapcar
  13057. (lambda (x)
  13058. (if (member x org-use-tag-inheritance) x nil))
  13059. tags)))))
  13060. (defun org-match-sparse-tree (&optional todo-only match)
  13061. "Create a sparse tree according to tags string MATCH.
  13062. MATCH is a string with match syntax. It can contain a selection
  13063. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  13064. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  13065. those. See the manual for details.
  13066. If optional argument TODO-ONLY is non-nil, only select lines that
  13067. are also TODO tasks."
  13068. (interactive "P")
  13069. (org-agenda-prepare-buffers (list (current-buffer)))
  13070. (let ((org--matcher-tags-todo-only todo-only))
  13071. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
  13072. org--matcher-tags-todo-only)))
  13073. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  13074. (defvar org-cached-props nil)
  13075. (defun org-cached-entry-get (pom property)
  13076. (if (or (eq t org-use-property-inheritance)
  13077. (and (stringp org-use-property-inheritance)
  13078. (let ((case-fold-search t))
  13079. (string-match-p org-use-property-inheritance property)))
  13080. (and (listp org-use-property-inheritance)
  13081. (member-ignore-case property org-use-property-inheritance)))
  13082. ;; Caching is not possible, check it directly.
  13083. (org-entry-get pom property 'inherit)
  13084. ;; Get all properties, so we can do complicated checks easily.
  13085. (cdr (assoc-string property
  13086. (or org-cached-props
  13087. (setq org-cached-props (org-entry-properties pom)))
  13088. t))))
  13089. (defun org-global-tags-completion-table (&optional files)
  13090. "Return the list of all tags in all agenda buffer/files.
  13091. Optional FILES argument is a list of files which can be used
  13092. instead of the agenda files."
  13093. (save-excursion
  13094. (org-uniquify
  13095. (delq nil
  13096. (apply #'append
  13097. (mapcar
  13098. (lambda (file)
  13099. (set-buffer (find-file-noselect file))
  13100. (mapcar (lambda (x)
  13101. (and (stringp (car-safe x))
  13102. (list (car-safe x))))
  13103. (or org-current-tag-alist (org-get-buffer-tags))))
  13104. (if (car-safe files) files
  13105. (org-agenda-files))))))))
  13106. (defun org-make-tags-matcher (match)
  13107. "Create the TAGS/TODO matcher form for the selection string MATCH.
  13108. Returns a cons of the selection string MATCH and a function
  13109. implementing the matcher.
  13110. The matcher is to be called at an Org entry, with point on the
  13111. headline, and returns non-nil if the entry matches the selection
  13112. string MATCH. It must be called with three arguments: the TODO
  13113. keyword at the entry (or nil if none), the list of all tags at
  13114. the entry including inherited ones and the reduced level of the
  13115. headline. Additionally, the category of the entry, if any, must
  13116. be specified as the text property `org-category' on the headline.
  13117. This function sets the variable `org--matcher-tags-todo-only' to
  13118. a non-nil value if the matcher restricts matching to TODO
  13119. entries, otherwise it is not touched.
  13120. See also `org-scan-tags'."
  13121. (unless match
  13122. ;; Get a new match request, with completion against the global
  13123. ;; tags table and the local tags in current buffer.
  13124. (let ((org-last-tags-completion-table
  13125. (org-uniquify
  13126. (delq nil (append (org-get-buffer-tags)
  13127. (org-global-tags-completion-table))))))
  13128. (setq match
  13129. (completing-read
  13130. "Match: "
  13131. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  13132. (let ((match0 match)
  13133. (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
  13134. (start 0)
  13135. tagsmatch todomatch tagsmatcher todomatcher)
  13136. ;; Expand group tags.
  13137. (setq match (org-tags-expand match))
  13138. ;; Check if there is a TODO part of this match, which would be the
  13139. ;; part after a "/". To make sure that this slash is not part of
  13140. ;; a property value to be matched against, we also check that
  13141. ;; there is no / after that slash. First, find the last slash.
  13142. (let ((s 0))
  13143. (while (string-match "/+" match s)
  13144. (setq start (match-beginning 0))
  13145. (setq s (match-end 0))))
  13146. (if (and (string-match "/+" match start)
  13147. (not (string-match-p "\"" match start)))
  13148. ;; Match contains also a TODO-matching request.
  13149. (progn
  13150. (setq tagsmatch (substring match 0 (match-beginning 0)))
  13151. (setq todomatch (substring match (match-end 0)))
  13152. (when (string-prefix-p "!" todomatch)
  13153. (setq org--matcher-tags-todo-only t)
  13154. (setq todomatch (substring todomatch 1)))
  13155. (when (string-match "\\`\\s-*\\'" todomatch)
  13156. (setq todomatch nil)))
  13157. ;; Only matching tags.
  13158. (setq tagsmatch match)
  13159. (setq todomatch nil))
  13160. ;; Make the tags matcher.
  13161. (when (org-string-nw-p tagsmatch)
  13162. (let ((orlist nil)
  13163. (orterms (org-split-string tagsmatch "|"))
  13164. term)
  13165. (while (setq term (pop orterms))
  13166. (while (and (equal (substring term -1) "\\") orterms)
  13167. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  13168. (while (string-match re term)
  13169. (let* ((rest (substring term (match-end 0)))
  13170. (minus (and (match-end 1)
  13171. (equal (match-string 1 term) "-")))
  13172. (tag (save-match-data
  13173. (replace-regexp-in-string
  13174. "\\\\-" "-" (match-string 2 term))))
  13175. (regexp (eq (string-to-char tag) ?{))
  13176. (levelp (match-end 4))
  13177. (propp (match-end 5))
  13178. (mm
  13179. (cond
  13180. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  13181. (levelp
  13182. `(,(org-op-to-function (match-string 3 term))
  13183. level
  13184. ,(string-to-number (match-string 4 term))))
  13185. (propp
  13186. (let* ((gv (pcase (upcase (match-string 5 term))
  13187. ("CATEGORY"
  13188. '(get-text-property (point) 'org-category))
  13189. ("TODO" 'todo)
  13190. (p `(org-cached-entry-get nil ,p))))
  13191. (pv (match-string 7 term))
  13192. (regexp (eq (string-to-char pv) ?{))
  13193. (strp (eq (string-to-char pv) ?\"))
  13194. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  13195. (po (org-op-to-function (match-string 6 term)
  13196. (if timep 'time strp))))
  13197. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  13198. (when timep (setq pv (org-matcher-time pv)))
  13199. (cond ((and regexp (eq po 'org<>))
  13200. `(not (string-match ,pv (or ,gv ""))))
  13201. (regexp `(string-match ,pv (or ,gv "")))
  13202. (strp `(,po (or ,gv "") ,pv))
  13203. (t
  13204. `(,po
  13205. (string-to-number (or ,gv ""))
  13206. ,(string-to-number pv))))))
  13207. (t `(member ,tag tags-list)))))
  13208. (push (if minus `(not ,mm) mm) tagsmatcher)
  13209. (setq term rest)))
  13210. (push `(and ,@tagsmatcher) orlist)
  13211. (setq tagsmatcher nil))
  13212. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  13213. ;; Make the TODO matcher.
  13214. (when (org-string-nw-p todomatch)
  13215. (let ((orlist nil))
  13216. (dolist (term (org-split-string todomatch "|"))
  13217. (while (string-match re term)
  13218. (let* ((minus (and (match-end 1)
  13219. (equal (match-string 1 term) "-")))
  13220. (kwd (match-string 2 term))
  13221. (regexp (eq (string-to-char kwd) ?{))
  13222. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  13223. `(equal todo ,kwd))))
  13224. (push (if minus `(not ,mm) mm) todomatcher))
  13225. (setq term (substring term (match-end 0))))
  13226. (push (if (> (length todomatcher) 1)
  13227. (cons 'and todomatcher)
  13228. (car todomatcher))
  13229. orlist)
  13230. (setq todomatcher nil))
  13231. (setq todomatcher (cons 'or orlist))))
  13232. ;; Return the string and function of the matcher. If no
  13233. ;; tags-specific or todo-specific matcher exists, match
  13234. ;; everything.
  13235. (let ((matcher (if (and tagsmatcher todomatcher)
  13236. `(and ,tagsmatcher ,todomatcher)
  13237. (or tagsmatcher todomatcher t))))
  13238. (when org--matcher-tags-todo-only
  13239. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  13240. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  13241. (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
  13242. "Expand group tags in MATCH.
  13243. This replaces every group tag in MATCH with a regexp tag search.
  13244. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  13245. will be replaced like this:
  13246. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13247. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13248. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  13249. Replacing by a regexp preserves the structure of the match.
  13250. E.g., this expansion
  13251. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  13252. will match anything tagged with \"Lab\" and \"Home\", or tagged
  13253. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
  13254. A group tag in MATCH can contain regular expressions of its own.
  13255. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  13256. will be replaced like this:
  13257. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  13258. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  13259. assumed to be a single group tag, and the function will return
  13260. the list of tags in this group.
  13261. When DOWNCASE is non-nil, expand downcased TAGS."
  13262. (if org-group-tags
  13263. (let* ((case-fold-search t)
  13264. (stable org-mode-syntax-table)
  13265. (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
  13266. (taggroups (if downcased
  13267. (mapcar (lambda (tg) (mapcar #'downcase tg))
  13268. taggroups)
  13269. taggroups))
  13270. (taggroups-keys (mapcar #'car taggroups))
  13271. (return-match (if downcased (downcase match) match))
  13272. (count 0)
  13273. (work-already-expanded tags-already-expanded)
  13274. regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
  13275. ;; @ and _ are allowed as word-components in tags.
  13276. (modify-syntax-entry ?@ "w" stable)
  13277. (modify-syntax-entry ?_ "w" stable)
  13278. ;; Temporarily replace regexp-expressions in the match-expression.
  13279. (while (string-match "{.+?}" return-match)
  13280. (cl-incf count)
  13281. (push (match-string 0 return-match) regexps-in-match)
  13282. (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
  13283. (while (and taggroups-keys
  13284. (with-syntax-table stable
  13285. (string-match
  13286. (concat "\\(?1:[+-]?\\)\\(?2:\\<"
  13287. (regexp-opt taggroups-keys) "\\>\\)")
  13288. return-match)))
  13289. (let* ((dir (match-string 1 return-match))
  13290. (tag (match-string 2 return-match))
  13291. (tag (if downcased (downcase tag) tag)))
  13292. (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
  13293. (member tag work-already-expanded))
  13294. (setq tags-in-group (assoc tag taggroups))
  13295. (push tag work-already-expanded)
  13296. ;; Recursively expand each tag in the group, if the tag hasn't
  13297. ;; already been expanded. Restore the match-data after all recursive calls.
  13298. (save-match-data
  13299. (let (tags-expanded)
  13300. (dolist (x (cdr tags-in-group))
  13301. (if (and (member x taggroups-keys)
  13302. (not (member x work-already-expanded)))
  13303. (setq tags-expanded
  13304. (delete-dups
  13305. (append
  13306. (org-tags-expand x t downcased
  13307. work-already-expanded)
  13308. tags-expanded)))
  13309. (setq tags-expanded
  13310. (append (list x) tags-expanded)))
  13311. (setq work-already-expanded
  13312. (delete-dups
  13313. (append tags-expanded
  13314. work-already-expanded))))
  13315. (setq tags-in-group
  13316. (delete-dups (cons (car tags-in-group)
  13317. tags-expanded)))))
  13318. ;; Filter tag-regexps from tags.
  13319. (setq regexp-in-group-escaped
  13320. (delq nil (mapcar (lambda (x)
  13321. (if (stringp x)
  13322. (and (equal "{" (substring x 0 1))
  13323. (equal "}" (substring x -1))
  13324. x)
  13325. x))
  13326. tags-in-group))
  13327. regexp-in-group
  13328. (mapcar (lambda (x)
  13329. (substring x 1 -1))
  13330. regexp-in-group-escaped)
  13331. tags-in-group
  13332. (delq nil (mapcar (lambda (x)
  13333. (if (stringp x)
  13334. (and (not (equal "{" (substring x 0 1)))
  13335. (not (equal "}" (substring x -1)))
  13336. x)
  13337. x))
  13338. tags-in-group)))
  13339. ;; If single-as-list, do no more in the while-loop.
  13340. (if (not single-as-list)
  13341. (progn
  13342. (when regexp-in-group
  13343. (setq regexp-in-group
  13344. (concat "\\|"
  13345. (mapconcat 'identity regexp-in-group
  13346. "\\|"))))
  13347. (setq tags-in-group
  13348. (concat dir
  13349. "{\\<"
  13350. (regexp-opt tags-in-group)
  13351. "\\>"
  13352. regexp-in-group
  13353. "}"))
  13354. (when (stringp tags-in-group)
  13355. (org-add-props tags-in-group '(grouptag t)))
  13356. (setq return-match
  13357. (replace-match tags-in-group t t return-match)))
  13358. (setq tags-in-group
  13359. (append regexp-in-group-escaped tags-in-group))))
  13360. (setq taggroups-keys (delete tag taggroups-keys))))
  13361. ;; Add the regular expressions back into the match-expression again.
  13362. (while regexps-in-match
  13363. (setq return-match (replace-regexp-in-string (format "<%d>" count)
  13364. (pop regexps-in-match)
  13365. return-match t t))
  13366. (cl-decf count))
  13367. (if single-as-list
  13368. (if tags-in-group tags-in-group (list return-match))
  13369. return-match))
  13370. (if single-as-list
  13371. (list (if downcased (downcase match) match))
  13372. match)))
  13373. (defun org-op-to-function (op &optional stringp)
  13374. "Turn an operator into the appropriate function."
  13375. (setq op
  13376. (cond
  13377. ((equal op "<" ) '(< string< org-time<))
  13378. ((equal op ">" ) '(> org-string> org-time>))
  13379. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  13380. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  13381. ((member op '("=" "==")) '(= string= org-time=))
  13382. ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
  13383. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  13384. (defun org<> (a b) (not (= a b)))
  13385. (defun org-string<= (a b) (or (string= a b) (string< a b)))
  13386. (defun org-string>= (a b) (not (string< a b)))
  13387. (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
  13388. (defun org-string<> (a b) (not (string= a b)))
  13389. (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
  13390. (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
  13391. (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
  13392. (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
  13393. (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
  13394. (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
  13395. (defun org-2ft (s)
  13396. "Convert S to a floating point time.
  13397. If S is already a number, just return it. If it is a string, parse
  13398. it as a time string and apply `float-time' to it. If S is nil, just return 0."
  13399. (cond
  13400. ((numberp s) s)
  13401. ((stringp s)
  13402. (condition-case nil
  13403. (float-time (apply #'encode-time (org-parse-time-string s nil t)))
  13404. (error 0.)))
  13405. (t 0.)))
  13406. (defun org-time-today ()
  13407. "Time in seconds today at 0:00.
  13408. Returns the float number of seconds since the beginning of the
  13409. epoch to the beginning of today (00:00)."
  13410. (float-time (apply 'encode-time
  13411. (append '(0 0 0) (nthcdr 3 (decode-time))))))
  13412. (defun org-matcher-time (s)
  13413. "Interpret a time comparison value."
  13414. (save-match-data
  13415. (cond
  13416. ((string= s "<now>") (float-time))
  13417. ((string= s "<today>") (org-time-today))
  13418. ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
  13419. ((string= s "<yesterday>") (- (org-time-today) 86400.0))
  13420. ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
  13421. (+ (org-time-today)
  13422. (* (string-to-number (match-string 1 s))
  13423. (cdr (assoc (match-string 2 s)
  13424. '(("d" . 86400.0) ("w" . 604800.0)
  13425. ("m" . 2678400.0) ("y" . 31557600.0)))))))
  13426. (t (org-2ft s)))))
  13427. (defun org-match-any-p (re list)
  13428. "Does re match any element of list?"
  13429. (setq list (mapcar (lambda (x) (string-match re x)) list))
  13430. (delq nil list))
  13431. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  13432. (defvar org-tags-overlay (make-overlay 1 1))
  13433. (delete-overlay org-tags-overlay)
  13434. (defun org-get-local-tags-at (&optional pos)
  13435. "Get a list of tags defined in the current headline."
  13436. (org-get-tags-at pos 'local))
  13437. (defun org-get-local-tags ()
  13438. "Get a list of tags defined in the current headline."
  13439. (org-get-tags-at nil 'local))
  13440. (defun org-get-tags-at (&optional pos local)
  13441. "Get a list of all headline tags applicable at POS.
  13442. POS defaults to point. If tags are inherited, the list contains
  13443. the targets in the same sequence as the headlines appear, i.e.
  13444. the tags of the current headline come last.
  13445. When LOCAL is non-nil, only return tags from the current headline,
  13446. ignore inherited ones."
  13447. (interactive)
  13448. (if (and org-trust-scanner-tags
  13449. (or (not pos) (equal pos (point)))
  13450. (not local))
  13451. org-scanner-tags
  13452. (let (tags ltags lastpos parent)
  13453. (save-excursion
  13454. (save-restriction
  13455. (widen)
  13456. (goto-char (or pos (point)))
  13457. (save-match-data
  13458. (catch 'done
  13459. (condition-case nil
  13460. (progn
  13461. (org-back-to-heading t)
  13462. (while (not (equal lastpos (point)))
  13463. (setq lastpos (point))
  13464. (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
  13465. (setq ltags (org-split-string
  13466. (match-string-no-properties 1) ":"))
  13467. (when parent
  13468. (setq ltags (mapcar 'org-add-prop-inherited ltags)))
  13469. (setq tags (append
  13470. (if parent
  13471. (org-remove-uninherited-tags ltags)
  13472. ltags)
  13473. tags)))
  13474. (or org-use-tag-inheritance (throw 'done t))
  13475. (when local (throw 'done t))
  13476. (or (org-up-heading-safe) (error nil))
  13477. (setq parent t)))
  13478. (error nil)))))
  13479. (if local
  13480. tags
  13481. (reverse (delete-dups
  13482. (reverse (append
  13483. (org-remove-uninherited-tags
  13484. org-file-tags)
  13485. tags)))))))))
  13486. (defun org-add-prop-inherited (s)
  13487. (add-text-properties 0 (length s) '(inherited t) s)
  13488. s)
  13489. (defun org-toggle-tag (tag &optional onoff)
  13490. "Toggle the tag TAG for the current line.
  13491. If ONOFF is `on' or `off', don't toggle but set to this state."
  13492. (let (res current)
  13493. (save-excursion
  13494. (org-back-to-heading t)
  13495. (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
  13496. (point-at-eol) t)
  13497. (progn
  13498. (setq current (match-string 1))
  13499. (replace-match ""))
  13500. (setq current ""))
  13501. (setq current (nreverse (org-split-string current ":")))
  13502. (cond
  13503. ((eq onoff 'on)
  13504. (setq res t)
  13505. (or (member tag current) (push tag current)))
  13506. ((eq onoff 'off)
  13507. (or (not (member tag current)) (setq current (delete tag current))))
  13508. (t (if (member tag current)
  13509. (setq current (delete tag current))
  13510. (setq res t)
  13511. (push tag current))))
  13512. (end-of-line 1)
  13513. (if current
  13514. (progn
  13515. (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
  13516. (org-set-tags nil t))
  13517. (delete-horizontal-space))
  13518. (run-hooks 'org-after-tags-change-hook))
  13519. res))
  13520. (defun org--align-tags-here (to-col)
  13521. "Align tags on the current headline to TO-COL.
  13522. Assume point is on a headline."
  13523. (let ((pos (point)))
  13524. (beginning-of-line)
  13525. (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
  13526. (>= pos (match-beginning 2)))
  13527. ;; No tags or point within tags: do not align.
  13528. (goto-char pos)
  13529. (goto-char (match-beginning 1))
  13530. (let ((shift (max (- (if (>= to-col 0) to-col
  13531. (- (abs to-col) (string-width (match-string 2))))
  13532. (current-column))
  13533. 1)))
  13534. (replace-match (make-string shift ?\s) nil nil nil 1)
  13535. ;; Preserve initial position, if possible. In any case, stop
  13536. ;; before tags.
  13537. (when (< pos (point)) (goto-char pos))))))
  13538. (defun org-set-tags-command (&optional arg just-align)
  13539. "Call the set-tags command for the current entry."
  13540. (interactive "P")
  13541. (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
  13542. (org-set-tags arg just-align)
  13543. (save-excursion
  13544. (unless (and (org-region-active-p)
  13545. org-loop-over-headlines-in-active-region)
  13546. (org-back-to-heading t))
  13547. (org-set-tags arg just-align))))
  13548. (defun org-set-tags-to (data)
  13549. "Set the tags of the current entry to DATA, replacing the current tags.
  13550. DATA may be a tags string like :aa:bb:cc:, or a list of tags.
  13551. If DATA is nil or the empty string, any tags will be removed."
  13552. (interactive "sTags: ")
  13553. (setq data
  13554. (cond
  13555. ((eq data nil) "")
  13556. ((equal data "") "")
  13557. ((stringp data)
  13558. (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
  13559. ":"))
  13560. ((listp data)
  13561. (concat ":" (mapconcat 'identity data ":") ":"))))
  13562. (when data
  13563. (save-excursion
  13564. (org-back-to-heading t)
  13565. (when (let ((case-fold-search nil))
  13566. (looking-at org-complex-heading-regexp))
  13567. (if (match-end 5)
  13568. (progn
  13569. (goto-char (match-beginning 5))
  13570. (insert data)
  13571. (delete-region (point) (point-at-eol))
  13572. (org-set-tags nil 'align))
  13573. (goto-char (point-at-eol))
  13574. (insert " " data)
  13575. (org-set-tags nil 'align)))
  13576. (beginning-of-line 1)
  13577. (when (looking-at ".*?\\([ \t]+\\)$")
  13578. (delete-region (match-beginning 1) (match-end 1))))))
  13579. (defun org-align-all-tags ()
  13580. "Align the tags in all headings."
  13581. (interactive)
  13582. (save-excursion
  13583. (or (ignore-errors (org-back-to-heading t))
  13584. (outline-next-heading))
  13585. (if (org-at-heading-p)
  13586. (org-set-tags t)
  13587. (message "No headings"))))
  13588. (defvar org-indent-indentation-per-level)
  13589. (defun org-set-tags (&optional arg just-align)
  13590. "Set the tags for the current headline.
  13591. With prefix ARG, realign all tags in headings in the current buffer.
  13592. When JUST-ALIGN is non-nil, only align tags."
  13593. (interactive "P")
  13594. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  13595. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  13596. 'region-start-level
  13597. 'region))
  13598. org-loop-over-headlines-in-active-region)
  13599. (org-map-entries
  13600. ;; We don't use ARG and JUST-ALIGN here because these args
  13601. ;; are not useful when looping over headlines.
  13602. #'org-set-tags
  13603. org-loop-over-headlines-in-active-region
  13604. cl
  13605. '(when (org-invisible-p) (org-end-of-subtree nil t))))
  13606. (let ((org-setting-tags t))
  13607. (if arg
  13608. (save-excursion
  13609. (goto-char (point-min))
  13610. (while (re-search-forward org-outline-regexp-bol nil t)
  13611. (org-set-tags nil t)
  13612. (end-of-line))
  13613. (message "All tags realigned to column %d" org-tags-column))
  13614. (let* ((current (org-get-tags-string))
  13615. (tags
  13616. (if just-align current
  13617. ;; Get a new set of tags from the user.
  13618. (save-excursion
  13619. (let* ((seen)
  13620. (table
  13621. (setq
  13622. org-last-tags-completion-table
  13623. ;; Uniquify tags in alists, yet preserve
  13624. ;; structure (i.e., keywords).
  13625. (delq nil
  13626. (mapcar
  13627. (lambda (pair)
  13628. (let ((head (car pair)))
  13629. (cond ((symbolp head) pair)
  13630. ((member head seen) nil)
  13631. (t (push head seen)
  13632. pair))))
  13633. (append
  13634. (or org-current-tag-alist
  13635. (org-get-buffer-tags))
  13636. (and
  13637. org-complete-tags-always-offer-all-agenda-tags
  13638. (org-global-tags-completion-table
  13639. (org-agenda-files))))))))
  13640. (current-tags (org-split-string current ":"))
  13641. (inherited-tags
  13642. (nreverse (nthcdr (length current-tags)
  13643. (nreverse (org-get-tags-at))))))
  13644. (replace-regexp-in-string
  13645. "\\([-+&]+\\|,\\)"
  13646. ":"
  13647. (if (or (eq t org-use-fast-tag-selection)
  13648. (and org-use-fast-tag-selection
  13649. (delq nil (mapcar #'cdr table))))
  13650. (org-fast-tag-selection
  13651. current-tags inherited-tags table
  13652. (and org-fast-tag-selection-include-todo
  13653. org-todo-key-alist))
  13654. (let ((org-add-colon-after-tag-completion
  13655. (< 1 (length table))))
  13656. (org-trim
  13657. (completing-read
  13658. "Tags: "
  13659. #'org-tags-completion-function
  13660. nil nil current 'org-tags-history))))))))))
  13661. (when org-tags-sort-function
  13662. (setq tags
  13663. (mapconcat
  13664. #'identity
  13665. (sort (org-split-string tags "[^[:alnum:]_@#%]+")
  13666. org-tags-sort-function)
  13667. ":")))
  13668. (if (or (string= ":" tags)
  13669. (string= "::" tags))
  13670. (setq tags ""))
  13671. (if (not (org-string-nw-p tags)) (setq tags "")
  13672. (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
  13673. (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
  13674. ;; Insert new tags at the correct column.
  13675. (unless (equal current tags)
  13676. (save-excursion
  13677. (beginning-of-line)
  13678. (let ((case-fold-search nil))
  13679. (looking-at org-complex-heading-regexp))
  13680. ;; Remove current tags, if any.
  13681. (when (match-end 5) (replace-match "" nil nil nil 5))
  13682. ;; Insert new tags, if any. Otherwise, remove trailing
  13683. ;; white spaces.
  13684. (end-of-line)
  13685. (if (not (equal tags ""))
  13686. ;; When text is being inserted on an invisible
  13687. ;; region boundary, it can be inadvertently sucked
  13688. ;; into invisibility.
  13689. (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
  13690. (skip-chars-backward " \t")
  13691. (delete-region (point) (line-end-position)))))
  13692. ;; Align tags, if any. Fix tags column if `org-indent-mode'
  13693. ;; is on.
  13694. (unless (equal tags "")
  13695. (let* ((level (save-excursion
  13696. (beginning-of-line)
  13697. (skip-chars-forward "\\*")))
  13698. (offset (if (bound-and-true-p org-indent-mode)
  13699. (* (1- org-indent-indentation-per-level)
  13700. (1- level))
  13701. 0))
  13702. (tags-column
  13703. (+ org-tags-column
  13704. (if (> org-tags-column 0) (- offset) offset))))
  13705. (org--align-tags-here tags-column))))
  13706. (unless just-align (run-hooks 'org-after-tags-change-hook))))))
  13707. (defun org-change-tag-in-region (beg end tag off)
  13708. "Add or remove TAG for each entry in the region.
  13709. This works in the agenda, and also in an Org buffer."
  13710. (interactive
  13711. (list (region-beginning) (region-end)
  13712. (let ((org-last-tags-completion-table
  13713. (if (derived-mode-p 'org-mode)
  13714. (org-uniquify
  13715. (delq nil (append (org-get-buffer-tags)
  13716. (org-global-tags-completion-table))))
  13717. (org-global-tags-completion-table))))
  13718. (completing-read
  13719. "Tag: " 'org-tags-completion-function nil nil nil
  13720. 'org-tags-history))
  13721. (progn
  13722. (message "[s]et or [r]emove? ")
  13723. (equal (read-char-exclusive) ?r))))
  13724. (when (fboundp 'deactivate-mark) (deactivate-mark))
  13725. (let ((agendap (equal major-mode 'org-agenda-mode))
  13726. l1 l2 m buf pos newhead (cnt 0))
  13727. (goto-char end)
  13728. (setq l2 (1- (org-current-line)))
  13729. (goto-char beg)
  13730. (setq l1 (org-current-line))
  13731. (cl-loop for l from l1 to l2 do
  13732. (org-goto-line l)
  13733. (setq m (get-text-property (point) 'org-hd-marker))
  13734. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  13735. (and agendap m))
  13736. (setq buf (if agendap (marker-buffer m) (current-buffer))
  13737. pos (if agendap m (point)))
  13738. (with-current-buffer buf
  13739. (save-excursion
  13740. (save-restriction
  13741. (goto-char pos)
  13742. (setq cnt (1+ cnt))
  13743. (org-toggle-tag tag (if off 'off 'on))
  13744. (setq newhead (org-get-heading)))))
  13745. (and agendap (org-agenda-change-all-lines newhead m))))
  13746. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  13747. (defun org-tags-completion-function (string _predicate &optional flag)
  13748. (let (s1 s2 rtn (ctable org-last-tags-completion-table)
  13749. (confirm (lambda (x) (stringp (car x)))))
  13750. (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  13751. (setq s1 (match-string 1 string)
  13752. s2 (match-string 2 string))
  13753. (setq s1 "" s2 string))
  13754. (cond
  13755. ((eq flag nil)
  13756. ;; try completion
  13757. (setq rtn (try-completion s2 ctable confirm))
  13758. (when (stringp rtn)
  13759. (setq rtn
  13760. (concat s1 s2 (substring rtn (length s2))
  13761. (if (and org-add-colon-after-tag-completion
  13762. (assoc rtn ctable))
  13763. ":" ""))))
  13764. rtn)
  13765. ((eq flag t)
  13766. ;; all-completions
  13767. (all-completions s2 ctable confirm))
  13768. ((eq flag 'lambda)
  13769. ;; exact match?
  13770. (assoc s2 ctable)))))
  13771. (defun org-fast-tag-insert (kwd tags face &optional end)
  13772. "Insert KDW, and the TAGS, the latter with face FACE.
  13773. Also insert END."
  13774. (insert (format "%-12s" (concat kwd ":"))
  13775. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  13776. (or end "")))
  13777. (defun org-fast-tag-show-exit (flag)
  13778. (save-excursion
  13779. (org-goto-line 3)
  13780. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  13781. (replace-match ""))
  13782. (when flag
  13783. (end-of-line 1)
  13784. (org-move-to-column (- (window-width) 19) t)
  13785. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  13786. (defun org-set-current-tags-overlay (current prefix)
  13787. "Add an overlay to CURRENT tag with PREFIX."
  13788. (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
  13789. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  13790. (org-overlay-display org-tags-overlay (concat prefix s))))
  13791. (defvar org-last-tag-selection-key nil)
  13792. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  13793. "Fast tag selection with single keys.
  13794. CURRENT is the current list of tags in the headline, INHERITED is the
  13795. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  13796. possibly with grouping information. TODO-TABLE is a similar table with
  13797. TODO keywords, should these have keys assigned to them.
  13798. If the keys are nil, a-z are automatically assigned.
  13799. Returns the new tags string, or nil to not change the current settings."
  13800. (let* ((fulltable (append table todo-table))
  13801. (maxlen (apply 'max (mapcar
  13802. (lambda (x)
  13803. (if (stringp (car x)) (string-width (car x)) 0))
  13804. fulltable)))
  13805. (buf (current-buffer))
  13806. (expert (eq org-fast-tag-selection-single-key 'expert))
  13807. (buffer-tags nil)
  13808. (fwidth (+ maxlen 3 1 3))
  13809. (ncol (/ (- (window-width) 4) fwidth))
  13810. (i-face 'org-done)
  13811. (c-face 'org-todo)
  13812. tg cnt e c char c1 c2 ntable tbl rtn
  13813. ov-start ov-end ov-prefix
  13814. (exit-after-next org-fast-tag-selection-single-key)
  13815. (done-keywords org-done-keywords)
  13816. groups ingroup intaggroup)
  13817. (save-excursion
  13818. (beginning-of-line 1)
  13819. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13820. (setq ov-start (match-beginning 1)
  13821. ov-end (match-end 1)
  13822. ov-prefix "")
  13823. (setq ov-start (1- (point-at-eol))
  13824. ov-end (1+ ov-start))
  13825. (skip-chars-forward "^\n\r")
  13826. (setq ov-prefix
  13827. (concat
  13828. (buffer-substring (1- (point)) (point))
  13829. (if (> (current-column) org-tags-column)
  13830. " "
  13831. (make-string (- org-tags-column (current-column)) ?\ ))))))
  13832. (move-overlay org-tags-overlay ov-start ov-end)
  13833. (save-window-excursion
  13834. (if expert
  13835. (set-buffer (get-buffer-create " *Org tags*"))
  13836. (delete-other-windows)
  13837. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  13838. (org-switch-to-buffer-other-window " *Org tags*"))
  13839. (erase-buffer)
  13840. (setq-local org-done-keywords done-keywords)
  13841. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  13842. (org-fast-tag-insert "Current" current c-face "\n\n")
  13843. (org-fast-tag-show-exit exit-after-next)
  13844. (org-set-current-tags-overlay current ov-prefix)
  13845. (setq tbl fulltable char ?a cnt 0)
  13846. (while (setq e (pop tbl))
  13847. (cond
  13848. ((eq (car e) :startgroup)
  13849. (push '() groups) (setq ingroup t)
  13850. (unless (zerop cnt)
  13851. (setq cnt 0)
  13852. (insert "\n"))
  13853. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  13854. ((eq (car e) :endgroup)
  13855. (setq ingroup nil cnt 0)
  13856. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  13857. ((eq (car e) :startgrouptag)
  13858. (setq intaggroup t)
  13859. (unless (zerop cnt)
  13860. (setq cnt 0)
  13861. (insert "\n"))
  13862. (insert "[ "))
  13863. ((eq (car e) :endgrouptag)
  13864. (setq intaggroup nil cnt 0)
  13865. (insert "]\n"))
  13866. ((equal e '(:newline))
  13867. (unless (zerop cnt)
  13868. (setq cnt 0)
  13869. (insert "\n")
  13870. (setq e (car tbl))
  13871. (while (equal (car tbl) '(:newline))
  13872. (insert "\n")
  13873. (setq tbl (cdr tbl)))))
  13874. ((equal e '(:grouptags)) (insert " : "))
  13875. (t
  13876. (setq tg (copy-sequence (car e)) c2 nil)
  13877. (if (cdr e)
  13878. (setq c (cdr e))
  13879. ;; automatically assign a character.
  13880. (setq c1 (string-to-char
  13881. (downcase (substring
  13882. tg (if (= (string-to-char tg) ?@) 1 0)))))
  13883. (if (or (rassoc c1 ntable) (rassoc c1 table))
  13884. (while (or (rassoc char ntable) (rassoc char table))
  13885. (setq char (1+ char)))
  13886. (setq c2 c1))
  13887. (setq c (or c2 char)))
  13888. (when ingroup (push tg (car groups)))
  13889. (setq tg (org-add-props tg nil 'face
  13890. (cond
  13891. ((not (assoc tg table))
  13892. (org-get-todo-face tg))
  13893. ((member tg current) c-face)
  13894. ((member tg inherited) i-face))))
  13895. (when (equal (caar tbl) :grouptags)
  13896. (org-add-props tg nil 'face 'org-tag-group))
  13897. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  13898. (insert "[" c "] " tg (make-string
  13899. (- fwidth 4 (length tg)) ?\ ))
  13900. (push (cons tg c) ntable)
  13901. (when (= (cl-incf cnt) ncol)
  13902. (insert "\n")
  13903. (when (or ingroup intaggroup) (insert " "))
  13904. (setq cnt 0)))))
  13905. (setq ntable (nreverse ntable))
  13906. (insert "\n")
  13907. (goto-char (point-min))
  13908. (unless expert (org-fit-window-to-buffer))
  13909. (setq rtn
  13910. (catch 'exit
  13911. (while t
  13912. (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
  13913. (if (not groups) "no " "")
  13914. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  13915. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  13916. (setq org-last-tag-selection-key c)
  13917. (cond
  13918. ((= c ?\r) (throw 'exit t))
  13919. ((= c ?!)
  13920. (setq groups (not groups))
  13921. (goto-char (point-min))
  13922. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  13923. ((= c ?\C-c)
  13924. (if (not expert)
  13925. (org-fast-tag-show-exit
  13926. (setq exit-after-next (not exit-after-next)))
  13927. (setq expert nil)
  13928. (delete-other-windows)
  13929. (set-window-buffer (split-window-vertically) " *Org tags*")
  13930. (org-switch-to-buffer-other-window " *Org tags*")
  13931. (org-fit-window-to-buffer)))
  13932. ((or (= c ?\C-g)
  13933. (and (= c ?q) (not (rassoc c ntable))))
  13934. (delete-overlay org-tags-overlay)
  13935. (setq quit-flag t))
  13936. ((= c ?\ )
  13937. (setq current nil)
  13938. (when exit-after-next (setq exit-after-next 'now)))
  13939. ((= c ?\t)
  13940. (condition-case nil
  13941. (setq tg (completing-read
  13942. "Tag: "
  13943. (or buffer-tags
  13944. (with-current-buffer buf
  13945. (setq buffer-tags
  13946. (org-get-buffer-tags))))))
  13947. (quit (setq tg "")))
  13948. (when (string-match "\\S-" tg)
  13949. (cl-pushnew (list tg) buffer-tags :test #'equal)
  13950. (if (member tg current)
  13951. (setq current (delete tg current))
  13952. (push tg current)))
  13953. (when exit-after-next (setq exit-after-next 'now)))
  13954. ((setq e (rassoc c todo-table) tg (car e))
  13955. (with-current-buffer buf
  13956. (save-excursion (org-todo tg)))
  13957. (when exit-after-next (setq exit-after-next 'now)))
  13958. ((setq e (rassoc c ntable) tg (car e))
  13959. (if (member tg current)
  13960. (setq current (delete tg current))
  13961. (cl-loop for g in groups do
  13962. (when (member tg g)
  13963. (dolist (x g) (setq current (delete x current)))))
  13964. (push tg current))
  13965. (when exit-after-next (setq exit-after-next 'now))))
  13966. ;; Create a sorted list
  13967. (setq current
  13968. (sort current
  13969. (lambda (a b)
  13970. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  13971. (when (eq exit-after-next 'now) (throw 'exit t))
  13972. (goto-char (point-min))
  13973. (beginning-of-line 2)
  13974. (delete-region (point) (point-at-eol))
  13975. (org-fast-tag-insert "Current" current c-face)
  13976. (org-set-current-tags-overlay current ov-prefix)
  13977. (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
  13978. (setq tg (match-string 1))
  13979. (add-text-properties
  13980. (match-beginning 1) (match-end 1)
  13981. (list 'face
  13982. (cond
  13983. ((member tg current) c-face)
  13984. ((member tg inherited) i-face)
  13985. (t (get-text-property (match-beginning 1) 'face))))))
  13986. (goto-char (point-min)))))
  13987. (delete-overlay org-tags-overlay)
  13988. (if rtn
  13989. (mapconcat 'identity current ":")
  13990. nil))))
  13991. (defun org-get-tags-string ()
  13992. "Get the TAGS string in the current headline."
  13993. (unless (org-at-heading-p t)
  13994. (user-error "Not on a heading"))
  13995. (save-excursion
  13996. (beginning-of-line 1)
  13997. (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
  13998. (match-string-no-properties 1)
  13999. "")))
  14000. (defun org-get-tags ()
  14001. "Get the list of tags specified in the current headline."
  14002. (org-split-string (org-get-tags-string) ":"))
  14003. (defun org-get-buffer-tags ()
  14004. "Get a table of all tags used in the buffer, for completion."
  14005. (org-with-wide-buffer
  14006. (goto-char (point-min))
  14007. (let ((tag-re (concat org-outline-regexp-bol
  14008. "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
  14009. tags)
  14010. (while (re-search-forward tag-re nil t)
  14011. (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
  14012. (push tag tags)))
  14013. (mapcar #'list (append org-file-tags (org-uniquify tags))))))
  14014. ;;;; The mapping API
  14015. (defvar org-agenda-skip-comment-trees)
  14016. (defvar org-agenda-skip-function)
  14017. (defun org-map-entries (func &optional match scope &rest skip)
  14018. "Call FUNC at each headline selected by MATCH in SCOPE.
  14019. FUNC is a function or a lisp form. The function will be called without
  14020. arguments, with the cursor positioned at the beginning of the headline.
  14021. The return values of all calls to the function will be collected and
  14022. returned as a list.
  14023. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  14024. does not need to preserve point. After evaluation, the cursor will be
  14025. moved to the end of the line (presumably of the headline of the
  14026. processed entry) and search continues from there. Under some
  14027. circumstances, this may not produce the wanted results. For example,
  14028. if you have removed (e.g. archived) the current (sub)tree it could
  14029. mean that the next entry will be skipped entirely. In such cases, you
  14030. can specify the position from where search should continue by making
  14031. FUNC set the variable `org-map-continue-from' to the desired buffer
  14032. position.
  14033. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  14034. Only headlines that are matched by this query will be considered during
  14035. the iteration. When MATCH is nil or t, all headlines will be
  14036. visited by the iteration.
  14037. SCOPE determines the scope of this command. It can be any of:
  14038. nil The current buffer, respecting the restriction if any
  14039. tree The subtree started with the entry at point
  14040. region The entries within the active region, if any
  14041. region-start-level
  14042. The entries within the active region, but only those at
  14043. the same level than the first one.
  14044. file The current buffer, without restriction
  14045. file-with-archives
  14046. The current buffer, and any archives associated with it
  14047. agenda All agenda files
  14048. agenda-with-archives
  14049. All agenda files with any archive files associated with them
  14050. \(file1 file2 ...)
  14051. If this is a list, all files in the list will be scanned
  14052. The remaining args are treated as settings for the skipping facilities of
  14053. the scanner. The following items can be given here:
  14054. archive skip trees with the archive tag
  14055. comment skip trees with the COMMENT keyword
  14056. function or Emacs Lisp form:
  14057. will be used as value for `org-agenda-skip-function', so
  14058. whenever the function returns a position, FUNC will not be
  14059. called for that entry and search will continue from the
  14060. position returned
  14061. If your function needs to retrieve the tags including inherited tags
  14062. at the *current* entry, you can use the value of the variable
  14063. `org-scanner-tags' which will be much faster than getting the value
  14064. with `org-get-tags-at'. If your function gets properties with
  14065. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  14066. to t around the call to `org-entry-properties' to get the same speedup.
  14067. Note that if your function moves around to retrieve tags and properties at
  14068. a *different* entry, you cannot use these techniques."
  14069. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  14070. (not (org-region-active-p)))
  14071. (let* ((org-agenda-archives-mode nil) ; just to make sure
  14072. (org-agenda-skip-archived-trees (memq 'archive skip))
  14073. (org-agenda-skip-comment-trees (memq 'comment skip))
  14074. (org-agenda-skip-function
  14075. (car (org-delete-all '(comment archive) skip)))
  14076. (org-tags-match-list-sublevels t)
  14077. (start-level (eq scope 'region-start-level))
  14078. matcher res
  14079. org-todo-keywords-for-agenda
  14080. org-done-keywords-for-agenda
  14081. org-todo-keyword-alist-for-agenda
  14082. org-tag-alist-for-agenda
  14083. org--matcher-tags-todo-only)
  14084. (cond
  14085. ((eq match t) (setq matcher t))
  14086. ((eq match nil) (setq matcher t))
  14087. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  14088. (save-excursion
  14089. (save-restriction
  14090. (cond ((eq scope 'tree)
  14091. (org-back-to-heading t)
  14092. (org-narrow-to-subtree)
  14093. (setq scope nil))
  14094. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  14095. (org-region-active-p))
  14096. ;; If needed, set start-level to a string like "2"
  14097. (when start-level
  14098. (save-excursion
  14099. (goto-char (region-beginning))
  14100. (unless (org-at-heading-p) (outline-next-heading))
  14101. (setq start-level (org-current-level))))
  14102. (narrow-to-region (region-beginning)
  14103. (save-excursion
  14104. (goto-char (region-end))
  14105. (unless (and (bolp) (org-at-heading-p))
  14106. (outline-next-heading))
  14107. (point)))
  14108. (setq scope nil)))
  14109. (if (not scope)
  14110. (progn
  14111. (org-agenda-prepare-buffers
  14112. (and buffer-file-name (list buffer-file-name)))
  14113. (setq res
  14114. (org-scan-tags
  14115. func matcher org--matcher-tags-todo-only start-level)))
  14116. ;; Get the right scope
  14117. (cond
  14118. ((and scope (listp scope) (symbolp (car scope)))
  14119. (setq scope (eval scope)))
  14120. ((eq scope 'agenda)
  14121. (setq scope (org-agenda-files t)))
  14122. ((eq scope 'agenda-with-archives)
  14123. (setq scope (org-agenda-files t))
  14124. (setq scope (org-add-archive-files scope)))
  14125. ((eq scope 'file)
  14126. (setq scope (and buffer-file-name (list buffer-file-name))))
  14127. ((eq scope 'file-with-archives)
  14128. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  14129. (org-agenda-prepare-buffers scope)
  14130. (dolist (file scope)
  14131. (with-current-buffer (org-find-base-buffer-visiting file)
  14132. (org-with-wide-buffer
  14133. (goto-char (point-min))
  14134. (setq res
  14135. (append
  14136. res
  14137. (org-scan-tags
  14138. func matcher org--matcher-tags-todo-only)))))))))
  14139. res)))
  14140. ;;; Properties API
  14141. (defconst org-special-properties
  14142. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  14143. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  14144. "The special properties valid in Org mode.
  14145. These are properties that are not defined in the property drawer,
  14146. but in some other way.")
  14147. (defconst org-default-properties
  14148. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  14149. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  14150. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  14151. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  14152. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  14153. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  14154. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  14155. "Some properties that are used by Org mode for various purposes.
  14156. Being in this list makes sure that they are offered for completion.")
  14157. (defun org--valid-property-p (property)
  14158. "Non nil when string PROPERTY is a valid property name."
  14159. (not
  14160. (or (equal property "")
  14161. (string-match-p "\\s-" property))))
  14162. (defun org--update-property-plist (key val props)
  14163. "Associate KEY to VAL in alist PROPS.
  14164. Modifications are made by side-effect. Return new alist."
  14165. (let* ((appending (string= (substring key -1) "+"))
  14166. (key (if appending (substring key 0 -1) key))
  14167. (old (assoc-string key props t)))
  14168. (if (not old) (cons (cons key val) props)
  14169. (setcdr old (if appending (concat (cdr old) " " val) val))
  14170. props)))
  14171. (defun org-get-property-block (&optional beg force)
  14172. "Return the (beg . end) range of the body of the property drawer.
  14173. BEG is the beginning of the current subtree, or of the part
  14174. before the first headline. If it is not given, it will be found.
  14175. If the drawer does not exist, create it if FORCE is non-nil, or
  14176. return nil."
  14177. (org-with-wide-buffer
  14178. (when beg (goto-char beg))
  14179. (unless (org-before-first-heading-p)
  14180. (let ((beg (cond (beg)
  14181. ((or (not (featurep 'org-inlinetask))
  14182. (org-inlinetask-in-task-p))
  14183. (org-back-to-heading t))
  14184. (t (org-with-limited-levels (org-back-to-heading t))))))
  14185. (forward-line)
  14186. (when (looking-at-p org-planning-line-re) (forward-line))
  14187. (cond ((looking-at org-property-drawer-re)
  14188. (forward-line)
  14189. (cons (point) (progn (goto-char (match-end 0))
  14190. (line-beginning-position))))
  14191. (force
  14192. (goto-char beg)
  14193. (org-insert-property-drawer)
  14194. (let ((pos (save-excursion (search-forward ":END:")
  14195. (line-beginning-position))))
  14196. (cons pos pos))))))))
  14197. (defun org-at-property-p ()
  14198. "Non-nil when point is inside a property drawer.
  14199. See `org-property-re' for match data, if applicable."
  14200. (save-excursion
  14201. (beginning-of-line)
  14202. (and (looking-at org-property-re)
  14203. (let ((property-drawer (save-match-data (org-get-property-block))))
  14204. (and property-drawer
  14205. (>= (point) (car property-drawer))
  14206. (< (point) (cdr property-drawer)))))))
  14207. (defun org-property-action ()
  14208. "Do an action on properties."
  14209. (interactive)
  14210. (unless (org-at-property-p) (user-error "Not at a property"))
  14211. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  14212. (let ((c (read-char-exclusive)))
  14213. (cl-case c
  14214. (?s (call-interactively #'org-set-property))
  14215. (?d (call-interactively #'org-delete-property))
  14216. (?D (call-interactively #'org-delete-property-globally))
  14217. (?c (call-interactively #'org-compute-property-at-point))
  14218. (otherwise (user-error "No such property action %c" c)))))
  14219. (defun org-inc-effort ()
  14220. "Increment the value of the effort property in the current entry."
  14221. (interactive)
  14222. (org-set-effort nil t))
  14223. (defvar org-clock-effort) ; Defined in org-clock.el.
  14224. (defvar org-clock-current-task) ; Defined in org-clock.el.
  14225. (defun org-set-effort (&optional value increment)
  14226. "Set the effort property of the current entry.
  14227. With numerical prefix arg, use the nth allowed value, 0 stands for the
  14228. 10th allowed value.
  14229. When INCREMENT is non-nil, set the property to the next allowed value."
  14230. (interactive "P")
  14231. (when (equal value 0) (setq value 10))
  14232. (let* ((completion-ignore-case t)
  14233. (prop org-effort-property)
  14234. (cur (org-entry-get nil prop))
  14235. (allowed (org-property-get-allowed-values nil prop 'table))
  14236. (existing (mapcar 'list (org-property-values prop)))
  14237. (heading (nth 4 (org-heading-components)))
  14238. rpl
  14239. (val (cond
  14240. ((stringp value) value)
  14241. ((and allowed (integerp value))
  14242. (or (car (nth (1- value) allowed))
  14243. (car (org-last allowed))))
  14244. ((and allowed increment)
  14245. (or (cl-caadr (member (list cur) allowed))
  14246. (user-error "Allowed effort values are not set")))
  14247. (allowed
  14248. (message "Select 1-9,0, [RET%s]: %s"
  14249. (if cur (concat "=" cur) "")
  14250. (mapconcat 'car allowed " "))
  14251. (setq rpl (read-char-exclusive))
  14252. (if (equal rpl ?\r)
  14253. cur
  14254. (setq rpl (- rpl ?0))
  14255. (when (equal rpl 0) (setq rpl 10))
  14256. (if (and (> rpl 0) (<= rpl (length allowed)))
  14257. (car (nth (1- rpl) allowed))
  14258. (org-completing-read "Effort: " allowed nil))))
  14259. (t
  14260. (org-completing-read
  14261. (concat "Effort" (and cur (string-match "\\S-" cur)
  14262. (concat " [" cur "]"))
  14263. ": ")
  14264. existing nil nil "" nil cur)))))
  14265. (unless (equal (org-entry-get nil prop) val)
  14266. (org-entry-put nil prop val))
  14267. (org-refresh-property
  14268. '((effort . identity)
  14269. (effort-minutes . org-duration-string-to-minutes))
  14270. val)
  14271. (when (equal heading (bound-and-true-p org-clock-current-task))
  14272. (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
  14273. (org-clock-update-mode-line))
  14274. (message "%s is now %s" prop val)))
  14275. (defun org-entry-properties (&optional pom which)
  14276. "Get all properties of the current entry.
  14277. When POM is a buffer position, get all properties from the entry
  14278. there instead.
  14279. This includes the TODO keyword, the tags, time strings for
  14280. deadline, scheduled, and clocking, and any additional properties
  14281. defined in the entry.
  14282. If WHICH is nil or `all', get all properties. If WHICH is
  14283. `special' or `standard', only get that subclass. If WHICH is
  14284. a string, only get that property.
  14285. Return value is an alist. Keys are properties, as upcased
  14286. strings."
  14287. (org-with-point-at pom
  14288. (when (and (derived-mode-p 'org-mode)
  14289. (ignore-errors (org-back-to-heading t)))
  14290. (catch 'exit
  14291. (let* ((beg (point))
  14292. (specific (and (stringp which) (upcase which)))
  14293. (which (cond ((not specific) which)
  14294. ((member specific org-special-properties) 'special)
  14295. (t 'standard)))
  14296. props)
  14297. ;; Get the special properties, like TODO and TAGS.
  14298. (when (memq which '(nil all special))
  14299. (when (or (not specific) (string= specific "CLOCKSUM"))
  14300. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  14301. (when clocksum
  14302. (push (cons "CLOCKSUM"
  14303. (org-minutes-to-clocksum-string clocksum))
  14304. props)))
  14305. (when specific (throw 'exit props)))
  14306. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  14307. (let ((clocksumt (get-text-property (point)
  14308. :org-clock-minutes-today)))
  14309. (when clocksumt
  14310. (push (cons "CLOCKSUM_T"
  14311. (org-minutes-to-clocksum-string clocksumt))
  14312. props)))
  14313. (when specific (throw 'exit props)))
  14314. (when (or (not specific) (string= specific "ITEM"))
  14315. (let ((case-fold-search nil))
  14316. (when (looking-at org-complex-heading-regexp)
  14317. (push (cons "ITEM"
  14318. (let ((title (match-string-no-properties 4)))
  14319. (if (org-string-nw-p title)
  14320. (org-remove-tabs title)
  14321. "")))
  14322. props)))
  14323. (when specific (throw 'exit props)))
  14324. (when (or (not specific) (string= specific "TODO"))
  14325. (let ((case-fold-search nil))
  14326. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  14327. (push (cons "TODO" (match-string-no-properties 2)) props)))
  14328. (when specific (throw 'exit props)))
  14329. (when (or (not specific) (string= specific "PRIORITY"))
  14330. (push (cons "PRIORITY"
  14331. (if (looking-at org-priority-regexp)
  14332. (match-string-no-properties 2)
  14333. (char-to-string org-default-priority)))
  14334. props)
  14335. (when specific (throw 'exit props)))
  14336. (when (or (not specific) (string= specific "FILE"))
  14337. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  14338. props)
  14339. (when specific (throw 'exit props)))
  14340. (when (or (not specific) (string= specific "TAGS"))
  14341. (let ((value (org-string-nw-p (org-get-tags-string))))
  14342. (when value (push (cons "TAGS" value) props)))
  14343. (when specific (throw 'exit props)))
  14344. (when (or (not specific) (string= specific "ALLTAGS"))
  14345. (let ((value (org-get-tags-at)))
  14346. (when value
  14347. (push (cons "ALLTAGS"
  14348. (format ":%s:" (mapconcat #'identity value ":")))
  14349. props)))
  14350. (when specific (throw 'exit props)))
  14351. (when (or (not specific) (string= specific "BLOCKED"))
  14352. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  14353. (when specific (throw 'exit props)))
  14354. (when (or (not specific)
  14355. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  14356. (forward-line)
  14357. (when (looking-at-p org-planning-line-re)
  14358. (end-of-line)
  14359. (let ((bol (line-beginning-position))
  14360. ;; Backward compatibility: time keywords used to
  14361. ;; be configurable (before 8.3). Make sure we
  14362. ;; get the correct keyword.
  14363. (key-assoc `(("CLOSED" . ,org-closed-string)
  14364. ("DEADLINE" . ,org-deadline-string)
  14365. ("SCHEDULED" . ,org-scheduled-string))))
  14366. (dolist (pair (if specific (list (assoc specific key-assoc))
  14367. key-assoc))
  14368. (save-excursion
  14369. (when (search-backward (cdr pair) bol t)
  14370. (goto-char (match-end 0))
  14371. (skip-chars-forward " \t")
  14372. (and (looking-at org-ts-regexp-both)
  14373. (push (cons (car pair)
  14374. (match-string-no-properties 0))
  14375. props)))))))
  14376. (when specific (throw 'exit props)))
  14377. (when (or (not specific)
  14378. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  14379. (let ((find-ts
  14380. (lambda (end ts)
  14381. ;; Fix next time-stamp before END. TS is the
  14382. ;; list of time-stamps found so far.
  14383. (let ((ts ts)
  14384. (regexp (cond
  14385. ((string= specific "TIMESTAMP")
  14386. org-ts-regexp)
  14387. ((string= specific "TIMESTAMP_IA")
  14388. org-ts-regexp-inactive)
  14389. ((assoc "TIMESTAMP_IA" ts)
  14390. org-ts-regexp)
  14391. ((assoc "TIMESTAMP" ts)
  14392. org-ts-regexp-inactive)
  14393. (t org-ts-regexp-both))))
  14394. (catch 'next
  14395. (while (re-search-forward regexp end t)
  14396. (backward-char)
  14397. (let ((object (org-element-context)))
  14398. ;; Accept to match timestamps in node
  14399. ;; properties, too.
  14400. (when (memq (org-element-type object)
  14401. '(node-property timestamp))
  14402. (let ((type
  14403. (org-element-property :type object)))
  14404. (cond
  14405. ((and (memq type '(active active-range))
  14406. (not (equal specific "TIMESTAMP_IA")))
  14407. (unless (assoc "TIMESTAMP" ts)
  14408. (push (cons "TIMESTAMP"
  14409. (org-element-property
  14410. :raw-value object))
  14411. ts)
  14412. (when specific (throw 'exit ts))))
  14413. ((and (memq type '(inactive inactive-range))
  14414. (not (string= specific "TIMESTAMP")))
  14415. (unless (assoc "TIMESTAMP_IA" ts)
  14416. (push (cons "TIMESTAMP_IA"
  14417. (org-element-property
  14418. :raw-value object))
  14419. ts)
  14420. (when specific (throw 'exit ts))))))
  14421. ;; Both timestamp types are found,
  14422. ;; move to next part.
  14423. (when (= (length ts) 2) (throw 'next ts)))))
  14424. ts)))))
  14425. (goto-char beg)
  14426. ;; First look for timestamps within headline.
  14427. (let ((ts (funcall find-ts (line-end-position) nil)))
  14428. (if (= (length ts) 2) (setq props (nconc ts props))
  14429. ;; Then find timestamps in the section, skipping
  14430. ;; planning line.
  14431. (let ((end (save-excursion (outline-next-heading))))
  14432. (forward-line)
  14433. (when (looking-at-p org-planning-line-re) (forward-line))
  14434. (setq props (nconc (funcall find-ts end ts) props))))))))
  14435. ;; Get the standard properties, like :PROP:.
  14436. (when (memq which '(nil all standard))
  14437. ;; If we are looking after a specific property, delegate
  14438. ;; to `org-entry-get', which is faster. However, make an
  14439. ;; exception for "CATEGORY", since it can be also set
  14440. ;; through keywords (i.e. #+CATEGORY).
  14441. (if (and specific (not (equal specific "CATEGORY")))
  14442. (let ((value (org-entry-get beg specific nil t)))
  14443. (throw 'exit (and value (list (cons specific value)))))
  14444. (let ((range (org-get-property-block beg)))
  14445. (when range
  14446. (let ((end (cdr range)) seen-base)
  14447. (goto-char (car range))
  14448. ;; Unlike to `org--update-property-plist', we
  14449. ;; handle the case where base values is found
  14450. ;; after its extension. We also forbid standard
  14451. ;; properties to be named as special properties.
  14452. (while (re-search-forward org-property-re end t)
  14453. (let* ((key (upcase (match-string-no-properties 2)))
  14454. (extendp (string-match-p "\\+\\'" key))
  14455. (key-base (if extendp (substring key 0 -1) key))
  14456. (value (match-string-no-properties 3)))
  14457. (cond
  14458. ((member-ignore-case key-base org-special-properties))
  14459. (extendp
  14460. (setq props
  14461. (org--update-property-plist key value props)))
  14462. ((member key seen-base))
  14463. (t (push key seen-base)
  14464. (let ((p (assoc-string key props t)))
  14465. (if p (setcdr p (concat value " " (cdr p)))
  14466. (push (cons key value) props))))))))))))
  14467. (unless (assoc "CATEGORY" props)
  14468. (push (cons "CATEGORY" (org-get-category beg)) props)
  14469. (when (string= specific "CATEGORY") (throw 'exit props)))
  14470. ;; Return value.
  14471. props)))))
  14472. (defun org--property-local-values (property literal-nil)
  14473. "Return value for PROPERTY in current entry.
  14474. Value is a list whose car is the base value for PROPERTY and cdr
  14475. a list of accumulated values. Return nil if neither is found in
  14476. the entry. Also return nil when PROPERTY is set to \"nil\",
  14477. unless LITERAL-NIL is non-nil."
  14478. (let ((range (org-get-property-block)))
  14479. (when range
  14480. (goto-char (car range))
  14481. (let* ((case-fold-search t)
  14482. (end (cdr range))
  14483. (value
  14484. ;; Base value.
  14485. (save-excursion
  14486. (let ((v (and (re-search-forward
  14487. (org-re-property property nil t) end t)
  14488. (match-string-no-properties 3))))
  14489. (list (if literal-nil v (org-not-nil v)))))))
  14490. ;; Find additional values.
  14491. (let* ((property+ (org-re-property (concat property "+") nil t)))
  14492. (while (re-search-forward property+ end t)
  14493. (push (match-string-no-properties 3) value)))
  14494. ;; Return final values.
  14495. (and (not (equal value '(nil))) (nreverse value))))))
  14496. (defun org--property-global-value (property literal-nil)
  14497. "Return value for PROPERTY in current buffer.
  14498. Return value is a string. Return nil if property is not set
  14499. globally. Also return nil when PROPERTY is set to \"nil\",
  14500. unless LITERAL-NIL is non-nil."
  14501. (let ((global
  14502. (cdr (or (assoc-string property org-file-properties t)
  14503. (assoc-string property org-global-properties t)
  14504. (assoc-string property org-global-properties-fixed t)))))
  14505. (if literal-nil global (org-not-nil global))))
  14506. (defun org-entry-get (pom property &optional inherit literal-nil)
  14507. "Get value of PROPERTY for entry or content at point-or-marker POM.
  14508. If INHERIT is non-nil and the entry does not have the property,
  14509. then also check higher levels of the hierarchy. If INHERIT is
  14510. the symbol `selective', use inheritance only if the setting in
  14511. `org-use-property-inheritance' selects PROPERTY for inheritance.
  14512. If the property is present but empty, the return value is the
  14513. empty string. If the property is not present at all, nil is
  14514. returned. In any other case, return the value as a string.
  14515. Search is case-insensitive.
  14516. If LITERAL-NIL is set, return the string value \"nil\" as
  14517. a string, do not interpret it as the list atom nil. This is used
  14518. for inheritance when a \"nil\" value can supersede a non-nil
  14519. value higher up the hierarchy."
  14520. (org-with-point-at pom
  14521. (cond
  14522. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  14523. ;; We need a special property. Use `org-entry-properties' to
  14524. ;; retrieve it, but specify the wanted property.
  14525. (cdr (assoc-string property (org-entry-properties nil property))))
  14526. ((and inherit
  14527. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  14528. (org-entry-get-with-inheritance property literal-nil))
  14529. (t
  14530. (let* ((local (org--property-local-values property literal-nil))
  14531. (value (and local (mapconcat #'identity (delq nil local) " "))))
  14532. (if literal-nil value (org-not-nil value)))))))
  14533. (defun org-property-or-variable-value (var &optional inherit)
  14534. "Check if there is a property fixing the value of VAR.
  14535. If yes, return this value. If not, return the current value of the variable."
  14536. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  14537. (if (and prop (stringp prop) (string-match "\\S-" prop))
  14538. (read prop)
  14539. (symbol-value var))))
  14540. (defun org-entry-delete (pom property)
  14541. "Delete PROPERTY from entry at point-or-marker POM.
  14542. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  14543. non-nil when a property was removed."
  14544. (org-with-point-at pom
  14545. (pcase (org-get-property-block)
  14546. (`(,begin . ,origin)
  14547. (let* ((end (copy-marker origin))
  14548. (re (org-re-property
  14549. (concat (regexp-quote property) "\\+?") t t)))
  14550. (goto-char begin)
  14551. (while (re-search-forward re end t)
  14552. (delete-region (match-beginning 0) (line-beginning-position 2)))
  14553. ;; If drawer is empty, remove it altogether.
  14554. (when (= begin end)
  14555. (delete-region (line-beginning-position 0)
  14556. (line-beginning-position 2)))
  14557. ;; Return non-nil if some property was removed.
  14558. (prog1 (/= end origin) (set-marker end nil))))
  14559. (_ nil))))
  14560. ;; Multi-values properties are properties that contain multiple values
  14561. ;; These values are assumed to be single words, separated by whitespace.
  14562. (defun org-entry-add-to-multivalued-property (pom property value)
  14563. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  14564. (let* ((old (org-entry-get pom property))
  14565. (values (and old (org-split-string old "[ \t]"))))
  14566. (setq value (org-entry-protect-space value))
  14567. (unless (member value values)
  14568. (setq values (append values (list value)))
  14569. (org-entry-put pom property
  14570. (mapconcat 'identity values " ")))))
  14571. (defun org-entry-remove-from-multivalued-property (pom property value)
  14572. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  14573. (let* ((old (org-entry-get pom property))
  14574. (values (and old (org-split-string old "[ \t]"))))
  14575. (setq value (org-entry-protect-space value))
  14576. (when (member value values)
  14577. (setq values (delete value values))
  14578. (org-entry-put pom property
  14579. (mapconcat 'identity values " ")))))
  14580. (defun org-entry-member-in-multivalued-property (pom property value)
  14581. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  14582. (let* ((old (org-entry-get pom property))
  14583. (values (and old (org-split-string old "[ \t]"))))
  14584. (setq value (org-entry-protect-space value))
  14585. (member value values)))
  14586. (defun org-entry-get-multivalued-property (pom property)
  14587. "Return a list of values in a multivalued property."
  14588. (let* ((value (org-entry-get pom property))
  14589. (values (and value (org-split-string value "[ \t]"))))
  14590. (mapcar 'org-entry-restore-space values)))
  14591. (defun org-entry-put-multivalued-property (pom property &rest values)
  14592. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  14593. VALUES should be a list of strings. Spaces will be protected."
  14594. (org-entry-put pom property
  14595. (mapconcat 'org-entry-protect-space values " "))
  14596. (let* ((value (org-entry-get pom property))
  14597. (values (and value (org-split-string value "[ \t]"))))
  14598. (mapcar 'org-entry-restore-space values)))
  14599. (defun org-entry-protect-space (s)
  14600. "Protect spaces and newline in string S."
  14601. (while (string-match " " s)
  14602. (setq s (replace-match "%20" t t s)))
  14603. (while (string-match "\n" s)
  14604. (setq s (replace-match "%0A" t t s)))
  14605. s)
  14606. (defun org-entry-restore-space (s)
  14607. "Restore spaces and newline in string S."
  14608. (while (string-match "%20" s)
  14609. (setq s (replace-match " " t t s)))
  14610. (while (string-match "%0A" s)
  14611. (setq s (replace-match "\n" t t s)))
  14612. s)
  14613. (defvar org-entry-property-inherited-from (make-marker)
  14614. "Marker pointing to the entry from where a property was inherited.
  14615. Each call to `org-entry-get-with-inheritance' will set this marker to the
  14616. location of the entry where the inheritance search matched. If there was
  14617. no match, the marker will point nowhere.
  14618. Note that also `org-entry-get' calls this function, if the INHERIT flag
  14619. is set.")
  14620. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  14621. "Get PROPERTY of entry or content at point, search higher levels if needed.
  14622. The search will stop at the first ancestor which has the property defined.
  14623. If the value found is \"nil\", return nil to show that the property
  14624. should be considered as undefined (this is the meaning of nil here).
  14625. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  14626. (move-marker org-entry-property-inherited-from nil)
  14627. (org-with-wide-buffer
  14628. (let (value)
  14629. (catch 'exit
  14630. (while t
  14631. (let ((v (org--property-local-values property literal-nil)))
  14632. (when v
  14633. (setq value
  14634. (concat (mapconcat #'identity (delq nil v) " ")
  14635. (and value " ")
  14636. value)))
  14637. (cond
  14638. ((car v)
  14639. (org-back-to-heading t)
  14640. (move-marker org-entry-property-inherited-from (point))
  14641. (throw 'exit nil))
  14642. ((org-up-heading-safe))
  14643. (t
  14644. (let ((global (org--property-global-value property literal-nil)))
  14645. (cond ((not global))
  14646. (value (setq value (concat global " " value)))
  14647. (t (setq value global))))
  14648. (throw 'exit nil))))))
  14649. (if literal-nil value (org-not-nil value)))))
  14650. (defvar org-property-changed-functions nil
  14651. "Hook called when the value of a property has changed.
  14652. Each hook function should accept two arguments, the name of the property
  14653. and the new value.")
  14654. (defun org-entry-put (pom property value)
  14655. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  14656. If the value is nil, it is converted to the empty string. If it
  14657. is not a string, an error is raised. Also raise an error on
  14658. invalid property names.
  14659. PROPERTY can be any regular property (see
  14660. `org-special-properties'). It can also be \"TODO\",
  14661. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  14662. For the last two properties, VALUE may have any of the special
  14663. values \"earlier\" and \"later\". The function then increases or
  14664. decreases scheduled or deadline date by one day."
  14665. (cond ((null value) (setq value ""))
  14666. ((not (stringp value)) (error "Properties values should be strings"))
  14667. ((not (org--valid-property-p property))
  14668. (user-error "Invalid property name: \"%s\"" property)))
  14669. (org-with-point-at pom
  14670. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14671. (org-back-to-heading t)
  14672. (org-with-limited-levels (org-back-to-heading t)))
  14673. (let ((beg (point)))
  14674. (cond
  14675. ((equal property "TODO")
  14676. (cond ((not (org-string-nw-p value)) (setq value 'none))
  14677. ((not (member value org-todo-keywords-1))
  14678. (user-error "\"%s\" is not a valid TODO state" value)))
  14679. (org-todo value)
  14680. (org-set-tags nil 'align))
  14681. ((equal property "PRIORITY")
  14682. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  14683. (org-set-tags nil 'align))
  14684. ((equal property "SCHEDULED")
  14685. (forward-line)
  14686. (if (and (looking-at-p org-planning-line-re)
  14687. (re-search-forward
  14688. org-scheduled-time-regexp (line-end-position) t))
  14689. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14690. ((string= value "later") (org-timestamp-change 1 'day))
  14691. ((string= value "") (org-schedule '(4)))
  14692. (t (org-schedule nil value)))
  14693. (if (member value '("earlier" "later" ""))
  14694. (call-interactively #'org-schedule)
  14695. (org-schedule nil value))))
  14696. ((equal property "DEADLINE")
  14697. (forward-line)
  14698. (if (and (looking-at-p org-planning-line-re)
  14699. (re-search-forward
  14700. org-deadline-time-regexp (line-end-position) t))
  14701. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  14702. ((string= value "later") (org-timestamp-change 1 'day))
  14703. ((string= value "") (org-deadline '(4)))
  14704. (t (org-deadline nil value)))
  14705. (if (member value '("earlier" "later" ""))
  14706. (call-interactively #'org-deadline)
  14707. (org-deadline nil value))))
  14708. ((member property org-special-properties)
  14709. (error "The %s property cannot be set with `org-entry-put'" property))
  14710. (t
  14711. (let* ((range (org-get-property-block beg 'force))
  14712. (end (cdr range))
  14713. (case-fold-search t))
  14714. (goto-char (car range))
  14715. (if (re-search-forward (org-re-property property nil t) end t)
  14716. (progn (delete-region (match-beginning 0) (match-end 0))
  14717. (goto-char (match-beginning 0)))
  14718. (goto-char end)
  14719. (insert "\n")
  14720. (backward-char))
  14721. (insert ":" property ":")
  14722. (when value (insert " " value))
  14723. (org-indent-line)))))
  14724. (run-hook-with-args 'org-property-changed-functions property value)))
  14725. (defun org-buffer-property-keys
  14726. (&optional specials defaults columns ignore-malformed)
  14727. "Get all property keys in the current buffer.
  14728. When SPECIALS is non-nil, also list the special properties that
  14729. reflect things like tags and TODO state.
  14730. When DEFAULTS is non-nil, also include properties that has
  14731. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  14732. DESCRIPTION, LOCATION, and LOGGING and others.
  14733. When COLUMNS in non-nil, also include property names given in
  14734. COLUMN formats in the current buffer.
  14735. When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
  14736. automatically performed, such drawers will be silently ignored."
  14737. (let ((case-fold-search t)
  14738. (props (append
  14739. (and specials org-special-properties)
  14740. (and defaults (cons org-effort-property org-default-properties))
  14741. nil)))
  14742. (org-with-wide-buffer
  14743. (goto-char (point-min))
  14744. (while (re-search-forward org-property-start-re nil t)
  14745. (let ((range (org-get-property-block)))
  14746. (catch 'skip
  14747. (unless range
  14748. (when (and (not ignore-malformed)
  14749. (not (org-before-first-heading-p))
  14750. (y-or-n-p (format "Malformed drawer at %d, repair?"
  14751. (line-beginning-position))))
  14752. (org-get-property-block nil t))
  14753. (throw 'skip nil))
  14754. (goto-char (car range))
  14755. (let ((begin (car range))
  14756. (end (cdr range)))
  14757. ;; Make sure that found property block is not located
  14758. ;; before current point, as it would generate an infloop.
  14759. ;; It can happen, for example, in the following
  14760. ;; situation:
  14761. ;;
  14762. ;; * Headline
  14763. ;; :PROPERTIES:
  14764. ;; ...
  14765. ;; :END:
  14766. ;; *************** Inlinetask
  14767. ;; #+BEGIN_EXAMPLE
  14768. ;; :PROPERTIES:
  14769. ;; #+END_EXAMPLE
  14770. ;;
  14771. (if (< begin (point)) (throw 'skip nil) (goto-char begin))
  14772. (while (< (point) end)
  14773. (let ((p (progn (looking-at org-property-re)
  14774. (match-string-no-properties 2))))
  14775. ;; Only add true property name, not extension symbol.
  14776. (push (if (not (string-match-p "\\+\\'" p)) p
  14777. (substring p 0 -1))
  14778. props))
  14779. (forward-line))))
  14780. (outline-next-heading)))
  14781. (when columns
  14782. (goto-char (point-min))
  14783. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  14784. (let ((element (org-element-at-point)))
  14785. (when (memq (org-element-type element) '(keyword node-property))
  14786. (let ((value (org-element-property :value element))
  14787. (start 0))
  14788. (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
  14789. (setq start (match-end 0))
  14790. (let ((p (match-string-no-properties 1 value)))
  14791. (unless (member-ignore-case p org-special-properties)
  14792. (push p props))))))))))
  14793. (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
  14794. (defun org-property-values (key)
  14795. "List all non-nil values of property KEY in current buffer."
  14796. (org-with-wide-buffer
  14797. (goto-char (point-min))
  14798. (let ((case-fold-search t)
  14799. (re (org-re-property key))
  14800. values)
  14801. (while (re-search-forward re nil t)
  14802. (push (org-entry-get (point) key) values))
  14803. (delete-dups values))))
  14804. (defun org-insert-property-drawer ()
  14805. "Insert a property drawer into the current entry."
  14806. (org-with-wide-buffer
  14807. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  14808. (org-back-to-heading t)
  14809. (org-with-limited-levels (org-back-to-heading t)))
  14810. (forward-line)
  14811. (when (looking-at-p org-planning-line-re) (forward-line))
  14812. (unless (looking-at-p org-property-drawer-re)
  14813. ;; Make sure we start editing a line from current entry, not from
  14814. ;; next one. It prevents extending text properties or overlays
  14815. ;; belonging to the latter.
  14816. (when (bolp) (backward-char))
  14817. (let ((begin (1+ (point)))
  14818. (inhibit-read-only t))
  14819. (insert "\n:PROPERTIES:\n:END:")
  14820. (when (eobp) (insert "\n"))
  14821. (org-indent-region begin (point))))))
  14822. (defun org-insert-drawer (&optional arg drawer)
  14823. "Insert a drawer at point.
  14824. When optional argument ARG is non-nil, insert a property drawer.
  14825. Optional argument DRAWER, when non-nil, is a string representing
  14826. drawer's name. Otherwise, the user is prompted for a name.
  14827. If a region is active, insert the drawer around that region
  14828. instead.
  14829. Point is left between drawer's boundaries."
  14830. (interactive "P")
  14831. (let* ((drawer (if arg "PROPERTIES"
  14832. (or drawer (read-from-minibuffer "Drawer: ")))))
  14833. (cond
  14834. ;; With C-u, fall back on `org-insert-property-drawer'
  14835. (arg (org-insert-property-drawer))
  14836. ;; Check validity of suggested drawer's name.
  14837. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  14838. (user-error "Invalid drawer name"))
  14839. ;; With an active region, insert a drawer at point.
  14840. ((not (org-region-active-p))
  14841. (progn
  14842. (unless (bolp) (insert "\n"))
  14843. (insert (format ":%s:\n\n:END:\n" drawer))
  14844. (forward-line -2)))
  14845. ;; Otherwise, insert the drawer at point
  14846. (t
  14847. (let ((rbeg (region-beginning))
  14848. (rend (copy-marker (region-end))))
  14849. (unwind-protect
  14850. (progn
  14851. (goto-char rbeg)
  14852. (beginning-of-line)
  14853. (when (save-excursion
  14854. (re-search-forward org-outline-regexp-bol rend t))
  14855. (user-error "Drawers cannot contain headlines"))
  14856. ;; Position point at the beginning of the first
  14857. ;; non-blank line in region. Insert drawer's opening
  14858. ;; there, then indent it.
  14859. (org-skip-whitespace)
  14860. (beginning-of-line)
  14861. (insert ":" drawer ":\n")
  14862. (forward-line -1)
  14863. (indent-for-tab-command)
  14864. ;; Move point to the beginning of the first blank line
  14865. ;; after the last non-blank line in region. Insert
  14866. ;; drawer's closing, then indent it.
  14867. (goto-char rend)
  14868. (skip-chars-backward " \r\t\n")
  14869. (insert "\n:END:")
  14870. (deactivate-mark t)
  14871. (indent-for-tab-command)
  14872. (unless (eolp) (insert "\n")))
  14873. ;; Clear marker, whatever the outcome of insertion is.
  14874. (set-marker rend nil)))))))
  14875. (defvar org-property-set-functions-alist nil
  14876. "Property set function alist.
  14877. Each entry should have the following format:
  14878. (PROPERTY . READ-FUNCTION)
  14879. The read function will be called with the same argument as
  14880. `org-completing-read'.")
  14881. (defun org-set-property-function (property)
  14882. "Get the function that should be used to set PROPERTY.
  14883. This is computed according to `org-property-set-functions-alist'."
  14884. (or (cdr (assoc property org-property-set-functions-alist))
  14885. 'org-completing-read))
  14886. (defun org-read-property-value (property)
  14887. "Read PROPERTY value from user."
  14888. (let* ((completion-ignore-case t)
  14889. (allowed (org-property-get-allowed-values nil property 'table))
  14890. (cur (org-entry-get nil property))
  14891. (prompt (concat property " value"
  14892. (if (and cur (string-match "\\S-" cur))
  14893. (concat " [" cur "]") "") ": "))
  14894. (set-function (org-set-property-function property))
  14895. (val (if allowed
  14896. (funcall set-function prompt allowed nil
  14897. (not (get-text-property 0 'org-unrestricted
  14898. (caar allowed))))
  14899. (funcall set-function prompt
  14900. (mapcar 'list (org-property-values property))
  14901. nil nil "" nil cur))))
  14902. (org-trim val)))
  14903. (defvar org-last-set-property nil)
  14904. (defvar org-last-set-property-value nil)
  14905. (defun org-read-property-name ()
  14906. "Read a property name."
  14907. (let ((completion-ignore-case t)
  14908. (default-prop (or (and (org-at-property-p)
  14909. (match-string-no-properties 2))
  14910. org-last-set-property)))
  14911. (org-completing-read
  14912. (concat "Property"
  14913. (if default-prop (concat " [" default-prop "]") "")
  14914. ": ")
  14915. (mapcar #'list (org-buffer-property-keys nil t t))
  14916. nil nil nil nil default-prop)))
  14917. (defun org-set-property-and-value (use-last)
  14918. "Allow to set [PROPERTY]: [value] direction from prompt.
  14919. When use-default, don't even ask, just use the last
  14920. \"[PROPERTY]: [value]\" string from the history."
  14921. (interactive "P")
  14922. (let* ((completion-ignore-case t)
  14923. (pv (or (and use-last org-last-set-property-value)
  14924. (org-completing-read
  14925. "Enter a \"[Property]: [value]\" pair: "
  14926. nil nil nil nil nil
  14927. org-last-set-property-value)))
  14928. prop val)
  14929. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  14930. (setq prop (match-string 1 pv)
  14931. val (match-string 2 pv))
  14932. (org-set-property prop val))))
  14933. (defun org-set-property (property value)
  14934. "In the current entry, set PROPERTY to VALUE.
  14935. When called interactively, this will prompt for a property name, offering
  14936. completion on existing and default properties. And then it will prompt
  14937. for a value, offering completion either on allowed values (via an inherited
  14938. xxx_ALL property) or on existing values in other instances of this property
  14939. in the current file.
  14940. Throw an error when trying to set a property with an invalid name."
  14941. (interactive (list nil nil))
  14942. (let ((property (or property (org-read-property-name))))
  14943. ;; `org-entry-put' also makes the following check, but this one
  14944. ;; avoids polluting `org-last-set-property' and
  14945. ;; `org-last-set-property-value' needlessly.
  14946. (unless (org--valid-property-p property)
  14947. (user-error "Invalid property name: \"%s\"" property))
  14948. (let ((value (or value (org-read-property-value property)))
  14949. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  14950. (setq org-last-set-property property)
  14951. (setq org-last-set-property-value (concat property ": " value))
  14952. ;; Possibly postprocess the inserted value:
  14953. (when fn (setq value (funcall fn value)))
  14954. (unless (equal (org-entry-get nil property) value)
  14955. (org-entry-put nil property value)))))
  14956. (defun org-find-property (property &optional value)
  14957. "Find first entry in buffer that sets PROPERTY.
  14958. When optional argument VALUE is non-nil, only consider an entry
  14959. if it contains PROPERTY set to this value. If PROPERTY should be
  14960. explicitly set to nil, use string \"nil\" for VALUE.
  14961. Return position where the entry begins, or nil if there is no
  14962. such entry. If narrowing is in effect, only search the visible
  14963. part of the buffer."
  14964. (save-excursion
  14965. (goto-char (point-min))
  14966. (let ((case-fold-search t)
  14967. (re (org-re-property property nil (not value) value)))
  14968. (catch 'exit
  14969. (while (re-search-forward re nil t)
  14970. (when (if value (org-at-property-p)
  14971. (org-entry-get (point) property nil t))
  14972. (throw 'exit (progn (org-back-to-heading t) (point)))))))))
  14973. (defun org-delete-property (property)
  14974. "In the current entry, delete PROPERTY."
  14975. (interactive
  14976. (let* ((completion-ignore-case t)
  14977. (cat (org-entry-get (point) "CATEGORY"))
  14978. (props0 (org-entry-properties nil 'standard))
  14979. (props (if cat props0
  14980. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  14981. (prop (if (< 1 (length props))
  14982. (completing-read "Property: " props nil t)
  14983. (caar props))))
  14984. (list prop)))
  14985. (if (not property)
  14986. (message "No property to delete in this entry")
  14987. (org-entry-delete nil property)
  14988. (message "Property \"%s\" deleted" property)))
  14989. (defun org-delete-property-globally (property)
  14990. "Remove PROPERTY globally, from all entries.
  14991. This function ignores narrowing, if any."
  14992. (interactive
  14993. (let* ((completion-ignore-case t)
  14994. (prop (completing-read
  14995. "Globally remove property: "
  14996. (mapcar #'list (org-buffer-property-keys)))))
  14997. (list prop)))
  14998. (org-with-wide-buffer
  14999. (goto-char (point-min))
  15000. (let ((count 0)
  15001. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  15002. (while (re-search-forward re nil t)
  15003. (when (org-entry-delete (point) property) (cl-incf count)))
  15004. (message "Property \"%s\" removed from %d entries" property count))))
  15005. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  15006. (defun org-compute-property-at-point ()
  15007. "Compute the property at point.
  15008. This looks for an enclosing column format, extracts the operator and
  15009. then applies it to the property in the column format's scope."
  15010. (interactive)
  15011. (unless (org-at-property-p)
  15012. (user-error "Not at a property"))
  15013. (let ((prop (match-string-no-properties 2)))
  15014. (org-columns-get-format-and-top-level)
  15015. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  15016. (user-error "No operator defined for property %s" prop))
  15017. (org-columns-compute prop)))
  15018. (defvar org-property-allowed-value-functions nil
  15019. "Hook for functions supplying allowed values for a specific property.
  15020. The functions must take a single argument, the name of the property, and
  15021. return a flat list of allowed values. If \":ETC\" is one of
  15022. the values, this means that these values are intended as defaults for
  15023. completion, but that other values should be allowed too.
  15024. The functions must return nil if they are not responsible for this
  15025. property.")
  15026. (defun org-property-get-allowed-values (pom property &optional table)
  15027. "Get allowed values for the property PROPERTY.
  15028. When TABLE is non-nil, return an alist that can directly be used for
  15029. completion."
  15030. (let (vals)
  15031. (cond
  15032. ((equal property "TODO")
  15033. (setq vals (org-with-point-at pom
  15034. (append org-todo-keywords-1 '("")))))
  15035. ((equal property "PRIORITY")
  15036. (let ((n org-lowest-priority))
  15037. (while (>= n org-highest-priority)
  15038. (push (char-to-string n) vals)
  15039. (setq n (1- n)))))
  15040. ((equal property "CATEGORY"))
  15041. ((member property org-special-properties))
  15042. ((setq vals (run-hook-with-args-until-success
  15043. 'org-property-allowed-value-functions property)))
  15044. (t
  15045. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  15046. (when (and vals (string-match "\\S-" vals))
  15047. (setq vals (car (read-from-string (concat "(" vals ")"))))
  15048. (setq vals (mapcar (lambda (x)
  15049. (cond ((stringp x) x)
  15050. ((numberp x) (number-to-string x))
  15051. ((symbolp x) (symbol-name x))
  15052. (t "???")))
  15053. vals)))))
  15054. (when (member ":ETC" vals)
  15055. (setq vals (remove ":ETC" vals))
  15056. (org-add-props (car vals) '(org-unrestricted t)))
  15057. (if table (mapcar 'list vals) vals)))
  15058. (defun org-property-previous-allowed-value (&optional _previous)
  15059. "Switch to the next allowed value for this property."
  15060. (interactive)
  15061. (org-property-next-allowed-value t))
  15062. (defun org-property-next-allowed-value (&optional previous)
  15063. "Switch to the next allowed value for this property."
  15064. (interactive)
  15065. (unless (org-at-property-p)
  15066. (user-error "Not at a property"))
  15067. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  15068. (key (match-string 2))
  15069. (value (match-string 3))
  15070. (allowed (or (org-property-get-allowed-values (point) key)
  15071. (and (member value '("[ ]" "[-]" "[X]"))
  15072. '("[ ]" "[X]"))))
  15073. (heading (save-match-data (nth 4 (org-heading-components))))
  15074. nval)
  15075. (unless allowed
  15076. (user-error "Allowed values for this property have not been defined"))
  15077. (when previous (setq allowed (reverse allowed)))
  15078. (when (member value allowed)
  15079. (setq nval (car (cdr (member value allowed)))))
  15080. (setq nval (or nval (car allowed)))
  15081. (when (equal nval value)
  15082. (user-error "Only one allowed value for this property"))
  15083. (org-at-property-p)
  15084. (replace-match (concat " :" key ": " nval) t t)
  15085. (org-indent-line)
  15086. (beginning-of-line 1)
  15087. (skip-chars-forward " \t")
  15088. (when (equal prop org-effort-property)
  15089. (org-refresh-property
  15090. '((effort . identity)
  15091. (effort-minutes . org-duration-string-to-minutes))
  15092. nval)
  15093. (when (string= org-clock-current-task heading)
  15094. (setq org-clock-effort nval)
  15095. (org-clock-update-mode-line)))
  15096. (run-hook-with-args 'org-property-changed-functions key nval)))
  15097. (defun org-find-olp (path &optional this-buffer)
  15098. "Return a marker pointing to the entry at outline path OLP.
  15099. If anything goes wrong, throw an error.
  15100. You can wrap this call to catch the error like this:
  15101. (condition-case msg
  15102. (org-mobile-locate-entry (match-string 4))
  15103. (error (nth 1 msg)))
  15104. The return value will then be either a string with the error message,
  15105. or a marker if everything is OK.
  15106. If THIS-BUFFER is set, the outline path does not contain a file,
  15107. only headings."
  15108. (let* ((file (if this-buffer buffer-file-name (pop path)))
  15109. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  15110. (level 1)
  15111. (lmin 1)
  15112. (lmax 1)
  15113. end found flevel)
  15114. (unless buffer (error "File not found :%s" file))
  15115. (with-current-buffer buffer
  15116. (org-with-wide-buffer
  15117. (goto-char (point-min))
  15118. (dolist (heading path)
  15119. (let ((re (format org-complex-heading-regexp-format
  15120. (regexp-quote heading)))
  15121. (cnt 0))
  15122. (while (re-search-forward re end t)
  15123. (setq level (- (match-end 1) (match-beginning 1)))
  15124. (when (and (>= level lmin) (<= level lmax))
  15125. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  15126. (when (= cnt 0)
  15127. (error "Heading not found on level %d: %s" lmax heading))
  15128. (when (> cnt 1)
  15129. (error "Heading not unique on level %d: %s" lmax heading))
  15130. (goto-char found)
  15131. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  15132. (setq end (save-excursion (org-end-of-subtree t t)))))
  15133. (when (org-at-heading-p)
  15134. (point-marker))))))
  15135. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  15136. "Find node HEADING in BUFFER.
  15137. Return a marker to the heading if it was found, or nil if not.
  15138. If POS-ONLY is set, return just the position instead of a marker.
  15139. The heading text must match exact, but it may have a TODO keyword,
  15140. a priority cookie and tags in the standard locations."
  15141. (with-current-buffer (or buffer (current-buffer))
  15142. (org-with-wide-buffer
  15143. (goto-char (point-min))
  15144. (let (case-fold-search)
  15145. (when (re-search-forward
  15146. (format org-complex-heading-regexp-format
  15147. (regexp-quote heading)) nil t)
  15148. (if pos-only
  15149. (match-beginning 0)
  15150. (move-marker (make-marker) (match-beginning 0))))))))
  15151. (defun org-find-exact-heading-in-directory (heading &optional dir)
  15152. "Find Org node headline HEADING in all .org files in directory DIR.
  15153. When the target headline is found, return a marker to this location."
  15154. (let ((files (directory-files (or dir default-directory)
  15155. t "\\`[^.#].*\\.org\\'"))
  15156. visiting m buffer)
  15157. (catch 'found
  15158. (dolist (file files)
  15159. (message "trying %s" file)
  15160. (setq visiting (org-find-base-buffer-visiting file))
  15161. (setq buffer (or visiting (find-file-noselect file)))
  15162. (setq m (org-find-exact-headline-in-buffer
  15163. heading buffer))
  15164. (when (and (not m) (not visiting)) (kill-buffer buffer))
  15165. (and m (throw 'found m))))))
  15166. (defun org-find-entry-with-id (ident)
  15167. "Locate the entry that contains the ID property with exact value IDENT.
  15168. IDENT can be a string, a symbol or a number, this function will search for
  15169. the string representation of it.
  15170. Return the position where this entry starts, or nil if there is no such entry."
  15171. (interactive "sID: ")
  15172. (let ((id (cond
  15173. ((stringp ident) ident)
  15174. ((symbolp ident) (symbol-name ident))
  15175. ((numberp ident) (number-to-string ident))
  15176. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  15177. (org-with-wide-buffer (org-find-property "ID" id))))
  15178. ;;;; Timestamps
  15179. (defvar org-last-changed-timestamp nil)
  15180. (defvar org-last-inserted-timestamp nil
  15181. "The last time stamp inserted with `org-insert-time-stamp'.")
  15182. (defvar org-ts-what) ; dynamically scoped parameter
  15183. (defun org-time-stamp (arg &optional inactive)
  15184. "Prompt for a date/time and insert a time stamp.
  15185. If the user specifies a time like HH:MM or if this command is
  15186. called with at least one prefix argument, the time stamp contains
  15187. the date and the time. Otherwise, only the date is included.
  15188. All parts of a date not specified by the user are filled in from
  15189. the timestamp at point, if any, or the current date/time
  15190. otherwise.
  15191. If there is already a timestamp at the cursor, it is replaced.
  15192. With two universal prefix arguments, insert an active timestamp
  15193. with the current time without prompting the user.
  15194. When called from lisp, the timestamp is inactive if INACTIVE is
  15195. non-nil."
  15196. (interactive "P")
  15197. (let* ((ts (cond
  15198. ((org-at-date-range-p t)
  15199. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  15200. ((org-at-timestamp-p t) (match-string 0))))
  15201. ;; Default time is either the timestamp at point or today.
  15202. ;; When entering a range, only the range start is considered.
  15203. (default-time (if (not ts) (current-time)
  15204. (apply #'encode-time (org-parse-time-string ts))))
  15205. (default-input (and ts (org-get-compact-tod ts)))
  15206. (repeater (and ts
  15207. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  15208. (match-string 0 ts)))
  15209. org-time-was-given
  15210. org-end-time-was-given
  15211. (time
  15212. (and (if (equal arg '(16)) (current-time)
  15213. ;; Preserve `this-command' and `last-command'.
  15214. (let ((this-command this-command)
  15215. (last-command last-command))
  15216. (org-read-date
  15217. arg 'totime nil nil default-time default-input
  15218. inactive))))))
  15219. (cond
  15220. ((and ts
  15221. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  15222. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  15223. (insert "--")
  15224. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  15225. (ts
  15226. ;; Make sure we're on a timestamp. When in the middle of a date
  15227. ;; range, move arbitrarily to range end.
  15228. (unless (org-at-timestamp-p t)
  15229. (skip-chars-forward "-")
  15230. (org-at-timestamp-p t))
  15231. (replace-match "")
  15232. (setq org-last-changed-timestamp
  15233. (org-insert-time-stamp
  15234. time (or org-time-was-given arg)
  15235. inactive nil nil (list org-end-time-was-given)))
  15236. (when repeater
  15237. (backward-char)
  15238. (insert " " repeater)
  15239. (setq org-last-changed-timestamp
  15240. (concat (substring org-last-inserted-timestamp 0 -1)
  15241. " " repeater ">")))
  15242. (message "Timestamp updated"))
  15243. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  15244. (t (org-insert-time-stamp
  15245. time (or org-time-was-given arg) inactive nil nil
  15246. (list org-end-time-was-given))))))
  15247. ;; FIXME: can we use this for something else, like computing time differences?
  15248. (defun org-get-compact-tod (s)
  15249. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  15250. (let* ((t1 (match-string 1 s))
  15251. (h1 (string-to-number (match-string 2 s)))
  15252. (m1 (string-to-number (match-string 3 s)))
  15253. (t2 (and (match-end 4) (match-string 5 s)))
  15254. (h2 (and t2 (string-to-number (match-string 6 s))))
  15255. (m2 (and t2 (string-to-number (match-string 7 s))))
  15256. dh dm)
  15257. (if (not t2)
  15258. t1
  15259. (setq dh (- h2 h1) dm (- m2 m1))
  15260. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  15261. (concat t1 "+" (number-to-string dh)
  15262. (and (/= 0 dm) (format ":%02d" dm)))))))
  15263. (defun org-time-stamp-inactive (&optional arg)
  15264. "Insert an inactive time stamp.
  15265. An inactive time stamp is enclosed in square brackets instead of angle
  15266. brackets. It is inactive in the sense that it does not trigger agenda entries,
  15267. does not link to the calendar and cannot be changed with the S-cursor keys.
  15268. So these are more for recording a certain time/date."
  15269. (interactive "P")
  15270. (org-time-stamp arg 'inactive))
  15271. (defvar org-date-ovl (make-overlay 1 1))
  15272. (overlay-put org-date-ovl 'face 'org-date-selected)
  15273. (delete-overlay org-date-ovl)
  15274. (defvar org-ans1) ; dynamically scoped parameter
  15275. (defvar org-ans2) ; dynamically scoped parameter
  15276. (defvar org-plain-time-of-day-regexp) ; defined below
  15277. (defvar org-overriding-default-time nil) ; dynamically scoped
  15278. (defvar org-read-date-overlay nil)
  15279. (defvar org-dcst nil) ; dynamically scoped
  15280. (defvar org-read-date-history nil)
  15281. (defvar org-read-date-final-answer nil)
  15282. (defvar org-read-date-analyze-futurep nil)
  15283. (defvar org-read-date-analyze-forced-year nil)
  15284. (defvar org-read-date-inactive)
  15285. (defvar org-read-date-minibuffer-local-map
  15286. (let* ((map (make-sparse-keymap)))
  15287. (set-keymap-parent map minibuffer-local-map)
  15288. (org-defkey map (kbd ".")
  15289. (lambda () (interactive)
  15290. ;; Are we at the beginning of the prompt?
  15291. (if (looking-back "^[^:]+: "
  15292. (let ((inhibit-field-text-motion t))
  15293. (line-beginning-position)))
  15294. (org-eval-in-calendar '(calendar-goto-today))
  15295. (insert "."))))
  15296. (org-defkey map (kbd "C-.")
  15297. (lambda () (interactive)
  15298. (org-eval-in-calendar '(calendar-goto-today))))
  15299. (org-defkey map [(meta shift left)]
  15300. (lambda () (interactive)
  15301. (org-eval-in-calendar '(calendar-backward-month 1))))
  15302. (org-defkey map [(meta shift right)]
  15303. (lambda () (interactive)
  15304. (org-eval-in-calendar '(calendar-forward-month 1))))
  15305. (org-defkey map [(meta shift up)]
  15306. (lambda () (interactive)
  15307. (org-eval-in-calendar '(calendar-backward-year 1))))
  15308. (org-defkey map [(meta shift down)]
  15309. (lambda () (interactive)
  15310. (org-eval-in-calendar '(calendar-forward-year 1))))
  15311. (org-defkey map [?\e (shift left)]
  15312. (lambda () (interactive)
  15313. (org-eval-in-calendar '(calendar-backward-month 1))))
  15314. (org-defkey map [?\e (shift right)]
  15315. (lambda () (interactive)
  15316. (org-eval-in-calendar '(calendar-forward-month 1))))
  15317. (org-defkey map [?\e (shift up)]
  15318. (lambda () (interactive)
  15319. (org-eval-in-calendar '(calendar-backward-year 1))))
  15320. (org-defkey map [?\e (shift down)]
  15321. (lambda () (interactive)
  15322. (org-eval-in-calendar '(calendar-forward-year 1))))
  15323. (org-defkey map [(shift up)]
  15324. (lambda () (interactive)
  15325. (org-eval-in-calendar '(calendar-backward-week 1))))
  15326. (org-defkey map [(shift down)]
  15327. (lambda () (interactive)
  15328. (org-eval-in-calendar '(calendar-forward-week 1))))
  15329. (org-defkey map [(shift left)]
  15330. (lambda () (interactive)
  15331. (org-eval-in-calendar '(calendar-backward-day 1))))
  15332. (org-defkey map [(shift right)]
  15333. (lambda () (interactive)
  15334. (org-eval-in-calendar '(calendar-forward-day 1))))
  15335. (org-defkey map "!"
  15336. (lambda () (interactive)
  15337. (org-eval-in-calendar '(diary-view-entries))
  15338. (message "")))
  15339. (org-defkey map ">"
  15340. (lambda () (interactive)
  15341. (org-eval-in-calendar '(calendar-scroll-left 1))))
  15342. (org-defkey map "<"
  15343. (lambda () (interactive)
  15344. (org-eval-in-calendar '(calendar-scroll-right 1))))
  15345. (org-defkey map "\C-v"
  15346. (lambda () (interactive)
  15347. (org-eval-in-calendar
  15348. '(calendar-scroll-left-three-months 1))))
  15349. (org-defkey map "\M-v"
  15350. (lambda () (interactive)
  15351. (org-eval-in-calendar
  15352. '(calendar-scroll-right-three-months 1))))
  15353. map)
  15354. "Keymap for minibuffer commands when using `org-read-date'.")
  15355. (defvar org-def)
  15356. (defvar org-defdecode)
  15357. (defvar org-with-time)
  15358. (defvar calendar-setup) ; Dynamically scoped.
  15359. (defun org-read-date (&optional with-time to-time from-string prompt
  15360. default-time default-input inactive)
  15361. "Read a date, possibly a time, and make things smooth for the user.
  15362. The prompt will suggest to enter an ISO date, but you can also enter anything
  15363. which will at least partially be understood by `parse-time-string'.
  15364. Unrecognized parts of the date will default to the current day, month, year,
  15365. hour and minute. If this command is called to replace a timestamp at point,
  15366. or to enter the second timestamp of a range, the default time is taken
  15367. from the existing stamp. Furthermore, the command prefers the future,
  15368. so if you are giving a date where the year is not given, and the day-month
  15369. combination is already past in the current year, it will assume you
  15370. mean next year. For details, see the manual. A few examples:
  15371. 3-2-5 --> 2003-02-05
  15372. feb 15 --> currentyear-02-15
  15373. 2/15 --> currentyear-02-15
  15374. sep 12 9 --> 2009-09-12
  15375. 12:45 --> today 12:45
  15376. 22 sept 0:34 --> currentyear-09-22 0:34
  15377. 12 --> currentyear-currentmonth-12
  15378. Fri --> nearest Friday after today
  15379. -Tue --> last Tuesday
  15380. etc.
  15381. Furthermore you can specify a relative date by giving, as the *first* thing
  15382. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  15383. change in days weeks, months, years.
  15384. With a single plus or minus, the date is relative to today. With a double
  15385. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  15386. +4d --> four days from today
  15387. +4 --> same as above
  15388. +2w --> two weeks from today
  15389. ++5 --> five days from default date
  15390. The function understands only English month and weekday abbreviations.
  15391. While prompting, a calendar is popped up - you can also select the
  15392. date with the mouse (button 1). The calendar shows a period of three
  15393. months. To scroll it to other months, use the keys `>' and `<'.
  15394. If you don't like the calendar, turn it off with
  15395. (setq org-read-date-popup-calendar nil)
  15396. With optional argument TO-TIME, the date will immediately be converted
  15397. to an internal time.
  15398. With an optional argument WITH-TIME, the prompt will suggest to
  15399. also insert a time. Note that when WITH-TIME is not set, you can
  15400. still enter a time, and this function will inform the calling routine
  15401. about this change. The calling routine may then choose to change the
  15402. format used to insert the time stamp into the buffer to include the time.
  15403. With optional argument FROM-STRING, read from this string instead from
  15404. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  15405. the time/date that is used for everything that is not specified by the
  15406. user."
  15407. (require 'parse-time)
  15408. (let* ((org-with-time with-time)
  15409. (org-time-stamp-rounding-minutes
  15410. (if (equal org-with-time '(16))
  15411. '(0 0)
  15412. org-time-stamp-rounding-minutes))
  15413. (org-dcst org-display-custom-times)
  15414. (ct (org-current-time))
  15415. (org-def (or org-overriding-default-time default-time ct))
  15416. (org-defdecode (decode-time org-def))
  15417. (cur-frame (selected-frame))
  15418. (mouse-autoselect-window nil) ; Don't let the mouse jump
  15419. (calendar-setup
  15420. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  15421. (calendar-move-hook nil)
  15422. (calendar-view-diary-initially-flag nil)
  15423. (calendar-view-holidays-initially-flag nil)
  15424. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  15425. ;; Rationalize `org-def' and `org-defdecode', if required.
  15426. (when (< (nth 2 org-defdecode) org-extend-today-until)
  15427. (setf (nth 2 org-defdecode) -1)
  15428. (setf (nth 1 org-defdecode) 59)
  15429. (setq org-def (apply #'encode-time org-defdecode))
  15430. (setq org-defdecode (decode-time org-def)))
  15431. (let* ((timestr (format-time-string
  15432. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  15433. org-def))
  15434. (prompt (concat (if prompt (concat prompt " ") "")
  15435. (format "Date+time [%s]: " timestr))))
  15436. (cond
  15437. (from-string (setq ans from-string))
  15438. (org-read-date-popup-calendar
  15439. (save-excursion
  15440. (save-window-excursion
  15441. (calendar)
  15442. (when (eq calendar-setup 'calendar-only)
  15443. (setq cal-frame
  15444. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  15445. (select-frame cal-frame))
  15446. (org-eval-in-calendar '(setq cursor-type nil) t)
  15447. (unwind-protect
  15448. (progn
  15449. (calendar-forward-day (- (time-to-days org-def)
  15450. (calendar-absolute-from-gregorian
  15451. (calendar-current-date))))
  15452. (org-eval-in-calendar nil t)
  15453. (let* ((old-map (current-local-map))
  15454. (map (copy-keymap calendar-mode-map))
  15455. (minibuffer-local-map
  15456. (copy-keymap org-read-date-minibuffer-local-map)))
  15457. (org-defkey map (kbd "RET") 'org-calendar-select)
  15458. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  15459. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  15460. (unwind-protect
  15461. (progn
  15462. (use-local-map map)
  15463. (setq org-read-date-inactive inactive)
  15464. (add-hook 'post-command-hook 'org-read-date-display)
  15465. (setq org-ans0
  15466. (read-string prompt
  15467. default-input
  15468. 'org-read-date-history
  15469. nil))
  15470. ;; org-ans0: from prompt
  15471. ;; org-ans1: from mouse click
  15472. ;; org-ans2: from calendar motion
  15473. (setq ans
  15474. (concat org-ans0 " " (or org-ans1 org-ans2))))
  15475. (remove-hook 'post-command-hook 'org-read-date-display)
  15476. (use-local-map old-map)
  15477. (when org-read-date-overlay
  15478. (delete-overlay org-read-date-overlay)
  15479. (setq org-read-date-overlay nil)))))
  15480. (bury-buffer "*Calendar*")
  15481. (when cal-frame
  15482. (delete-frame cal-frame)
  15483. (select-frame-set-input-focus cur-frame))))))
  15484. (t ; Naked prompt only
  15485. (unwind-protect
  15486. (setq ans (read-string prompt default-input
  15487. 'org-read-date-history timestr))
  15488. (when org-read-date-overlay
  15489. (delete-overlay org-read-date-overlay)
  15490. (setq org-read-date-overlay nil))))))
  15491. (setq final (org-read-date-analyze ans org-def org-defdecode))
  15492. (when org-read-date-analyze-forced-year
  15493. (message "Year was forced into %s"
  15494. (if org-read-date-force-compatible-dates
  15495. "compatible range (1970-2037)"
  15496. "range representable on this machine"))
  15497. (ding))
  15498. ;; One round trip to get rid of 34th of August and stuff like that....
  15499. (setq final (decode-time (apply 'encode-time final)))
  15500. (setq org-read-date-final-answer ans)
  15501. (if to-time
  15502. (apply 'encode-time final)
  15503. (if (and (boundp 'org-time-was-given) org-time-was-given)
  15504. (format "%04d-%02d-%02d %02d:%02d"
  15505. (nth 5 final) (nth 4 final) (nth 3 final)
  15506. (nth 2 final) (nth 1 final))
  15507. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  15508. (defun org-read-date-display ()
  15509. "Display the current date prompt interpretation in the minibuffer."
  15510. (when org-read-date-display-live
  15511. (when org-read-date-overlay
  15512. (delete-overlay org-read-date-overlay))
  15513. (when (minibufferp (current-buffer))
  15514. (save-excursion
  15515. (end-of-line 1)
  15516. (while (not (equal (buffer-substring
  15517. (max (point-min) (- (point) 4)) (point))
  15518. " "))
  15519. (insert " ")))
  15520. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  15521. " " (or org-ans1 org-ans2)))
  15522. (org-end-time-was-given nil)
  15523. (f (org-read-date-analyze ans org-def org-defdecode))
  15524. (fmts (if org-dcst
  15525. org-time-stamp-custom-formats
  15526. org-time-stamp-formats))
  15527. (fmt (if (or org-with-time
  15528. (and (boundp 'org-time-was-given) org-time-was-given))
  15529. (cdr fmts)
  15530. (car fmts)))
  15531. (txt (format-time-string fmt (apply 'encode-time f)))
  15532. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  15533. (txt (concat "=> " txt)))
  15534. (when (and org-end-time-was-given
  15535. (string-match org-plain-time-of-day-regexp txt))
  15536. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  15537. org-end-time-was-given
  15538. (substring txt (match-end 0)))))
  15539. (when org-read-date-analyze-futurep
  15540. (setq txt (concat txt " (=>F)")))
  15541. (setq org-read-date-overlay
  15542. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  15543. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  15544. (defun org-read-date-analyze (ans def defdecode)
  15545. "Analyze the combined answer of the date prompt."
  15546. ;; FIXME: cleanup and comment
  15547. ;; Pass `current-time' result to `decode-time' (instead of calling
  15548. ;; without arguments) so that only `current-time' has to be
  15549. ;; overridden in tests.
  15550. (let ((org-def def)
  15551. (org-defdecode defdecode)
  15552. (nowdecode (decode-time (current-time)))
  15553. delta deltan deltaw deltadef year month day
  15554. hour minute second wday pm h2 m2 tl wday1
  15555. iso-year iso-weekday iso-week iso-date futurep kill-year)
  15556. (setq org-read-date-analyze-futurep nil
  15557. org-read-date-analyze-forced-year nil)
  15558. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  15559. (setq ans "+0"))
  15560. (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
  15561. (setq ans (replace-match "" t t ans)
  15562. deltan (car delta)
  15563. deltaw (nth 1 delta)
  15564. deltadef (nth 2 delta)))
  15565. ;; Check if there is an iso week date in there. If yes, store the
  15566. ;; info and postpone interpreting it until the rest of the parsing
  15567. ;; is done.
  15568. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  15569. (setq iso-year (when (match-end 1)
  15570. (org-small-year-to-year
  15571. (string-to-number (match-string 1 ans))))
  15572. iso-weekday (when (match-end 3)
  15573. (string-to-number (match-string 3 ans)))
  15574. iso-week (string-to-number (match-string 2 ans)))
  15575. (setq ans (replace-match "" t t ans)))
  15576. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  15577. (when (string-match
  15578. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  15579. (setq year (if (match-end 2)
  15580. (string-to-number (match-string 2 ans))
  15581. (progn (setq kill-year t)
  15582. (string-to-number (format-time-string "%Y"))))
  15583. month (string-to-number (match-string 3 ans))
  15584. day (string-to-number (match-string 4 ans)))
  15585. (setq year (org-small-year-to-year year))
  15586. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15587. t nil ans)))
  15588. ;; Help matching dotted european dates
  15589. (when (string-match
  15590. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  15591. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  15592. (setq kill-year t)
  15593. (string-to-number (format-time-string "%Y")))
  15594. day (string-to-number (match-string 1 ans))
  15595. month (string-to-number (match-string 2 ans))
  15596. ans (replace-match (format "%04d-%02d-%02d" year month day)
  15597. t nil ans)))
  15598. ;; Help matching american dates, like 5/30 or 5/30/7
  15599. (when (string-match
  15600. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  15601. (setq year (if (match-end 4)
  15602. (string-to-number (match-string 4 ans))
  15603. (progn (setq kill-year t)
  15604. (string-to-number (format-time-string "%Y"))))
  15605. month (string-to-number (match-string 1 ans))
  15606. day (string-to-number (match-string 2 ans)))
  15607. (setq year (org-small-year-to-year year))
  15608. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  15609. t nil ans)))
  15610. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  15611. ;; If there is a time with am/pm, and *no* time without it, we convert
  15612. ;; so that matching will be successful.
  15613. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  15614. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  15615. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  15616. (setq hour (string-to-number (match-string 1 ans))
  15617. minute (if (match-end 3)
  15618. (string-to-number (match-string 3 ans))
  15619. 0)
  15620. pm (equal ?p
  15621. (string-to-char (downcase (match-string 4 ans)))))
  15622. (if (and (= hour 12) (not pm))
  15623. (setq hour 0)
  15624. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  15625. (setq ans (replace-match (format "%02d:%02d" hour minute)
  15626. t t ans))))
  15627. ;; Check if a time range is given as a duration
  15628. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  15629. (setq hour (string-to-number (match-string 1 ans))
  15630. h2 (+ hour (string-to-number (match-string 3 ans)))
  15631. minute (string-to-number (match-string 2 ans))
  15632. m2 (+ minute (if (match-end 5) (string-to-number
  15633. (match-string 5 ans))0)))
  15634. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  15635. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  15636. t t ans)))
  15637. ;; Check if there is a time range
  15638. (when (boundp 'org-end-time-was-given)
  15639. (setq org-time-was-given nil)
  15640. (when (and (string-match org-plain-time-of-day-regexp ans)
  15641. (match-end 8))
  15642. (setq org-end-time-was-given (match-string 8 ans))
  15643. (setq ans (concat (substring ans 0 (match-beginning 7))
  15644. (substring ans (match-end 7))))))
  15645. (setq tl (parse-time-string ans)
  15646. day (or (nth 3 tl) (nth 3 org-defdecode))
  15647. month
  15648. (cond ((nth 4 tl))
  15649. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  15650. ;; Day was specified. Make sure DAY+MONTH
  15651. ;; combination happens in the future.
  15652. ((nth 3 tl)
  15653. (setq futurep t)
  15654. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  15655. (nth 4 nowdecode)))
  15656. (t (nth 4 org-defdecode)))
  15657. year
  15658. (cond ((and (not kill-year) (nth 5 tl)))
  15659. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  15660. ;; Month was guessed in the future and is at least
  15661. ;; equal to NOWDECODE's. Fix year accordingly.
  15662. (futurep
  15663. (if (or (> month (nth 4 nowdecode))
  15664. (>= day (nth 3 nowdecode)))
  15665. (nth 5 nowdecode)
  15666. (1+ (nth 5 nowdecode))))
  15667. ;; Month was specified. Make sure MONTH+YEAR
  15668. ;; combination happens in the future.
  15669. ((nth 4 tl)
  15670. (setq futurep t)
  15671. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  15672. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  15673. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  15674. (t (nth 5 nowdecode))))
  15675. (t (nth 5 org-defdecode)))
  15676. hour (or (nth 2 tl) (nth 2 org-defdecode))
  15677. minute (or (nth 1 tl) (nth 1 org-defdecode))
  15678. second (or (nth 0 tl) 0)
  15679. wday (nth 6 tl))
  15680. (when (and (eq org-read-date-prefer-future 'time)
  15681. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  15682. (equal day (nth 3 nowdecode))
  15683. (equal month (nth 4 nowdecode))
  15684. (equal year (nth 5 nowdecode))
  15685. (nth 2 tl)
  15686. (or (< (nth 2 tl) (nth 2 nowdecode))
  15687. (and (= (nth 2 tl) (nth 2 nowdecode))
  15688. (nth 1 tl)
  15689. (< (nth 1 tl) (nth 1 nowdecode)))))
  15690. (setq day (1+ day)
  15691. futurep t))
  15692. ;; Special date definitions below
  15693. (cond
  15694. (iso-week
  15695. ;; There was an iso week
  15696. (require 'cal-iso)
  15697. (setq futurep nil)
  15698. (setq year (or iso-year year)
  15699. day (or iso-weekday wday 1)
  15700. wday nil ; to make sure that the trigger below does not match
  15701. iso-date (calendar-gregorian-from-absolute
  15702. (calendar-iso-to-absolute
  15703. (list iso-week day year))))
  15704. ; FIXME: Should we also push ISO weeks into the future?
  15705. ; (when (and org-read-date-prefer-future
  15706. ; (not iso-year)
  15707. ; (< (calendar-absolute-from-gregorian iso-date)
  15708. ; (time-to-days (current-time))))
  15709. ; (setq year (1+ year)
  15710. ; iso-date (calendar-gregorian-from-absolute
  15711. ; (calendar-iso-to-absolute
  15712. ; (list iso-week day year)))))
  15713. (setq month (car iso-date)
  15714. year (nth 2 iso-date)
  15715. day (nth 1 iso-date)))
  15716. (deltan
  15717. (setq futurep nil)
  15718. (unless deltadef
  15719. ;; Pass `current-time' result to `decode-time' (instead of
  15720. ;; calling without arguments) so that only `current-time' has
  15721. ;; to be overridden in tests.
  15722. (let ((now (decode-time (current-time))))
  15723. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  15724. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  15725. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  15726. ((equal deltaw "m") (setq month (+ month deltan)))
  15727. ((equal deltaw "y") (setq year (+ year deltan)))))
  15728. ((and wday (not (nth 3 tl)))
  15729. ;; Weekday was given, but no day, so pick that day in the week
  15730. ;; on or after the derived date.
  15731. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  15732. (unless (equal wday wday1)
  15733. (setq day (+ day (% (- wday wday1 -7) 7))))))
  15734. (when (and (boundp 'org-time-was-given)
  15735. (nth 2 tl))
  15736. (setq org-time-was-given t))
  15737. (when (< year 100) (setq year (+ 2000 year)))
  15738. ;; Check of the date is representable
  15739. (if org-read-date-force-compatible-dates
  15740. (progn
  15741. (when (< year 1970)
  15742. (setq year 1970 org-read-date-analyze-forced-year t))
  15743. (when (> year 2037)
  15744. (setq year 2037 org-read-date-analyze-forced-year t)))
  15745. (condition-case nil
  15746. (ignore (encode-time second minute hour day month year))
  15747. (error
  15748. (setq year (nth 5 org-defdecode))
  15749. (setq org-read-date-analyze-forced-year t))))
  15750. (setq org-read-date-analyze-futurep futurep)
  15751. (list second minute hour day month year)))
  15752. (defvar parse-time-weekdays)
  15753. (defun org-read-date-get-relative (s today default)
  15754. "Check string S for special relative date string.
  15755. TODAY and DEFAULT are internal times, for today and for a default.
  15756. Return shift list (N what def-flag)
  15757. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  15758. N is the number of WHATs to shift.
  15759. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  15760. the DEFAULT date rather than TODAY."
  15761. (require 'parse-time)
  15762. (when (and
  15763. (string-match
  15764. (concat
  15765. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  15766. "\\([0-9]+\\)?"
  15767. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  15768. "\\([ \t]\\|$\\)") s)
  15769. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  15770. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  15771. (string-to-char (substring (match-string 1 s) -1))
  15772. ?+))
  15773. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  15774. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  15775. (what (if (match-end 3) (match-string 3 s) "d"))
  15776. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  15777. (date (if rel default today))
  15778. (wday (nth 6 (decode-time date)))
  15779. delta)
  15780. (if wday1
  15781. (progn
  15782. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  15783. (when (= delta 0) (setq delta 7))
  15784. (when (= dir ?-)
  15785. (setq delta (- delta 7))
  15786. (when (= delta 0) (setq delta -7)))
  15787. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  15788. (list delta "d" rel))
  15789. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  15790. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  15791. "Turn a user-specified date into the internal representation.
  15792. The internal representation needed by the calendar is (month day year).
  15793. This is a wrapper to handle the brain-dead convention in calendar that
  15794. user function argument order change dependent on argument order."
  15795. (pcase calendar-date-style
  15796. (`american (list arg1 arg2 arg3))
  15797. (`european (list arg2 arg1 arg3))
  15798. (`iso (list arg2 arg3 arg1))))
  15799. (defun org-eval-in-calendar (form &optional keepdate)
  15800. "Eval FORM in the calendar window and return to current window.
  15801. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  15802. (let ((sf (selected-frame))
  15803. (sw (selected-window)))
  15804. (select-window (get-buffer-window "*Calendar*" t))
  15805. (eval form)
  15806. (when (and (not keepdate) (calendar-cursor-to-date))
  15807. (let* ((date (calendar-cursor-to-date))
  15808. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15809. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  15810. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  15811. (select-window sw)
  15812. (select-frame-set-input-focus sf)))
  15813. (defun org-calendar-select ()
  15814. "Return to `org-read-date' with the date currently selected.
  15815. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15816. (interactive)
  15817. (when (calendar-cursor-to-date)
  15818. (let* ((date (calendar-cursor-to-date))
  15819. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15820. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15821. (when (active-minibuffer-window) (exit-minibuffer))))
  15822. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  15823. "Insert a date stamp for the date given by the internal TIME.
  15824. See `format-time-string' for the format of TIME.
  15825. WITH-HM means use the stamp format that includes the time of the day.
  15826. INACTIVE means use square brackets instead of angular ones, so that the
  15827. stamp will not contribute to the agenda.
  15828. PRE and POST are optional strings to be inserted before and after the
  15829. stamp.
  15830. The command returns the inserted time stamp."
  15831. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  15832. stamp)
  15833. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  15834. (insert-before-markers (or pre ""))
  15835. (when (listp extra)
  15836. (setq extra (car extra))
  15837. (if (and (stringp extra)
  15838. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  15839. (setq extra (format "-%02d:%02d"
  15840. (string-to-number (match-string 1 extra))
  15841. (string-to-number (match-string 2 extra))))
  15842. (setq extra nil)))
  15843. (when extra
  15844. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  15845. (insert-before-markers (setq stamp (format-time-string fmt time)))
  15846. (insert-before-markers (or post ""))
  15847. (setq org-last-inserted-timestamp stamp)))
  15848. (defun org-toggle-time-stamp-overlays ()
  15849. "Toggle the use of custom time stamp formats."
  15850. (interactive)
  15851. (setq org-display-custom-times (not org-display-custom-times))
  15852. (unless org-display-custom-times
  15853. (let ((p (point-min)) (bmp (buffer-modified-p)))
  15854. (while (setq p (next-single-property-change p 'display))
  15855. (when (and (get-text-property p 'display)
  15856. (eq (get-text-property p 'face) 'org-date))
  15857. (remove-text-properties
  15858. p (setq p (next-single-property-change p 'display))
  15859. '(display t))))
  15860. (set-buffer-modified-p bmp)))
  15861. (org-restart-font-lock)
  15862. (setq org-table-may-need-update t)
  15863. (if org-display-custom-times
  15864. (message "Time stamps are overlaid with custom format")
  15865. (message "Time stamp overlays removed")))
  15866. (defun org-display-custom-time (beg end)
  15867. "Overlay modified time stamp format over timestamp between BEG and END."
  15868. (let* ((ts (buffer-substring beg end))
  15869. t1 w1 with-hm tf time str w2 (off 0))
  15870. (save-match-data
  15871. (setq t1 (org-parse-time-string ts t))
  15872. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  15873. (setq off (- (match-end 0) (match-beginning 0)))))
  15874. (setq end (- end off))
  15875. (setq w1 (- end beg)
  15876. with-hm (and (nth 1 t1) (nth 2 t1))
  15877. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  15878. time (org-fix-decoded-time t1)
  15879. str (org-add-props
  15880. (format-time-string
  15881. (substring tf 1 -1) (apply 'encode-time time))
  15882. nil 'mouse-face 'highlight)
  15883. w2 (length str))
  15884. (unless (= w2 w1)
  15885. (add-text-properties (1+ beg) (+ 2 beg)
  15886. (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
  15887. (put-text-property beg end 'display str)))
  15888. (defun org-fix-decoded-time (time)
  15889. "Set 0 instead of nil for the first 6 elements of time.
  15890. Don't touch the rest."
  15891. (let ((n 0))
  15892. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  15893. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  15894. "Difference between TIMESTAMP-STRING and now in days.
  15895. If SECONDS is non-nil, return the difference in seconds."
  15896. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  15897. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  15898. (funcall fdiff (current-time)))))
  15899. (defun org-deadline-close-p (timestamp-string &optional ndays)
  15900. "Is the time in TIMESTAMP-STRING close to the current date?"
  15901. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  15902. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  15903. (not (org-entry-is-done-p))))
  15904. (defun org-get-wdays (ts &optional delay zero-delay)
  15905. "Get the deadline lead time appropriate for timestring TS.
  15906. When DELAY is non-nil, get the delay time for scheduled items
  15907. instead of the deadline lead time. When ZERO-DELAY is non-nil
  15908. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  15909. don't try to find the delay cookie in the scheduled timestamp."
  15910. (let ((tv (if delay org-scheduled-delay-days
  15911. org-deadline-warning-days)))
  15912. (cond
  15913. ((or (and delay (< tv 0))
  15914. (and delay zero-delay (<= tv 0))
  15915. (and (not delay) (<= tv 0)))
  15916. ;; Enforce this value no matter what
  15917. (- tv))
  15918. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  15919. ;; lead time is specified.
  15920. (floor (* (string-to-number (match-string 1 ts))
  15921. (cdr (assoc (match-string 2 ts)
  15922. '(("d" . 1) ("w" . 7)
  15923. ("m" . 30.4) ("y" . 365.25)
  15924. ("h" . 0.041667)))))))
  15925. ;; go for the default.
  15926. (t tv))))
  15927. (defun org-calendar-select-mouse (ev)
  15928. "Return to `org-read-date' with the date currently selected.
  15929. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  15930. (interactive "e")
  15931. (mouse-set-point ev)
  15932. (when (calendar-cursor-to-date)
  15933. (let* ((date (calendar-cursor-to-date))
  15934. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  15935. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  15936. (when (active-minibuffer-window) (exit-minibuffer))))
  15937. (defun org-check-deadlines (ndays)
  15938. "Check if there are any deadlines due or past due.
  15939. A deadline is considered due if it happens within `org-deadline-warning-days'
  15940. days from today's date. If the deadline appears in an entry marked DONE,
  15941. it is not shown. A numeric prefix argument NDAYS can be used to test that
  15942. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  15943. are shown."
  15944. (interactive "P")
  15945. (let* ((org-warn-days
  15946. (cond
  15947. ((equal ndays '(4)) 100000)
  15948. (ndays (prefix-numeric-value ndays))
  15949. (t (abs org-deadline-warning-days))))
  15950. (case-fold-search nil)
  15951. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  15952. (callback
  15953. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  15954. (message "%d deadlines past-due or due within %d days"
  15955. (org-occur regexp nil callback)
  15956. org-warn-days)))
  15957. (defsubst org-re-timestamp (type)
  15958. "Return a regexp for timestamp TYPE.
  15959. Allowed values for TYPE are:
  15960. all: all timestamps
  15961. active: only active timestamps (<...>)
  15962. inactive: only inactive timestamps ([...])
  15963. scheduled: only scheduled timestamps
  15964. deadline: only deadline timestamps
  15965. closed: only closed time-stamps
  15966. When TYPE is nil, fall back on returning a regexp that matches
  15967. both scheduled and deadline timestamps."
  15968. (cl-case type
  15969. (all org-ts-regexp-both)
  15970. (active org-ts-regexp)
  15971. (inactive org-ts-regexp-inactive)
  15972. (scheduled org-scheduled-time-regexp)
  15973. (deadline org-deadline-time-regexp)
  15974. (closed org-closed-time-regexp)
  15975. (otherwise
  15976. (concat "\\<"
  15977. (regexp-opt (list org-deadline-string org-scheduled-string))
  15978. " *<\\([^>]+\\)>"))))
  15979. (defun org-check-before-date (d)
  15980. "Check if there are deadlines or scheduled entries before date D."
  15981. (interactive (list (org-read-date)))
  15982. (let* ((case-fold-search nil)
  15983. (regexp (org-re-timestamp org-ts-type))
  15984. (ts-type org-ts-type)
  15985. (callback
  15986. (lambda ()
  15987. (let ((match (match-string 1)))
  15988. (and (if (memq ts-type '(active inactive all))
  15989. (eq (org-element-type (save-excursion
  15990. (backward-char)
  15991. (org-element-context)))
  15992. 'timestamp)
  15993. (org-at-planning-p))
  15994. (time-less-p
  15995. (org-time-string-to-time match)
  15996. (org-time-string-to-time d)))))))
  15997. (message "%d entries before %s"
  15998. (org-occur regexp nil callback)
  15999. d)))
  16000. (defun org-check-after-date (d)
  16001. "Check if there are deadlines or scheduled entries after date D."
  16002. (interactive (list (org-read-date)))
  16003. (let* ((case-fold-search nil)
  16004. (regexp (org-re-timestamp org-ts-type))
  16005. (ts-type org-ts-type)
  16006. (callback
  16007. (lambda ()
  16008. (let ((match (match-string 1)))
  16009. (and (if (memq ts-type '(active inactive all))
  16010. (eq (org-element-type (save-excursion
  16011. (backward-char)
  16012. (org-element-context)))
  16013. 'timestamp)
  16014. (org-at-planning-p))
  16015. (not (time-less-p
  16016. (org-time-string-to-time match)
  16017. (org-time-string-to-time d))))))))
  16018. (message "%d entries after %s"
  16019. (org-occur regexp nil callback)
  16020. d)))
  16021. (defun org-check-dates-range (start-date end-date)
  16022. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  16023. (interactive (list (org-read-date nil nil nil "Range starts")
  16024. (org-read-date nil nil nil "Range end")))
  16025. (let ((case-fold-search nil)
  16026. (regexp (org-re-timestamp org-ts-type))
  16027. (callback
  16028. (let ((type org-ts-type))
  16029. (lambda ()
  16030. (let ((match (match-string 1)))
  16031. (and
  16032. (if (memq type '(active inactive all))
  16033. (eq (org-element-type (save-excursion
  16034. (backward-char)
  16035. (org-element-context)))
  16036. 'timestamp)
  16037. (org-at-planning-p))
  16038. (not (time-less-p
  16039. (org-time-string-to-time match)
  16040. (org-time-string-to-time start-date)))
  16041. (time-less-p
  16042. (org-time-string-to-time match)
  16043. (org-time-string-to-time end-date))))))))
  16044. (message "%d entries between %s and %s"
  16045. (org-occur regexp nil callback) start-date end-date)))
  16046. (defun org-evaluate-time-range (&optional to-buffer)
  16047. "Evaluate a time range by computing the difference between start and end.
  16048. Normally the result is just printed in the echo area, but with prefix arg
  16049. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  16050. If the time range is actually in a table, the result is inserted into the
  16051. next column.
  16052. For time difference computation, a year is assumed to be exactly 365
  16053. days in order to avoid rounding problems."
  16054. (interactive "P")
  16055. (or
  16056. (org-clock-update-time-maybe)
  16057. (save-excursion
  16058. (unless (org-at-date-range-p t)
  16059. (goto-char (point-at-bol))
  16060. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  16061. (unless (org-at-date-range-p t)
  16062. (user-error "Not at a time-stamp range, and none found in current line")))
  16063. (let* ((ts1 (match-string 1))
  16064. (ts2 (match-string 2))
  16065. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  16066. (match-end (match-end 0))
  16067. (time1 (org-time-string-to-time ts1))
  16068. (time2 (org-time-string-to-time ts2))
  16069. (t1 (float-time time1))
  16070. (t2 (float-time time2))
  16071. (diff (abs (- t2 t1)))
  16072. (negative (< (- t2 t1) 0))
  16073. ;; (ys (floor (* 365 24 60 60)))
  16074. (ds (* 24 60 60))
  16075. (hs (* 60 60))
  16076. (fy "%dy %dd %02d:%02d")
  16077. (fy1 "%dy %dd")
  16078. (fd "%dd %02d:%02d")
  16079. (fd1 "%dd")
  16080. (fh "%02d:%02d")
  16081. y d h m align)
  16082. (if havetime
  16083. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16084. y 0
  16085. d (floor (/ diff ds)) diff (mod diff ds)
  16086. h (floor (/ diff hs)) diff (mod diff hs)
  16087. m (floor (/ diff 60)))
  16088. (setq ; y (floor (/ diff ys)) diff (mod diff ys)
  16089. y 0
  16090. d (floor (+ (/ diff ds) 0.5))
  16091. h 0 m 0))
  16092. (if (not to-buffer)
  16093. (message "%s" (org-make-tdiff-string y d h m))
  16094. (if (org-at-table-p)
  16095. (progn
  16096. (goto-char match-end)
  16097. (setq align t)
  16098. (and (looking-at " *|") (goto-char (match-end 0))))
  16099. (goto-char match-end))
  16100. (when (looking-at
  16101. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  16102. (replace-match ""))
  16103. (when negative (insert " -"))
  16104. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  16105. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  16106. (insert " " (format fh h m))))
  16107. (when align (org-table-align))
  16108. (message "Time difference inserted")))))
  16109. (defun org-make-tdiff-string (y d h m)
  16110. (let ((fmt "")
  16111. (l nil))
  16112. (when (> y 0)
  16113. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  16114. (push y l))
  16115. (when (> d 0)
  16116. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  16117. (push d l))
  16118. (when (> h 0)
  16119. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  16120. (push h l))
  16121. (when (> m 0)
  16122. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  16123. (push m l))
  16124. (apply 'format fmt (nreverse l))))
  16125. (defun org-time-string-to-time (s &optional buffer pos)
  16126. "Convert a timestamp string into internal time."
  16127. (condition-case errdata
  16128. (apply 'encode-time (org-parse-time-string s))
  16129. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16130. s (if (not (and buffer pos))
  16131. ""
  16132. (format-message " at %d in buffer `%s'" pos buffer))
  16133. (cdr errdata)))))
  16134. (defun org-time-string-to-seconds (s)
  16135. "Convert a timestamp string to a number of seconds."
  16136. (float-time (org-time-string-to-time s)))
  16137. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  16138. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  16139. "Convert time stamp S to an absolute day number.
  16140. If DAYNR in non-nil, and there is a specifier for a cyclic time
  16141. stamp, get the closest date to DAYNR. If PREFER is
  16142. `past' (respectively `future') return a date past (respectively
  16143. after) or equal to DAYNR.
  16144. POS is the location of time stamp S, as a buffer position in
  16145. BUFFER.
  16146. Diary sexp timestamps are matched against DAYNR, when non-nil.
  16147. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  16148. signaled."
  16149. (cond
  16150. ((string-match "\\`%%\\((.*)\\)" s)
  16151. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  16152. ;; only able to match individual dates. If it fails, raise an
  16153. ;; error.
  16154. (if (and daynr
  16155. (org-diary-sexp-entry
  16156. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  16157. daynr
  16158. (signal 'org-diary-sexp-no-match (list s))))
  16159. (daynr (org-closest-date s daynr prefer))
  16160. (t (time-to-days
  16161. (condition-case errdata
  16162. (apply #'encode-time (org-parse-time-string s))
  16163. (error (error "Bad timestamp `%s'%s\nError was: %s"
  16164. s
  16165. (if (not (and buffer pos)) ""
  16166. (format-message " at %d in buffer `%s'" pos buffer))
  16167. (cdr errdata))))))))
  16168. (defun org-days-to-iso-week (days)
  16169. "Return the iso week number."
  16170. (require 'cal-iso)
  16171. (car (calendar-iso-from-absolute days)))
  16172. (defun org-small-year-to-year (year)
  16173. "Convert 2-digit years into 4-digit years.
  16174. YEAR is expanded into one of the 30 next years, if possible, or
  16175. into a past one. Any year larger than 99 is returned unchanged."
  16176. (if (>= year 100) year
  16177. (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
  16178. (century (/ current 100))
  16179. (offset (- year (% current 100))))
  16180. (cond ((> offset 30) (+ (* (1- century) 100) year))
  16181. ((> offset -70) (+ (* century 100) year))
  16182. (t (+ (* (1+ century) 100) year))))))
  16183. (defun org-time-from-absolute (d)
  16184. "Return the time corresponding to date D.
  16185. D may be an absolute day number, or a calendar-type list (month day year)."
  16186. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  16187. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  16188. (defvar org-agenda-current-date)
  16189. (defun org-calendar-holiday ()
  16190. "List of holidays, for Diary display in Org mode."
  16191. (require 'holidays)
  16192. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  16193. (and hl (mapconcat #'identity hl "; "))))
  16194. (defun org-diary-sexp-entry (sexp entry d)
  16195. "Process a SEXP diary ENTRY for date D."
  16196. (require 'diary-lib)
  16197. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  16198. ;; dynamically.
  16199. (let* ((sexp `(let ((entry ,entry)
  16200. (date ',d))
  16201. ,(car (read-from-string sexp))))
  16202. (result (if calendar-debug-sexp (eval sexp)
  16203. (condition-case nil
  16204. (eval sexp)
  16205. (error
  16206. (beep)
  16207. (message "Bad sexp at line %d in %s: %s"
  16208. (org-current-line)
  16209. (buffer-file-name) sexp)
  16210. (sleep-for 2))))))
  16211. (cond ((stringp result) (split-string result "; "))
  16212. ((and (consp result)
  16213. (not (consp (cdr result)))
  16214. (stringp (cdr result))) (cdr result))
  16215. ((and (consp result)
  16216. (stringp (car result))) result)
  16217. (result entry))))
  16218. (defun org-diary-to-ical-string (frombuf)
  16219. "Get iCalendar entries from diary entries in buffer FROMBUF.
  16220. This uses the icalendar.el library."
  16221. (let* ((tmpdir temporary-file-directory)
  16222. (tmpfile (make-temp-name
  16223. (expand-file-name "orgics" tmpdir)))
  16224. buf rtn b e)
  16225. (with-current-buffer frombuf
  16226. (icalendar-export-region (point-min) (point-max) tmpfile)
  16227. (setq buf (find-buffer-visiting tmpfile))
  16228. (set-buffer buf)
  16229. (goto-char (point-min))
  16230. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  16231. (setq b (match-beginning 0)))
  16232. (goto-char (point-max))
  16233. (when (re-search-backward "^END:VEVENT" nil t)
  16234. (setq e (match-end 0)))
  16235. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  16236. (kill-buffer buf)
  16237. (delete-file tmpfile)
  16238. rtn))
  16239. (defun org-closest-date (start current prefer)
  16240. "Return closest date to CURRENT starting from START.
  16241. CURRENT and START are both time stamps.
  16242. When PREFER is `past', return a date that is either CURRENT or
  16243. past. When PREFER is `future', return a date that is either
  16244. CURRENT or future.
  16245. Only time stamps with a repeater are modified. Any other time
  16246. stamp stay unchanged. In any case, return value is an absolute
  16247. day number."
  16248. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  16249. ;; No repeater. Do not shift time stamp.
  16250. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16251. (let ((value (string-to-number (match-string 1 start)))
  16252. (type (match-string 2 start)))
  16253. (if (= 0 value)
  16254. ;; Repeater with a 0-value is considered as void.
  16255. (time-to-days (apply #'encode-time (org-parse-time-string start)))
  16256. (let* ((base (org-date-to-gregorian start))
  16257. (target (org-date-to-gregorian current))
  16258. (sday (calendar-absolute-from-gregorian base))
  16259. (cday (calendar-absolute-from-gregorian target))
  16260. n1 n2)
  16261. ;; If START is already past CURRENT, just return START.
  16262. (if (<= cday sday) sday
  16263. ;; Compute closest date before (N1) and closest date past
  16264. ;; (N2) CURRENT.
  16265. (pcase type
  16266. ("h"
  16267. (let ((missing-hours
  16268. (mod (+ (- (* 24 (- cday sday))
  16269. (nth 2 (org-parse-time-string start)))
  16270. org-extend-today-until)
  16271. value)))
  16272. (setf n1 (if (= missing-hours 0) cday
  16273. (- cday (1+ (/ missing-hours 24)))))
  16274. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  16275. ((or "d" "w")
  16276. (let ((value (if (equal type "w") (* 7 value) value)))
  16277. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  16278. (setf n2 (+ n1 value))))
  16279. ("m"
  16280. (let* ((add-months
  16281. (lambda (d n)
  16282. ;; Add N months to gregorian date D, i.e.,
  16283. ;; a list (MONTH DAY YEAR). Return a valid
  16284. ;; gregorian date.
  16285. (let ((m (+ (nth 0 d) n)))
  16286. (list (mod m 12)
  16287. (nth 1 d)
  16288. (+ (/ m 12) (nth 2 d))))))
  16289. (months ; Complete months to TARGET.
  16290. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  16291. (- (nth 0 target) (nth 0 base))
  16292. ;; If START's day is greater than
  16293. ;; TARGET's, remove incomplete month.
  16294. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  16295. value)
  16296. value))
  16297. (before (funcall add-months base months)))
  16298. (setf n1 (calendar-absolute-from-gregorian before))
  16299. (setf n2
  16300. (calendar-absolute-from-gregorian
  16301. (funcall add-months before value)))))
  16302. (_
  16303. (let* ((d (nth 1 base))
  16304. (m (nth 0 base))
  16305. (y (nth 2 base))
  16306. (years ; Complete years to TARGET.
  16307. (* (/ (- (nth 2 target)
  16308. y
  16309. ;; If START's month and day are
  16310. ;; greater than TARGET's, remove
  16311. ;; incomplete year.
  16312. (if (or (> (nth 0 target) m)
  16313. (and (= (nth 0 target) m)
  16314. (> (nth 1 target) d)))
  16315. 0
  16316. 1))
  16317. value)
  16318. value))
  16319. (before (list m d (+ y years))))
  16320. (setf n1 (calendar-absolute-from-gregorian before))
  16321. (setf n2 (calendar-absolute-from-gregorian
  16322. (list m d (+ (nth 2 before) value)))))))
  16323. ;; Handle PREFER parameter, if any.
  16324. (cond
  16325. ((eq prefer 'past) (if (= cday n2) n2 n1))
  16326. ((eq prefer 'future) (if (= cday n1) n1 n2))
  16327. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  16328. (defun org-date-to-gregorian (d)
  16329. "Turn any specification of date D into a Gregorian date for the calendar."
  16330. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  16331. ((and (listp d) (= (length d) 3)) d)
  16332. ((stringp d)
  16333. (let ((d (org-parse-time-string d)))
  16334. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  16335. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  16336. (defun org-parse-time-string (s &optional nodefault zone)
  16337. "Parse the standard Org time string.
  16338. This should be a lot faster than the normal `parse-time-string'.
  16339. If time is not given, defaults to 0:00. However, with optional
  16340. NODEFAULT, hour and minute fields will be nil if not given.
  16341. The optional ZONE is omitted or nil for Emacs local time, t for
  16342. Universal Time, ‘wall’ for system wall clock time, or a string as
  16343. in the TZ environment variable."
  16344. (cond ((string-match org-ts-regexp0 s)
  16345. (list 0
  16346. (when (or (match-beginning 8) (not nodefault))
  16347. (string-to-number (or (match-string 8 s) "0")))
  16348. (when (or (match-beginning 7) (not nodefault))
  16349. (string-to-number (or (match-string 7 s) "0")))
  16350. (string-to-number (match-string 4 s))
  16351. (string-to-number (match-string 3 s))
  16352. (string-to-number (match-string 2 s))
  16353. nil nil zone))
  16354. ((string-match "^<[^>]+>$" s)
  16355. ;; FIXME: `decode-time' needs to be called with ZONE as its
  16356. ;; second argument. However, this requires at least Emacs
  16357. ;; 25.1. We can do it when we switch to this version as our
  16358. ;; minimal requirement.
  16359. (decode-time (seconds-to-time (org-matcher-time s))))
  16360. (t (error "Not a standard Org time string: %s" s))))
  16361. (defun org-timestamp-up (&optional arg)
  16362. "Increase the date item at the cursor by one.
  16363. If the cursor is on the year, change the year. If it is on the month,
  16364. the day or the time, change that.
  16365. With prefix ARG, change by that many units."
  16366. (interactive "p")
  16367. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  16368. (defun org-timestamp-down (&optional arg)
  16369. "Decrease the date item at the cursor by one.
  16370. If the cursor is on the year, change the year. If it is on the month,
  16371. the day or the time, change that.
  16372. With prefix ARG, change by that many units."
  16373. (interactive "p")
  16374. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  16375. (defun org-timestamp-up-day (&optional arg)
  16376. "Increase the date in the time stamp by one day.
  16377. With prefix ARG, change that many days."
  16378. (interactive "p")
  16379. (if (and (not (org-at-timestamp-p t))
  16380. (org-at-heading-p))
  16381. (org-todo 'up)
  16382. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  16383. (defun org-timestamp-down-day (&optional arg)
  16384. "Decrease the date in the time stamp by one day.
  16385. With prefix ARG, change that many days."
  16386. (interactive "p")
  16387. (if (and (not (org-at-timestamp-p t))
  16388. (org-at-heading-p))
  16389. (org-todo 'down)
  16390. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  16391. (defun org-at-timestamp-p (&optional inactive-ok)
  16392. "Non-nil if point is inside a timestamp.
  16393. When optional argument INACTIVE-OK is non-nil, also consider
  16394. inactive timestamps.
  16395. When this function returns a non-nil value, match data is set
  16396. according to `org-ts-regexp3' or `org-ts-regexp2', depending on
  16397. INACTIVE-OK."
  16398. (interactive)
  16399. (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
  16400. (pos (point))
  16401. (ans (or (looking-at tsr)
  16402. (save-excursion
  16403. (skip-chars-backward "^[<\n\r\t")
  16404. (when (> (point) (point-min)) (backward-char 1))
  16405. (and (looking-at tsr)
  16406. (> (- (match-end 0) pos) -1))))))
  16407. (and ans
  16408. (boundp 'org-ts-what)
  16409. (setq org-ts-what
  16410. (cond
  16411. ((= pos (match-beginning 0)) 'bracket)
  16412. ;; Point is considered to be "on the bracket" whether
  16413. ;; it's really on it or right after it.
  16414. ((= pos (1- (match-end 0))) 'bracket)
  16415. ((= pos (match-end 0)) 'after)
  16416. ((org-pos-in-match-range pos 2) 'year)
  16417. ((org-pos-in-match-range pos 3) 'month)
  16418. ((org-pos-in-match-range pos 7) 'hour)
  16419. ((org-pos-in-match-range pos 8) 'minute)
  16420. ((or (org-pos-in-match-range pos 4)
  16421. (org-pos-in-match-range pos 5)) 'day)
  16422. ((and (> pos (or (match-end 8) (match-end 5)))
  16423. (< pos (match-end 0)))
  16424. (- pos (or (match-end 8) (match-end 5))))
  16425. (t 'day))))
  16426. ans))
  16427. (defun org-toggle-timestamp-type ()
  16428. "Toggle the type (<active> or [inactive]) of a time stamp."
  16429. (interactive)
  16430. (when (org-at-timestamp-p t)
  16431. (let ((beg (match-beginning 0)) (end (match-end 0))
  16432. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  16433. (save-excursion
  16434. (goto-char beg)
  16435. (while (re-search-forward "[][<>]" end t)
  16436. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  16437. t t)))
  16438. (message "Timestamp is now %sactive"
  16439. (if (equal (char-after beg) ?<) "" "in")))))
  16440. (defun org-at-clock-log-p nil
  16441. "Is the cursor on the clock log line?"
  16442. (save-excursion
  16443. (beginning-of-line)
  16444. (looking-at org-clock-line-re)))
  16445. (defvar org-clock-history) ; defined in org-clock.el
  16446. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  16447. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  16448. "Change the date in the time stamp at point.
  16449. The date will be changed by N times WHAT. WHAT can be `day', `month',
  16450. `year', `minute', `second'. If WHAT is not given, the cursor position
  16451. in the timestamp determines what will be changed.
  16452. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
  16453. (let ((origin (point)) origin-cat
  16454. with-hm inactive
  16455. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  16456. org-ts-what
  16457. extra rem
  16458. ts time time0 fixnext clrgx)
  16459. (unless (org-at-timestamp-p t)
  16460. (user-error "Not at a timestamp"))
  16461. (if (and (not what) (eq org-ts-what 'bracket))
  16462. (org-toggle-timestamp-type)
  16463. ;; Point isn't on brackets. Remember the part of the time-stamp
  16464. ;; the point was in. Indeed, size of time-stamps may change,
  16465. ;; but point must be kept in the same category nonetheless.
  16466. (setq origin-cat org-ts-what)
  16467. (when (and (not what) (not (eq org-ts-what 'day))
  16468. org-display-custom-times
  16469. (get-text-property (point) 'display)
  16470. (not (get-text-property (1- (point)) 'display)))
  16471. (setq org-ts-what 'day))
  16472. (setq org-ts-what (or what org-ts-what)
  16473. inactive (= (char-after (match-beginning 0)) ?\[)
  16474. ts (match-string 0))
  16475. (replace-match "")
  16476. (when (string-match
  16477. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  16478. ts)
  16479. (setq extra (match-string 1 ts))
  16480. (when suppress-tmp-delay
  16481. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  16482. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  16483. (setq with-hm t))
  16484. (setq time0 (org-parse-time-string ts))
  16485. (when (and updown
  16486. (eq org-ts-what 'minute)
  16487. (not current-prefix-arg))
  16488. ;; This looks like s-up and s-down. Change by one rounding step.
  16489. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  16490. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  16491. (setcar (cdr time0) (+ (nth 1 time0)
  16492. (if (> n 0) (- rem) (- dm rem))))))
  16493. (setq time
  16494. (apply #'encode-time
  16495. (or (car time0) 0)
  16496. (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
  16497. (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
  16498. (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
  16499. (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
  16500. (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
  16501. (nthcdr 6 time0)))
  16502. (when (and (member org-ts-what '(hour minute))
  16503. extra
  16504. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  16505. (setq extra (org-modify-ts-extra
  16506. extra
  16507. (if (eq org-ts-what 'hour) 2 5)
  16508. n dm)))
  16509. (when (integerp org-ts-what)
  16510. (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
  16511. (when (eq what 'calendar)
  16512. (let ((cal-date (org-get-date-from-calendar)))
  16513. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  16514. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  16515. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  16516. (setcar time0 (or (car time0) 0))
  16517. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  16518. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  16519. (setq time (apply 'encode-time time0))))
  16520. ;; Insert the new time-stamp, and ensure point stays in the same
  16521. ;; category as before (i.e. not after the last position in that
  16522. ;; category).
  16523. (let ((pos (point)))
  16524. ;; Stay before inserted string. `save-excursion' is of no use.
  16525. (setq org-last-changed-timestamp
  16526. (org-insert-time-stamp time with-hm inactive nil nil extra))
  16527. (goto-char pos))
  16528. (save-match-data
  16529. (looking-at org-ts-regexp3)
  16530. (goto-char
  16531. (pcase origin-cat
  16532. ;; `day' category ends before `hour' if any, or at the end
  16533. ;; of the day name.
  16534. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  16535. (`hour (min (match-end 7) origin))
  16536. (`minute (min (1- (match-end 8)) origin))
  16537. ((pred integerp) (min (1- (match-end 0)) origin))
  16538. ;; Point was right after the time-stamp. However, the
  16539. ;; time-stamp length might have changed, so refer to
  16540. ;; (match-end 0) instead.
  16541. (`after (match-end 0))
  16542. ;; `year' and `month' have both fixed size: point couldn't
  16543. ;; have moved into another part.
  16544. (_ origin))))
  16545. ;; Update clock if on a CLOCK line.
  16546. (org-clock-update-time-maybe)
  16547. ;; Maybe adjust the closest clock in `org-clock-history'
  16548. (when org-clock-adjust-closest
  16549. (if (not (and (org-at-clock-log-p)
  16550. (< 1 (length (delq nil (mapcar 'marker-position
  16551. org-clock-history))))))
  16552. (message "No clock to adjust")
  16553. (cond ((save-excursion ; fix previous clock?
  16554. (re-search-backward org-ts-regexp0 nil t)
  16555. (looking-back (concat org-clock-string " \\[")
  16556. (line-beginning-position)))
  16557. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  16558. ((save-excursion ; fix next clock?
  16559. (re-search-backward org-ts-regexp0 nil t)
  16560. (looking-at (concat org-ts-regexp0 "\\] =>")))
  16561. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  16562. (save-window-excursion
  16563. ;; Find closest clock to point, adjust the previous/next one in history
  16564. (let* ((p (save-excursion (org-back-to-heading t)))
  16565. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  16566. (clfixnth
  16567. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  16568. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  16569. (if (not clfixpos)
  16570. (message "No clock to adjust")
  16571. (save-excursion
  16572. (org-goto-marker-or-bmk clfixpos)
  16573. (org-show-subtree)
  16574. (when (re-search-forward clrgx nil t)
  16575. (goto-char (match-beginning 1))
  16576. (let (org-clock-adjust-closest)
  16577. (org-timestamp-change n org-ts-what updown))
  16578. (message "Clock adjusted in %s for heading: %s"
  16579. (file-name-nondirectory (buffer-file-name))
  16580. (org-get-heading t t)))))))))
  16581. ;; Try to recenter the calendar window, if any.
  16582. (when (and org-calendar-follow-timestamp-change
  16583. (get-buffer-window "*Calendar*" t)
  16584. (memq org-ts-what '(day month year)))
  16585. (org-recenter-calendar (time-to-days time))))))
  16586. (defun org-modify-ts-extra (s pos n dm)
  16587. "Change the different parts of the lead-time and repeat fields in timestamp."
  16588. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  16589. ng h m new rem)
  16590. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  16591. (cond
  16592. ((or (org-pos-in-match-range pos 2)
  16593. (org-pos-in-match-range pos 3))
  16594. (setq m (string-to-number (match-string 3 s))
  16595. h (string-to-number (match-string 2 s)))
  16596. (if (org-pos-in-match-range pos 2)
  16597. (setq h (+ h n))
  16598. (setq n (* dm (with-no-warnings (signum n))))
  16599. (unless (= 0 (setq rem (% m dm)))
  16600. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  16601. (setq m (+ m n)))
  16602. (when (< m 0) (setq m (+ m 60) h (1- h)))
  16603. (when (> m 59) (setq m (- m 60) h (1+ h)))
  16604. (setq h (mod h 24))
  16605. (setq ng 1 new (format "-%02d:%02d" h m)))
  16606. ((org-pos-in-match-range pos 6)
  16607. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  16608. ((org-pos-in-match-range pos 5)
  16609. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  16610. ((org-pos-in-match-range pos 9)
  16611. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  16612. ((org-pos-in-match-range pos 8)
  16613. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  16614. (when ng
  16615. (setq s (concat
  16616. (substring s 0 (match-beginning ng))
  16617. new
  16618. (substring s (match-end ng))))))
  16619. s))
  16620. (defun org-recenter-calendar (d)
  16621. "If the calendar is visible, recenter it to date D."
  16622. (let ((cwin (get-buffer-window "*Calendar*" t)))
  16623. (when cwin
  16624. (let ((calendar-move-hook nil))
  16625. (with-selected-window cwin
  16626. (calendar-goto-date
  16627. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  16628. (defun org-goto-calendar (&optional arg)
  16629. "Go to the Emacs calendar at the current date.
  16630. If there is a time stamp in the current line, go to that date.
  16631. A prefix ARG can be used to force the current date."
  16632. (interactive "P")
  16633. (let ((tsr org-ts-regexp) diff
  16634. (calendar-move-hook nil)
  16635. (calendar-view-holidays-initially-flag nil)
  16636. (calendar-view-diary-initially-flag nil))
  16637. (when (or (org-at-timestamp-p)
  16638. (save-excursion
  16639. (beginning-of-line 1)
  16640. (looking-at (concat ".*" tsr))))
  16641. (let ((d1 (time-to-days (current-time)))
  16642. (d2 (time-to-days
  16643. (org-time-string-to-time (match-string 1)))))
  16644. (setq diff (- d2 d1))))
  16645. (calendar)
  16646. (calendar-goto-today)
  16647. (when (and diff (not arg)) (calendar-forward-day diff))))
  16648. (defun org-get-date-from-calendar ()
  16649. "Return a list (month day year) of date at point in calendar."
  16650. (with-current-buffer "*Calendar*"
  16651. (save-match-data
  16652. (calendar-cursor-to-date))))
  16653. (defun org-date-from-calendar ()
  16654. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  16655. If there is already a time stamp at the cursor position, update it."
  16656. (interactive)
  16657. (if (org-at-timestamp-p t)
  16658. (org-timestamp-change 0 'calendar)
  16659. (let ((cal-date (org-get-date-from-calendar)))
  16660. (org-insert-time-stamp
  16661. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  16662. (defcustom org-effort-durations
  16663. `(("min" . 1)
  16664. ("h" . 60)
  16665. ("d" . ,(* 60 8))
  16666. ("w" . ,(* 60 8 5))
  16667. ("m" . ,(* 60 8 5 4))
  16668. ("y" . ,(* 60 8 5 40)))
  16669. "Conversion factor to minutes for an effort modifier.
  16670. Each entry has the form (MODIFIER . MINUTES).
  16671. In an effort string, a number followed by MODIFIER is multiplied
  16672. by the specified number of MINUTES to obtain an effort in
  16673. minutes.
  16674. For example, if the value of this variable is ((\"hours\" . 60)), then an
  16675. effort string \"2hours\" is equivalent to 120 minutes."
  16676. :group 'org-agenda
  16677. :version "26.1"
  16678. :package-version '(Org . "8.3")
  16679. :type '(alist :key-type (string :tag "Modifier")
  16680. :value-type (number :tag "Minutes")))
  16681. (defun org-minutes-to-clocksum-string (m)
  16682. "Format number of minutes as a clocksum string.
  16683. The format is determined by `org-time-clocksum-format',
  16684. `org-time-clocksum-use-fractional' and
  16685. `org-time-clocksum-fractional-format' and
  16686. `org-time-clocksum-use-effort-durations'."
  16687. (let ((clocksum "")
  16688. (m (round m)) ; Don't allow fractions of minutes
  16689. h d w mo y fmt n)
  16690. (setq h (if org-time-clocksum-use-effort-durations
  16691. (cdr (assoc "h" org-effort-durations)) 60)
  16692. d (if org-time-clocksum-use-effort-durations
  16693. (/ (cdr (assoc "d" org-effort-durations)) h) 24)
  16694. w (if org-time-clocksum-use-effort-durations
  16695. (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
  16696. mo (if org-time-clocksum-use-effort-durations
  16697. (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
  16698. y (if org-time-clocksum-use-effort-durations
  16699. (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
  16700. ;; fractional format
  16701. (if org-time-clocksum-use-fractional
  16702. (cond
  16703. ;; single format string
  16704. ((stringp org-time-clocksum-fractional-format)
  16705. (format org-time-clocksum-fractional-format (/ m (float h))))
  16706. ;; choice of fractional formats for different time units
  16707. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16708. (> (/ (truncate m) (* y d h)) 0))
  16709. (format fmt (/ m (* y d (float h)))))
  16710. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16711. (> (/ (truncate m) (* mo d h)) 0))
  16712. (format fmt (/ m (* mo d (float h)))))
  16713. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16714. (> (/ (truncate m) (* w d h)) 0))
  16715. (format fmt (/ m (* w d (float h)))))
  16716. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16717. (> (/ (truncate m) (* d h)) 0))
  16718. (format fmt (/ m (* d (float h)))))
  16719. ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16720. (> (/ (truncate m) h) 0))
  16721. (format fmt (/ m (float h))))
  16722. ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
  16723. (format fmt m))
  16724. ;; fall back to smallest time unit with a format
  16725. ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
  16726. (format fmt (/ m (float h))))
  16727. ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
  16728. (format fmt (/ m (* d (float h)))))
  16729. ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
  16730. (format fmt (/ m (* w d (float h)))))
  16731. ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
  16732. (format fmt (/ m (* mo d (float h)))))
  16733. ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
  16734. (format fmt (/ m (* y d (float h))))))
  16735. ;; standard (non-fractional) format, with single format string
  16736. (if (stringp org-time-clocksum-format)
  16737. (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
  16738. ;; separate formats components
  16739. (and (setq fmt (plist-get org-time-clocksum-format :years))
  16740. (or (> (setq n (/ (truncate m) (* y d h))) 0)
  16741. (plist-get org-time-clocksum-format :require-years))
  16742. (setq clocksum (concat clocksum (format fmt n))
  16743. m (- m (* n y d h))))
  16744. (and (setq fmt (plist-get org-time-clocksum-format :months))
  16745. (or (> (setq n (/ (truncate m) (* mo d h))) 0)
  16746. (plist-get org-time-clocksum-format :require-months))
  16747. (setq clocksum (concat clocksum (format fmt n))
  16748. m (- m (* n mo d h))))
  16749. (and (setq fmt (plist-get org-time-clocksum-format :weeks))
  16750. (or (> (setq n (/ (truncate m) (* w d h))) 0)
  16751. (plist-get org-time-clocksum-format :require-weeks))
  16752. (setq clocksum (concat clocksum (format fmt n))
  16753. m (- m (* n w d h))))
  16754. (and (setq fmt (plist-get org-time-clocksum-format :days))
  16755. (or (> (setq n (/ (truncate m) (* d h))) 0)
  16756. (plist-get org-time-clocksum-format :require-days))
  16757. (setq clocksum (concat clocksum (format fmt n))
  16758. m (- m (* n d h))))
  16759. (and (setq fmt (plist-get org-time-clocksum-format :hours))
  16760. (or (> (setq n (/ (truncate m) h)) 0)
  16761. (plist-get org-time-clocksum-format :require-hours))
  16762. (setq clocksum (concat clocksum (format fmt n))
  16763. m (- m (* n h))))
  16764. (and (setq fmt (plist-get org-time-clocksum-format :minutes))
  16765. (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
  16766. (setq clocksum (concat clocksum (format fmt m))))
  16767. ;; return formatted time duration
  16768. clocksum))))
  16769. (defun org-hours-to-clocksum-string (n)
  16770. (org-minutes-to-clocksum-string (* n 60)))
  16771. (defun org-hh:mm-string-to-minutes (s)
  16772. "Convert a string H:MM to a number of minutes.
  16773. If the string is just a number, interpret it as minutes.
  16774. In fact, the first hh:mm or number in the string will be taken,
  16775. there can be extra stuff in the string.
  16776. If no number is found, the return value is 0."
  16777. (cond
  16778. ((integerp s) s)
  16779. ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
  16780. (+ (* (string-to-number (match-string 1 s)) 60)
  16781. (string-to-number (match-string 2 s))))
  16782. ((string-match "\\([0-9]+\\)" s)
  16783. (string-to-number (match-string 1 s)))
  16784. (t 0)))
  16785. (defcustom org-image-actual-width t
  16786. "Should we use the actual width of images when inlining them?
  16787. When set to t, always use the image width.
  16788. When set to a number, use imagemagick (when available) to set
  16789. the image's width to this value.
  16790. When set to a number in a list, try to get the width from any
  16791. #+ATTR.* keyword if it matches a width specification like
  16792. #+ATTR_HTML: :width 300px
  16793. and fall back on that number if none is found.
  16794. When set to nil, try to get the width from an #+ATTR.* keyword
  16795. and fall back on the original width if none is found.
  16796. This requires Emacs >= 24.1, build with imagemagick support."
  16797. :group 'org-appearance
  16798. :version "24.4"
  16799. :package-version '(Org . "8.0")
  16800. :type '(choice
  16801. (const :tag "Use the image width" t)
  16802. (integer :tag "Use a number of pixels")
  16803. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  16804. (const :tag "Use #+ATTR* or don't resize" nil)))
  16805. (defcustom org-agenda-inhibit-startup nil
  16806. "Inhibit startup when preparing agenda buffers.
  16807. When this variable is t, the initialization of the Org agenda
  16808. buffers is inhibited: e.g. the visibility state is not set, the
  16809. tables are not re-aligned, etc."
  16810. :type 'boolean
  16811. :version "24.3"
  16812. :group 'org-agenda)
  16813. (defcustom org-agenda-ignore-properties nil
  16814. "Avoid updating text properties when building the agenda.
  16815. Properties are used to prepare buffers for effort estimates,
  16816. appointments, statistics and subtree-local categories.
  16817. If you don't use these in the agenda, you can add them to this
  16818. list and agenda building will be a bit faster.
  16819. The value is a list, with zero or more of the symbols `effort', `appt',
  16820. `stats' or `category'."
  16821. :type '(set :greedy t
  16822. (const effort)
  16823. (const appt)
  16824. (const stats)
  16825. (const category))
  16826. :version "26.1"
  16827. :package-version '(Org . "8.3")
  16828. :group 'org-agenda)
  16829. (defun org-duration-string-to-minutes (s &optional output-to-string)
  16830. "Convert a duration string S to minutes.
  16831. A bare number is interpreted as minutes, modifiers can be set by
  16832. customizing `org-effort-durations' (which see).
  16833. Entries containing a colon are interpreted as H:MM by
  16834. `org-hh:mm-string-to-minutes'."
  16835. (let ((result 0)
  16836. (re (concat "\\([0-9.]+\\) *\\("
  16837. (regexp-opt (mapcar 'car org-effort-durations))
  16838. "\\)")))
  16839. (while (string-match re s)
  16840. (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
  16841. (string-to-number (match-string 1 s))))
  16842. (setq s (replace-match "" nil t s)))
  16843. (setq result (floor result))
  16844. (cl-incf result (org-hh:mm-string-to-minutes s))
  16845. (if output-to-string (number-to-string result) result)))
  16846. ;;;; Files
  16847. (defun org-save-all-org-buffers ()
  16848. "Save all Org buffers without user confirmation."
  16849. (interactive)
  16850. (message "Saving all Org buffers...")
  16851. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  16852. (when (featurep 'org-id) (org-id-locations-save))
  16853. (message "Saving all Org buffers... done"))
  16854. (defun org-revert-all-org-buffers ()
  16855. "Revert all Org buffers.
  16856. Prompt for confirmation when there are unsaved changes.
  16857. Be sure you know what you are doing before letting this function
  16858. overwrite your changes.
  16859. This function is useful in a setup where one tracks org files
  16860. with a version control system, to revert on one machine after pulling
  16861. changes from another. I believe the procedure must be like this:
  16862. 1. M-x org-save-all-org-buffers
  16863. 2. Pull changes from the other machine, resolve conflicts
  16864. 3. M-x org-revert-all-org-buffers"
  16865. (interactive)
  16866. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  16867. (user-error "Abort"))
  16868. (save-excursion
  16869. (save-window-excursion
  16870. (dolist (b (buffer-list))
  16871. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  16872. (with-current-buffer b buffer-file-name))
  16873. (pop-to-buffer-same-window b)
  16874. (revert-buffer t 'no-confirm)))
  16875. (when (and (featurep 'org-id) org-id-track-globally)
  16876. (org-id-locations-load)))))
  16877. ;;;; Agenda files
  16878. ;;;###autoload
  16879. (defun org-switchb (&optional arg)
  16880. "Switch between Org buffers.
  16881. With `\\[universal-argument]' prefix, restrict available buffers to files.
  16882. With `\\[universal-argument] \\[universal-argument]' \
  16883. prefix, restrict available buffers to agenda files."
  16884. (interactive "P")
  16885. (let ((blist (org-buffer-list
  16886. (cond ((equal arg '(4)) 'files)
  16887. ((equal arg '(16)) 'agenda)))))
  16888. (pop-to-buffer-same-window
  16889. (completing-read "Org buffer: "
  16890. (mapcar #'list (mapcar #'buffer-name blist))
  16891. nil t))))
  16892. (defun org-buffer-list (&optional predicate exclude-tmp)
  16893. "Return a list of Org buffers.
  16894. PREDICATE can be `export', `files' or `agenda'.
  16895. export restrict the list to Export buffers.
  16896. files restrict the list to buffers visiting Org files.
  16897. agenda restrict the list to buffers visiting agenda files.
  16898. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  16899. (let* ((bfn nil)
  16900. (agenda-files (and (eq predicate 'agenda)
  16901. (mapcar 'file-truename (org-agenda-files t))))
  16902. (filter
  16903. (cond
  16904. ((eq predicate 'files)
  16905. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  16906. ((eq predicate 'export)
  16907. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  16908. ((eq predicate 'agenda)
  16909. (lambda (b)
  16910. (with-current-buffer b
  16911. (and (derived-mode-p 'org-mode)
  16912. (setq bfn (buffer-file-name b))
  16913. (member (file-truename bfn) agenda-files)))))
  16914. (t (lambda (b) (with-current-buffer b
  16915. (or (derived-mode-p 'org-mode)
  16916. (string-match "\\*Org .*Export"
  16917. (buffer-name b)))))))))
  16918. (delq nil
  16919. (mapcar
  16920. (lambda(b)
  16921. (if (and (funcall filter b)
  16922. (or (not exclude-tmp)
  16923. (not (string-match "tmp" (buffer-name b)))))
  16924. b
  16925. nil))
  16926. (buffer-list)))))
  16927. (defun org-agenda-files (&optional unrestricted archives)
  16928. "Get the list of agenda files.
  16929. Optional UNRESTRICTED means return the full list even if a restriction
  16930. is currently in place.
  16931. When ARCHIVES is t, include all archive files that are really being
  16932. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  16933. `org-agenda-archives-mode' is t."
  16934. (let ((files
  16935. (cond
  16936. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  16937. ((stringp org-agenda-files) (org-read-agenda-file-list))
  16938. ((listp org-agenda-files) org-agenda-files)
  16939. (t (error "Invalid value of `org-agenda-files'")))))
  16940. (setq files (apply 'append
  16941. (mapcar (lambda (f)
  16942. (if (file-directory-p f)
  16943. (directory-files
  16944. f t org-agenda-file-regexp)
  16945. (list f)))
  16946. files)))
  16947. (when org-agenda-skip-unavailable-files
  16948. (setq files (delq nil
  16949. (mapcar (function
  16950. (lambda (file)
  16951. (and (file-readable-p file) file)))
  16952. files))))
  16953. (when (or (eq archives t)
  16954. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  16955. (setq files (org-add-archive-files files)))
  16956. files))
  16957. (defun org-agenda-file-p (&optional file)
  16958. "Return non-nil, if FILE is an agenda file.
  16959. If FILE is omitted, use the file associated with the current
  16960. buffer."
  16961. (let ((fname (or file (buffer-file-name))))
  16962. (and fname
  16963. (member (file-truename fname)
  16964. (mapcar #'file-truename (org-agenda-files t))))))
  16965. (defun org-edit-agenda-file-list ()
  16966. "Edit the list of agenda files.
  16967. Depending on setup, this either uses customize to edit the variable
  16968. `org-agenda-files', or it visits the file that is holding the list. In the
  16969. latter case, the buffer is set up in a way that saving it automatically kills
  16970. the buffer and restores the previous window configuration."
  16971. (interactive)
  16972. (if (stringp org-agenda-files)
  16973. (let ((cw (current-window-configuration)))
  16974. (find-file org-agenda-files)
  16975. (setq-local org-window-configuration cw)
  16976. (add-hook 'after-save-hook
  16977. (lambda ()
  16978. (set-window-configuration
  16979. (prog1 org-window-configuration
  16980. (kill-buffer (current-buffer))))
  16981. (org-install-agenda-files-menu)
  16982. (message "New agenda file list installed"))
  16983. nil 'local)
  16984. (message "%s" (substitute-command-keys
  16985. "Edit list and finish with \\[save-buffer]")))
  16986. (customize-variable 'org-agenda-files)))
  16987. (defun org-store-new-agenda-file-list (list)
  16988. "Set new value for the agenda file list and save it correctly."
  16989. (if (stringp org-agenda-files)
  16990. (let ((fe (org-read-agenda-file-list t)) b u)
  16991. (while (setq b (find-buffer-visiting org-agenda-files))
  16992. (kill-buffer b))
  16993. (with-temp-file org-agenda-files
  16994. (insert
  16995. (mapconcat
  16996. (lambda (f) ;; Keep un-expanded entries.
  16997. (if (setq u (assoc f fe))
  16998. (cdr u)
  16999. f))
  17000. list "\n")
  17001. "\n")))
  17002. (let ((org-mode-hook nil) (org-inhibit-startup t)
  17003. (org-insert-mode-line-in-empty-file nil))
  17004. (setq org-agenda-files list)
  17005. (customize-save-variable 'org-agenda-files org-agenda-files))))
  17006. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  17007. "Read the list of agenda files from a file.
  17008. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  17009. filenames, used by `org-store-new-agenda-file-list' to write back
  17010. un-expanded file names."
  17011. (when (file-directory-p org-agenda-files)
  17012. (error "`org-agenda-files' cannot be a single directory"))
  17013. (when (stringp org-agenda-files)
  17014. (with-temp-buffer
  17015. (insert-file-contents org-agenda-files)
  17016. (mapcar
  17017. (lambda (f)
  17018. (let ((e (expand-file-name (substitute-in-file-name f)
  17019. org-directory)))
  17020. (if pair-with-expansion
  17021. (cons e f)
  17022. e)))
  17023. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  17024. ;;;###autoload
  17025. (defun org-cycle-agenda-files ()
  17026. "Cycle through the files in `org-agenda-files'.
  17027. If the current buffer visits an agenda file, find the next one in the list.
  17028. If the current buffer does not, find the first agenda file."
  17029. (interactive)
  17030. (let* ((fs (or (org-agenda-files t)
  17031. (user-error "No agenda files")))
  17032. (files (copy-sequence fs))
  17033. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  17034. file)
  17035. (when tcf
  17036. (while (and (setq file (pop files))
  17037. (not (equal (file-truename file) tcf)))))
  17038. (find-file (car (or files fs)))
  17039. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  17040. (defun org-agenda-file-to-front (&optional to-end)
  17041. "Move/add the current file to the top of the agenda file list.
  17042. If the file is not present in the list, it is added to the front. If it is
  17043. present, it is moved there. With optional argument TO-END, add/move to the
  17044. end of the list."
  17045. (interactive "P")
  17046. (let ((org-agenda-skip-unavailable-files nil)
  17047. (file-alist (mapcar (lambda (x)
  17048. (cons (file-truename x) x))
  17049. (org-agenda-files t)))
  17050. (ctf (file-truename
  17051. (or buffer-file-name
  17052. (user-error "Please save the current buffer to a file"))))
  17053. x had)
  17054. (setq x (assoc ctf file-alist) had x)
  17055. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  17056. (if to-end
  17057. (setq file-alist (append (delq x file-alist) (list x)))
  17058. (setq file-alist (cons x (delq x file-alist))))
  17059. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  17060. (org-install-agenda-files-menu)
  17061. (message "File %s to %s of agenda file list"
  17062. (if had "moved" "added") (if to-end "end" "front"))))
  17063. (defun org-remove-file (&optional file)
  17064. "Remove current file from the list of files in variable `org-agenda-files'.
  17065. These are the files which are being checked for agenda entries.
  17066. Optional argument FILE means use this file instead of the current."
  17067. (interactive)
  17068. (let* ((org-agenda-skip-unavailable-files nil)
  17069. (file (or file buffer-file-name
  17070. (user-error "Current buffer does not visit a file")))
  17071. (true-file (file-truename file))
  17072. (afile (abbreviate-file-name file))
  17073. (files (delq nil (mapcar
  17074. (lambda (x)
  17075. (unless (equal true-file
  17076. (file-truename x))
  17077. x))
  17078. (org-agenda-files t)))))
  17079. (if (not (= (length files) (length (org-agenda-files t))))
  17080. (progn
  17081. (org-store-new-agenda-file-list files)
  17082. (org-install-agenda-files-menu)
  17083. (message "Removed from Org Agenda list: %s" afile))
  17084. (message "File was not in list: %s (not removed)" afile))))
  17085. (defun org-file-menu-entry (file)
  17086. (vector file (list 'find-file file) t))
  17087. (defun org-check-agenda-file (file)
  17088. "Make sure FILE exists. If not, ask user what to do."
  17089. (unless (file-exists-p file)
  17090. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  17091. (abbreviate-file-name file))
  17092. (let ((r (downcase (read-char-exclusive))))
  17093. (cond
  17094. ((equal r ?r)
  17095. (org-remove-file file)
  17096. (throw 'nextfile t))
  17097. (t (user-error "Abort"))))))
  17098. (defun org-get-agenda-file-buffer (file)
  17099. "Get an agenda buffer visiting FILE.
  17100. If the buffer needs to be created, add it to the list of buffers
  17101. which might be released later."
  17102. (let ((buf (org-find-base-buffer-visiting file)))
  17103. (if buf
  17104. buf ; just return it
  17105. ;; Make a new buffer and remember it
  17106. (setq buf (find-file-noselect file))
  17107. (when buf (push buf org-agenda-new-buffers))
  17108. buf)))
  17109. (defun org-release-buffers (blist)
  17110. "Release all buffers in list, asking the user for confirmation when needed.
  17111. When a buffer is unmodified, it is just killed. When modified, it is saved
  17112. \(if the user agrees) and then killed."
  17113. (let (file)
  17114. (dolist (buf blist)
  17115. (setq file (buffer-file-name buf))
  17116. (when (and (buffer-modified-p buf)
  17117. file
  17118. (y-or-n-p (format "Save file %s? " file)))
  17119. (with-current-buffer buf (save-buffer)))
  17120. (kill-buffer buf))))
  17121. (defun org-agenda-prepare-buffers (files)
  17122. "Create buffers for all agenda files, protect archived trees and comments."
  17123. (interactive)
  17124. (let ((pa '(:org-archived t))
  17125. (pc '(:org-comment t))
  17126. (pall '(:org-archived t :org-comment t))
  17127. (inhibit-read-only t)
  17128. (org-inhibit-startup org-agenda-inhibit-startup)
  17129. (rea (concat ":" org-archive-tag ":"))
  17130. re pos)
  17131. (setq org-tag-alist-for-agenda nil
  17132. org-tag-groups-alist-for-agenda nil)
  17133. (save-excursion
  17134. (save-restriction
  17135. (dolist (file files)
  17136. (catch 'nextfile
  17137. (if (bufferp file)
  17138. (set-buffer file)
  17139. (org-check-agenda-file file)
  17140. (set-buffer (org-get-agenda-file-buffer file)))
  17141. (widen)
  17142. (org-set-regexps-and-options 'tags-only)
  17143. (setq pos (point))
  17144. (or (memq 'category org-agenda-ignore-properties)
  17145. (org-refresh-category-properties))
  17146. (or (memq 'stats org-agenda-ignore-properties)
  17147. (org-refresh-stats-properties))
  17148. (or (memq 'effort org-agenda-ignore-properties)
  17149. (org-refresh-effort-properties))
  17150. (or (memq 'appt org-agenda-ignore-properties)
  17151. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  17152. (setq org-todo-keywords-for-agenda
  17153. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  17154. (setq org-done-keywords-for-agenda
  17155. (append org-done-keywords-for-agenda org-done-keywords))
  17156. (setq org-todo-keyword-alist-for-agenda
  17157. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  17158. (setq org-tag-alist-for-agenda
  17159. (org-uniquify
  17160. (append org-tag-alist-for-agenda
  17161. org-current-tag-alist)))
  17162. ;; Merge current file's tag groups into global
  17163. ;; `org-tag-groups-alist-for-agenda'.
  17164. (when org-group-tags
  17165. (dolist (alist org-tag-groups-alist)
  17166. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  17167. (if old
  17168. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  17169. (push alist org-tag-groups-alist-for-agenda)))))
  17170. (org-with-silent-modifications
  17171. (save-excursion
  17172. (remove-text-properties (point-min) (point-max) pall)
  17173. (when org-agenda-skip-archived-trees
  17174. (goto-char (point-min))
  17175. (while (re-search-forward rea nil t)
  17176. (when (org-at-heading-p t)
  17177. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  17178. (goto-char (point-min))
  17179. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  17180. (while (re-search-forward re nil t)
  17181. (when (save-match-data (org-in-commented-heading-p t))
  17182. (add-text-properties
  17183. (match-beginning 0) (org-end-of-subtree t) pc)))))
  17184. (goto-char pos)))))
  17185. (setq org-todo-keywords-for-agenda
  17186. (org-uniquify org-todo-keywords-for-agenda))
  17187. (setq org-todo-keyword-alist-for-agenda
  17188. (org-uniquify org-todo-keyword-alist-for-agenda))))
  17189. ;;;; CDLaTeX minor mode
  17190. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  17191. "Keymap for the minor `org-cdlatex-mode'.")
  17192. (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
  17193. (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
  17194. (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
  17195. (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
  17196. (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
  17197. (defvar org-cdlatex-texmathp-advice-is-done nil
  17198. "Flag remembering if we have applied the advice to texmathp already.")
  17199. (define-minor-mode org-cdlatex-mode
  17200. "Toggle the minor `org-cdlatex-mode'.
  17201. This mode supports entering LaTeX environment and math in LaTeX fragments
  17202. in Org mode.
  17203. \\{org-cdlatex-mode-map}"
  17204. nil " OCDL" nil
  17205. (when org-cdlatex-mode
  17206. (require 'cdlatex)
  17207. (run-hooks 'cdlatex-mode-hook)
  17208. (cdlatex-compute-tables))
  17209. (unless org-cdlatex-texmathp-advice-is-done
  17210. (setq org-cdlatex-texmathp-advice-is-done t)
  17211. (defadvice texmathp (around org-math-always-on activate)
  17212. "Always return t in Org buffers.
  17213. This is because we want to insert math symbols without dollars even outside
  17214. the LaTeX math segments. If Org mode thinks that point is actually inside
  17215. an embedded LaTeX fragment, let `texmathp' do its job.
  17216. `\\[org-cdlatex-mode-map]'"
  17217. (interactive)
  17218. (let (p)
  17219. (cond
  17220. ((not (derived-mode-p 'org-mode)) ad-do-it)
  17221. ((eq this-command 'cdlatex-math-symbol)
  17222. (setq ad-return-value t
  17223. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  17224. (t
  17225. (let ((p (org-inside-LaTeX-fragment-p)))
  17226. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  17227. (setq ad-return-value t
  17228. texmathp-why '("Org mode embedded math" . 0))
  17229. (when p ad-do-it)))))))))
  17230. (defun turn-on-org-cdlatex ()
  17231. "Unconditionally turn on `org-cdlatex-mode'."
  17232. (org-cdlatex-mode 1))
  17233. (defun org-try-cdlatex-tab ()
  17234. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  17235. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  17236. - inside a LaTeX fragment, or
  17237. - after the first word in a line, where an abbreviation expansion could
  17238. insert a LaTeX environment."
  17239. (when org-cdlatex-mode
  17240. (cond
  17241. ;; Before any word on the line: No expansion possible.
  17242. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  17243. ;; Just after first word on the line: Expand it. Make sure it
  17244. ;; cannot happen on headlines, though.
  17245. ((save-excursion
  17246. (skip-chars-backward "a-zA-Z0-9*")
  17247. (skip-chars-backward " \t")
  17248. (and (bolp) (not (org-at-heading-p))))
  17249. (cdlatex-tab) t)
  17250. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  17251. (defun org-cdlatex-underscore-caret (&optional _arg)
  17252. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  17253. Revert to the normal definition outside of these fragments."
  17254. (interactive "P")
  17255. (if (org-inside-LaTeX-fragment-p)
  17256. (call-interactively 'cdlatex-sub-superscript)
  17257. (let (org-cdlatex-mode)
  17258. (call-interactively (key-binding (vector last-input-event))))))
  17259. (defun org-cdlatex-math-modify (&optional _arg)
  17260. "Execute `cdlatex-math-modify' in LaTeX fragments.
  17261. Revert to the normal definition outside of these fragments."
  17262. (interactive "P")
  17263. (if (org-inside-LaTeX-fragment-p)
  17264. (call-interactively 'cdlatex-math-modify)
  17265. (let (org-cdlatex-mode)
  17266. (call-interactively (key-binding (vector last-input-event))))))
  17267. (defun org-cdlatex-environment-indent (&optional environment item)
  17268. "Execute `cdlatex-environment' and indent the inserted environment.
  17269. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  17270. The inserted environment is indented to current indentation
  17271. unless point is at the beginning of the line, in which the
  17272. environment remains unintended."
  17273. (interactive)
  17274. ;; cdlatex-environment always return nil. Therefore, capture output
  17275. ;; first and determine if an environment was selected.
  17276. (let* ((beg (point-marker))
  17277. (end (copy-marker (point) t))
  17278. (inserted (progn
  17279. (ignore-errors (cdlatex-environment environment item))
  17280. (< beg end)))
  17281. ;; Figure out how many lines to move forward after the
  17282. ;; environment has been inserted.
  17283. (lines (when inserted
  17284. (save-excursion
  17285. (- (cl-loop while (< beg (point))
  17286. with x = 0
  17287. do (forward-line -1)
  17288. (cl-incf x)
  17289. finally return x)
  17290. (if (progn (goto-char beg)
  17291. (and (progn (skip-chars-forward " \t") (eolp))
  17292. (progn (skip-chars-backward " \t") (bolp))))
  17293. 1 0)))))
  17294. (env (org-trim (delete-and-extract-region beg end))))
  17295. (when inserted
  17296. ;; Get indentation of next line unless at column 0.
  17297. (let ((ind (if (bolp) 0
  17298. (save-excursion
  17299. (org-return-indent)
  17300. (prog1 (org-get-indentation)
  17301. (when (progn (skip-chars-forward " \t") (eolp))
  17302. (delete-region beg (point)))))))
  17303. (bol (progn (skip-chars-backward " \t") (bolp))))
  17304. ;; Insert a newline before environment unless at column zero
  17305. ;; to "escape" the current line. Insert a newline if
  17306. ;; something is one the same line as \end{ENVIRONMENT}.
  17307. (insert
  17308. (concat (unless bol "\n") env
  17309. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  17310. (unless (zerop ind)
  17311. (save-excursion
  17312. (goto-char beg)
  17313. (while (< (point) end)
  17314. (unless (eolp) (indent-line-to ind))
  17315. (forward-line))))
  17316. (goto-char beg)
  17317. (forward-line lines)
  17318. (indent-line-to ind)))
  17319. (set-marker beg nil)
  17320. (set-marker end nil)))
  17321. ;;;; LaTeX fragments
  17322. (defun org-inside-LaTeX-fragment-p ()
  17323. "Test if point is inside a LaTeX fragment.
  17324. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  17325. sequence appearing also before point.
  17326. Even though the matchers for math are configurable, this function assumes
  17327. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  17328. delimiters are skipped when they have been removed by customization.
  17329. The return value is nil, or a cons cell with the delimiter and the
  17330. position of this delimiter.
  17331. This function does a reasonably good job, but can locally be fooled by
  17332. for example currency specifications. For example it will assume being in
  17333. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  17334. fragments that are properly closed, but during editing, we have to live
  17335. with the uncertainty caused by missing closing delimiters. This function
  17336. looks only before point, not after."
  17337. (catch 'exit
  17338. (let ((pos (point))
  17339. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  17340. (lim (save-excursion (org-backward-paragraph) (point)))
  17341. dd-on str (start 0) m re)
  17342. (goto-char pos)
  17343. (when dodollar
  17344. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  17345. re (nth 1 (assoc "$" org-latex-regexps)))
  17346. (while (string-match re str start)
  17347. (cond
  17348. ((= (match-end 0) (length str))
  17349. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  17350. ((= (match-end 0) (- (length str) 5))
  17351. (throw 'exit nil))
  17352. (t (setq start (match-end 0))))))
  17353. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  17354. (goto-char pos)
  17355. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  17356. (and (match-beginning 2) (throw 'exit nil))
  17357. ;; count $$
  17358. (while (re-search-backward "\\$\\$" lim t)
  17359. (setq dd-on (not dd-on)))
  17360. (goto-char pos)
  17361. (when dd-on (cons "$$" m))))))
  17362. (defun org-inside-latex-macro-p ()
  17363. "Is point inside a LaTeX macro or its arguments?"
  17364. (save-match-data
  17365. (org-in-regexp
  17366. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  17367. (defun org--format-latex-make-overlay (beg end image &optional imagetype)
  17368. "Build an overlay between BEG and END using IMAGE file.
  17369. Argument IMAGETYPE is the extension of the displayed image,
  17370. as a string. It defaults to \"png\"."
  17371. (let ((ov (make-overlay beg end))
  17372. (imagetype (or (intern imagetype) 'png)))
  17373. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  17374. (overlay-put ov 'evaporate t)
  17375. (overlay-put ov
  17376. 'modification-hooks
  17377. (list (lambda (o _flag _beg _end &optional _l)
  17378. (delete-overlay o))))
  17379. (overlay-put ov
  17380. 'display
  17381. (list 'image :type imagetype :file image :ascent 'center))))
  17382. (defun org--list-latex-overlays (&optional beg end)
  17383. "List all Org LaTeX overlays in current buffer.
  17384. Limit to overlays between BEG and END when those are provided."
  17385. (cl-remove-if-not
  17386. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  17387. (overlays-in (or beg (point-min)) (or end (point-max)))))
  17388. (defun org-remove-latex-fragment-image-overlays (&optional beg end)
  17389. "Remove all overlays with LaTeX fragment images in current buffer.
  17390. When optional arguments BEG and END are non-nil, remove all
  17391. overlays between them instead. Return a non-nil value when some
  17392. overlays were removed, nil otherwise."
  17393. (let ((overlays (org--list-latex-overlays beg end)))
  17394. (mapc #'delete-overlay overlays)
  17395. overlays))
  17396. (defun org-toggle-latex-fragment (&optional arg)
  17397. "Preview the LaTeX fragment at point, or all locally or globally.
  17398. If the cursor is on a LaTeX fragment, create the image and overlay
  17399. it over the source code, if there is none. Remove it otherwise.
  17400. If there is no fragment at point, display all fragments in the
  17401. current section.
  17402. With prefix ARG, preview or clear image for all fragments in the
  17403. current subtree or in the whole buffer when used before the first
  17404. headline. With a prefix ARG `\\[universal-argument] \
  17405. \\[universal-argument]' preview or clear images
  17406. for all fragments in the buffer."
  17407. (interactive "P")
  17408. (when (display-graphic-p)
  17409. (catch 'exit
  17410. (save-excursion
  17411. (let (beg end msg)
  17412. (cond
  17413. ((or (equal arg '(16))
  17414. (and (equal arg '(4))
  17415. (org-with-limited-levels (org-before-first-heading-p))))
  17416. (if (org-remove-latex-fragment-image-overlays)
  17417. (progn (message "LaTeX fragments images removed from buffer")
  17418. (throw 'exit nil))
  17419. (setq msg "Creating images for buffer...")))
  17420. ((equal arg '(4))
  17421. (org-with-limited-levels (org-back-to-heading t))
  17422. (setq beg (point))
  17423. (setq end (progn (org-end-of-subtree t) (point)))
  17424. (if (org-remove-latex-fragment-image-overlays beg end)
  17425. (progn
  17426. (message "LaTeX fragment images removed from subtree")
  17427. (throw 'exit nil))
  17428. (setq msg "Creating images for subtree...")))
  17429. ((let ((datum (org-element-context)))
  17430. (when (memq (org-element-type datum)
  17431. '(latex-environment latex-fragment))
  17432. (setq beg (org-element-property :begin datum))
  17433. (setq end (org-element-property :end datum))
  17434. (if (org-remove-latex-fragment-image-overlays beg end)
  17435. (progn (message "LaTeX fragment image removed")
  17436. (throw 'exit nil))
  17437. (setq msg "Creating image...")))))
  17438. (t
  17439. (org-with-limited-levels
  17440. (setq beg (if (org-at-heading-p) (line-beginning-position)
  17441. (outline-previous-heading)
  17442. (point)))
  17443. (setq end (progn (outline-next-heading) (point)))
  17444. (if (org-remove-latex-fragment-image-overlays beg end)
  17445. (progn
  17446. (message "LaTeX fragment images removed from section")
  17447. (throw 'exit nil))
  17448. (setq msg "Creating images for section...")))))
  17449. (let ((file (buffer-file-name (buffer-base-buffer))))
  17450. (org-format-latex
  17451. (concat org-preview-latex-image-directory "org-ltximg")
  17452. beg end
  17453. ;; Emacs cannot overlay images from remote hosts. Create
  17454. ;; it in `temporary-file-directory' instead.
  17455. (if (or (not file) (file-remote-p file))
  17456. temporary-file-directory
  17457. default-directory)
  17458. 'overlays msg 'forbuffer org-preview-latex-default-process))
  17459. (message (concat msg "done")))))))
  17460. (defun org-format-latex
  17461. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  17462. "Replace LaTeX fragments with links to an image.
  17463. The function takes care of creating the replacement image.
  17464. Only consider fragments between BEG and END when those are
  17465. provided.
  17466. When optional argument OVERLAYS is non-nil, display the image on
  17467. top of the fragment instead of replacing it.
  17468. PROCESSING-TYPE is the conversion method to use, as a symbol.
  17469. Some of the options can be changed using the variable
  17470. `org-format-latex-options', which see."
  17471. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  17472. (unless (eq processing-type 'verbatim)
  17473. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  17474. (cnt 0)
  17475. checkdir-flag)
  17476. (goto-char (or beg (point-min)))
  17477. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  17478. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  17479. (overlay-recenter (or end (point-max))))
  17480. (while (re-search-forward math-regexp end t)
  17481. (unless (and overlays
  17482. (eq (get-char-property (point) 'org-overlay-type)
  17483. 'org-latex-overlay))
  17484. (let* ((context (org-element-context))
  17485. (type (org-element-type context)))
  17486. (when (memq type '(latex-environment latex-fragment))
  17487. (let ((block-type (eq type 'latex-environment))
  17488. (value (org-element-property :value context))
  17489. (beg (org-element-property :begin context))
  17490. (end (save-excursion
  17491. (goto-char (org-element-property :end context))
  17492. (skip-chars-backward " \r\t\n")
  17493. (point))))
  17494. (cond
  17495. ((eq processing-type 'mathjax)
  17496. ;; Prepare for MathJax processing.
  17497. (if (not (string-match "\\`\\$\\$?" value))
  17498. (goto-char end)
  17499. (delete-region beg end)
  17500. (if (string= (match-string 0 value) "$$")
  17501. (insert "\\[" (substring value 2 -2) "\\]")
  17502. (insert "\\(" (substring value 1 -1) "\\)"))))
  17503. ((assq processing-type org-preview-latex-process-alist)
  17504. ;; Process to an image.
  17505. (cl-incf cnt)
  17506. (goto-char beg)
  17507. (let* ((processing-info
  17508. (cdr (assq processing-type org-preview-latex-process-alist)))
  17509. (face (face-at-point))
  17510. ;; Get the colors from the face at point.
  17511. (fg
  17512. (let ((color (plist-get org-format-latex-options
  17513. :foreground)))
  17514. (if (and forbuffer (eq color 'auto))
  17515. (face-attribute face :foreground nil 'default)
  17516. color)))
  17517. (bg
  17518. (let ((color (plist-get org-format-latex-options
  17519. :background)))
  17520. (if (and forbuffer (eq color 'auto))
  17521. (face-attribute face :background nil 'default)
  17522. color)))
  17523. (hash (sha1 (prin1-to-string
  17524. (list org-format-latex-header
  17525. org-latex-default-packages-alist
  17526. org-latex-packages-alist
  17527. org-format-latex-options
  17528. forbuffer value fg bg))))
  17529. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  17530. (absprefix (expand-file-name prefix dir))
  17531. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  17532. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  17533. (sep (and block-type "\n\n"))
  17534. (link (concat sep "[[file:" linkfile "]]" sep))
  17535. (options
  17536. (org-combine-plists
  17537. org-format-latex-options
  17538. `(:foreground ,fg :background ,bg))))
  17539. (when msg (message msg cnt))
  17540. (unless checkdir-flag ; Ensure the directory exists.
  17541. (setq checkdir-flag t)
  17542. (let ((todir (file-name-directory absprefix)))
  17543. (unless (file-directory-p todir)
  17544. (make-directory todir t))))
  17545. (unless (file-exists-p movefile)
  17546. (org-create-formula-image
  17547. value movefile options forbuffer processing-type))
  17548. (if overlays
  17549. (progn
  17550. (dolist (o (overlays-in beg end))
  17551. (when (eq (overlay-get o 'org-overlay-type)
  17552. 'org-latex-overlay)
  17553. (delete-overlay o)))
  17554. (org--format-latex-make-overlay beg end movefile imagetype)
  17555. (goto-char end))
  17556. (delete-region beg end)
  17557. (insert
  17558. (org-add-props link
  17559. (list 'org-latex-src
  17560. (replace-regexp-in-string "\"" "" value)
  17561. 'org-latex-src-embed-type
  17562. (if block-type 'paragraph 'character)))))))
  17563. ((eq processing-type 'mathml)
  17564. ;; Process to MathML.
  17565. (unless (org-format-latex-mathml-available-p)
  17566. (user-error "LaTeX to MathML converter not configured"))
  17567. (cl-incf cnt)
  17568. (when msg (message msg cnt))
  17569. (goto-char beg)
  17570. (delete-region beg end)
  17571. (insert (org-format-latex-as-mathml
  17572. value block-type prefix dir)))
  17573. (t
  17574. (error "Unknown conversion process %s for LaTeX fragments"
  17575. processing-type)))))))))))
  17576. (defun org-create-math-formula (latex-frag &optional mathml-file)
  17577. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  17578. Use `org-latex-to-mathml-convert-command'. If the conversion is
  17579. sucessful, return the portion between \"<math...> </math>\"
  17580. elements otherwise return nil. When MATHML-FILE is specified,
  17581. write the results in to that file. When invoked as an
  17582. interactive command, prompt for LATEX-FRAG, with initial value
  17583. set to the current active region and echo the results for user
  17584. inspection."
  17585. (interactive (list (let ((frag (when (org-region-active-p)
  17586. (buffer-substring-no-properties
  17587. (region-beginning) (region-end)))))
  17588. (read-string "LaTeX Fragment: " frag nil frag))))
  17589. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  17590. (let* ((tmp-in-file
  17591. (let ((file (file-relative-name
  17592. (make-temp-name (expand-file-name "ltxmathml-in")))))
  17593. (write-region latex-frag nil file)
  17594. file))
  17595. (tmp-out-file (file-relative-name
  17596. (make-temp-name (expand-file-name "ltxmathml-out"))))
  17597. (cmd (format-spec
  17598. org-latex-to-mathml-convert-command
  17599. `((?j . ,(and org-latex-to-mathml-jar-file
  17600. (shell-quote-argument
  17601. (expand-file-name
  17602. org-latex-to-mathml-jar-file))))
  17603. (?I . ,(shell-quote-argument tmp-in-file))
  17604. (?i . ,latex-frag)
  17605. (?o . ,(shell-quote-argument tmp-out-file)))))
  17606. mathml shell-command-output)
  17607. (when (called-interactively-p 'any)
  17608. (unless (org-format-latex-mathml-available-p)
  17609. (user-error "LaTeX to MathML converter not configured")))
  17610. (message "Running %s" cmd)
  17611. (setq shell-command-output (shell-command-to-string cmd))
  17612. (setq mathml
  17613. (when (file-readable-p tmp-out-file)
  17614. (with-current-buffer (find-file-noselect tmp-out-file t)
  17615. (goto-char (point-min))
  17616. (when (re-search-forward
  17617. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  17618. (regexp-quote
  17619. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  17620. nil t)
  17621. (prog1 (match-string 0) (kill-buffer))))))
  17622. (cond
  17623. (mathml
  17624. (setq mathml
  17625. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  17626. (when mathml-file
  17627. (write-region mathml nil mathml-file))
  17628. (when (called-interactively-p 'any)
  17629. (message mathml)))
  17630. ((message "LaTeX to MathML conversion failed")
  17631. (message shell-command-output)))
  17632. (delete-file tmp-in-file)
  17633. (when (file-exists-p tmp-out-file)
  17634. (delete-file tmp-out-file))
  17635. mathml))
  17636. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  17637. prefix &optional dir)
  17638. "Use `org-create-math-formula' but check local cache first."
  17639. (let* ((absprefix (expand-file-name prefix dir))
  17640. (print-length nil) (print-level nil)
  17641. (formula-id (concat
  17642. "formula-"
  17643. (sha1
  17644. (prin1-to-string
  17645. (list latex-frag
  17646. org-latex-to-mathml-convert-command)))))
  17647. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  17648. (formula-cache-dir (file-name-directory formula-cache)))
  17649. (unless (file-directory-p formula-cache-dir)
  17650. (make-directory formula-cache-dir t))
  17651. (unless (file-exists-p formula-cache)
  17652. (org-create-math-formula latex-frag formula-cache))
  17653. (if (file-exists-p formula-cache)
  17654. ;; Successful conversion. Return the link to MathML file.
  17655. (org-add-props
  17656. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  17657. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  17658. 'org-latex-src-embed-type (if latex-frag-type
  17659. 'paragraph 'character)))
  17660. ;; Failed conversion. Return the LaTeX fragment verbatim
  17661. latex-frag)))
  17662. (defun org--get-display-dpi ()
  17663. "Get the DPI of the display.
  17664. The function assumes that the display has the same pixel width in
  17665. the horizontal and vertical directions."
  17666. (if (display-graphic-p)
  17667. (round (/ (display-pixel-height)
  17668. (/ (display-mm-height) 25.4)))
  17669. (error "Attempt to calculate the dpi of a non-graphic display")))
  17670. (defun org-create-formula-image
  17671. (string tofile options buffer &optional processing-type)
  17672. "Create an image from LaTeX source using external processes.
  17673. The LaTeX STRING is saved to a temporary LaTeX file, then
  17674. converted to an image file by process PROCESSING-TYPE defined in
  17675. `org-preview-latex-process-alist'. A nil value defaults to
  17676. `org-preview-latex-default-process'.
  17677. The generated image file is eventually moved to TOFILE.
  17678. The OPTIONS argument controls the size, foreground color and
  17679. background color of the generated image.
  17680. When BUFFER non-nil, this function is used for LaTeX previewing.
  17681. Otherwise, it is used to deal with LaTeX snippets showed in
  17682. a HTML file."
  17683. (let* ((processing-type (or processing-type
  17684. org-preview-latex-default-process))
  17685. (processing-info
  17686. (cdr (assq processing-type org-preview-latex-process-alist)))
  17687. (programs (plist-get processing-info :programs))
  17688. (error-message (or (plist-get processing-info :message) ""))
  17689. (use-xcolor (plist-get processing-info :use-xcolor))
  17690. (image-input-type (plist-get processing-info :image-input-type))
  17691. (image-output-type (plist-get processing-info :image-output-type))
  17692. (post-clean (or (plist-get processing-info :post-clean)
  17693. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  17694. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  17695. (latex-header
  17696. (or (plist-get processing-info :latex-header)
  17697. (org-latex-make-preamble
  17698. (org-export-get-environment (org-export-get-backend 'latex))
  17699. org-format-latex-header
  17700. 'snippet)))
  17701. (latex-compiler (plist-get processing-info :latex-compiler))
  17702. (image-converter (plist-get processing-info :image-converter))
  17703. (tmpdir temporary-file-directory)
  17704. (texfilebase (make-temp-name
  17705. (expand-file-name "orgtex" tmpdir)))
  17706. (texfile (concat texfilebase ".tex"))
  17707. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  17708. '(1.0 . 1.0)))
  17709. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  17710. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  17711. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  17712. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  17713. "Black"))
  17714. (bg (or (plist-get options (if buffer :background :html-background))
  17715. "Transparent"))
  17716. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  17717. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  17718. (dolist (program programs)
  17719. (org-check-external-command program error-message))
  17720. (if use-xcolor
  17721. (progn (if (eq fg 'default)
  17722. (setq fg (org-latex-color :foreground))
  17723. (setq fg (org-latex-color-format fg)))
  17724. (if (eq bg 'default)
  17725. (setq bg (org-latex-color :background))
  17726. (setq bg (org-latex-color-format
  17727. (if (string= bg "Transparent") "white" bg))))
  17728. (with-temp-file texfile
  17729. (insert latex-header)
  17730. (insert "\n\\begin{document}\n"
  17731. "\\definecolor{fg}{rgb}{" fg "}\n"
  17732. "\\definecolor{bg}{rgb}{" bg "}\n"
  17733. "\n\\pagecolor{bg}\n"
  17734. "\n{\\color{fg}\n"
  17735. string
  17736. "\n}\n"
  17737. "\n\\end{document}\n")))
  17738. (if (eq fg 'default)
  17739. (setq fg (org-dvipng-color :foreground))
  17740. (unless (string= fg "Transparent")
  17741. (setq fg (org-dvipng-color-format fg))))
  17742. (if (eq bg 'default)
  17743. (setq bg (org-dvipng-color :background))
  17744. (unless (string= bg "Transparent")
  17745. (setq bg (org-dvipng-color-format bg))))
  17746. (with-temp-file texfile
  17747. (insert latex-header)
  17748. (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
  17749. (let* ((err-msg (format "Please adjust `%s' part of \
  17750. `org-preview-latex-process-alist'."
  17751. processing-type))
  17752. (image-input-file
  17753. (org-compile-file
  17754. texfile latex-compiler image-input-type err-msg log-buf))
  17755. (image-output-file
  17756. (org-compile-file
  17757. image-input-file image-converter image-output-type err-msg log-buf
  17758. `((?F . ,(shell-quote-argument fg))
  17759. (?B . ,(shell-quote-argument bg))
  17760. (?D . ,(shell-quote-argument (format "%s" dpi)))
  17761. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  17762. (copy-file image-output-file tofile 'replace)
  17763. (dolist (e post-clean)
  17764. (when (file-exists-p (concat texfilebase e))
  17765. (delete-file (concat texfilebase e))))
  17766. image-output-file)))
  17767. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  17768. "Fill a LaTeX header template TPL.
  17769. In the template, the following place holders will be recognized:
  17770. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  17771. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  17772. [PACKAGES] \\usepackage statements for PKG
  17773. [NO-PACKAGES] do not include PKG
  17774. [EXTRA] the string EXTRA
  17775. [NO-EXTRA] do not include EXTRA
  17776. For backward compatibility, if both the positive and the negative place
  17777. holder is missing, the positive one (without the \"NO-\") will be
  17778. assumed to be present at the end of the template.
  17779. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  17780. EXTRA is a string.
  17781. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  17782. (let (rpl (end ""))
  17783. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  17784. (setq rpl (if (or (match-end 1) (not def-pkg))
  17785. "" (org-latex-packages-to-string def-pkg snippets-p t))
  17786. tpl (replace-match rpl t t tpl))
  17787. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  17788. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  17789. (setq rpl (if (or (match-end 1) (not pkg))
  17790. "" (org-latex-packages-to-string pkg snippets-p t))
  17791. tpl (replace-match rpl t t tpl))
  17792. (when pkg (setq end
  17793. (concat end "\n"
  17794. (org-latex-packages-to-string pkg snippets-p)))))
  17795. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  17796. (setq rpl (if (or (match-end 1) (not extra))
  17797. "" (concat extra "\n"))
  17798. tpl (replace-match rpl t t tpl))
  17799. (when (and extra (string-match "\\S-" extra))
  17800. (setq end (concat end "\n" extra))))
  17801. (if (string-match "\\S-" end)
  17802. (concat tpl "\n" end)
  17803. tpl)))
  17804. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  17805. "Turn an alist of packages into a string with the \\usepackage macros."
  17806. (setq pkg (mapconcat (lambda(p)
  17807. (cond
  17808. ((stringp p) p)
  17809. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  17810. (format "%% Package %s omitted" (cadr p)))
  17811. ((equal "" (car p))
  17812. (format "\\usepackage{%s}" (cadr p)))
  17813. (t
  17814. (format "\\usepackage[%s]{%s}"
  17815. (car p) (cadr p)))))
  17816. pkg
  17817. "\n"))
  17818. (if newline (concat pkg "\n") pkg))
  17819. (defun org-dvipng-color (attr)
  17820. "Return a RGB color specification for dvipng."
  17821. (org-dvipng-color-format (face-attribute 'default attr nil)))
  17822. (defun org-dvipng-color-format (color-name)
  17823. "Convert COLOR-NAME to a RGB color value for dvipng."
  17824. (apply #'format "rgb %s %s %s"
  17825. (mapcar 'org-normalize-color
  17826. (color-values color-name))))
  17827. (defun org-latex-color (attr)
  17828. "Return a RGB color for the LaTeX color package."
  17829. (org-latex-color-format (face-attribute 'default attr nil)))
  17830. (defun org-latex-color-format (color-name)
  17831. "Convert COLOR-NAME to a RGB color value."
  17832. (apply #'format "%s,%s,%s"
  17833. (mapcar 'org-normalize-color
  17834. (color-values color-name))))
  17835. (defun org-normalize-color (value)
  17836. "Return string to be used as color value for an RGB component."
  17837. (format "%g" (/ value 65535.0)))
  17838. ;; Image display
  17839. (defvar-local org-inline-image-overlays nil)
  17840. (defun org-toggle-inline-images (&optional include-linked)
  17841. "Toggle the display of inline images.
  17842. INCLUDE-LINKED is passed to `org-display-inline-images'."
  17843. (interactive "P")
  17844. (if org-inline-image-overlays
  17845. (progn
  17846. (org-remove-inline-images)
  17847. (when (called-interactively-p 'interactive)
  17848. (message "Inline image display turned off")))
  17849. (org-display-inline-images include-linked)
  17850. (when (called-interactively-p 'interactive)
  17851. (message (if org-inline-image-overlays
  17852. (format "%d images displayed inline"
  17853. (length org-inline-image-overlays))
  17854. "No images to display inline")))))
  17855. (defun org-redisplay-inline-images ()
  17856. "Refresh the display of inline images."
  17857. (interactive)
  17858. (if (not org-inline-image-overlays)
  17859. (org-toggle-inline-images)
  17860. (org-toggle-inline-images)
  17861. (org-toggle-inline-images)))
  17862. (defun org-display-inline-images (&optional include-linked refresh beg end)
  17863. "Display inline images.
  17864. An inline image is a link which follows either of these
  17865. conventions:
  17866. 1. Its path is a file with an extension matching return value
  17867. from `image-file-name-regexp' and it has no contents.
  17868. 2. Its description consists in a single link of the previous
  17869. type.
  17870. When optional argument INCLUDE-LINKED is non-nil, also links with
  17871. a text description part will be inlined. This can be nice for
  17872. a quick look at those images, but it does not reflect what
  17873. exported files will look like.
  17874. When optional argument REFRESH is non-nil, refresh existing
  17875. images between BEG and END. This will create new image displays
  17876. only if necessary. BEG and END default to the buffer
  17877. boundaries."
  17878. (interactive "P")
  17879. (when (display-graphic-p)
  17880. (unless refresh
  17881. (org-remove-inline-images)
  17882. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  17883. (org-with-wide-buffer
  17884. (goto-char (or beg (point-min)))
  17885. (let ((case-fold-search t)
  17886. (file-extension-re (image-file-name-regexp)))
  17887. (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
  17888. (let ((link (save-match-data (org-element-context))))
  17889. ;; Check if we're at an inline image.
  17890. (when (and (equal (org-element-property :type link) "file")
  17891. (or include-linked
  17892. (not (org-element-property :contents-begin link)))
  17893. (let ((parent (org-element-property :parent link)))
  17894. (or (not (eq (org-element-type parent) 'link))
  17895. (not (cdr (org-element-contents parent)))))
  17896. (string-match-p file-extension-re
  17897. (org-element-property :path link)))
  17898. (let ((file (expand-file-name
  17899. (org-link-unescape
  17900. (org-element-property :path link)))))
  17901. (when (file-exists-p file)
  17902. (let ((width
  17903. ;; Apply `org-image-actual-width' specifications.
  17904. (cond
  17905. ((not (image-type-available-p 'imagemagick)) nil)
  17906. ((eq org-image-actual-width t) nil)
  17907. ((listp org-image-actual-width)
  17908. (or
  17909. ;; First try to find a width among
  17910. ;; attributes associated to the paragraph
  17911. ;; containing link.
  17912. (let ((paragraph
  17913. (let ((e link))
  17914. (while (and (setq e (org-element-property
  17915. :parent e))
  17916. (not (eq (org-element-type e)
  17917. 'paragraph))))
  17918. e)))
  17919. (when paragraph
  17920. (save-excursion
  17921. (goto-char (org-element-property :begin paragraph))
  17922. (when
  17923. (re-search-forward
  17924. "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
  17925. (org-element-property
  17926. :post-affiliated paragraph)
  17927. t)
  17928. (string-to-number (match-string 1))))))
  17929. ;; Otherwise, fall-back to provided number.
  17930. (car org-image-actual-width)))
  17931. ((numberp org-image-actual-width)
  17932. org-image-actual-width)))
  17933. (old (get-char-property-and-overlay
  17934. (org-element-property :begin link)
  17935. 'org-image-overlay)))
  17936. (if (and (car-safe old) refresh)
  17937. (image-refresh (overlay-get (cdr old) 'display))
  17938. (let ((image (create-image file
  17939. (and width 'imagemagick)
  17940. nil
  17941. :width width)))
  17942. (when image
  17943. (let* ((link
  17944. ;; If inline image is the description
  17945. ;; of another link, be sure to
  17946. ;; consider the latter as the one to
  17947. ;; apply the overlay on.
  17948. (let ((parent
  17949. (org-element-property :parent link)))
  17950. (if (eq (org-element-type parent) 'link)
  17951. parent
  17952. link)))
  17953. (ov (make-overlay
  17954. (org-element-property :begin link)
  17955. (progn
  17956. (goto-char
  17957. (org-element-property :end link))
  17958. (skip-chars-backward " \t")
  17959. (point)))))
  17960. (overlay-put ov 'display image)
  17961. (overlay-put ov 'face 'default)
  17962. (overlay-put ov 'org-image-overlay t)
  17963. (overlay-put
  17964. ov 'modification-hooks
  17965. (list 'org-display-inline-remove-overlay))
  17966. (push ov org-inline-image-overlays)))))))))))))))
  17967. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  17968. "Remove inline-display overlay if a corresponding region is modified."
  17969. (let ((inhibit-modification-hooks t))
  17970. (when (and ov after)
  17971. (delete ov org-inline-image-overlays)
  17972. (delete-overlay ov))))
  17973. (defun org-remove-inline-images ()
  17974. "Remove inline display of images."
  17975. (interactive)
  17976. (mapc #'delete-overlay org-inline-image-overlays)
  17977. (setq org-inline-image-overlays nil))
  17978. ;;;; Key bindings
  17979. ;; Outline functions from `outline-mode-prefix-map'
  17980. ;; that can be remapped in Org:
  17981. (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
  17982. (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
  17983. (define-key org-mode-map [remap outline-forward-same-level]
  17984. 'org-forward-heading-same-level)
  17985. (define-key org-mode-map [remap outline-backward-same-level]
  17986. 'org-backward-heading-same-level)
  17987. (define-key org-mode-map [remap outline-show-branches]
  17988. 'org-kill-note-or-show-branches)
  17989. (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
  17990. (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
  17991. (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
  17992. (define-key org-mode-map [remap outline-next-visible-heading]
  17993. 'org-next-visible-heading)
  17994. (define-key org-mode-map [remap outline-previous-visible-heading]
  17995. 'org-previous-visible-heading)
  17996. (define-key org-mode-map [remap show-children] 'org-show-children)
  17997. ;; Outline functions from `outline-mode-prefix-map' that can not
  17998. ;; be remapped in Org:
  17999. ;; - the column "key binding" shows whether the Outline function is still
  18000. ;; available in Org mode on the same key that it has been bound to in
  18001. ;; Outline mode:
  18002. ;; - "overridden": key used for a different functionality in Org mode
  18003. ;; - else: key still bound to the same Outline function in Org mode
  18004. ;; | Outline function | key binding | Org replacement |
  18005. ;; |------------------------------------+-------------+--------------------------|
  18006. ;; | `outline-up-heading' | `C-c C-u' | still same function |
  18007. ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
  18008. ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
  18009. ;; | `show-entry' | overridden | no replacement |
  18010. ;; | `show-branches' | `C-c C-k' | still same function |
  18011. ;; | `show-subtree' | overridden | visibility cycling |
  18012. ;; | `show-all' | overridden | no replacement |
  18013. ;; | `hide-subtree' | overridden | visibility cycling |
  18014. ;; | `hide-body' | overridden | no replacement |
  18015. ;; | `hide-entry' | overridden | visibility cycling |
  18016. ;; | `hide-leaves' | overridden | no replacement |
  18017. ;; | `hide-sublevels' | overridden | no replacement |
  18018. ;; | `hide-other' | overridden | no replacement |
  18019. ;; Make `C-c C-x' a prefix key
  18020. (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
  18021. ;; TAB key with modifiers
  18022. (org-defkey org-mode-map "\C-i" 'org-cycle)
  18023. (org-defkey org-mode-map [(tab)] 'org-cycle)
  18024. (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
  18025. (org-defkey org-mode-map "\M-\t" #'pcomplete)
  18026. ;; The following line is necessary under Suse GNU/Linux
  18027. (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
  18028. (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
  18029. (define-key org-mode-map [backtab] 'org-shifttab)
  18030. (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
  18031. (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
  18032. (org-defkey org-mode-map [(meta return)] 'org-meta-return)
  18033. ;; Cursor keys with modifiers
  18034. (org-defkey org-mode-map [(meta left)] 'org-metaleft)
  18035. (org-defkey org-mode-map [(meta right)] 'org-metaright)
  18036. (org-defkey org-mode-map [(meta up)] 'org-metaup)
  18037. (org-defkey org-mode-map [(meta down)] 'org-metadown)
  18038. (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
  18039. (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
  18040. (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
  18041. (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
  18042. (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
  18043. (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
  18044. (org-defkey org-mode-map [(shift up)] 'org-shiftup)
  18045. (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
  18046. (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
  18047. (org-defkey org-mode-map [(shift right)] 'org-shiftright)
  18048. (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
  18049. (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
  18050. (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
  18051. (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
  18052. ;; Babel keys
  18053. (define-key org-mode-map org-babel-key-prefix org-babel-map)
  18054. (dolist (pair org-babel-key-bindings)
  18055. (define-key org-babel-map (car pair) (cdr pair)))
  18056. ;;; Extra keys for tty access.
  18057. ;; We only set them when really needed because otherwise the
  18058. ;; menus don't show the simple keys
  18059. (when (or org-use-extra-keys (not window-system))
  18060. (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
  18061. (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
  18062. (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
  18063. (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
  18064. (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
  18065. (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
  18066. (org-defkey org-mode-map [?\e (right)] 'org-metaright)
  18067. (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
  18068. (org-defkey org-mode-map [?\e (up)] 'org-metaup)
  18069. (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
  18070. (org-defkey org-mode-map [?\e (down)] 'org-metadown)
  18071. (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
  18072. (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
  18073. (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
  18074. (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
  18075. (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
  18076. (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
  18077. (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
  18078. (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
  18079. (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
  18080. (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
  18081. (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
  18082. (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
  18083. (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
  18084. (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
  18085. (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
  18086. (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
  18087. (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
  18088. ;; All the other keys
  18089. (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
  18090. (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
  18091. (if (boundp 'narrow-map)
  18092. (org-defkey narrow-map "s" 'org-narrow-to-subtree)
  18093. (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
  18094. (if (boundp 'narrow-map)
  18095. (org-defkey narrow-map "b" 'org-narrow-to-block)
  18096. (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
  18097. (if (boundp 'narrow-map)
  18098. (org-defkey narrow-map "e" 'org-narrow-to-element)
  18099. (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
  18100. (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
  18101. (org-defkey org-mode-map "\M-}" 'org-forward-element)
  18102. (org-defkey org-mode-map "\M-{" 'org-backward-element)
  18103. (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
  18104. (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
  18105. (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
  18106. (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
  18107. (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
  18108. (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
  18109. (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
  18110. (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
  18111. (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
  18112. (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
  18113. (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
  18114. (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
  18115. (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
  18116. (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
  18117. (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
  18118. (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
  18119. (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
  18120. (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
  18121. (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
  18122. (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
  18123. (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
  18124. (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
  18125. (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
  18126. (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
  18127. (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
  18128. (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
  18129. (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
  18130. (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
  18131. (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
  18132. (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
  18133. (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
  18134. (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
  18135. (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
  18136. (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
  18137. (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
  18138. (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
  18139. (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
  18140. (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
  18141. (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
  18142. (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
  18143. (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
  18144. (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
  18145. (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
  18146. (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
  18147. (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
  18148. (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
  18149. (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
  18150. (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
  18151. (org-defkey org-mode-map "\C-c]" 'org-remove-file)
  18152. (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
  18153. (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  18154. (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
  18155. (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
  18156. (org-defkey org-mode-map "\C-c^" 'org-sort)
  18157. (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
  18158. (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
  18159. (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
  18160. (org-defkey org-mode-map [remap open-line] 'org-open-line)
  18161. (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
  18162. (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
  18163. (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
  18164. (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
  18165. (org-defkey org-mode-map "\C-m" 'org-return)
  18166. (org-defkey org-mode-map "\C-j" 'org-return-indent)
  18167. (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
  18168. (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
  18169. (org-defkey org-mode-map "\C-c+" 'org-table-sum)
  18170. (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
  18171. (org-defkey org-mode-map "\C-c'" 'org-edit-special)
  18172. (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
  18173. (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
  18174. (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
  18175. (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
  18176. (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
  18177. (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
  18178. (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
  18179. (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
  18180. (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
  18181. (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
  18182. (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
  18183. (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
  18184. (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
  18185. (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
  18186. (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
  18187. (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
  18188. (org-defkey org-mode-map "\M-h" 'org-mark-element)
  18189. (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
  18190. ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
  18191. (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
  18192. (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
  18193. (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
  18194. (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
  18195. (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
  18196. (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
  18197. (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
  18198. (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
  18199. (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
  18200. (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
  18201. (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
  18202. (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
  18203. (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
  18204. (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
  18205. (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
  18206. (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
  18207. (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
  18208. (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
  18209. (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
  18210. (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
  18211. (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
  18212. (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
  18213. (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
  18214. (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
  18215. (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
  18216. (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
  18217. (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
  18218. (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
  18219. (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
  18220. (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
  18221. (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
  18222. (define-key org-mode-map "\C-c\C-x!" 'org-reload)
  18223. (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
  18224. (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
  18225. (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
  18226. (defconst org-speed-commands-default
  18227. '(
  18228. ("Outline Navigation")
  18229. ("n" . (org-speed-move-safe 'org-next-visible-heading))
  18230. ("p" . (org-speed-move-safe 'org-previous-visible-heading))
  18231. ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
  18232. ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
  18233. ("F" . org-next-block)
  18234. ("B" . org-previous-block)
  18235. ("u" . (org-speed-move-safe 'outline-up-heading))
  18236. ("j" . org-goto)
  18237. ("g" . (org-refile t))
  18238. ("Outline Visibility")
  18239. ("c" . org-cycle)
  18240. ("C" . org-shifttab)
  18241. (" " . org-display-outline-path)
  18242. ("s" . org-narrow-to-subtree)
  18243. ("=" . org-columns)
  18244. ("Outline Structure Editing")
  18245. ("U" . org-metaup)
  18246. ("D" . org-metadown)
  18247. ("r" . org-metaright)
  18248. ("l" . org-metaleft)
  18249. ("R" . org-shiftmetaright)
  18250. ("L" . org-shiftmetaleft)
  18251. ("i" . (progn (forward-char 1) (call-interactively
  18252. 'org-insert-heading-respect-content)))
  18253. ("^" . org-sort)
  18254. ("w" . org-refile)
  18255. ("a" . org-archive-subtree-default-with-confirmation)
  18256. ("@" . org-mark-subtree)
  18257. ("#" . org-toggle-comment)
  18258. ("Clock Commands")
  18259. ("I" . org-clock-in)
  18260. ("O" . org-clock-out)
  18261. ("Meta Data Editing")
  18262. ("t" . org-todo)
  18263. ("," . (org-priority))
  18264. ("0" . (org-priority ?\ ))
  18265. ("1" . (org-priority ?A))
  18266. ("2" . (org-priority ?B))
  18267. ("3" . (org-priority ?C))
  18268. (":" . org-set-tags-command)
  18269. ("e" . org-set-effort)
  18270. ("E" . org-inc-effort)
  18271. ("W" . (lambda(m) (interactive "sMinutes before warning: ")
  18272. (org-entry-put (point) "APPT_WARNTIME" m)))
  18273. ("Agenda Views etc")
  18274. ("v" . org-agenda)
  18275. ("/" . org-sparse-tree)
  18276. ("Misc")
  18277. ("o" . org-open-at-point)
  18278. ("?" . org-speed-command-help)
  18279. ("<" . (org-agenda-set-restriction-lock 'subtree))
  18280. (">" . (org-agenda-remove-restriction-lock))
  18281. )
  18282. "The default speed commands.")
  18283. (defun org-print-speed-command (e)
  18284. (if (> (length (car e)) 1)
  18285. (progn
  18286. (princ "\n")
  18287. (princ (car e))
  18288. (princ "\n")
  18289. (princ (make-string (length (car e)) ?-))
  18290. (princ "\n"))
  18291. (princ (car e))
  18292. (princ " ")
  18293. (if (symbolp (cdr e))
  18294. (princ (symbol-name (cdr e)))
  18295. (prin1 (cdr e)))
  18296. (princ "\n")))
  18297. (defun org-speed-command-help ()
  18298. "Show the available speed commands."
  18299. (interactive)
  18300. (if (not org-use-speed-commands)
  18301. (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
  18302. (with-output-to-temp-buffer "*Help*"
  18303. (princ "User-defined Speed commands\n===========================\n")
  18304. (mapc #'org-print-speed-command org-speed-commands-user)
  18305. (princ "\n")
  18306. (princ "Built-in Speed commands\n=======================\n")
  18307. (mapc #'org-print-speed-command org-speed-commands-default))
  18308. (with-current-buffer "*Help*"
  18309. (setq truncate-lines t))))
  18310. (defun org-speed-move-safe (cmd)
  18311. "Execute CMD, but make sure that the cursor always ends up in a headline.
  18312. If not, return to the original position and throw an error."
  18313. (interactive)
  18314. (let ((pos (point)))
  18315. (call-interactively cmd)
  18316. (unless (and (bolp) (org-at-heading-p))
  18317. (goto-char pos)
  18318. (error "Boundary reached while executing %s" cmd))))
  18319. (defvar org-self-insert-command-undo-counter 0)
  18320. (defvar org-table-auto-blank-field) ; defined in org-table.el
  18321. (defvar org-speed-command nil)
  18322. (defun org-speed-command-activate (keys)
  18323. "Hook for activating single-letter speed commands.
  18324. `org-speed-commands-default' specifies a minimal command set.
  18325. Use `org-speed-commands-user' for further customization."
  18326. (when (or (and (bolp) (looking-at org-outline-regexp))
  18327. (and (functionp org-use-speed-commands)
  18328. (funcall org-use-speed-commands)))
  18329. (cdr (assoc keys (append org-speed-commands-user
  18330. org-speed-commands-default)))))
  18331. (defun org-babel-speed-command-activate (keys)
  18332. "Hook for activating single-letter code block commands."
  18333. (when (and (bolp) (looking-at org-babel-src-block-regexp))
  18334. (cdr (assoc keys org-babel-key-bindings))))
  18335. (defcustom org-speed-command-hook
  18336. '(org-speed-command-default-hook org-babel-speed-command-hook)
  18337. "Hook for activating speed commands at strategic locations.
  18338. Hook functions are called in sequence until a valid handler is
  18339. found.
  18340. Each hook takes a single argument, a user-pressed command key
  18341. which is also a `self-insert-command' from the global map.
  18342. Within the hook, examine the cursor position and the command key
  18343. and return nil or a valid handler as appropriate. Handler could
  18344. be one of an interactive command, a function, or a form.
  18345. Set `org-use-speed-commands' to non-nil value to enable this
  18346. hook. The default setting is `org-speed-command-activate'."
  18347. :group 'org-structure
  18348. :version "24.1"
  18349. :type 'hook)
  18350. (defun org-self-insert-command (N)
  18351. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  18352. If the cursor is in a table looking at whitespace, the whitespace is
  18353. overwritten, and the table is not marked as requiring realignment."
  18354. (interactive "p")
  18355. (org-check-before-invisible-edit 'insert)
  18356. (cond
  18357. ((and org-use-speed-commands
  18358. (let ((kv (this-command-keys-vector)))
  18359. (setq org-speed-command
  18360. (run-hook-with-args-until-success
  18361. 'org-speed-command-hook
  18362. (make-string 1 (aref kv (1- (length kv))))))))
  18363. (cond
  18364. ((commandp org-speed-command)
  18365. (setq this-command org-speed-command)
  18366. (call-interactively org-speed-command))
  18367. ((functionp org-speed-command)
  18368. (funcall org-speed-command))
  18369. ((and org-speed-command (listp org-speed-command))
  18370. (eval org-speed-command))
  18371. (t (let (org-use-speed-commands)
  18372. (call-interactively 'org-self-insert-command)))))
  18373. ((and
  18374. (org-at-table-p)
  18375. (eq N 1)
  18376. (not (org-region-active-p))
  18377. (progn
  18378. ;; Check if we blank the field, and if that triggers align.
  18379. (and (featurep 'org-table) org-table-auto-blank-field
  18380. (memq last-command
  18381. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  18382. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  18383. ;; Got extra space, this field does not determine
  18384. ;; column width.
  18385. (let (org-table-may-need-update) (org-table-blank-field))
  18386. ;; No extra space, this field may determine column
  18387. ;; width.
  18388. (org-table-blank-field)))
  18389. t)
  18390. (looking-at "[^|\n]* \\( \\)|"))
  18391. ;; There is room for insertion without re-aligning the table.
  18392. (delete-region (match-beginning 1) (match-end 1))
  18393. (self-insert-command N))
  18394. (t
  18395. (setq org-table-may-need-update t)
  18396. (self-insert-command N)
  18397. (org-fix-tags-on-the-fly)
  18398. (when org-self-insert-cluster-for-undo
  18399. (if (not (eq last-command 'org-self-insert-command))
  18400. (setq org-self-insert-command-undo-counter 1)
  18401. (if (>= org-self-insert-command-undo-counter 20)
  18402. (setq org-self-insert-command-undo-counter 1)
  18403. (and (> org-self-insert-command-undo-counter 0)
  18404. buffer-undo-list (listp buffer-undo-list)
  18405. (not (cadr buffer-undo-list)) ; remove nil entry
  18406. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  18407. (setq org-self-insert-command-undo-counter
  18408. (1+ org-self-insert-command-undo-counter))))))))
  18409. (defun org-check-before-invisible-edit (kind)
  18410. "Check is editing if kind KIND would be dangerous with invisible text around.
  18411. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  18412. ;; First, try to get out of here as quickly as possible, to reduce overhead
  18413. (when (and org-catch-invisible-edits
  18414. (or (not (boundp 'visible-mode)) (not visible-mode))
  18415. (or (get-char-property (point) 'invisible)
  18416. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  18417. ;; OK, we need to take a closer look. Do not consider
  18418. ;; invisibility obtained through text properties (e.g., link
  18419. ;; fontification), as it cannot be toggled.
  18420. (let* ((invisible-at-point
  18421. (pcase (get-char-property-and-overlay (point) 'invisible)
  18422. (`(,_ . ,(and (pred overlayp) o)) o)))
  18423. ;; Assume that point cannot land in the middle of an
  18424. ;; overlay, or between two overlays.
  18425. (invisible-before-point
  18426. (and (not invisible-at-point)
  18427. (not (bobp))
  18428. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  18429. (`(,_ . ,(and (pred overlayp) o)) o))))
  18430. (border-and-ok-direction
  18431. (or
  18432. ;; Check if we are acting predictably before invisible
  18433. ;; text.
  18434. (and invisible-at-point
  18435. (memq kind '(insert delete-backward)))
  18436. ;; Check if we are acting predictably after invisible text
  18437. ;; This works not well, and I have turned it off. It seems
  18438. ;; better to always show and stop after invisible text.
  18439. ;; (and (not invisible-at-point) invisible-before-point
  18440. ;; (memq kind '(insert delete)))
  18441. )))
  18442. (when (or invisible-at-point invisible-before-point)
  18443. (when (eq org-catch-invisible-edits 'error)
  18444. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  18445. (if (and org-custom-properties-overlays
  18446. (y-or-n-p "Display invisible properties in this buffer? "))
  18447. (org-toggle-custom-properties-visibility)
  18448. ;; Make the area visible
  18449. (save-excursion
  18450. (when invisible-before-point
  18451. (goto-char
  18452. (previous-single-char-property-change (point) 'invisible)))
  18453. ;; Remove whatever overlay is currently making yet-to-be
  18454. ;; edited text invisible. Also remove nested invisibility
  18455. ;; related overlays.
  18456. (delete-overlay (or invisible-at-point invisible-before-point))
  18457. (let ((origin (if invisible-at-point (point) (1- (point)))))
  18458. (while (pcase (get-char-property-and-overlay origin 'invisible)
  18459. (`(,_ . ,(and (pred overlayp) o))
  18460. (delete-overlay o)
  18461. t)))))
  18462. (cond
  18463. ((eq org-catch-invisible-edits 'show)
  18464. ;; That's it, we do the edit after showing
  18465. (message
  18466. "Unfolding invisible region around point before editing")
  18467. (sit-for 1))
  18468. ((and (eq org-catch-invisible-edits 'smart)
  18469. border-and-ok-direction)
  18470. (message "Unfolding invisible region around point before editing"))
  18471. (t
  18472. ;; Don't do the edit, make the user repeat it in full visibility
  18473. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  18474. (defun org-fix-tags-on-the-fly ()
  18475. "Align tags in headline at point.
  18476. Unlike to `org-set-tags', it ignores region and sorting."
  18477. (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
  18478. (org-at-heading-p))
  18479. (let ((org-ignore-region t)
  18480. (org-tags-sort-function nil))
  18481. (org-set-tags nil t))))
  18482. (defun org-delete-backward-char (N)
  18483. "Like `delete-backward-char', insert whitespace at field end in tables.
  18484. When deleting backwards, in tables this function will insert whitespace in
  18485. front of the next \"|\" separator, to keep the table aligned. The table will
  18486. still be marked for re-alignment if the field did fill the entire column,
  18487. because, in this case the deletion might narrow the column."
  18488. (interactive "p")
  18489. (save-match-data
  18490. (org-check-before-invisible-edit 'delete-backward)
  18491. (if (and (org-at-table-p)
  18492. (eq N 1)
  18493. (string-match "|" (buffer-substring (point-at-bol) (point)))
  18494. (looking-at ".*?|"))
  18495. (let ((pos (point))
  18496. (noalign (looking-at "[^|\n\r]* |"))
  18497. (c org-table-may-need-update))
  18498. (backward-delete-char N)
  18499. (unless overwrite-mode
  18500. (skip-chars-forward "^|")
  18501. (insert " ")
  18502. (goto-char (1- pos)))
  18503. ;; noalign: if there were two spaces at the end, this field
  18504. ;; does not determine the width of the column.
  18505. (when noalign (setq org-table-may-need-update c)))
  18506. (backward-delete-char N)
  18507. (org-fix-tags-on-the-fly))))
  18508. (defun org-delete-char (N)
  18509. "Like `delete-char', but insert whitespace at field end in tables.
  18510. When deleting characters, in tables this function will insert whitespace in
  18511. front of the next \"|\" separator, to keep the table aligned. The table will
  18512. still be marked for re-alignment if the field did fill the entire column,
  18513. because, in this case the deletion might narrow the column."
  18514. (interactive "p")
  18515. (save-match-data
  18516. (org-check-before-invisible-edit 'delete)
  18517. (if (and (org-at-table-p)
  18518. (not (bolp))
  18519. (not (= (char-after) ?|))
  18520. (eq N 1))
  18521. (if (looking-at ".*?|")
  18522. (let ((pos (point))
  18523. (noalign (looking-at "[^|\n\r]* |"))
  18524. (c org-table-may-need-update))
  18525. (replace-match
  18526. (concat (substring (match-string 0) 1 -1) " |") nil t)
  18527. (goto-char pos)
  18528. ;; noalign: if there were two spaces at the end, this field
  18529. ;; does not determine the width of the column.
  18530. (when noalign (setq org-table-may-need-update c)))
  18531. (delete-char N))
  18532. (delete-char N)
  18533. (org-fix-tags-on-the-fly))))
  18534. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  18535. (put 'org-self-insert-command 'delete-selection
  18536. (lambda ()
  18537. (not (run-hook-with-args-until-success
  18538. 'self-insert-uses-region-functions))))
  18539. (put 'orgtbl-self-insert-command 'delete-selection
  18540. (lambda ()
  18541. (not (run-hook-with-args-until-success
  18542. 'self-insert-uses-region-functions))))
  18543. (put 'org-delete-char 'delete-selection 'supersede)
  18544. (put 'org-delete-backward-char 'delete-selection 'supersede)
  18545. (put 'org-yank 'delete-selection 'yank)
  18546. ;; Make `flyspell-mode' delay after some commands
  18547. (put 'org-self-insert-command 'flyspell-delayed t)
  18548. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  18549. (put 'org-delete-char 'flyspell-delayed t)
  18550. (put 'org-delete-backward-char 'flyspell-delayed t)
  18551. ;; Make pabbrev-mode expand after Org mode commands
  18552. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  18553. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  18554. (defun org-remap (map &rest commands)
  18555. "In MAP, remap the functions given in COMMANDS.
  18556. COMMANDS is a list of alternating OLDDEF NEWDEF command names."
  18557. (let (new old)
  18558. (while commands
  18559. (setq old (pop commands) new (pop commands))
  18560. (org-defkey map (vector 'remap old) new))))
  18561. (defun org-transpose-words ()
  18562. "Transpose words for Org.
  18563. This uses the `org-mode-transpose-word-syntax-table' syntax
  18564. table, which interprets characters in `org-emphasis-alist' as
  18565. word constituents."
  18566. (interactive)
  18567. (with-syntax-table org-mode-transpose-word-syntax-table
  18568. (call-interactively 'transpose-words)))
  18569. (org-remap org-mode-map 'transpose-words 'org-transpose-words)
  18570. (when (eq org-enable-table-editor 'optimized)
  18571. ;; If the user wants maximum table support, we need to hijack
  18572. ;; some standard editing functions
  18573. (org-remap org-mode-map
  18574. 'self-insert-command 'org-self-insert-command
  18575. 'delete-char 'org-delete-char
  18576. 'delete-backward-char 'org-delete-backward-char)
  18577. (org-defkey org-mode-map "|" 'org-force-self-insert))
  18578. (defvar org-ctrl-c-ctrl-c-hook nil
  18579. "Hook for functions attaching themselves to `C-c C-c'.
  18580. This can be used to add additional functionality to the C-c C-c
  18581. key which executes context-dependent commands. This hook is run
  18582. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  18583. run after the last test.
  18584. Each function will be called with no arguments. The function
  18585. must check if the context is appropriate for it to act. If yes,
  18586. it should do its thing and then return a non-nil value. If the
  18587. context is wrong, just do nothing and return nil.")
  18588. (defvar org-ctrl-c-ctrl-c-final-hook nil
  18589. "Hook for functions attaching themselves to `C-c C-c'.
  18590. This can be used to add additional functionality to the C-c C-c
  18591. key which executes context-dependent commands. This hook is run
  18592. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  18593. before the first test.
  18594. Each function will be called with no arguments. The function
  18595. must check if the context is appropriate for it to act. If yes,
  18596. it should do its thing and then return a non-nil value. If the
  18597. context is wrong, just do nothing and return nil.")
  18598. (defvar org-tab-first-hook nil
  18599. "Hook for functions to attach themselves to TAB.
  18600. See `org-ctrl-c-ctrl-c-hook' for more information.
  18601. This hook runs as the first action when TAB is pressed, even before
  18602. `org-cycle' messes around with the `outline-regexp' to cater for
  18603. inline tasks and plain list item folding.
  18604. If any function in this hook returns t, any other actions that
  18605. would have been caused by TAB (such as table field motion or visibility
  18606. cycling) will not occur.")
  18607. (defvar org-tab-after-check-for-table-hook nil
  18608. "Hook for functions to attach themselves to TAB.
  18609. See `org-ctrl-c-ctrl-c-hook' for more information.
  18610. This hook runs after it has been established that the cursor is not in a
  18611. table, but before checking if the cursor is in a headline or if global cycling
  18612. should be done.
  18613. If any function in this hook returns t, not other actions like visibility
  18614. cycling will be done.")
  18615. (defvar org-tab-after-check-for-cycling-hook nil
  18616. "Hook for functions to attach themselves to TAB.
  18617. See `org-ctrl-c-ctrl-c-hook' for more information.
  18618. This hook runs after it has been established that not table field motion and
  18619. not visibility should be done because of current context. This is probably
  18620. the place where a package like yasnippets can hook in.")
  18621. (defvar org-tab-before-tab-emulation-hook nil
  18622. "Hook for functions to attach themselves to TAB.
  18623. See `org-ctrl-c-ctrl-c-hook' for more information.
  18624. This hook runs after every other options for TAB have been exhausted, but
  18625. before indentation and \t insertion takes place.")
  18626. (defvar org-metaleft-hook nil
  18627. "Hook for functions attaching themselves to `M-left'.
  18628. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18629. (defvar org-metaright-hook nil
  18630. "Hook for functions attaching themselves to `M-right'.
  18631. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18632. (defvar org-metaup-hook nil
  18633. "Hook for functions attaching themselves to `M-up'.
  18634. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18635. (defvar org-metadown-hook nil
  18636. "Hook for functions attaching themselves to `M-down'.
  18637. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18638. (defvar org-shiftmetaleft-hook nil
  18639. "Hook for functions attaching themselves to `M-S-left'.
  18640. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18641. (defvar org-shiftmetaright-hook nil
  18642. "Hook for functions attaching themselves to `M-S-right'.
  18643. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18644. (defvar org-shiftmetaup-hook nil
  18645. "Hook for functions attaching themselves to `M-S-up'.
  18646. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18647. (defvar org-shiftmetadown-hook nil
  18648. "Hook for functions attaching themselves to `M-S-down'.
  18649. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18650. (defvar org-metareturn-hook nil
  18651. "Hook for functions attaching themselves to `M-RET'.
  18652. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18653. (defvar org-shiftup-hook nil
  18654. "Hook for functions attaching themselves to `S-up'.
  18655. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18656. (defvar org-shiftup-final-hook nil
  18657. "Hook for functions attaching themselves to `S-up'.
  18658. This one runs after all other options except shift-select have been excluded.
  18659. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18660. (defvar org-shiftdown-hook nil
  18661. "Hook for functions attaching themselves to `S-down'.
  18662. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18663. (defvar org-shiftdown-final-hook nil
  18664. "Hook for functions attaching themselves to `S-down'.
  18665. This one runs after all other options except shift-select have been excluded.
  18666. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18667. (defvar org-shiftleft-hook nil
  18668. "Hook for functions attaching themselves to `S-left'.
  18669. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18670. (defvar org-shiftleft-final-hook nil
  18671. "Hook for functions attaching themselves to `S-left'.
  18672. This one runs after all other options except shift-select have been excluded.
  18673. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18674. (defvar org-shiftright-hook nil
  18675. "Hook for functions attaching themselves to `S-right'.
  18676. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18677. (defvar org-shiftright-final-hook nil
  18678. "Hook for functions attaching themselves to `S-right'.
  18679. This one runs after all other options except shift-select have been excluded.
  18680. See `org-ctrl-c-ctrl-c-hook' for more information.")
  18681. (defun org-modifier-cursor-error ()
  18682. "Throw an error, a modified cursor command was applied in wrong context."
  18683. (user-error "This command is active in special context like tables, headlines or items"))
  18684. (defun org-shiftselect-error ()
  18685. "Throw an error because Shift-Cursor command was applied in wrong context."
  18686. (if (and (boundp 'shift-select-mode) shift-select-mode)
  18687. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  18688. (user-error "This command works only in special context like headlines or timestamps")))
  18689. (defun org-call-for-shift-select (cmd)
  18690. (let ((this-command-keys-shift-translated t))
  18691. (call-interactively cmd)))
  18692. (defun org-shifttab (&optional arg)
  18693. "Global visibility cycling or move to previous table field.
  18694. Call `org-table-previous-field' within a table.
  18695. When ARG is nil, cycle globally through visibility states.
  18696. When ARG is a numeric prefix, show contents of this level."
  18697. (interactive "P")
  18698. (cond
  18699. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  18700. ((integerp arg)
  18701. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  18702. (message "Content view to level: %d" arg)
  18703. (org-content (prefix-numeric-value arg2))
  18704. (org-cycle-show-empty-lines t)
  18705. (setq org-cycle-global-status 'overview)))
  18706. (t (call-interactively 'org-global-cycle))))
  18707. (defun org-shiftmetaleft ()
  18708. "Promote subtree or delete table column.
  18709. Calls `org-promote-subtree', `org-outdent-item-tree', or
  18710. `org-table-delete-column', depending on context. See the
  18711. individual commands for more information."
  18712. (interactive)
  18713. (cond
  18714. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  18715. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  18716. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  18717. ((if (not (org-region-active-p)) (org-at-item-p)
  18718. (save-excursion (goto-char (region-beginning))
  18719. (org-at-item-p)))
  18720. (call-interactively 'org-outdent-item-tree))
  18721. (t (org-modifier-cursor-error))))
  18722. (defun org-shiftmetaright ()
  18723. "Demote subtree or insert table column.
  18724. Calls `org-demote-subtree', `org-indent-item-tree', or
  18725. `org-table-insert-column', depending on context. See the
  18726. individual commands for more information."
  18727. (interactive)
  18728. (cond
  18729. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  18730. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  18731. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  18732. ((if (not (org-region-active-p)) (org-at-item-p)
  18733. (save-excursion (goto-char (region-beginning))
  18734. (org-at-item-p)))
  18735. (call-interactively 'org-indent-item-tree))
  18736. (t (org-modifier-cursor-error))))
  18737. (defun org-shiftmetaup (&optional _arg)
  18738. "Drag the line at point up.
  18739. In a table, kill the current row.
  18740. On a clock timestamp, update the value of the timestamp like `S-<up>'
  18741. but also adjust the previous clocked item in the clock history.
  18742. Everywhere else, drag the line at point up."
  18743. (interactive "P")
  18744. (cond
  18745. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  18746. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  18747. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18748. (call-interactively 'org-timestamp-up)))
  18749. (t (call-interactively 'org-drag-line-backward))))
  18750. (defun org-shiftmetadown (&optional _arg)
  18751. "Drag the line at point down.
  18752. In a table, insert an empty row at the current line.
  18753. On a clock timestamp, update the value of the timestamp like `S-<down>'
  18754. but also adjust the previous clocked item in the clock history.
  18755. Everywhere else, drag the line at point down."
  18756. (interactive "P")
  18757. (cond
  18758. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  18759. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  18760. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  18761. (call-interactively 'org-timestamp-down)))
  18762. (t (call-interactively 'org-drag-line-forward))))
  18763. (defsubst org-hidden-tree-error ()
  18764. (user-error
  18765. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  18766. (defun org-metaleft (&optional _arg)
  18767. "Promote heading, list item at point or move table column left.
  18768. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  18769. depending on context. With no specific context, calls the Emacs
  18770. default `backward-word'. See the individual commands for more
  18771. information.
  18772. This function runs the hook `org-metaleft-hook' as a first step,
  18773. and returns at first non-nil value."
  18774. (interactive "P")
  18775. (cond
  18776. ((run-hook-with-args-until-success 'org-metaleft-hook))
  18777. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  18778. ((org-with-limited-levels
  18779. (or (org-at-heading-p)
  18780. (and (org-region-active-p)
  18781. (save-excursion
  18782. (goto-char (region-beginning))
  18783. (org-at-heading-p)))))
  18784. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18785. (call-interactively 'org-do-promote))
  18786. ;; At an inline task.
  18787. ((org-at-heading-p)
  18788. (call-interactively 'org-inlinetask-promote))
  18789. ((or (org-at-item-p)
  18790. (and (org-region-active-p)
  18791. (save-excursion
  18792. (goto-char (region-beginning))
  18793. (org-at-item-p))))
  18794. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18795. (call-interactively 'org-outdent-item))
  18796. (t (call-interactively 'backward-word))))
  18797. (defun org-metaright (&optional _arg)
  18798. "Demote heading, list item at point or move table column right.
  18799. In front of a drawer or a block keyword, indent it correctly.
  18800. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  18801. `org-indent-drawer' or `org-indent-block' depending on context.
  18802. With no specific context, calls the Emacs default `forward-word'.
  18803. See the individual commands for more information.
  18804. This function runs the hook `org-metaright-hook' as a first step,
  18805. and returns at first non-nil value."
  18806. (interactive "P")
  18807. (cond
  18808. ((run-hook-with-args-until-success 'org-metaright-hook))
  18809. ((org-at-table-p) (call-interactively 'org-table-move-column))
  18810. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  18811. ((org-at-block-p) (call-interactively 'org-indent-block))
  18812. ((org-with-limited-levels
  18813. (or (org-at-heading-p)
  18814. (and (org-region-active-p)
  18815. (save-excursion
  18816. (goto-char (region-beginning))
  18817. (org-at-heading-p)))))
  18818. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  18819. (call-interactively 'org-do-demote))
  18820. ;; At an inline task.
  18821. ((org-at-heading-p)
  18822. (call-interactively 'org-inlinetask-demote))
  18823. ((or (org-at-item-p)
  18824. (and (org-region-active-p)
  18825. (save-excursion
  18826. (goto-char (region-beginning))
  18827. (org-at-item-p))))
  18828. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  18829. (call-interactively 'org-indent-item))
  18830. (t (call-interactively 'forward-word))))
  18831. (defun org-check-for-hidden (what)
  18832. "Check if there are hidden headlines/items in the current visual line.
  18833. WHAT can be either `headlines' or `items'. If the current line is
  18834. an outline or item heading and it has a folded subtree below it,
  18835. this function returns t, nil otherwise."
  18836. (let ((re (cond
  18837. ((eq what 'headlines) org-outline-regexp-bol)
  18838. ((eq what 'items) (org-item-beginning-re))
  18839. (t (error "This should not happen"))))
  18840. beg end)
  18841. (save-excursion
  18842. (catch 'exit
  18843. (unless (org-region-active-p)
  18844. (setq beg (point-at-bol))
  18845. (beginning-of-line 2)
  18846. (while (and (not (eobp)) ;; this is like `next-line'
  18847. (get-char-property (1- (point)) 'invisible))
  18848. (beginning-of-line 2))
  18849. (setq end (point))
  18850. (goto-char beg)
  18851. (goto-char (point-at-eol))
  18852. (setq end (max end (point)))
  18853. (while (re-search-forward re end t)
  18854. (when (get-char-property (match-beginning 0) 'invisible)
  18855. (throw 'exit t))))
  18856. nil))))
  18857. (defun org-metaup (&optional _arg)
  18858. "Move subtree up or move table row up.
  18859. Calls `org-move-subtree-up' or `org-table-move-row' or
  18860. `org-move-item-up', depending on context. See the individual commands
  18861. for more information."
  18862. (interactive "P")
  18863. (cond
  18864. ((run-hook-with-args-until-success 'org-metaup-hook))
  18865. ((org-region-active-p)
  18866. (let* ((a (min (region-beginning) (region-end)))
  18867. (b (1- (max (region-beginning) (region-end))))
  18868. (c (save-excursion (goto-char a)
  18869. (move-beginning-of-line 0)))
  18870. (d (save-excursion (goto-char a)
  18871. (move-end-of-line 0) (point))))
  18872. (transpose-regions a b c d)
  18873. (goto-char c)))
  18874. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  18875. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  18876. ((org-at-item-p) (call-interactively 'org-move-item-up))
  18877. (t (org-drag-element-backward))))
  18878. (defun org-metadown (&optional _arg)
  18879. "Move subtree down or move table row down.
  18880. Calls `org-move-subtree-down' or `org-table-move-row' or
  18881. `org-move-item-down', depending on context. See the individual
  18882. commands for more information."
  18883. (interactive "P")
  18884. (cond
  18885. ((run-hook-with-args-until-success 'org-metadown-hook))
  18886. ((org-region-active-p)
  18887. (let* ((a (min (region-beginning) (region-end)))
  18888. (b (max (region-beginning) (region-end)))
  18889. (c (save-excursion (goto-char b)
  18890. (move-beginning-of-line 1)))
  18891. (d (save-excursion (goto-char b)
  18892. (move-end-of-line 1) (1+ (point)))))
  18893. (transpose-regions a b c d)
  18894. (goto-char d)))
  18895. ((org-at-table-p) (call-interactively 'org-table-move-row))
  18896. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  18897. ((org-at-item-p) (call-interactively 'org-move-item-down))
  18898. (t (org-drag-element-forward))))
  18899. (defun org-shiftup (&optional arg)
  18900. "Increase item in timestamp or increase priority of current headline.
  18901. Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
  18902. depending on context. See the individual commands for more information."
  18903. (interactive "P")
  18904. (cond
  18905. ((run-hook-with-args-until-success 'org-shiftup-hook))
  18906. ((and org-support-shift-select (org-region-active-p))
  18907. (org-call-for-shift-select 'previous-line))
  18908. ((org-at-timestamp-p t)
  18909. (call-interactively (if org-edit-timestamp-down-means-later
  18910. 'org-timestamp-down 'org-timestamp-up)))
  18911. ((and (not (eq org-support-shift-select 'always))
  18912. org-enable-priority-commands
  18913. (org-at-heading-p))
  18914. (call-interactively 'org-priority-up))
  18915. ((and (not org-support-shift-select) (org-at-item-p))
  18916. (call-interactively 'org-previous-item))
  18917. ((org-clocktable-try-shift 'up arg))
  18918. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  18919. (org-support-shift-select
  18920. (org-call-for-shift-select 'previous-line))
  18921. (t (org-shiftselect-error))))
  18922. (defun org-shiftdown (&optional arg)
  18923. "Decrease item in timestamp or decrease priority of current headline.
  18924. Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
  18925. depending on context. See the individual commands for more information."
  18926. (interactive "P")
  18927. (cond
  18928. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  18929. ((and org-support-shift-select (org-region-active-p))
  18930. (org-call-for-shift-select 'next-line))
  18931. ((org-at-timestamp-p t)
  18932. (call-interactively (if org-edit-timestamp-down-means-later
  18933. 'org-timestamp-up 'org-timestamp-down)))
  18934. ((and (not (eq org-support-shift-select 'always))
  18935. org-enable-priority-commands
  18936. (org-at-heading-p))
  18937. (call-interactively 'org-priority-down))
  18938. ((and (not org-support-shift-select) (org-at-item-p))
  18939. (call-interactively 'org-next-item))
  18940. ((org-clocktable-try-shift 'down arg))
  18941. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  18942. (org-support-shift-select
  18943. (org-call-for-shift-select 'next-line))
  18944. (t (org-shiftselect-error))))
  18945. (defun org-shiftright (&optional arg)
  18946. "Cycle the thing at point or in the current line, depending on context.
  18947. Depending on context, this does one of the following:
  18948. - switch a timestamp at point one day into the future
  18949. - on a headline, switch to the next TODO keyword.
  18950. - on an item, switch entire list to the next bullet type
  18951. - on a property line, switch to the next allowed value
  18952. - on a clocktable definition line, move time block into the future"
  18953. (interactive "P")
  18954. (cond
  18955. ((run-hook-with-args-until-success 'org-shiftright-hook))
  18956. ((and org-support-shift-select (org-region-active-p))
  18957. (org-call-for-shift-select 'forward-char))
  18958. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
  18959. ((and (not (eq org-support-shift-select 'always))
  18960. (org-at-heading-p))
  18961. (let ((org-inhibit-logging
  18962. (not org-treat-S-cursor-todo-selection-as-state-change))
  18963. (org-inhibit-blocking
  18964. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18965. (org-call-with-arg 'org-todo 'right)))
  18966. ((or (and org-support-shift-select
  18967. (not (eq org-support-shift-select 'always))
  18968. (org-at-item-bullet-p))
  18969. (and (not org-support-shift-select) (org-at-item-p)))
  18970. (org-call-with-arg 'org-cycle-list-bullet nil))
  18971. ((and (not (eq org-support-shift-select 'always))
  18972. (org-at-property-p))
  18973. (call-interactively 'org-property-next-allowed-value))
  18974. ((org-clocktable-try-shift 'right arg))
  18975. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  18976. (org-support-shift-select
  18977. (org-call-for-shift-select 'forward-char))
  18978. (t (org-shiftselect-error))))
  18979. (defun org-shiftleft (&optional arg)
  18980. "Cycle the thing at point or in the current line, depending on context.
  18981. Depending on context, this does one of the following:
  18982. - switch a timestamp at point one day into the past
  18983. - on a headline, switch to the previous TODO keyword.
  18984. - on an item, switch entire list to the previous bullet type
  18985. - on a property line, switch to the previous allowed value
  18986. - on a clocktable definition line, move time block into the past"
  18987. (interactive "P")
  18988. (cond
  18989. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  18990. ((and org-support-shift-select (org-region-active-p))
  18991. (org-call-for-shift-select 'backward-char))
  18992. ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
  18993. ((and (not (eq org-support-shift-select 'always))
  18994. (org-at-heading-p))
  18995. (let ((org-inhibit-logging
  18996. (not org-treat-S-cursor-todo-selection-as-state-change))
  18997. (org-inhibit-blocking
  18998. (not org-treat-S-cursor-todo-selection-as-state-change)))
  18999. (org-call-with-arg 'org-todo 'left)))
  19000. ((or (and org-support-shift-select
  19001. (not (eq org-support-shift-select 'always))
  19002. (org-at-item-bullet-p))
  19003. (and (not org-support-shift-select) (org-at-item-p)))
  19004. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  19005. ((and (not (eq org-support-shift-select 'always))
  19006. (org-at-property-p))
  19007. (call-interactively 'org-property-previous-allowed-value))
  19008. ((org-clocktable-try-shift 'left arg))
  19009. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  19010. (org-support-shift-select
  19011. (org-call-for-shift-select 'backward-char))
  19012. (t (org-shiftselect-error))))
  19013. (defun org-shiftcontrolright ()
  19014. "Switch to next TODO set."
  19015. (interactive)
  19016. (cond
  19017. ((and org-support-shift-select (org-region-active-p))
  19018. (org-call-for-shift-select 'forward-word))
  19019. ((and (not (eq org-support-shift-select 'always))
  19020. (org-at-heading-p))
  19021. (org-call-with-arg 'org-todo 'nextset))
  19022. (org-support-shift-select
  19023. (org-call-for-shift-select 'forward-word))
  19024. (t (org-shiftselect-error))))
  19025. (defun org-shiftcontrolleft ()
  19026. "Switch to previous TODO set."
  19027. (interactive)
  19028. (cond
  19029. ((and org-support-shift-select (org-region-active-p))
  19030. (org-call-for-shift-select 'backward-word))
  19031. ((and (not (eq org-support-shift-select 'always))
  19032. (org-at-heading-p))
  19033. (org-call-with-arg 'org-todo 'previousset))
  19034. (org-support-shift-select
  19035. (org-call-for-shift-select 'backward-word))
  19036. (t (org-shiftselect-error))))
  19037. (defun org-shiftcontrolup (&optional n)
  19038. "Change timestamps synchronously up in CLOCK log lines.
  19039. Optional argument N tells to change by that many units."
  19040. (interactive "P")
  19041. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19042. (let (org-support-shift-select)
  19043. (org-clock-timestamps-up n))
  19044. (user-error "Not at a clock log")))
  19045. (defun org-shiftcontroldown (&optional n)
  19046. "Change timestamps synchronously down in CLOCK log lines.
  19047. Optional argument N tells to change by that many units."
  19048. (interactive "P")
  19049. (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
  19050. (let (org-support-shift-select)
  19051. (org-clock-timestamps-down n))
  19052. (user-error "Not at a clock log")))
  19053. (defun org-increase-number-at-point (&optional inc)
  19054. "Increment the number at point.
  19055. With an optional prefix numeric argument INC, increment using
  19056. this numeric value."
  19057. (interactive "p")
  19058. (if (not (number-at-point))
  19059. (user-error "Not on a number")
  19060. (unless inc (setq inc 1))
  19061. (let ((pos (point))
  19062. (beg (skip-chars-backward "-+^/*0-9eE."))
  19063. (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
  19064. (setq nap (buffer-substring-no-properties
  19065. (+ pos beg) (+ pos beg end)))
  19066. (delete-region (+ pos beg) (+ pos beg end))
  19067. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  19068. (when (org-at-table-p)
  19069. (org-table-align)
  19070. (org-table-end-of-field 1))))
  19071. (defun org-decrease-number-at-point (&optional inc)
  19072. "Decrement the number at point.
  19073. With an optional prefix numeric argument INC, decrement using
  19074. this numeric value."
  19075. (interactive "p")
  19076. (org-increase-number-at-point (- (or inc 1))))
  19077. (defun org-ctrl-c-ret ()
  19078. "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
  19079. (interactive)
  19080. (cond
  19081. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  19082. (t (call-interactively 'org-insert-heading))))
  19083. (defun org-find-visible ()
  19084. (let ((s (point)))
  19085. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19086. (get-char-property s 'invisible)))
  19087. s))
  19088. (defun org-find-invisible ()
  19089. (let ((s (point)))
  19090. (while (and (not (= (point-max) (setq s (next-overlay-change s))))
  19091. (not (get-char-property s 'invisible))))
  19092. s))
  19093. (defun org-copy-visible (beg end)
  19094. "Copy the visible parts of the region."
  19095. (interactive "r")
  19096. (let (snippets s)
  19097. (save-excursion
  19098. (save-restriction
  19099. (narrow-to-region beg end)
  19100. (setq s (goto-char (point-min)))
  19101. (while (not (= (point) (point-max)))
  19102. (goto-char (org-find-invisible))
  19103. (push (buffer-substring s (point)) snippets)
  19104. (setq s (goto-char (org-find-visible))))))
  19105. (kill-new (apply 'concat (nreverse snippets)))))
  19106. (defun org-copy-special ()
  19107. "Copy region in table or copy current subtree.
  19108. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  19109. context. See the individual commands for more information."
  19110. (interactive)
  19111. (call-interactively
  19112. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  19113. (defun org-cut-special ()
  19114. "Cut region in table or cut current subtree.
  19115. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  19116. context. See the individual commands for more information."
  19117. (interactive)
  19118. (call-interactively
  19119. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  19120. (defun org-paste-special (arg)
  19121. "Paste rectangular region into table, or past subtree relative to level.
  19122. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  19123. See the individual commands for more information."
  19124. (interactive "P")
  19125. (if (org-at-table-p)
  19126. (org-table-paste-rectangle)
  19127. (org-paste-subtree arg)))
  19128. (defun org-edit-special (&optional arg)
  19129. "Call a special editor for the element at point.
  19130. When at a table, call the formula editor with `org-table-edit-formulas'.
  19131. When in a source code block, call `org-edit-src-code'.
  19132. When in a fixed-width region, call `org-edit-fixed-width-region'.
  19133. When in an export block, call `org-edit-export-block'.
  19134. When at an #+INCLUDE keyword, visit the included file.
  19135. When at a footnote reference, call `org-edit-footnote-reference'
  19136. On a link, call `ffap' to visit the link at point.
  19137. Otherwise, return a user error."
  19138. (interactive "P")
  19139. (let ((element (org-element-at-point)))
  19140. (barf-if-buffer-read-only)
  19141. (pcase (org-element-type element)
  19142. (`src-block
  19143. (if (not arg) (org-edit-src-code)
  19144. (let* ((info (org-babel-get-src-block-info))
  19145. (lang (nth 0 info))
  19146. (params (nth 2 info))
  19147. (session (cdr (assq :session params))))
  19148. (if (not session) (org-edit-src-code)
  19149. ;; At a src-block with a session and function called with
  19150. ;; an ARG: switch to the buffer related to the inferior
  19151. ;; process.
  19152. (switch-to-buffer
  19153. (funcall (intern (concat "org-babel-prep-session:" lang))
  19154. session params))))))
  19155. (`keyword
  19156. (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
  19157. (org-open-link-from-string
  19158. (format "[[%s]]"
  19159. (expand-file-name
  19160. (let ((value (org-element-property :value element)))
  19161. (cond ((not (org-string-nw-p value))
  19162. (user-error "No file to edit"))
  19163. ((string-match "\\`\"\\(.*?\\)\"" value)
  19164. (match-string 1 value))
  19165. ((string-match "\\`[^ \t\"]\\S-*" value)
  19166. (match-string 0 value))
  19167. (t (user-error "No valid file specified")))))))
  19168. (user-error "No special environment to edit here")))
  19169. (`table
  19170. (if (eq (org-element-property :type element) 'table.el)
  19171. (org-edit-table.el)
  19172. (call-interactively 'org-table-edit-formulas)))
  19173. ;; Only Org tables contain `table-row' type elements.
  19174. (`table-row (call-interactively 'org-table-edit-formulas))
  19175. (`example-block (org-edit-src-code))
  19176. (`export-block (org-edit-export-block))
  19177. (`fixed-width (org-edit-fixed-width-region))
  19178. (_
  19179. ;; No notable element at point. Though, we may be at a link or
  19180. ;; a footnote reference, which are objects. Thus, scan deeper.
  19181. (let ((context (org-element-context element)))
  19182. (pcase (org-element-type context)
  19183. (`footnote-reference (org-edit-footnote-reference))
  19184. (`inline-src-block (org-edit-inline-src-code))
  19185. (`link (call-interactively #'ffap))
  19186. (_ (user-error "No special environment to edit here"))))))))
  19187. (defvar org-table-coordinate-overlays) ; defined in org-table.el
  19188. (defun org-ctrl-c-ctrl-c (&optional arg)
  19189. "Set tags in headline, or update according to changed information at point.
  19190. This command does many different things, depending on context:
  19191. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  19192. this is what we do.
  19193. - If the cursor is on a statistics cookie, update it.
  19194. - If the cursor is in a headline, prompt for tags and insert them
  19195. into the current line, aligned to `org-tags-column'. When called
  19196. with prefix arg, realign all tags in the current buffer.
  19197. - If the cursor is in one of the special #+KEYWORD lines, this
  19198. triggers scanning the buffer for these lines and updating the
  19199. information.
  19200. - If the cursor is inside a table, realign the table. This command
  19201. works even if the automatic table editor has been turned off.
  19202. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  19203. the entire table.
  19204. - If the cursor is at a footnote reference or definition, jump to
  19205. the corresponding definition or references, respectively.
  19206. - If the cursor is a the beginning of a dynamic block, update it.
  19207. - If the current buffer is a capture buffer, close note and file it.
  19208. - If the cursor is on a <<<target>>>, update radio targets and
  19209. corresponding links in this buffer.
  19210. - If the cursor is on a numbered item in a plain list, renumber the
  19211. ordered list.
  19212. - If the cursor is on a checkbox, toggle it.
  19213. - If the cursor is on a code block, evaluate it. The variable
  19214. `org-confirm-babel-evaluate' can be used to control prompting
  19215. before code block evaluation, by default every code block
  19216. evaluation requires confirmation. Code block evaluation can be
  19217. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  19218. (interactive "P")
  19219. (cond
  19220. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  19221. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  19222. (org-remove-occur-highlights)
  19223. (message "Temporary highlights/overlays removed from current buffer"))
  19224. ((and (local-variable-p 'org-finish-function)
  19225. (fboundp org-finish-function))
  19226. (funcall org-finish-function))
  19227. ((org-babel-hash-at-point))
  19228. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  19229. (t
  19230. (let* ((context
  19231. (org-element-lineage
  19232. (org-element-context)
  19233. ;; Limit to supported contexts.
  19234. '(babel-call clock dynamic-block footnote-definition
  19235. footnote-reference inline-babel-call inline-src-block
  19236. inlinetask item keyword node-property paragraph
  19237. plain-list property-drawer radio-target src-block
  19238. statistics-cookie table table-cell table-row
  19239. timestamp)
  19240. t))
  19241. (type (org-element-type context)))
  19242. ;; For convenience: at the first line of a paragraph on the same
  19243. ;; line as an item, apply function on that item instead.
  19244. (when (eq type 'paragraph)
  19245. (let ((parent (org-element-property :parent context)))
  19246. (when (and (eq (org-element-type parent) 'item)
  19247. (= (line-beginning-position)
  19248. (org-element-property :begin parent)))
  19249. (setq context parent)
  19250. (setq type 'item))))
  19251. ;; Act according to type of element or object at point.
  19252. ;;
  19253. ;; Do nothing on a blank line, except if it is contained in
  19254. ;; a src block. Hence, we first check if point is in such
  19255. ;; a block and then if it is at a blank line.
  19256. (pcase type
  19257. ((or `inline-src-block `src-block)
  19258. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  19259. (org-babel-eval-wipe-error-buffer)
  19260. (org-babel-execute-src-block
  19261. current-prefix-arg (org-babel-get-src-block-info nil context))))
  19262. ((guard (org-match-line "[ \t]*$"))
  19263. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  19264. (user-error
  19265. (substitute-command-keys
  19266. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  19267. ((or `babel-call `inline-babel-call)
  19268. (let ((info (org-babel-lob-get-info context)))
  19269. (when info (org-babel-execute-src-block nil info))))
  19270. (`clock (org-clock-update-time-maybe))
  19271. (`dynamic-block
  19272. (save-excursion
  19273. (goto-char (org-element-property :post-affiliated context))
  19274. (org-update-dblock)))
  19275. (`footnote-definition
  19276. (goto-char (org-element-property :post-affiliated context))
  19277. (call-interactively 'org-footnote-action))
  19278. (`footnote-reference (call-interactively #'org-footnote-action))
  19279. ((or `headline `inlinetask)
  19280. (save-excursion (goto-char (org-element-property :begin context))
  19281. (call-interactively #'org-set-tags)))
  19282. (`item
  19283. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  19284. ;; unconditionally, whereas `C-u' will toggle its presence.
  19285. ;; Without a universal argument, if the item has a checkbox,
  19286. ;; toggle it. Otherwise repair the list.
  19287. (let* ((box (org-element-property :checkbox context))
  19288. (struct (org-element-property :structure context))
  19289. (old-struct (copy-tree struct))
  19290. (parents (org-list-parents-alist struct))
  19291. (prevs (org-list-prevs-alist struct))
  19292. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  19293. (org-list-set-checkbox
  19294. (org-element-property :begin context) struct
  19295. (cond ((equal arg '(16)) "[-]")
  19296. ((and (not box) (equal arg '(4))) "[ ]")
  19297. ((or (not box) (equal arg '(4))) nil)
  19298. ((eq box 'on) "[ ]")
  19299. (t "[X]")))
  19300. ;; Mimic `org-list-write-struct' but with grabbing a return
  19301. ;; value from `org-list-struct-fix-box'.
  19302. (org-list-struct-fix-ind struct parents 2)
  19303. (org-list-struct-fix-item-end struct)
  19304. (org-list-struct-fix-bul struct prevs)
  19305. (org-list-struct-fix-ind struct parents)
  19306. (let ((block-item
  19307. (org-list-struct-fix-box struct parents prevs orderedp)))
  19308. (if (and box (equal struct old-struct))
  19309. (if (equal arg '(16))
  19310. (message "Checkboxes already reset")
  19311. (user-error "Cannot toggle this checkbox: %s"
  19312. (if (eq box 'on)
  19313. "all subitems checked"
  19314. "unchecked subitems")))
  19315. (org-list-struct-apply-struct struct old-struct)
  19316. (org-update-checkbox-count-maybe))
  19317. (when block-item
  19318. (message "Checkboxes were removed due to empty box at line %d"
  19319. (org-current-line block-item))))))
  19320. (`keyword
  19321. (let ((org-inhibit-startup-visibility-stuff t)
  19322. (org-startup-align-all-tables nil))
  19323. (when (boundp 'org-table-coordinate-overlays)
  19324. (mapc #'delete-overlay org-table-coordinate-overlays)
  19325. (setq org-table-coordinate-overlays nil))
  19326. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  19327. (message "Local setup has been refreshed"))
  19328. (`plain-list
  19329. ;; At a plain list, with a double C-u argument, set
  19330. ;; checkboxes of each item to "[-]", whereas a single one
  19331. ;; will toggle their presence according to the state of the
  19332. ;; first item in the list. Without an argument, repair the
  19333. ;; list.
  19334. (let* ((begin (org-element-property :contents-begin context))
  19335. (beginm (move-marker (make-marker) begin))
  19336. (struct (org-element-property :structure context))
  19337. (old-struct (copy-tree struct))
  19338. (first-box (save-excursion
  19339. (goto-char begin)
  19340. (looking-at org-list-full-item-re)
  19341. (match-string-no-properties 3)))
  19342. (new-box (cond ((equal arg '(16)) "[-]")
  19343. ((equal arg '(4)) (unless first-box "[ ]"))
  19344. ((equal first-box "[X]") "[ ]")
  19345. (t "[X]"))))
  19346. (cond
  19347. (arg
  19348. (dolist (pos
  19349. (org-list-get-all-items
  19350. begin struct (org-list-prevs-alist struct)))
  19351. (org-list-set-checkbox pos struct new-box)))
  19352. ((and first-box (eq (point) begin))
  19353. ;; For convenience, when point is at bol on the first
  19354. ;; item of the list and no argument is provided, simply
  19355. ;; toggle checkbox of that item, if any.
  19356. (org-list-set-checkbox begin struct new-box)))
  19357. (org-list-write-struct
  19358. struct (org-list-parents-alist struct) old-struct)
  19359. (org-update-checkbox-count-maybe)
  19360. (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
  19361. ((or `property-drawer `node-property)
  19362. (call-interactively #'org-property-action))
  19363. (`radio-target
  19364. (call-interactively #'org-update-radio-target-regexp))
  19365. (`statistics-cookie
  19366. (call-interactively #'org-update-statistics-cookies))
  19367. ((or `table `table-cell `table-row)
  19368. ;; At a table, recalculate every field and align it. Also
  19369. ;; send the table if necessary. If the table has
  19370. ;; a `table.el' type, just give up. At a table row or cell,
  19371. ;; maybe recalculate line but always align table.
  19372. (if (eq (org-element-property :type context) 'table.el)
  19373. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  19374. Use `\\[org-edit-special]' to edit table.el tables"))
  19375. (let ((org-enable-table-editor t))
  19376. (if (or (eq type 'table)
  19377. ;; Check if point is at a TBLFM line.
  19378. (and (eq type 'table-row)
  19379. (= (point) (org-element-property :end context))))
  19380. (save-excursion
  19381. (if (org-at-TBLFM-p)
  19382. (progn (require 'org-table)
  19383. (org-table-calc-current-TBLFM))
  19384. (goto-char (org-element-property :contents-begin context))
  19385. (org-call-with-arg 'org-table-recalculate (or arg t))
  19386. (orgtbl-send-table 'maybe)))
  19387. (org-table-maybe-eval-formula)
  19388. (cond (arg (call-interactively #'org-table-recalculate))
  19389. ((org-table-maybe-recalculate-line))
  19390. (t (org-table-align)))))))
  19391. (`timestamp (org-timestamp-change 0 'day))
  19392. ((and `nil (guard (org-at-heading-p)))
  19393. ;; When point is on an unsupported object type, we can miss
  19394. ;; the fact that it also is at a heading. Handle it here.
  19395. (call-interactively #'org-set-tags))
  19396. ((guard
  19397. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  19398. (_
  19399. (user-error
  19400. (substitute-command-keys
  19401. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  19402. (defun org-mode-restart ()
  19403. (interactive)
  19404. (let ((indent-status (bound-and-true-p org-indent-mode)))
  19405. (funcall major-mode)
  19406. (hack-local-variables)
  19407. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  19408. (org-indent-mode -1)))
  19409. (message "%s restarted" major-mode))
  19410. (defun org-kill-note-or-show-branches ()
  19411. "Abort storing current note, or call `outline-show-branches'."
  19412. (interactive)
  19413. (if (not org-finish-function)
  19414. (progn
  19415. (outline-hide-subtree)
  19416. (call-interactively 'outline-show-branches))
  19417. (let ((org-note-abort t))
  19418. (funcall org-finish-function))))
  19419. (defun org-delete-indentation (&optional arg)
  19420. "Join current line to previous and fix whitespace at join.
  19421. If previous line is a headline add to headline title. Otherwise
  19422. the function calls `delete-indentation'.
  19423. With a non-nil optional argument, join it to the following one."
  19424. (interactive "*P")
  19425. (if (save-excursion
  19426. (beginning-of-line (if arg 1 0))
  19427. (let ((case-fold-search nil))
  19428. (looking-at org-complex-heading-regexp)))
  19429. ;; At headline.
  19430. (let ((tags-column (when (match-beginning 5)
  19431. (save-excursion (goto-char (match-beginning 5))
  19432. (current-column))))
  19433. (string (concat " " (progn (when arg (forward-line 1))
  19434. (org-trim (delete-and-extract-region
  19435. (line-beginning-position)
  19436. (line-end-position)))))))
  19437. (unless (bobp) (delete-region (point) (1- (point))))
  19438. (goto-char (or (match-end 4)
  19439. (match-beginning 5)
  19440. (match-end 0)))
  19441. (skip-chars-backward " \t")
  19442. (save-excursion (insert string))
  19443. ;; Adjust alignment of tags.
  19444. (cond
  19445. ((not tags-column)) ;no tags
  19446. (org-auto-align-tags (org-set-tags nil t))
  19447. (t (org--align-tags-here tags-column)))) ;preserve tags column
  19448. (delete-indentation arg)))
  19449. (defun org-open-line (n)
  19450. "Insert a new row in tables, call `open-line' elsewhere.
  19451. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  19452. As a special case, when a document starts with a table, allow to
  19453. call `open-line' on the very first character."
  19454. (interactive "*p")
  19455. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  19456. (org-table-insert-row)
  19457. (open-line n)))
  19458. (defun org-return (&optional indent)
  19459. "Goto next table row or insert a newline.
  19460. Calls `org-table-next-row' or `newline', depending on context.
  19461. When optional INDENT argument is non-nil, call
  19462. `newline-and-indent' instead of `newline'.
  19463. When `org-return-follows-link' is non-nil and point is on
  19464. a timestamp or a link, call `org-open-at-point'. However, it
  19465. will not happen if point is in a table or on a \"dead\"
  19466. object (e.g., within a comment). In these case, you need to use
  19467. `org-open-at-point' directly."
  19468. (interactive)
  19469. (let ((context (if org-return-follows-link (org-element-context)
  19470. (org-element-at-point))))
  19471. (cond
  19472. ;; In a table, call `org-table-next-row'.
  19473. ((or (and (eq (org-element-type context) 'table)
  19474. (>= (point) (org-element-property :contents-begin context))
  19475. (< (point) (org-element-property :contents-end context)))
  19476. (org-element-lineage context '(table-row table-cell) t))
  19477. (org-table-justify-field-maybe)
  19478. (call-interactively #'org-table-next-row))
  19479. ;; On a link or a timestamp, call `org-open-at-point' if
  19480. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  19481. ;; locations, e.g., in a comment, as `org-open-at-point'.
  19482. ((and org-return-follows-link
  19483. (or (org-in-regexp org-ts-regexp-both nil t)
  19484. (org-in-regexp org-tsr-regexp-both nil t)
  19485. (org-in-regexp org-any-link-re nil t)))
  19486. (call-interactively #'org-open-at-point))
  19487. ;; Insert newline in heading, but preserve tags.
  19488. ((and (not (bolp))
  19489. (save-excursion (beginning-of-line)
  19490. (let ((case-fold-search nil))
  19491. (looking-at org-complex-heading-regexp))))
  19492. ;; At headline. Split line. However, if point is on keyword,
  19493. ;; priority cookie or tags, do not break any of them: add
  19494. ;; a newline after the headline instead.
  19495. (let ((tags-column (and (match-beginning 5)
  19496. (save-excursion (goto-char (match-beginning 5))
  19497. (current-column))))
  19498. (string
  19499. (when (and (match-end 4) (org-point-in-group (point) 4))
  19500. (delete-and-extract-region (point) (match-end 4)))))
  19501. ;; Adjust tag alignment.
  19502. (cond
  19503. ((not (and tags-column string)))
  19504. (org-auto-align-tags (org-set-tags nil t))
  19505. (t (org--align-tags-here tags-column))) ;preserve tags column
  19506. (end-of-line)
  19507. (org-show-entry)
  19508. (if indent (newline-and-indent) (newline))
  19509. (when string (save-excursion (insert (org-trim string))))))
  19510. ;; In a list, make sure indenting keeps trailing text within.
  19511. ((and indent
  19512. (not (eolp))
  19513. (org-element-lineage context '(item)))
  19514. (let ((trailing-data
  19515. (delete-and-extract-region (point) (line-end-position))))
  19516. (newline-and-indent)
  19517. (save-excursion (insert trailing-data))))
  19518. (t (if indent (newline-and-indent) (newline))))))
  19519. (defun org-return-indent ()
  19520. "Goto next table row or insert a newline and indent.
  19521. Calls `org-table-next-row' or `newline-and-indent', depending on
  19522. context. See the individual commands for more information."
  19523. (interactive)
  19524. (org-return t))
  19525. (defun org-ctrl-c-star ()
  19526. "Compute table, or change heading status of lines.
  19527. Calls `org-table-recalculate' or `org-toggle-heading',
  19528. depending on context."
  19529. (interactive)
  19530. (cond
  19531. ((org-at-table-p)
  19532. (call-interactively 'org-table-recalculate))
  19533. (t
  19534. ;; Convert all lines in region to list items
  19535. (call-interactively 'org-toggle-heading))))
  19536. (defun org-ctrl-c-minus ()
  19537. "Insert separator line in table or modify bullet status of line.
  19538. Also turns a plain line or a region of lines into list items.
  19539. Calls `org-table-insert-hline', `org-toggle-item', or
  19540. `org-cycle-list-bullet', depending on context."
  19541. (interactive)
  19542. (cond
  19543. ((org-at-table-p)
  19544. (call-interactively 'org-table-insert-hline))
  19545. ((org-region-active-p)
  19546. (call-interactively 'org-toggle-item))
  19547. ((org-in-item-p)
  19548. (call-interactively 'org-cycle-list-bullet))
  19549. (t
  19550. (call-interactively 'org-toggle-item))))
  19551. (defun org-toggle-heading (&optional nstars)
  19552. "Convert headings to normal text, or items or text to headings.
  19553. If there is no active region, only convert the current line.
  19554. With a `\\[universal-argument]' prefix, convert the whole list at
  19555. point into heading.
  19556. In a region:
  19557. - If the first non blank line is a headline, remove the stars
  19558. from all headlines in the region.
  19559. - If it is a normal line, turn each and every normal line (i.e.,
  19560. not an heading or an item) in the region into headings. If you
  19561. want to convert only the first line of this region, use one
  19562. universal prefix argument.
  19563. - If it is a plain list item, turn all plain list items into headings.
  19564. When converting a line into a heading, the number of stars is chosen
  19565. such that the lines become children of the current entry. However,
  19566. when a numeric prefix argument is given, its value determines the
  19567. number of stars to add."
  19568. (interactive "P")
  19569. (let ((skip-blanks
  19570. (function
  19571. ;; Return beginning of first non-blank line, starting from
  19572. ;; line at POS.
  19573. (lambda (pos)
  19574. (save-excursion
  19575. (goto-char pos)
  19576. (while (org-at-comment-p) (forward-line))
  19577. (skip-chars-forward " \r\t\n")
  19578. (point-at-bol)))))
  19579. beg end toggled)
  19580. ;; Determine boundaries of changes. If a universal prefix has
  19581. ;; been given, put the list in a region. If region ends at a bol,
  19582. ;; do not consider the last line to be in the region.
  19583. (when (and current-prefix-arg (org-at-item-p))
  19584. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  19585. (org-mark-element))
  19586. (if (org-region-active-p)
  19587. (setq beg (funcall skip-blanks (region-beginning))
  19588. end (copy-marker (save-excursion
  19589. (goto-char (region-end))
  19590. (if (bolp) (point) (point-at-eol)))))
  19591. (setq beg (funcall skip-blanks (point-at-bol))
  19592. end (copy-marker (point-at-eol))))
  19593. ;; Ensure inline tasks don't count as headings.
  19594. (org-with-limited-levels
  19595. (save-excursion
  19596. (goto-char beg)
  19597. (cond
  19598. ;; Case 1. Started at an heading: de-star headings.
  19599. ((org-at-heading-p)
  19600. (while (< (point) end)
  19601. (when (org-at-heading-p t)
  19602. (looking-at org-outline-regexp) (replace-match "")
  19603. (setq toggled t))
  19604. (forward-line)))
  19605. ;; Case 2. Started at an item: change items into headlines.
  19606. ;; One star will be added by `org-list-to-subtree'.
  19607. ((org-at-item-p)
  19608. (while (< (point) end)
  19609. (when (org-at-item-p)
  19610. ;; Pay attention to cases when region ends before list.
  19611. (let* ((struct (org-list-struct))
  19612. (list-end
  19613. (min (org-list-get-bottom-point struct) (1+ end))))
  19614. (save-restriction
  19615. (narrow-to-region (point) list-end)
  19616. (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
  19617. (setq toggled t))
  19618. (forward-line)))
  19619. ;; Case 3. Started at normal text: make every line an heading,
  19620. ;; skipping headlines and items.
  19621. (t (let* ((stars
  19622. (make-string
  19623. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  19624. (add-stars
  19625. (cond (nstars "") ; stars from prefix only
  19626. ((equal stars "") "*") ; before first heading
  19627. (org-odd-levels-only "**") ; inside heading, odd
  19628. (t "*"))) ; inside heading, oddeven
  19629. (rpl (concat stars add-stars " "))
  19630. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  19631. (while (< (point) (if (equal nstars '(4)) lend end))
  19632. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  19633. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  19634. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  19635. (forward-line)))))))
  19636. (unless toggled (message "Cannot toggle heading from here"))))
  19637. (defun org-meta-return (&optional _arg)
  19638. "Insert a new heading or wrap a region in a table.
  19639. Calls `org-insert-heading' or `org-table-wrap-region', depending
  19640. on context. See the individual commands for more information."
  19641. (interactive)
  19642. (org-check-before-invisible-edit 'insert)
  19643. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  19644. (call-interactively (if (org-at-table-p) #'org-table-wrap-region
  19645. #'org-insert-heading))))
  19646. ;;; Menu entries
  19647. (defsubst org-in-subtree-not-table-p ()
  19648. "Are we in a subtree and not in a table?"
  19649. (and (not (org-before-first-heading-p))
  19650. (not (org-at-table-p))))
  19651. ;; Define the Org mode menus
  19652. (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
  19653. '("Tbl"
  19654. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  19655. ["Next Field" org-cycle (org-at-table-p)]
  19656. ["Previous Field" org-shifttab (org-at-table-p)]
  19657. ["Next Row" org-return (org-at-table-p)]
  19658. "--"
  19659. ["Blank Field" org-table-blank-field (org-at-table-p)]
  19660. ["Edit Field" org-table-edit-field (org-at-table-p)]
  19661. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  19662. "--"
  19663. ("Column"
  19664. ["Move Column Left" org-metaleft (org-at-table-p)]
  19665. ["Move Column Right" org-metaright (org-at-table-p)]
  19666. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  19667. ["Insert Column" org-shiftmetaright (org-at-table-p)])
  19668. ("Row"
  19669. ["Move Row Up" org-metaup (org-at-table-p)]
  19670. ["Move Row Down" org-metadown (org-at-table-p)]
  19671. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  19672. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  19673. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  19674. "--"
  19675. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  19676. ("Rectangle"
  19677. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  19678. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  19679. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  19680. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  19681. "--"
  19682. ("Calculate"
  19683. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  19684. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  19685. ["Edit Formulas" org-edit-special (org-at-table-p)]
  19686. "--"
  19687. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  19688. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  19689. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  19690. "--"
  19691. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  19692. "--"
  19693. ["Sum Column/Rectangle" org-table-sum
  19694. (or (org-at-table-p) (org-region-active-p))]
  19695. ["Which Column?" org-table-current-column (org-at-table-p)])
  19696. ["Debug Formulas"
  19697. org-table-toggle-formula-debugger
  19698. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  19699. ["Show Col/Row Numbers"
  19700. org-table-toggle-coordinate-overlays
  19701. :style toggle
  19702. :selected (bound-and-true-p org-table-overlay-coordinates)]
  19703. "--"
  19704. ["Create" org-table-create (and (not (org-at-table-p))
  19705. org-enable-table-editor)]
  19706. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  19707. ["Import from File" org-table-import (not (org-at-table-p))]
  19708. ["Export to File" org-table-export (org-at-table-p)]
  19709. "--"
  19710. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  19711. "--"
  19712. ("Plot"
  19713. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  19714. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  19715. (easy-menu-define org-org-menu org-mode-map "Org menu"
  19716. '("Org"
  19717. ("Show/Hide"
  19718. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  19719. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  19720. ["Sparse Tree..." org-sparse-tree t]
  19721. ["Reveal Context" org-reveal t]
  19722. ["Show All" outline-show-all t]
  19723. "--"
  19724. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  19725. "--"
  19726. ["New Heading" org-insert-heading t]
  19727. ("Navigate Headings"
  19728. ["Up" outline-up-heading t]
  19729. ["Next" outline-next-visible-heading t]
  19730. ["Previous" outline-previous-visible-heading t]
  19731. ["Next Same Level" outline-forward-same-level t]
  19732. ["Previous Same Level" outline-backward-same-level t]
  19733. "--"
  19734. ["Jump" org-goto t])
  19735. ("Edit Structure"
  19736. ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
  19737. "--"
  19738. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  19739. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  19740. "--"
  19741. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  19742. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  19743. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  19744. "--"
  19745. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  19746. "--"
  19747. ["Copy visible text" org-copy-visible t]
  19748. "--"
  19749. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  19750. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  19751. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  19752. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  19753. "--"
  19754. ["Sort Region/Children" org-sort t]
  19755. "--"
  19756. ["Convert to odd levels" org-convert-to-odd-levels t]
  19757. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  19758. ("Editing"
  19759. ["Emphasis..." org-emphasize t]
  19760. ["Edit Source Example" org-edit-special t]
  19761. "--"
  19762. ["Footnote new/jump" org-footnote-action t]
  19763. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  19764. ("Archive"
  19765. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  19766. "--"
  19767. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  19768. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  19769. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
  19770. )
  19771. "--"
  19772. ("Hyperlinks"
  19773. ["Store Link (Global)" org-store-link t]
  19774. ["Find existing link to here" org-occur-link-in-agenda-files t]
  19775. ["Insert Link" org-insert-link t]
  19776. ["Follow Link" org-open-at-point t]
  19777. "--"
  19778. ["Next link" org-next-link t]
  19779. ["Previous link" org-previous-link t]
  19780. "--"
  19781. ["Descriptive Links"
  19782. org-toggle-link-display
  19783. :style radio
  19784. :selected org-descriptive-links
  19785. ]
  19786. ["Literal Links"
  19787. org-toggle-link-display
  19788. :style radio
  19789. :selected (not org-descriptive-links)])
  19790. "--"
  19791. ("TODO Lists"
  19792. ["TODO/DONE/-" org-todo t]
  19793. ("Select keyword"
  19794. ["Next keyword" org-shiftright (org-at-heading-p)]
  19795. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  19796. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  19797. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  19798. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  19799. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  19800. ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
  19801. "--"
  19802. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  19803. :selected org-enforce-todo-dependencies :style toggle :active t]
  19804. "Settings for tree at point"
  19805. ["Do Children sequentially" org-toggle-ordered-property :style radio
  19806. :selected (org-entry-get nil "ORDERED")
  19807. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19808. ["Do Children parallel" org-toggle-ordered-property :style radio
  19809. :selected (not (org-entry-get nil "ORDERED"))
  19810. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  19811. "--"
  19812. ["Set Priority" org-priority t]
  19813. ["Priority Up" org-shiftup t]
  19814. ["Priority Down" org-shiftdown t]
  19815. "--"
  19816. ["Get news from all feeds" org-feed-update-all t]
  19817. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  19818. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  19819. ("TAGS and Properties"
  19820. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  19821. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  19822. "--"
  19823. ["Set property" org-set-property (not (org-before-first-heading-p))]
  19824. ["Column view of properties" org-columns t]
  19825. ["Insert Column View DBlock" org-columns-insert-dblock t])
  19826. ("Dates and Scheduling"
  19827. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  19828. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  19829. ("Change Date"
  19830. ["1 Day Later" org-shiftright (org-at-timestamp-p)]
  19831. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
  19832. ["1 ... Later" org-shiftup (org-at-timestamp-p)]
  19833. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
  19834. ["Compute Time Range" org-evaluate-time-range t]
  19835. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  19836. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  19837. "--"
  19838. ["Custom time format" org-toggle-time-stamp-overlays
  19839. :style radio :selected org-display-custom-times]
  19840. "--"
  19841. ["Goto Calendar" org-goto-calendar t]
  19842. ["Date from Calendar" org-date-from-calendar t]
  19843. "--"
  19844. ["Start/Restart Timer" org-timer-start t]
  19845. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  19846. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  19847. ["Insert Timer String" org-timer t]
  19848. ["Insert Timer Item" org-timer-item t])
  19849. ("Logging work"
  19850. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  19851. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  19852. ["Clock out" org-clock-out t]
  19853. ["Clock cancel" org-clock-cancel t]
  19854. "--"
  19855. ["Mark as default task" org-clock-mark-default-task t]
  19856. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  19857. ["Goto running clock" org-clock-goto t]
  19858. "--"
  19859. ["Display times" org-clock-display t]
  19860. ["Create clock table" org-clock-report t]
  19861. "--"
  19862. ["Record DONE time"
  19863. (progn (setq org-log-done (not org-log-done))
  19864. (message "Switching to %s will %s record a timestamp"
  19865. (car org-done-keywords)
  19866. (if org-log-done "automatically" "not")))
  19867. :style toggle :selected org-log-done])
  19868. "--"
  19869. ["Agenda Command..." org-agenda t]
  19870. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  19871. ("File List for Agenda")
  19872. ("Special views current file"
  19873. ["TODO Tree" org-show-todo-tree t]
  19874. ["Check Deadlines" org-check-deadlines t]
  19875. ["Timeline" org-timeline t]
  19876. ["Tags/Property tree" org-match-sparse-tree t])
  19877. "--"
  19878. ["Export/Publish..." org-export-dispatch t]
  19879. ("LaTeX"
  19880. ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
  19881. :selected org-cdlatex-mode]
  19882. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  19883. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  19884. ["Modify math symbol" org-cdlatex-math-modify
  19885. (org-inside-LaTeX-fragment-p)]
  19886. ["Insert citation" org-reftex-citation t])
  19887. "--"
  19888. ("MobileOrg"
  19889. ["Push Files and Views" org-mobile-push t]
  19890. ["Get Captured and Flagged" org-mobile-pull t]
  19891. ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
  19892. "--"
  19893. ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
  19894. "--"
  19895. ("Documentation"
  19896. ["Show Version" org-version t]
  19897. ["Info Documentation" org-info t])
  19898. ("Customize"
  19899. ["Browse Org Group" org-customize t]
  19900. "--"
  19901. ["Expand This Menu" org-create-customize-menu
  19902. (fboundp 'customize-menu-create)])
  19903. ["Send bug report" org-submit-bug-report t]
  19904. "--"
  19905. ("Refresh/Reload"
  19906. ["Refresh setup current buffer" org-mode-restart t]
  19907. ["Reload Org (after update)" org-reload t]
  19908. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
  19909. ))
  19910. (defun org-info (&optional node)
  19911. "Read documentation for Org in the info system.
  19912. With optional NODE, go directly to that node."
  19913. (interactive)
  19914. (info (format "(org)%s" (or node ""))))
  19915. ;;;###autoload
  19916. (defun org-submit-bug-report ()
  19917. "Submit a bug report on Org via mail.
  19918. Don't hesitate to report any problems or inaccurate documentation.
  19919. If you don't have setup sending mail from (X)Emacs, please copy the
  19920. output buffer into your mail program, as it gives us important
  19921. information about your Org version and configuration."
  19922. (interactive)
  19923. (require 'reporter)
  19924. (defvar reporter-prompt-for-summary-p)
  19925. (org-load-modules-maybe)
  19926. (org-require-autoloaded-modules)
  19927. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  19928. (reporter-submit-bug-report
  19929. "emacs-orgmode@gnu.org"
  19930. (org-version nil 'full)
  19931. (let (list)
  19932. (save-window-excursion
  19933. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  19934. (delete-other-windows)
  19935. (erase-buffer)
  19936. (insert "You are about to submit a bug report to the Org mailing list.
  19937. We would like to add your full Org and Outline configuration to the
  19938. bug report. This greatly simplifies the work of the maintainer and
  19939. other experts on the mailing list.
  19940. HOWEVER, some variables you have customized may contain private
  19941. information. The names of customers, colleagues, or friends, might
  19942. appear in the form of file names, tags, todo states, or search strings.
  19943. If you answer yes to the prompt, you might want to check and remove
  19944. such private information before sending the email.")
  19945. (add-text-properties (point-min) (point-max) '(face org-warning))
  19946. (when (yes-or-no-p "Include your Org configuration ")
  19947. (mapatoms
  19948. (lambda (v)
  19949. (and (boundp v)
  19950. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  19951. (or (and (symbol-value v)
  19952. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  19953. (and
  19954. (get v 'custom-type) (get v 'standard-value)
  19955. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  19956. (push v list)))))
  19957. (kill-buffer (get-buffer "*Warn about privacy*"))
  19958. list))
  19959. nil nil
  19960. "Remember to cover the basics, that is, what you expected to happen and
  19961. what in fact did happen. You don't know how to make a good report? See
  19962. http://orgmode.org/manual/Feedback.html#Feedback
  19963. Your bug report will be posted to the Org mailing list.
  19964. ------------------------------------------------------------------------")
  19965. (save-excursion
  19966. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  19967. (replace-match "\\1Bug: \\3 [\\2]")))))
  19968. (defun org-install-agenda-files-menu ()
  19969. (let ((bl (buffer-list)))
  19970. (save-excursion
  19971. (while bl
  19972. (set-buffer (pop bl))
  19973. (when (derived-mode-p 'org-mode) (setq bl nil)))
  19974. (when (derived-mode-p 'org-mode)
  19975. (easy-menu-change
  19976. '("Org") "File List for Agenda"
  19977. (append
  19978. (list
  19979. ["Edit File List" (org-edit-agenda-file-list) t]
  19980. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  19981. ["Remove Current File from List" org-remove-file t]
  19982. ["Cycle through agenda files" org-cycle-agenda-files t]
  19983. ["Occur in all agenda files" org-occur-in-agenda-files t]
  19984. "--")
  19985. (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
  19986. ;;;; Documentation
  19987. (defun org-require-autoloaded-modules ()
  19988. (interactive)
  19989. (mapc #'require
  19990. '(org-agenda org-archive org-attach org-clock org-colview org-id
  19991. org-table org-timer)))
  19992. ;;;###autoload
  19993. (defun org-reload (&optional uncompiled)
  19994. "Reload all org lisp files.
  19995. With prefix arg UNCOMPILED, load the uncompiled versions."
  19996. (interactive "P")
  19997. (require 'loadhist)
  19998. (let* ((org-dir (org-find-library-dir "org"))
  19999. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  20000. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  20001. (remove-re (format "\\`%s\\'"
  20002. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  20003. (feats (delete-dups
  20004. (mapcar 'file-name-sans-extension
  20005. (mapcar 'file-name-nondirectory
  20006. (delq nil
  20007. (mapcar 'feature-file
  20008. features))))))
  20009. (lfeat (append
  20010. (sort
  20011. (setq feats
  20012. (delq nil (mapcar
  20013. (lambda (f)
  20014. (if (and (string-match feature-re f)
  20015. (not (string-match remove-re f)))
  20016. f nil))
  20017. feats)))
  20018. 'string-lessp)
  20019. (list "org-version" "org")))
  20020. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  20021. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  20022. load-uncore load-misses)
  20023. (setq load-misses
  20024. (delq 't
  20025. (mapcar (lambda (f)
  20026. (or (org-load-noerror-mustsuffix (concat org-dir f))
  20027. (and (string= org-dir contrib-dir)
  20028. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  20029. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  20030. (add-to-list 'load-uncore f 'append)
  20031. 't)
  20032. f))
  20033. lfeat)))
  20034. (when load-uncore
  20035. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  20036. (if (> (length load-uncore) 1) "s were" " was") load-uncore))
  20037. (if load-misses
  20038. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  20039. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  20040. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  20041. ;;;###autoload
  20042. (defun org-customize ()
  20043. "Call the customize function with org as argument."
  20044. (interactive)
  20045. (org-load-modules-maybe)
  20046. (org-require-autoloaded-modules)
  20047. (customize-browse 'org))
  20048. (defun org-create-customize-menu ()
  20049. "Create a full customization menu for Org mode, insert it into the menu."
  20050. (interactive)
  20051. (org-load-modules-maybe)
  20052. (org-require-autoloaded-modules)
  20053. (if (fboundp 'customize-menu-create)
  20054. (progn
  20055. (easy-menu-change
  20056. '("Org") "Customize"
  20057. `(["Browse Org group" org-customize t]
  20058. "--"
  20059. ,(customize-menu-create 'org)
  20060. ["Set" Custom-set t]
  20061. ["Save" Custom-save t]
  20062. ["Reset to Current" Custom-reset-current t]
  20063. ["Reset to Saved" Custom-reset-saved t]
  20064. ["Reset to Standard Settings" Custom-reset-standard t]))
  20065. (message "\"Org\"-menu now contains full customization menu"))
  20066. (error "Cannot expand menu (outdated version of cus-edit.el)")))
  20067. ;;;; Miscellaneous stuff
  20068. ;;; Generally useful functions
  20069. (defun org-get-at-eol (property n)
  20070. "Get text property PROPERTY at the end of line less N characters."
  20071. (get-text-property (- (point-at-eol) n) property))
  20072. (defun org-find-text-property-in-string (prop s)
  20073. "Return the first non-nil value of property PROP in string S."
  20074. (or (get-text-property 0 prop s)
  20075. (get-text-property (or (next-single-property-change 0 prop s) 0)
  20076. prop s)))
  20077. (defun org-display-warning (message)
  20078. "Display the given MESSAGE as a warning."
  20079. (display-warning 'org message :warning))
  20080. (defun org-eval (form)
  20081. "Eval FORM and return result."
  20082. (condition-case error
  20083. (eval form)
  20084. (error (format "%%![Error: %s]" error))))
  20085. (defun org-in-clocktable-p ()
  20086. "Check if the cursor is in a clocktable."
  20087. (let ((pos (point)) start)
  20088. (save-excursion
  20089. (end-of-line 1)
  20090. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  20091. (setq start (match-beginning 0))
  20092. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  20093. (>= (match-end 0) pos)
  20094. start))))
  20095. (defun org-in-verbatim-emphasis ()
  20096. (save-match-data
  20097. (and (org-in-regexp org-emph-re 2)
  20098. (>= (point) (match-beginning 3))
  20099. (<= (point) (match-end 4))
  20100. (member (match-string 3) '("=" "~")))))
  20101. (defun org-overlay-display (ovl text &optional face evap)
  20102. "Make overlay OVL display TEXT with face FACE."
  20103. (overlay-put ovl 'display text)
  20104. (if face (overlay-put ovl 'face face))
  20105. (if evap (overlay-put ovl 'evaporate t)))
  20106. (defun org-overlay-before-string (ovl text &optional face evap)
  20107. "Make overlay OVL display TEXT with face FACE."
  20108. (if face (org-add-props text nil 'face face))
  20109. (overlay-put ovl 'before-string text)
  20110. (if evap (overlay-put ovl 'evaporate t)))
  20111. (defun org-find-overlays (prop &optional pos delete)
  20112. "Find all overlays specifying PROP at POS or point.
  20113. If DELETE is non-nil, delete all those overlays."
  20114. (let (found)
  20115. (dolist (ov (overlays-at (or pos (point))) found)
  20116. (cond ((not (overlay-get ov prop)))
  20117. (delete (delete-overlay ov))
  20118. (t (push ov found))))))
  20119. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  20120. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  20121. (if (and marker (marker-buffer marker)
  20122. (buffer-live-p (marker-buffer marker)))
  20123. (progn
  20124. (pop-to-buffer-same-window (marker-buffer marker))
  20125. (when (or (> marker (point-max)) (< marker (point-min)))
  20126. (widen))
  20127. (goto-char marker)
  20128. (org-show-context 'org-goto))
  20129. (if bookmark
  20130. (bookmark-jump bookmark)
  20131. (error "Cannot find location"))))
  20132. (defun org-quote-csv-field (s)
  20133. "Quote field for inclusion in CSV material."
  20134. (if (string-match "[\",]" s)
  20135. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  20136. s))
  20137. (defun org-force-self-insert (N)
  20138. "Needed to enforce self-insert under remapping."
  20139. (interactive "p")
  20140. (self-insert-command N))
  20141. (defun org-string-width (s)
  20142. "Compute width of string, ignoring invisible characters.
  20143. This ignores character with invisibility property `org-link', and also
  20144. characters with property `org-cwidth', because these will become invisible
  20145. upon the next fontification round."
  20146. (let (b l)
  20147. (when (or (eq t buffer-invisibility-spec)
  20148. (assq 'org-link buffer-invisibility-spec))
  20149. (while (setq b (text-property-any 0 (length s)
  20150. 'invisible 'org-link s))
  20151. (setq s (concat (substring s 0 b)
  20152. (substring s (or (next-single-property-change
  20153. b 'invisible s)
  20154. (length s)))))))
  20155. (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
  20156. (setq s (concat (substring s 0 b)
  20157. (substring s (or (next-single-property-change
  20158. b 'org-cwidth s)
  20159. (length s))))))
  20160. (setq l (string-width s) b -1)
  20161. (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
  20162. (setq l (- l (get-text-property b 'org-dwidth-n s))))
  20163. l))
  20164. (defun org-shorten-string (s maxlength)
  20165. "Shorten string S so that it is no longer than MAXLENGTH characters.
  20166. If the string is shorter or has length MAXLENGTH, just return the
  20167. original string. If it is longer, the functions finds a space in the
  20168. string, breaks this string off at that locations and adds three dots
  20169. as ellipsis. Including the ellipsis, the string will not be longer
  20170. than MAXLENGTH. If finding a good breaking point in the string does
  20171. not work, the string is just chopped off in the middle of a word
  20172. if necessary."
  20173. (if (<= (length s) maxlength)
  20174. s
  20175. (let* ((n (max (- maxlength 4) 1))
  20176. (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
  20177. (if (string-match re s)
  20178. (concat (match-string 1 s) "...")
  20179. (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
  20180. (defun org-get-indentation (&optional line)
  20181. "Get the indentation of the current line, interpreting tabs.
  20182. When LINE is given, assume it represents a line and compute its indentation."
  20183. (if line
  20184. (when (string-match "^ *" (org-remove-tabs line))
  20185. (match-end 0))
  20186. (save-excursion
  20187. (beginning-of-line 1)
  20188. (skip-chars-forward " \t")
  20189. (current-column))))
  20190. (defun org-get-string-indentation (s)
  20191. "What indentation has S due to SPACE and TAB at the beginning of the string?"
  20192. (let ((n -1) (i 0) (w tab-width) c)
  20193. (catch 'exit
  20194. (while (< (setq n (1+ n)) (length s))
  20195. (setq c (aref s n))
  20196. (cond ((= c ?\ ) (setq i (1+ i)))
  20197. ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
  20198. (t (throw 'exit t)))))
  20199. i))
  20200. (defun org-remove-tabs (s &optional width)
  20201. "Replace tabulators in S with spaces.
  20202. Assumes that s is a single line, starting in column 0."
  20203. (setq width (or width tab-width))
  20204. (while (string-match "\t" s)
  20205. (setq s (replace-match
  20206. (make-string
  20207. (- (* width (/ (+ (match-beginning 0) width) width))
  20208. (match-beginning 0)) ?\ )
  20209. t t s)))
  20210. s)
  20211. (defun org-fix-indentation (line ind)
  20212. "Fix indentation in LINE.
  20213. IND is a cons cell with target and minimum indentation.
  20214. If the current indentation in LINE is smaller than the minimum,
  20215. leave it alone. If it is larger than ind, set it to the target."
  20216. (let* ((l (org-remove-tabs line))
  20217. (i (org-get-indentation l))
  20218. (i1 (car ind)) (i2 (cdr ind)))
  20219. (when (>= i i2) (setq l (substring line i2)))
  20220. (if (> i1 0)
  20221. (concat (make-string i1 ?\ ) l)
  20222. l)))
  20223. (defun org-remove-indentation (code &optional n)
  20224. "Remove maximum common indentation in string CODE and return it.
  20225. N may optionally be the number of columns to remove. Return CODE
  20226. as-is if removal failed."
  20227. (with-temp-buffer
  20228. (insert code)
  20229. (if (org-do-remove-indentation n) (buffer-string) code)))
  20230. (defun org-do-remove-indentation (&optional n)
  20231. "Remove the maximum common indentation from the buffer.
  20232. When optional argument N is a positive integer, remove exactly
  20233. that much characters from indentation, if possible. Return nil
  20234. if it fails."
  20235. (catch :exit
  20236. (goto-char (point-min))
  20237. ;; Find maximum common indentation, if not specified.
  20238. (let ((n (or n
  20239. (let ((min-ind (point-max)))
  20240. (save-excursion
  20241. (while (re-search-forward "^[ \t]*\\S-" nil t)
  20242. (let ((ind (1- (current-column))))
  20243. (if (zerop ind) (throw :exit nil)
  20244. (setq min-ind (min min-ind ind))))))
  20245. min-ind))))
  20246. (if (zerop n) (throw :exit nil)
  20247. ;; Remove exactly N indentation, but give up if not possible.
  20248. (while (not (eobp))
  20249. (let ((ind (progn (skip-chars-forward " \t") (current-column))))
  20250. (cond ((eolp) (delete-region (line-beginning-position) (point)))
  20251. ((< ind n) (throw :exit nil))
  20252. (t (indent-line-to (- ind n))))
  20253. (forward-line)))
  20254. ;; Signal success.
  20255. t))))
  20256. (defun org-fill-template (template alist)
  20257. "Find each %key of ALIST in TEMPLATE and replace it."
  20258. (let ((case-fold-search nil))
  20259. (dolist (entry (sort (copy-sequence alist)
  20260. (lambda (a b) (< (length (car a)) (length (car b))))))
  20261. (setq template
  20262. (replace-regexp-in-string
  20263. (concat "%" (regexp-quote (car entry)))
  20264. (or (cdr entry) "") template t t)))
  20265. template))
  20266. (defun org-base-buffer (buffer)
  20267. "Return the base buffer of BUFFER, if it has one. Else return the buffer."
  20268. (if (not buffer)
  20269. buffer
  20270. (or (buffer-base-buffer buffer)
  20271. buffer)))
  20272. (defun org-wrap (string &optional width lines)
  20273. "Wrap string to either a number of lines, or a width in characters.
  20274. If WIDTH is non-nil, the string is wrapped to that width, however many lines
  20275. that costs. If there is a word longer than WIDTH, the text is actually
  20276. wrapped to the length of that word.
  20277. IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
  20278. many lines, whatever width that takes.
  20279. The return value is a list of lines, without newlines at the end."
  20280. (let* ((words (org-split-string string "[ \t\n]+"))
  20281. (maxword (apply 'max (mapcar 'org-string-width words)))
  20282. w ll)
  20283. (cond (width
  20284. (org-do-wrap words (max maxword width)))
  20285. (lines
  20286. (setq w maxword)
  20287. (setq ll (org-do-wrap words maxword))
  20288. (if (<= (length ll) lines)
  20289. ll
  20290. (setq ll words)
  20291. (while (> (length ll) lines)
  20292. (setq w (1+ w))
  20293. (setq ll (org-do-wrap words w)))
  20294. ll))
  20295. (t (error "Cannot wrap this")))))
  20296. (defun org-do-wrap (words width)
  20297. "Create lines of maximum width WIDTH (in characters) from word list WORDS."
  20298. (let (lines line)
  20299. (while words
  20300. (setq line (pop words))
  20301. (while (and words (< (+ (length line) (length (car words))) width))
  20302. (setq line (concat line " " (pop words))))
  20303. (setq lines (push line lines)))
  20304. (nreverse lines)))
  20305. (defun org-split-string (string &optional separators)
  20306. "Splits STRING into substrings at SEPARATORS.
  20307. SEPARATORS is a regular expression.
  20308. No empty strings are returned if there are matches at the beginning
  20309. and end of string."
  20310. ;; FIXME: why not use (split-string STRING SEPARATORS t)?
  20311. (let ((start 0) notfirst list)
  20312. (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
  20313. (if (and notfirst
  20314. (= start (match-beginning 0))
  20315. (< start (length string)))
  20316. (1+ start) start))
  20317. (< (match-beginning 0) (length string)))
  20318. (setq notfirst t)
  20319. (or (eq (match-beginning 0) 0)
  20320. (and (eq (match-beginning 0) (match-end 0))
  20321. (eq (match-beginning 0) start))
  20322. (push (substring string start (match-beginning 0)) list))
  20323. (setq start (match-end 0)))
  20324. (or (eq start (length string))
  20325. (push (substring string start) list))
  20326. (nreverse list)))
  20327. (defun org-quote-vert (s)
  20328. "Replace \"|\" with \"\\vert\"."
  20329. (while (string-match "|" s)
  20330. (setq s (replace-match "\\vert" t t s)))
  20331. s)
  20332. (defun org-uuidgen-p (s)
  20333. "Is S an ID created by UUIDGEN?"
  20334. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  20335. (defun org-in-src-block-p (&optional inside)
  20336. "Whether point is in a code source block.
  20337. When INSIDE is non-nil, don't consider we are within a src block
  20338. when point is at #+BEGIN_SRC or #+END_SRC."
  20339. (let ((case-fold-search t))
  20340. (or (and (eq (get-char-property (point) 'src-block) t))
  20341. (and (not inside)
  20342. (save-match-data
  20343. (save-excursion
  20344. (beginning-of-line)
  20345. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  20346. (defun org-context ()
  20347. "Return a list of contexts of the current cursor position.
  20348. If several contexts apply, all are returned.
  20349. Each context entry is a list with a symbol naming the context, and
  20350. two positions indicating start and end of the context. Possible
  20351. contexts are:
  20352. :headline anywhere in a headline
  20353. :headline-stars on the leading stars in a headline
  20354. :todo-keyword on a TODO keyword (including DONE) in a headline
  20355. :tags on the TAGS in a headline
  20356. :priority on the priority cookie in a headline
  20357. :item on the first line of a plain list item
  20358. :item-bullet on the bullet/number of a plain list item
  20359. :checkbox on the checkbox in a plain list item
  20360. :table in an Org table
  20361. :table-special on a special filed in a table
  20362. :table-table in a table.el table
  20363. :clocktable in a clocktable
  20364. :src-block in a source block
  20365. :link on a hyperlink
  20366. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  20367. :target on a <<target>>
  20368. :radio-target on a <<<radio-target>>>
  20369. :latex-fragment on a LaTeX fragment
  20370. :latex-preview on a LaTeX fragment with overlaid preview image
  20371. This function expects the position to be visible because it uses font-lock
  20372. faces as a help to recognize the following contexts: :table-special, :link,
  20373. and :keyword."
  20374. (let* ((f (get-text-property (point) 'face))
  20375. (faces (if (listp f) f (list f)))
  20376. (case-fold-search t)
  20377. (p (point)) clist o)
  20378. ;; First the large context
  20379. (cond
  20380. ((org-at-heading-p t)
  20381. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  20382. (when (progn
  20383. (beginning-of-line 1)
  20384. (looking-at org-todo-line-tags-regexp))
  20385. (push (org-point-in-group p 1 :headline-stars) clist)
  20386. (push (org-point-in-group p 2 :todo-keyword) clist)
  20387. (push (org-point-in-group p 4 :tags) clist))
  20388. (goto-char p)
  20389. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  20390. (when (looking-at "\\[#[A-Z0-9]\\]")
  20391. (push (org-point-in-group p 0 :priority) clist)))
  20392. ((org-at-item-p)
  20393. (push (org-point-in-group p 2 :item-bullet) clist)
  20394. (push (list :item (point-at-bol)
  20395. (save-excursion (org-end-of-item) (point)))
  20396. clist)
  20397. (and (org-at-item-checkbox-p)
  20398. (push (org-point-in-group p 0 :checkbox) clist)))
  20399. ((org-at-table-p)
  20400. (push (list :table (org-table-begin) (org-table-end)) clist)
  20401. (when (memq 'org-formula faces)
  20402. (push (list :table-special
  20403. (previous-single-property-change p 'face)
  20404. (next-single-property-change p 'face)) clist)))
  20405. ((org-at-table-p 'any)
  20406. (push (list :table-table) clist)))
  20407. (goto-char p)
  20408. (let ((case-fold-search t))
  20409. ;; New the "medium" contexts: clocktables, source blocks
  20410. (cond ((org-in-clocktable-p)
  20411. (push (list :clocktable
  20412. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  20413. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  20414. (match-beginning 1))
  20415. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  20416. (match-end 0))) clist))
  20417. ((org-in-src-block-p)
  20418. (push (list :src-block
  20419. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  20420. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  20421. (match-beginning 1))
  20422. (and (search-forward "#+END_SRC" nil t)
  20423. (match-beginning 0))) clist))))
  20424. (goto-char p)
  20425. ;; Now the small context
  20426. (cond
  20427. ((org-at-timestamp-p)
  20428. (push (org-point-in-group p 0 :timestamp) clist))
  20429. ((memq 'org-link faces)
  20430. (push (list :link
  20431. (previous-single-property-change p 'face)
  20432. (next-single-property-change p 'face)) clist))
  20433. ((memq 'org-special-keyword faces)
  20434. (push (list :keyword
  20435. (previous-single-property-change p 'face)
  20436. (next-single-property-change p 'face)) clist))
  20437. ((org-at-target-p)
  20438. (push (org-point-in-group p 0 :target) clist)
  20439. (goto-char (1- (match-beginning 0)))
  20440. (when (looking-at org-radio-target-regexp)
  20441. (push (org-point-in-group p 0 :radio-target) clist))
  20442. (goto-char p))
  20443. ((setq o (cl-some
  20444. (lambda (o)
  20445. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  20446. o))
  20447. (overlays-at (point))))
  20448. (push (list :latex-fragment
  20449. (overlay-start o) (overlay-end o)) clist)
  20450. (push (list :latex-preview
  20451. (overlay-start o) (overlay-end o)) clist))
  20452. ((org-inside-LaTeX-fragment-p)
  20453. ;; FIXME: positions wrong.
  20454. (push (list :latex-fragment (point) (point)) clist)))
  20455. (setq clist (nreverse (delq nil clist)))
  20456. clist))
  20457. (defun org-in-regexp (regexp &optional nlines visually)
  20458. "Check if point is inside a match of REGEXP.
  20459. Normally only the current line is checked, but you can include
  20460. NLINES extra lines around point into the search. If VISUALLY is
  20461. set, require that the cursor is not after the match but really
  20462. on, so that the block visually is on the match.
  20463. Return nil or a cons cell (BEG . END) where BEG and END are,
  20464. respectively, the positions at the beginning and the end of the
  20465. match."
  20466. (catch :exit
  20467. (let ((pos (point))
  20468. (eol (line-end-position (if nlines (1+ nlines) 1))))
  20469. (save-excursion
  20470. (beginning-of-line (- 1 (or nlines 0)))
  20471. (while (and (re-search-forward regexp eol t)
  20472. (<= (match-beginning 0) pos))
  20473. (let ((end (match-end 0)))
  20474. (when (or (> end pos) (and (= end pos) (not visually)))
  20475. (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
  20476. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  20477. "Non-nil when point is between matches of START-RE and END-RE.
  20478. Also return a non-nil value when point is on one of the matches.
  20479. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  20480. buffer positions. Default values are the positions of headlines
  20481. surrounding the point.
  20482. The functions returns a cons cell whose car (resp. cdr) is the
  20483. position before START-RE (resp. after END-RE)."
  20484. (save-match-data
  20485. (let ((pos (point))
  20486. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  20487. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  20488. beg end)
  20489. (save-excursion
  20490. ;; Point is on a block when on START-RE or if START-RE can be
  20491. ;; found before it...
  20492. (and (or (org-in-regexp start-re)
  20493. (re-search-backward start-re limit-up t))
  20494. (setq beg (match-beginning 0))
  20495. ;; ... and END-RE after it...
  20496. (goto-char (match-end 0))
  20497. (re-search-forward end-re limit-down t)
  20498. (> (setq end (match-end 0)) pos)
  20499. ;; ... without another START-RE in-between.
  20500. (goto-char (match-beginning 0))
  20501. (not (re-search-backward start-re (1+ beg) t))
  20502. ;; Return value.
  20503. (cons beg end))))))
  20504. (defun org-in-block-p (names)
  20505. "Non-nil when point belongs to a block whose name belongs to NAMES.
  20506. NAMES is a list of strings containing names of blocks.
  20507. Return first block name matched, or nil. Beware that in case of
  20508. nested blocks, the returned name may not belong to the closest
  20509. block from point."
  20510. (save-match-data
  20511. (catch 'exit
  20512. (let ((case-fold-search t)
  20513. (lim-up (save-excursion (outline-previous-heading)))
  20514. (lim-down (save-excursion (outline-next-heading))))
  20515. (dolist (name names)
  20516. (let ((n (regexp-quote name)))
  20517. (when (org-between-regexps-p
  20518. (concat "^[ \t]*#\\+begin_" n)
  20519. (concat "^[ \t]*#\\+end_" n)
  20520. lim-up lim-down)
  20521. (throw 'exit n)))))
  20522. nil)))
  20523. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  20524. "Call `multi-occur' with buffers for all agenda files."
  20525. (interactive "sOrg-files matching: ")
  20526. (let* ((files (org-agenda-files))
  20527. (tnames (mapcar #'file-truename files))
  20528. (extra org-agenda-text-search-extra-files))
  20529. (when (eq (car extra) 'agenda-archives)
  20530. (setq extra (cdr extra))
  20531. (setq files (org-add-archive-files files)))
  20532. (dolist (f extra)
  20533. (unless (member (file-truename f) tnames)
  20534. (unless (member f files) (setq files (append files (list f))))
  20535. (setq tnames (append tnames (list (file-truename f))))))
  20536. (multi-occur
  20537. (mapcar (lambda (x)
  20538. (with-current-buffer
  20539. ;; FIXME: Why not just (find-file-noselect x)?
  20540. ;; Is it to avoid the "revert buffer" prompt?
  20541. (or (get-file-buffer x) (find-file-noselect x))
  20542. (widen)
  20543. (current-buffer)))
  20544. files)
  20545. regexp)))
  20546. (add-hook 'occur-mode-find-occurrence-hook
  20547. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  20548. (defun org-occur-link-in-agenda-files ()
  20549. "Create a link and search for it in the agendas.
  20550. The link is not stored in `org-stored-links', it is just created
  20551. for the search purpose."
  20552. (interactive)
  20553. (let ((link (condition-case nil
  20554. (org-store-link nil)
  20555. (error "Unable to create a link to here"))))
  20556. (org-occur-in-agenda-files (regexp-quote link))))
  20557. (defun org-reverse-string (string)
  20558. "Return the reverse of STRING."
  20559. (apply 'string (reverse (string-to-list string))))
  20560. ;; defsubst org-uniquify must be defined before first use
  20561. (defun org-uniquify-alist (alist)
  20562. "Merge elements of ALIST with the same key.
  20563. For example, in this alist:
  20564. \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
  20565. => \\='((a 1 3) (b 2))
  20566. merge (a 1) and (a 3) into (a 1 3).
  20567. The function returns the new ALIST."
  20568. (let (rtn)
  20569. (dolist (e alist rtn)
  20570. (let (n)
  20571. (if (not (assoc (car e) rtn))
  20572. (push e rtn)
  20573. (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
  20574. (setq rtn (assq-delete-all (car e) rtn))
  20575. (push n rtn))))))
  20576. (defun org-delete-all (elts list)
  20577. "Remove all elements in ELTS from LIST.
  20578. Comparison is done with `equal'. It is a destructive operation
  20579. that may remove elements by altering the list structure."
  20580. (while elts
  20581. (setq list (delete (pop elts) list)))
  20582. list)
  20583. (defun org-back-over-empty-lines ()
  20584. "Move backwards over whitespace, to the beginning of the first empty line.
  20585. Returns the number of empty lines passed."
  20586. (let ((pos (point)))
  20587. (if (cdr (assq 'heading org-blank-before-new-entry))
  20588. (skip-chars-backward " \t\n\r")
  20589. (unless (eobp)
  20590. (forward-line -1)))
  20591. (beginning-of-line 2)
  20592. (goto-char (min (point) pos))
  20593. (count-lines (point) pos)))
  20594. (defun org-skip-whitespace ()
  20595. (skip-chars-forward " \t\n\r"))
  20596. (defun org-point-in-group (point group &optional context)
  20597. "Check if POINT is in match-group GROUP.
  20598. If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
  20599. match. If the match group does not exist or point is not inside it,
  20600. return nil."
  20601. (and (match-beginning group)
  20602. (>= point (match-beginning group))
  20603. (<= point (match-end group))
  20604. (if context
  20605. (list context (match-beginning group) (match-end group))
  20606. t)))
  20607. (defun org-switch-to-buffer-other-window (&rest args)
  20608. "Switch to buffer in a second window on the current frame.
  20609. In particular, do not allow pop-up frames.
  20610. Returns the newly created buffer."
  20611. (org-no-popups
  20612. (apply 'switch-to-buffer-other-window args)))
  20613. (defun org-combine-plists (&rest plists)
  20614. "Create a single property list from all plists in PLISTS.
  20615. The process starts by copying the first list, and then setting properties
  20616. from the other lists. Settings in the last list are the most significant
  20617. ones and overrule settings in the other lists."
  20618. (let ((rtn (copy-sequence (pop plists)))
  20619. p v ls)
  20620. (while plists
  20621. (setq ls (pop plists))
  20622. (while ls
  20623. (setq p (pop ls) v (pop ls))
  20624. (setq rtn (plist-put rtn p v))))
  20625. rtn))
  20626. (defun org-replace-escapes (string table)
  20627. "Replace %-escapes in STRING with values in TABLE.
  20628. TABLE is an association list with keys like \"%a\" and string values.
  20629. The sequences in STRING may contain normal field width and padding information,
  20630. for example \"%-5s\". Replacements happen in the sequence given by TABLE,
  20631. so values can contain further %-escapes if they are define later in TABLE."
  20632. (let ((tbl (copy-alist table))
  20633. (case-fold-search nil)
  20634. (pchg 0)
  20635. re rpl)
  20636. (dolist (e tbl)
  20637. (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
  20638. (when (and (cdr e) (string-match re (cdr e)))
  20639. (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
  20640. (safe "SREF"))
  20641. (add-text-properties 0 3 (list 'sref sref) safe)
  20642. (setcdr e (replace-match safe t t (cdr e)))))
  20643. (while (string-match re string)
  20644. (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
  20645. (cdr e)))
  20646. (setq string (replace-match rpl t t string))))
  20647. (while (setq pchg (next-property-change pchg string))
  20648. (let ((sref (get-text-property pchg 'sref string)))
  20649. (when (and sref (string-match "SREF" string pchg))
  20650. (setq string (replace-match sref t t string)))))
  20651. string))
  20652. (defun org-find-base-buffer-visiting (file)
  20653. "Like `find-buffer-visiting' but always return the base buffer and
  20654. not an indirect buffer."
  20655. (let ((buf (or (get-file-buffer file)
  20656. (find-buffer-visiting file))))
  20657. (if buf
  20658. (or (buffer-base-buffer buf) buf)
  20659. nil)))
  20660. ;;; TODO: Only called once, from ox-odt which should probably use
  20661. ;;; org-export-inline-image-p or something.
  20662. (defun org-file-image-p (file)
  20663. "Return non-nil if FILE is an image."
  20664. (save-match-data
  20665. (string-match (image-file-name-regexp) file)))
  20666. (defun org-get-cursor-date (&optional with-time)
  20667. "Return the date at cursor in as a time.
  20668. This works in the calendar and in the agenda, anywhere else it just
  20669. returns the current time.
  20670. If WITH-TIME is non-nil, returns the time of the event at point (in
  20671. the agenda) or the current time of the day."
  20672. (let (date day defd tp hod mod)
  20673. (when with-time
  20674. (setq tp (get-text-property (point) 'time))
  20675. (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
  20676. (setq hod (string-to-number (match-string 1 tp))
  20677. mod (string-to-number (match-string 2 tp))))
  20678. (or tp (let ((now (decode-time)))
  20679. (setq hod (nth 2 now)
  20680. mod (nth 1 now)))))
  20681. (cond
  20682. ((eq major-mode 'calendar-mode)
  20683. (setq date (calendar-cursor-to-date)
  20684. defd (encode-time 0 (or mod 0) (or hod 0)
  20685. (nth 1 date) (nth 0 date) (nth 2 date))))
  20686. ((eq major-mode 'org-agenda-mode)
  20687. (setq day (get-text-property (point) 'day))
  20688. (when day
  20689. (setq date (calendar-gregorian-from-absolute day)
  20690. defd (encode-time 0 (or mod 0) (or hod 0)
  20691. (nth 1 date) (nth 0 date) (nth 2 date))))))
  20692. (or defd (current-time))))
  20693. (defun org-mark-subtree (&optional up)
  20694. "Mark the current subtree.
  20695. This puts point at the start of the current subtree, and mark at
  20696. the end. If a numeric prefix UP is given, move up into the
  20697. hierarchy of headlines by UP levels before marking the subtree."
  20698. (interactive "P")
  20699. (org-with-limited-levels
  20700. (cond ((org-at-heading-p) (beginning-of-line))
  20701. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  20702. (t (outline-previous-visible-heading 1))))
  20703. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  20704. (if (called-interactively-p 'any)
  20705. (call-interactively 'org-mark-element)
  20706. (org-mark-element)))
  20707. (defun org-file-newer-than-p (file time)
  20708. "Non-nil if FILE is newer than TIME.
  20709. FILE is a filename, as a string, TIME is a list of integers, as
  20710. returned by, e.g., `current-time'."
  20711. (and (file-exists-p file)
  20712. ;; Only compare times up to whole seconds as some file-systems
  20713. ;; (e.g. HFS+) do not retain any finer granularity. As
  20714. ;; a consequence, make sure we return non-nil when the two
  20715. ;; times are equal.
  20716. (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
  20717. (cl-subseq time 0 2)))))
  20718. (defun org-compile-file (source process ext &optional err-msg log-buf spec)
  20719. "Compile a SOURCE file using PROCESS.
  20720. PROCESS is either a function or a list of shell commands, as
  20721. strings. EXT is a file extension, without the leading dot, as
  20722. a string. It is used to check if the process actually succeeded.
  20723. PROCESS must create a file with the same base name and directory
  20724. as SOURCE, but ending with EXT. The function then returns its
  20725. filename. Otherwise, it raises an error. The error message can
  20726. then be refined by providing string ERR-MSG, which is appended to
  20727. the standard message.
  20728. If PROCESS is a function, it is called with a single argument:
  20729. the SOURCE file.
  20730. If it is a list of commands, each of them is called using
  20731. `shell-command'. By default, in each command, %b, %f, %F, %o and
  20732. %O are replaced with, respectively, SOURCE base name, name, full
  20733. name, directory and absolute output file name. It is possible,
  20734. however, to use more place-holders by specifying them in optional
  20735. argument SPEC, as an alist following the pattern
  20736. (CHARACTER . REPLACEMENT-STRING).
  20737. When PROCESS is a list of commands, optional argument LOG-BUF can
  20738. be set to a buffer or a buffer name. `shell-command' then uses
  20739. it for output."
  20740. (let* ((base-name (file-name-base source))
  20741. (full-name (file-truename source))
  20742. (out-dir (or (file-name-directory source) "./"))
  20743. (output (expand-file-name (concat base-name "." ext) out-dir))
  20744. (time (current-time))
  20745. (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
  20746. (save-window-excursion
  20747. (pcase process
  20748. ((pred functionp) (funcall process (shell-quote-argument source)))
  20749. ((pred consp)
  20750. (let ((log-buf (and log-buf (get-buffer-create log-buf)))
  20751. (spec (append spec
  20752. `((?b . ,(shell-quote-argument base-name))
  20753. (?f . ,(shell-quote-argument source))
  20754. (?F . ,(shell-quote-argument full-name))
  20755. (?o . ,(shell-quote-argument out-dir))
  20756. (?O . ,(shell-quote-argument output))))))
  20757. (dolist (command process)
  20758. (shell-command (format-spec command spec) log-buf))))
  20759. (_ (error "No valid command to process %S%s" source err-msg))))
  20760. ;; Check for process failure. Output file is expected to be
  20761. ;; located in the same directory as SOURCE.
  20762. (unless (org-file-newer-than-p output time)
  20763. (error (format "File %S wasn't produced%s" output err-msg)))
  20764. output))
  20765. ;;; Indentation
  20766. (defvar org-element-greater-elements)
  20767. (defun org--get-expected-indentation (element contentsp)
  20768. "Expected indentation column for current line, according to ELEMENT.
  20769. ELEMENT is an element containing point. CONTENTSP is non-nil
  20770. when indentation is to be computed according to contents of
  20771. ELEMENT."
  20772. (let ((type (org-element-type element))
  20773. (start (org-element-property :begin element))
  20774. (post-affiliated (org-element-property :post-affiliated element)))
  20775. (org-with-wide-buffer
  20776. (cond
  20777. (contentsp
  20778. (cl-case type
  20779. ((diary-sexp footnote-definition) 0)
  20780. ((headline inlinetask nil)
  20781. (if (not org-adapt-indentation) 0
  20782. (let ((level (org-current-level)))
  20783. (if level (1+ level) 0))))
  20784. ((item plain-list) (org-list-item-body-column post-affiliated))
  20785. (t
  20786. (goto-char start)
  20787. (org-get-indentation))))
  20788. ((memq type '(headline inlinetask nil))
  20789. (if (org-match-line "[ \t]*$")
  20790. (org--get-expected-indentation element t)
  20791. 0))
  20792. ((memq type '(diary-sexp footnote-definition)) 0)
  20793. ;; First paragraph of a footnote definition or an item.
  20794. ;; Indent like parent.
  20795. ((< (line-beginning-position) start)
  20796. (org--get-expected-indentation
  20797. (org-element-property :parent element) t))
  20798. ;; At first line: indent according to previous sibling, if any,
  20799. ;; ignoring footnote definitions and inline tasks, or parent's
  20800. ;; contents.
  20801. ((= (line-beginning-position) start)
  20802. (catch 'exit
  20803. (while t
  20804. (if (= (point-min) start) (throw 'exit 0)
  20805. (goto-char (1- start))
  20806. (let* ((previous (org-element-at-point))
  20807. (parent previous))
  20808. (while (and parent (<= (org-element-property :end parent) start))
  20809. (setq previous parent
  20810. parent (org-element-property :parent parent)))
  20811. (cond
  20812. ((not previous) (throw 'exit 0))
  20813. ((> (org-element-property :end previous) start)
  20814. (throw 'exit (org--get-expected-indentation previous t)))
  20815. ((memq (org-element-type previous)
  20816. '(footnote-definition inlinetask))
  20817. (setq start (org-element-property :begin previous)))
  20818. (t (goto-char (org-element-property :begin previous))
  20819. (throw 'exit
  20820. (if (bolp) (org-get-indentation)
  20821. ;; At first paragraph in an item or
  20822. ;; a footnote definition.
  20823. (org--get-expected-indentation
  20824. (org-element-property :parent previous) t))))))))))
  20825. ;; Otherwise, move to the first non-blank line above.
  20826. (t
  20827. (beginning-of-line)
  20828. (let ((pos (point)))
  20829. (skip-chars-backward " \r\t\n")
  20830. (cond
  20831. ;; Two blank lines end a footnote definition or a plain
  20832. ;; list. When we indent an empty line after them, the
  20833. ;; containing list or footnote definition is over, so it
  20834. ;; qualifies as a previous sibling. Therefore, we indent
  20835. ;; like its first line.
  20836. ((and (memq type '(footnote-definition plain-list))
  20837. (> (count-lines (point) pos) 2))
  20838. (goto-char start)
  20839. (org-get-indentation))
  20840. ;; Line above is the first one of a paragraph at the
  20841. ;; beginning of an item or a footnote definition. Indent
  20842. ;; like parent.
  20843. ((< (line-beginning-position) start)
  20844. (org--get-expected-indentation
  20845. (org-element-property :parent element) t))
  20846. ;; Line above is the beginning of an element, i.e., point
  20847. ;; was originally on the blank lines between element's start
  20848. ;; and contents.
  20849. ((= (line-beginning-position) post-affiliated)
  20850. (org--get-expected-indentation element t))
  20851. ;; POS is after contents in a greater element. Indent like
  20852. ;; the beginning of the element.
  20853. ((and (memq type org-element-greater-elements)
  20854. (let ((cend (org-element-property :contents-end element)))
  20855. (and cend (<= cend pos))))
  20856. ;; As a special case, if point is at the end of a footnote
  20857. ;; definition or an item, indent like the very last element
  20858. ;; within. If that last element is an item, indent like
  20859. ;; its contents.
  20860. (if (memq type '(footnote-definition item plain-list))
  20861. (let ((last (org-element-at-point)))
  20862. (goto-char pos)
  20863. (org--get-expected-indentation
  20864. last (eq (org-element-type last) 'item)))
  20865. (goto-char start)
  20866. (org-get-indentation)))
  20867. ;; In any other case, indent like the current line.
  20868. (t (org-get-indentation)))))))))
  20869. (defun org--align-node-property ()
  20870. "Align node property at point.
  20871. Alignment is done according to `org-property-format', which see."
  20872. (when (save-excursion
  20873. (beginning-of-line)
  20874. (looking-at org-property-re))
  20875. (replace-match
  20876. (concat (match-string 4)
  20877. (org-trim
  20878. (format org-property-format (match-string 1) (match-string 3))))
  20879. t t)))
  20880. (defun org-indent-line ()
  20881. "Indent line depending on context.
  20882. Indentation is done according to the following rules:
  20883. - Footnote definitions, diary sexps, headlines and inline tasks
  20884. have to start at column 0.
  20885. - On the very first line of an element, consider, in order, the
  20886. next rules until one matches:
  20887. 1. If there's a sibling element before, ignoring footnote
  20888. definitions and inline tasks, indent like its first line.
  20889. 2. If element has a parent, indent like its contents. More
  20890. precisely, if parent is an item, indent after the
  20891. description part, if any, or the bullet (see
  20892. `org-list-description-max-indent'). Else, indent like
  20893. parent's first line.
  20894. 3. Otherwise, indent relatively to current level, if
  20895. `org-adapt-indentation' is non-nil, or to left margin.
  20896. - On a blank line at the end of an element, indent according to
  20897. the type of the element. More precisely
  20898. 1. If element is a plain list, an item, or a footnote
  20899. definition, indent like the very last element within.
  20900. 2. If element is a paragraph, indent like its last non blank
  20901. line.
  20902. 3. Otherwise, indent like its very first line.
  20903. - In the code part of a source block, use language major mode
  20904. to indent current line if `org-src-tab-acts-natively' is
  20905. non-nil. If it is nil, do nothing.
  20906. - Otherwise, indent like the first non-blank line above.
  20907. The function doesn't indent an item as it could break the whole
  20908. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  20909. `\\[org-shiftmetaright]'.
  20910. Also align node properties according to `org-property-format'."
  20911. (interactive)
  20912. (cond
  20913. (orgstruct-is-++
  20914. (let ((indent-line-function
  20915. (cl-cadadr (assq 'indent-line-function org-fb-vars))))
  20916. (indent-according-to-mode)))
  20917. ((org-at-heading-p) 'noindent)
  20918. (t
  20919. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  20920. (type (org-element-type element)))
  20921. (cond ((and (memq type '(plain-list item))
  20922. (= (line-beginning-position)
  20923. (org-element-property :post-affiliated element)))
  20924. 'noindent)
  20925. ((and (eq type 'latex-environment)
  20926. (>= (point) (org-element-property :post-affiliated element))
  20927. (< (point) (org-with-wide-buffer
  20928. (goto-char (org-element-property :end element))
  20929. (skip-chars-backward " \r\t\n")
  20930. (line-beginning-position 2))))
  20931. 'noindent)
  20932. ((and (eq type 'src-block)
  20933. org-src-tab-acts-natively
  20934. (> (line-beginning-position)
  20935. (org-element-property :post-affiliated element))
  20936. (< (line-beginning-position)
  20937. (org-with-wide-buffer
  20938. (goto-char (org-element-property :end element))
  20939. (skip-chars-backward " \r\t\n")
  20940. (line-beginning-position))))
  20941. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  20942. (t
  20943. (let ((column (org--get-expected-indentation element nil)))
  20944. ;; Preserve current column.
  20945. (if (<= (current-column) (current-indentation))
  20946. (indent-line-to column)
  20947. (save-excursion (indent-line-to column))))
  20948. ;; Align node property. Also preserve current column.
  20949. (when (eq type 'node-property)
  20950. (let ((column (current-column)))
  20951. (org--align-node-property)
  20952. (org-move-to-column column)))))))))
  20953. (defun org-indent-region (start end)
  20954. "Indent each non-blank line in the region.
  20955. Called from a program, START and END specify the region to
  20956. indent. The function will not indent contents of example blocks,
  20957. verse blocks and export blocks as leading white spaces are
  20958. assumed to be significant there."
  20959. (interactive "r")
  20960. (save-excursion
  20961. (goto-char start)
  20962. (skip-chars-forward " \r\t\n")
  20963. (unless (eobp) (beginning-of-line))
  20964. (let ((indent-to
  20965. (lambda (ind pos)
  20966. ;; Set IND as indentation for all lines between point and
  20967. ;; POS. Blank lines are ignored. Leave point after POS
  20968. ;; once done.
  20969. (let ((limit (copy-marker pos)))
  20970. (while (< (point) limit)
  20971. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  20972. (forward-line))
  20973. (set-marker limit nil))))
  20974. (end (copy-marker end)))
  20975. (while (< (point) end)
  20976. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  20977. (let* ((element (org-element-at-point))
  20978. (type (org-element-type element))
  20979. (element-end (copy-marker (org-element-property :end element)))
  20980. (ind (org--get-expected-indentation element nil)))
  20981. (cond
  20982. ;; Element indented as a single block. Example blocks
  20983. ;; preserving indentation are a special case since the
  20984. ;; "contents" must not be indented whereas the block
  20985. ;; boundaries can.
  20986. ((or (memq type '(export-block latex-environment))
  20987. (and (eq type 'example-block)
  20988. (not
  20989. (or org-src-preserve-indentation
  20990. (org-element-property :preserve-indent element)))))
  20991. (let ((offset (- ind (org-get-indentation))))
  20992. (unless (zerop offset)
  20993. (indent-rigidly (org-element-property :begin element)
  20994. (org-element-property :end element)
  20995. offset)))
  20996. (goto-char element-end))
  20997. ;; Elements indented line wise. Be sure to exclude
  20998. ;; example blocks (preserving indentation) and source
  20999. ;; blocks from this category as they are treated
  21000. ;; specially later.
  21001. ((or (memq type '(paragraph table table-row))
  21002. (not (or (org-element-property :contents-begin element)
  21003. (memq type '(example-block src-block)))))
  21004. (when (eq type 'node-property)
  21005. (org--align-node-property)
  21006. (beginning-of-line))
  21007. (funcall indent-to ind (min element-end end)))
  21008. ;; Elements consisting of three parts: before the
  21009. ;; contents, the contents, and after the contents. The
  21010. ;; contents are treated specially, according to the
  21011. ;; element type, or not indented at all. Other parts are
  21012. ;; indented as a single block.
  21013. (t
  21014. (let* ((post (copy-marker
  21015. (org-element-property :post-affiliated element)))
  21016. (cbeg
  21017. (copy-marker
  21018. (cond
  21019. ((not (org-element-property :contents-begin element))
  21020. ;; Fake contents for source blocks.
  21021. (org-with-wide-buffer
  21022. (goto-char post)
  21023. (line-beginning-position 2)))
  21024. ((memq type '(footnote-definition item plain-list))
  21025. ;; Contents in these elements could start on
  21026. ;; the same line as the beginning of the
  21027. ;; element. Make sure we start indenting
  21028. ;; from the second line.
  21029. (org-with-wide-buffer
  21030. (goto-char post)
  21031. (end-of-line)
  21032. (skip-chars-forward " \r\t\n")
  21033. (if (eobp) (point) (line-beginning-position))))
  21034. (t (org-element-property :contents-begin element)))))
  21035. (cend (copy-marker
  21036. (or (org-element-property :contents-end element)
  21037. ;; Fake contents for source blocks.
  21038. (org-with-wide-buffer
  21039. (goto-char element-end)
  21040. (skip-chars-backward " \r\t\n")
  21041. (line-beginning-position)))
  21042. t)))
  21043. ;; Do not change items indentation individually as it
  21044. ;; might break the list as a whole. On the other
  21045. ;; hand, when at a plain list, indent it as a whole.
  21046. (cond ((eq type 'plain-list)
  21047. (let ((offset (- ind (org-get-indentation))))
  21048. (unless (zerop offset)
  21049. (indent-rigidly (org-element-property :begin element)
  21050. (org-element-property :end element)
  21051. offset))
  21052. (goto-char cbeg)))
  21053. ((eq type 'item) (goto-char cbeg))
  21054. (t (funcall indent-to ind (min cbeg end))))
  21055. (when (< (point) end)
  21056. (cl-case type
  21057. ((example-block verse-block))
  21058. (src-block
  21059. ;; In a source block, indent source code
  21060. ;; according to language major mode, but only if
  21061. ;; `org-src-tab-acts-natively' is non-nil.
  21062. (when (and (< (point) end) org-src-tab-acts-natively)
  21063. (ignore-errors
  21064. (org-babel-do-in-edit-buffer
  21065. (indent-region (point-min) (point-max))))))
  21066. (t (org-indent-region (point) (min cend end))))
  21067. (goto-char (min cend end))
  21068. (when (< (point) end)
  21069. (funcall indent-to ind (min element-end end))))
  21070. (set-marker post nil)
  21071. (set-marker cbeg nil)
  21072. (set-marker cend nil))))
  21073. (set-marker element-end nil))))
  21074. (set-marker end nil))))
  21075. (defun org-indent-drawer ()
  21076. "Indent the drawer at point."
  21077. (interactive)
  21078. (unless (save-excursion
  21079. (beginning-of-line)
  21080. (looking-at-p org-drawer-regexp))
  21081. (user-error "Not at a drawer"))
  21082. (let ((element (org-element-at-point)))
  21083. (unless (memq (org-element-type element) '(drawer property-drawer))
  21084. (user-error "Not at a drawer"))
  21085. (org-with-wide-buffer
  21086. (org-indent-region (org-element-property :begin element)
  21087. (org-element-property :end element))))
  21088. (message "Drawer at point indented"))
  21089. (defun org-indent-block ()
  21090. "Indent the block at point."
  21091. (interactive)
  21092. (unless (save-excursion
  21093. (beginning-of-line)
  21094. (let ((case-fold-search t))
  21095. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  21096. (user-error "Not at a block"))
  21097. (let ((element (org-element-at-point)))
  21098. (unless (memq (org-element-type element)
  21099. '(comment-block center-block dynamic-block example-block
  21100. export-block quote-block special-block
  21101. src-block verse-block))
  21102. (user-error "Not at a block"))
  21103. (org-with-wide-buffer
  21104. (org-indent-region (org-element-property :begin element)
  21105. (org-element-property :end element))))
  21106. (message "Block at point indented"))
  21107. ;;; Filling
  21108. ;; We use our own fill-paragraph and auto-fill functions.
  21109. ;; `org-fill-paragraph' relies on adaptive filling and context
  21110. ;; checking. Appropriate `fill-prefix' is computed with
  21111. ;; `org-adaptive-fill-function'.
  21112. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  21113. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  21114. ;; `org-adaptive-fill-function' value. Internally,
  21115. ;; `org-comment-line-break-function' breaks the line.
  21116. ;; `org-setup-filling' installs filling and auto-filling related
  21117. ;; variables during `org-mode' initialization.
  21118. (defvar org-element-paragraph-separate) ; org-element.el
  21119. (defun org-setup-filling ()
  21120. (require 'org-element)
  21121. ;; Prevent auto-fill from inserting unwanted new items.
  21122. (when (boundp 'fill-nobreak-predicate)
  21123. (setq-local
  21124. fill-nobreak-predicate
  21125. (org-uniquify
  21126. (append fill-nobreak-predicate
  21127. '(org-fill-line-break-nobreak-p
  21128. org-fill-paragraph-with-timestamp-nobreak-p)))))
  21129. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  21130. (setq-local paragraph-start paragraph-ending)
  21131. (setq-local paragraph-separate paragraph-ending))
  21132. (setq-local fill-paragraph-function 'org-fill-paragraph)
  21133. (setq-local auto-fill-inhibit-regexp nil)
  21134. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  21135. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  21136. (setq-local comment-line-break-function 'org-comment-line-break-function))
  21137. (defun org-fill-line-break-nobreak-p ()
  21138. "Non-nil when a new line at point would create an Org line break."
  21139. (save-excursion
  21140. (skip-chars-backward "[ \t]")
  21141. (skip-chars-backward "\\\\")
  21142. (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
  21143. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  21144. "Non-nil when a new line at point would split a timestamp."
  21145. (and (org-at-timestamp-p t)
  21146. (not (looking-at org-ts-regexp-both))))
  21147. (declare-function message-in-body-p "message" ())
  21148. (defvar orgtbl-line-start-regexp) ; From org-table.el
  21149. (defun org-adaptive-fill-function ()
  21150. "Compute a fill prefix for the current line.
  21151. Return fill prefix, as a string, or nil if current line isn't
  21152. meant to be filled. For convenience, if `adaptive-fill-regexp'
  21153. matches in paragraphs or comments, use it."
  21154. (catch 'exit
  21155. (when (derived-mode-p 'message-mode)
  21156. (save-excursion
  21157. (beginning-of-line)
  21158. (cond ((not (message-in-body-p)) (throw 'exit nil))
  21159. ((looking-at-p org-table-line-regexp) (throw 'exit nil))
  21160. ((looking-at message-cite-prefix-regexp)
  21161. (throw 'exit (match-string-no-properties 0)))
  21162. ((looking-at org-outline-regexp)
  21163. (throw 'exit (make-string (length (match-string 0)) ?\s))))))
  21164. (org-with-wide-buffer
  21165. (unless (org-at-heading-p)
  21166. (let* ((p (line-beginning-position))
  21167. (element (save-excursion
  21168. (beginning-of-line)
  21169. (org-element-at-point)))
  21170. (type (org-element-type element))
  21171. (post-affiliated (org-element-property :post-affiliated element)))
  21172. (unless (< p post-affiliated)
  21173. (cl-case type
  21174. (comment
  21175. (save-excursion
  21176. (beginning-of-line)
  21177. (looking-at "[ \t]*")
  21178. (concat (match-string 0) "# ")))
  21179. (footnote-definition "")
  21180. ((item plain-list)
  21181. (make-string (org-list-item-body-column post-affiliated) ?\s))
  21182. (paragraph
  21183. ;; Fill prefix is usually the same as the current line,
  21184. ;; unless the paragraph is at the beginning of an item.
  21185. (let ((parent (org-element-property :parent element)))
  21186. (save-excursion
  21187. (beginning-of-line)
  21188. (cond ((eq (org-element-type parent) 'item)
  21189. (make-string (org-list-item-body-column
  21190. (org-element-property :begin parent))
  21191. ?\s))
  21192. ((and adaptive-fill-regexp
  21193. ;; Locally disable
  21194. ;; `adaptive-fill-function' to let
  21195. ;; `fill-context-prefix' handle
  21196. ;; `adaptive-fill-regexp' variable.
  21197. (let (adaptive-fill-function)
  21198. (fill-context-prefix
  21199. post-affiliated
  21200. (org-element-property :end element)))))
  21201. ((looking-at "[ \t]+") (match-string 0))
  21202. (t "")))))
  21203. (comment-block
  21204. ;; Only fill contents if P is within block boundaries.
  21205. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  21206. (forward-line)
  21207. (point)))
  21208. (cend (save-excursion
  21209. (goto-char (org-element-property :end element))
  21210. (skip-chars-backward " \r\t\n")
  21211. (line-beginning-position))))
  21212. (when (and (>= p cbeg) (< p cend))
  21213. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  21214. (match-string 0)
  21215. "")))))))))))
  21216. (declare-function message-goto-body "message" ())
  21217. (defvar message-cite-prefix-regexp) ; From message.el
  21218. (defun org-fill-paragraph (&optional justify)
  21219. "Fill element at point, when applicable.
  21220. This function only applies to comment blocks, comments, example
  21221. blocks and paragraphs. Also, as a special case, re-align table
  21222. when point is at one.
  21223. If JUSTIFY is non-nil (interactively, with prefix argument),
  21224. justify as well. If `sentence-end-double-space' is non-nil, then
  21225. period followed by one space does not end a sentence, so don't
  21226. break a line there. The variable `fill-column' controls the
  21227. width for filling.
  21228. For convenience, when point is at a plain list, an item or
  21229. a footnote definition, try to fill the first paragraph within."
  21230. (interactive)
  21231. (if (and (derived-mode-p 'message-mode)
  21232. (or (not (message-in-body-p))
  21233. (save-excursion (move-beginning-of-line 1)
  21234. (looking-at message-cite-prefix-regexp))))
  21235. ;; First ensure filling is correct in message-mode.
  21236. (let ((fill-paragraph-function
  21237. (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
  21238. (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
  21239. (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
  21240. (paragraph-separate
  21241. (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
  21242. (fill-paragraph nil))
  21243. (with-syntax-table org-mode-transpose-word-syntax-table
  21244. ;; Move to end of line in order to get the first paragraph
  21245. ;; within a plain list or a footnote definition.
  21246. (let ((element (save-excursion
  21247. (end-of-line)
  21248. (or (ignore-errors (org-element-at-point))
  21249. (user-error "An element cannot be parsed line %d"
  21250. (line-number-at-pos (point)))))))
  21251. ;; First check if point is in a blank line at the beginning of
  21252. ;; the buffer. In that case, ignore filling.
  21253. (cl-case (org-element-type element)
  21254. ;; Use major mode filling function is src blocks.
  21255. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  21256. ;; Align Org tables, leave table.el tables as-is.
  21257. (table-row (org-table-align) t)
  21258. (table
  21259. (when (eq (org-element-property :type element) 'org)
  21260. (save-excursion
  21261. (goto-char (org-element-property :post-affiliated element))
  21262. (org-table-align)))
  21263. t)
  21264. (paragraph
  21265. ;; Paragraphs may contain `line-break' type objects.
  21266. (let ((beg (max (point-min)
  21267. (org-element-property :contents-begin element)))
  21268. (end (min (point-max)
  21269. (org-element-property :contents-end element))))
  21270. ;; Do nothing if point is at an affiliated keyword.
  21271. (if (< (line-end-position) beg) t
  21272. (when (derived-mode-p 'message-mode)
  21273. ;; In `message-mode', do not fill following citation
  21274. ;; in current paragraph nor text before message body.
  21275. (let ((body-start (save-excursion (message-goto-body))))
  21276. (when body-start (setq beg (max body-start beg))))
  21277. (when (save-excursion
  21278. (re-search-forward
  21279. (concat "^" message-cite-prefix-regexp) end t))
  21280. (setq end (match-beginning 0))))
  21281. ;; Fill paragraph, taking line breaks into account.
  21282. (save-excursion
  21283. (goto-char beg)
  21284. (let ((cuts (list beg)))
  21285. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  21286. (when (eq 'line-break
  21287. (org-element-type
  21288. (save-excursion (backward-char)
  21289. (org-element-context))))
  21290. (push (point) cuts)))
  21291. (dolist (c (delq end cuts))
  21292. (fill-region-as-paragraph c end justify)
  21293. (setq end c))))
  21294. t)))
  21295. ;; Contents of `comment-block' type elements should be
  21296. ;; filled as plain text, but only if point is within block
  21297. ;; markers.
  21298. (comment-block
  21299. (let* ((case-fold-search t)
  21300. (beg (save-excursion
  21301. (goto-char (org-element-property :begin element))
  21302. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  21303. (forward-line)
  21304. (point)))
  21305. (end (save-excursion
  21306. (goto-char (org-element-property :end element))
  21307. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  21308. (line-beginning-position))))
  21309. (if (or (< (point) beg) (> (point) end)) t
  21310. (fill-region-as-paragraph
  21311. (save-excursion (end-of-line)
  21312. (re-search-backward "^[ \t]*$" beg 'move)
  21313. (line-beginning-position))
  21314. (save-excursion (beginning-of-line)
  21315. (re-search-forward "^[ \t]*$" end 'move)
  21316. (line-beginning-position))
  21317. justify))))
  21318. ;; Fill comments.
  21319. (comment
  21320. (let ((begin (org-element-property :post-affiliated element))
  21321. (end (org-element-property :end element)))
  21322. (when (and (>= (point) begin) (<= (point) end))
  21323. (let ((begin (save-excursion
  21324. (end-of-line)
  21325. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  21326. (progn (forward-line) (point))
  21327. begin)))
  21328. (end (save-excursion
  21329. (end-of-line)
  21330. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  21331. (1- (line-beginning-position))
  21332. (skip-chars-backward " \r\t\n")
  21333. (line-end-position)))))
  21334. ;; Do not fill comments when at a blank line.
  21335. (when (> end begin)
  21336. (let ((fill-prefix
  21337. (save-excursion
  21338. (beginning-of-line)
  21339. (looking-at "[ \t]*#")
  21340. (let ((comment-prefix (match-string 0)))
  21341. (goto-char (match-end 0))
  21342. (if (looking-at adaptive-fill-regexp)
  21343. (concat comment-prefix (match-string 0))
  21344. (concat comment-prefix " "))))))
  21345. (save-excursion
  21346. (fill-region-as-paragraph begin end justify))))))
  21347. t))
  21348. ;; Ignore every other element.
  21349. (otherwise t))))))
  21350. (defun org-auto-fill-function ()
  21351. "Auto-fill function."
  21352. ;; Check if auto-filling is meaningful.
  21353. (let ((fc (current-fill-column)))
  21354. (when (and fc (> (current-column) fc))
  21355. (let* ((fill-prefix (org-adaptive-fill-function))
  21356. ;; Enforce empty fill prefix, if required. Otherwise, it
  21357. ;; will be computed again.
  21358. (adaptive-fill-mode (not (equal fill-prefix ""))))
  21359. (when fill-prefix (do-auto-fill))))))
  21360. (defun org-comment-line-break-function (&optional soft)
  21361. "Break line at point and indent, continuing comment if within one.
  21362. The inserted newline is marked hard if variable
  21363. `use-hard-newlines' is true, unless optional argument SOFT is
  21364. non-nil."
  21365. (if soft (insert-and-inherit ?\n) (newline 1))
  21366. (save-excursion (forward-char -1) (delete-horizontal-space))
  21367. (delete-horizontal-space)
  21368. (indent-to-left-margin)
  21369. (insert-before-markers-and-inherit fill-prefix))
  21370. ;;; Fixed Width Areas
  21371. (defun org-toggle-fixed-width ()
  21372. "Toggle fixed-width markup.
  21373. Add or remove fixed-width markup on current line, whenever it
  21374. makes sense. Return an error otherwise.
  21375. If a region is active and if it contains only fixed-width areas
  21376. or blank lines, remove all fixed-width markup in it. If the
  21377. region contains anything else, convert all non-fixed-width lines
  21378. to fixed-width ones.
  21379. Blank lines at the end of the region are ignored unless the
  21380. region only contains such lines."
  21381. (interactive)
  21382. (if (not (org-region-active-p))
  21383. ;; No region:
  21384. ;;
  21385. ;; Remove fixed width marker only in a fixed-with element.
  21386. ;;
  21387. ;; Add fixed width maker in paragraphs, in blank lines after
  21388. ;; elements or at the beginning of a headline or an inlinetask,
  21389. ;; and before any one-line elements (e.g., a clock).
  21390. (progn
  21391. (beginning-of-line)
  21392. (let* ((element (org-element-at-point))
  21393. (type (org-element-type element)))
  21394. (cond
  21395. ((and (eq type 'fixed-width)
  21396. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  21397. (replace-match
  21398. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  21399. ((and (memq type '(babel-call clock comment diary-sexp headline
  21400. horizontal-rule keyword paragraph
  21401. planning))
  21402. (<= (org-element-property :post-affiliated element) (point)))
  21403. (skip-chars-forward " \t")
  21404. (insert ": "))
  21405. ((and (looking-at-p "[ \t]*$")
  21406. (or (eq type 'inlinetask)
  21407. (save-excursion
  21408. (skip-chars-forward " \r\t\n")
  21409. (<= (org-element-property :end element) (point)))))
  21410. (delete-region (point) (line-end-position))
  21411. (org-indent-line)
  21412. (insert ": "))
  21413. (t (user-error "Cannot insert a fixed-width line here")))))
  21414. ;; Region active.
  21415. (let* ((begin (save-excursion
  21416. (goto-char (region-beginning))
  21417. (line-beginning-position)))
  21418. (end (copy-marker
  21419. (save-excursion
  21420. (goto-char (region-end))
  21421. (unless (eolp) (beginning-of-line))
  21422. (if (save-excursion (re-search-backward "\\S-" begin t))
  21423. (progn (skip-chars-backward " \r\t\n") (point))
  21424. (point)))))
  21425. (all-fixed-width-p
  21426. (catch 'not-all-p
  21427. (save-excursion
  21428. (goto-char begin)
  21429. (skip-chars-forward " \r\t\n")
  21430. (when (eobp) (throw 'not-all-p nil))
  21431. (while (< (point) end)
  21432. (let ((element (org-element-at-point)))
  21433. (if (eq (org-element-type element) 'fixed-width)
  21434. (goto-char (org-element-property :end element))
  21435. (throw 'not-all-p nil))))
  21436. t))))
  21437. (if all-fixed-width-p
  21438. (save-excursion
  21439. (goto-char begin)
  21440. (while (< (point) end)
  21441. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  21442. (replace-match
  21443. "" nil nil nil
  21444. (if (= (line-end-position) (match-end 0)) 0 1)))
  21445. (forward-line)))
  21446. (let ((min-ind (point-max)))
  21447. ;; Find minimum indentation across all lines.
  21448. (save-excursion
  21449. (goto-char begin)
  21450. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  21451. (setq min-ind 0)
  21452. (catch 'zerop
  21453. (while (< (point) end)
  21454. (unless (looking-at-p "[ \t]*$")
  21455. (let ((ind (org-get-indentation)))
  21456. (setq min-ind (min min-ind ind))
  21457. (when (zerop ind) (throw 'zerop t))))
  21458. (forward-line)))))
  21459. ;; Loop over all lines and add fixed-width markup everywhere
  21460. ;; but in fixed-width lines.
  21461. (save-excursion
  21462. (goto-char begin)
  21463. (while (< (point) end)
  21464. (cond
  21465. ((org-at-heading-p)
  21466. (insert ": ")
  21467. (forward-line)
  21468. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  21469. (insert ":")
  21470. (forward-line)))
  21471. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  21472. (let* ((element (org-element-at-point))
  21473. (element-end (org-element-property :end element)))
  21474. (if (eq (org-element-type element) 'fixed-width)
  21475. (progn (goto-char element-end)
  21476. (skip-chars-backward " \r\t\n")
  21477. (forward-line))
  21478. (let ((limit (min end element-end)))
  21479. (while (< (point) limit)
  21480. (org-move-to-column min-ind t)
  21481. (insert ": ")
  21482. (forward-line))))))
  21483. (t
  21484. (org-move-to-column min-ind t)
  21485. (insert ": ")
  21486. (forward-line)))))))
  21487. (set-marker end nil))))
  21488. ;;; Comments
  21489. ;; Org comments syntax is quite complex. It requires the entire line
  21490. ;; to be just a comment. Also, even with the right syntax at the
  21491. ;; beginning of line, some some elements (i.e. verse-block or
  21492. ;; example-block) don't accept comments. Usual Emacs comment commands
  21493. ;; cannot cope with those requirements. Therefore, Org replaces them.
  21494. ;; Org still relies on `comment-dwim', but cannot trust
  21495. ;; `comment-only-p'. So, `comment-region-function' and
  21496. ;; `uncomment-region-function' both point
  21497. ;; to`org-comment-or-uncomment-region'. Eventually,
  21498. ;; `org-insert-comment' takes care of insertion of comments at the
  21499. ;; beginning of line.
  21500. ;; `org-setup-comments-handling' install comments related variables
  21501. ;; during `org-mode' initialization.
  21502. (defun org-setup-comments-handling ()
  21503. (interactive)
  21504. (setq-local comment-use-syntax nil)
  21505. (setq-local comment-start "# ")
  21506. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  21507. (setq-local comment-insert-comment-function 'org-insert-comment)
  21508. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  21509. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  21510. (defun org-insert-comment ()
  21511. "Insert an empty comment above current line.
  21512. If the line is empty, insert comment at its beginning. When
  21513. point is within a source block, comment according to the related
  21514. major mode."
  21515. (if (let ((element (org-element-at-point)))
  21516. (and (eq (org-element-type element) 'src-block)
  21517. (< (save-excursion
  21518. (goto-char (org-element-property :post-affiliated element))
  21519. (line-end-position))
  21520. (point))
  21521. (> (save-excursion
  21522. (goto-char (org-element-property :end element))
  21523. (skip-chars-backward " \r\t\n")
  21524. (line-beginning-position))
  21525. (point))))
  21526. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21527. (beginning-of-line)
  21528. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  21529. (open-line 1))
  21530. (org-indent-line)
  21531. (insert "# ")))
  21532. (defvar comment-empty-lines) ; From newcomment.el.
  21533. (defun org-comment-or-uncomment-region (beg end &rest _)
  21534. "Comment or uncomment each non-blank line in the region.
  21535. Uncomment each non-blank line between BEG and END if it only
  21536. contains commented lines. Otherwise, comment them. If region is
  21537. strictly within a source block, use appropriate comment syntax."
  21538. (if (let ((element (org-element-at-point)))
  21539. (and (eq (org-element-type element) 'src-block)
  21540. (< (save-excursion
  21541. (goto-char (org-element-property :post-affiliated element))
  21542. (line-end-position))
  21543. beg)
  21544. (>= (save-excursion
  21545. (goto-char (org-element-property :end element))
  21546. (skip-chars-backward " \r\t\n")
  21547. (line-beginning-position))
  21548. end)))
  21549. ;; Translate region boundaries for the Org buffer to the source
  21550. ;; buffer.
  21551. (let ((offset (- end beg)))
  21552. (save-excursion
  21553. (goto-char beg)
  21554. (org-babel-do-in-edit-buffer
  21555. (comment-or-uncomment-region (point) (+ offset (point))))))
  21556. (save-restriction
  21557. ;; Restrict region
  21558. (narrow-to-region (save-excursion (goto-char beg)
  21559. (skip-chars-forward " \r\t\n" end)
  21560. (line-beginning-position))
  21561. (save-excursion (goto-char end)
  21562. (skip-chars-backward " \r\t\n" beg)
  21563. (line-end-position)))
  21564. (let ((uncommentp
  21565. ;; UNCOMMENTP is non-nil when every non blank line between
  21566. ;; BEG and END is a comment.
  21567. (save-excursion
  21568. (goto-char (point-min))
  21569. (while (and (not (eobp))
  21570. (let ((element (org-element-at-point)))
  21571. (and (eq (org-element-type element) 'comment)
  21572. (goto-char (min (point-max)
  21573. (org-element-property
  21574. :end element)))))))
  21575. (eobp))))
  21576. (if uncommentp
  21577. ;; Only blank lines and comments in region: uncomment it.
  21578. (save-excursion
  21579. (goto-char (point-min))
  21580. (while (not (eobp))
  21581. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  21582. (replace-match "" nil nil nil 1))
  21583. (forward-line)))
  21584. ;; Comment each line in region.
  21585. (let ((min-indent (point-max)))
  21586. ;; First find the minimum indentation across all lines.
  21587. (save-excursion
  21588. (goto-char (point-min))
  21589. (while (and (not (eobp)) (not (zerop min-indent)))
  21590. (unless (looking-at "[ \t]*$")
  21591. (setq min-indent (min min-indent (current-indentation))))
  21592. (forward-line)))
  21593. ;; Then loop over all lines.
  21594. (save-excursion
  21595. (goto-char (point-min))
  21596. (while (not (eobp))
  21597. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  21598. ;; Don't get fooled by invisible text (e.g. link path)
  21599. ;; when moving to column MIN-INDENT.
  21600. (let ((buffer-invisibility-spec nil))
  21601. (org-move-to-column min-indent t))
  21602. (insert comment-start))
  21603. (forward-line)))))))))
  21604. (defun org-comment-dwim (_arg)
  21605. "Call `comment-dwim' within a source edit buffer if needed."
  21606. (interactive "*P")
  21607. (if (org-in-src-block-p)
  21608. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  21609. (call-interactively 'comment-dwim)))
  21610. ;;; Timestamps API
  21611. ;; This section contains tools to operate on timestamp objects, as
  21612. ;; returned by, e.g. `org-element-context'.
  21613. (defun org-timestamp--to-internal-time (timestamp &optional end)
  21614. "Encode TIMESTAMP object into Emacs internal time.
  21615. Use end of date range or time range when END is non-nil."
  21616. (apply #'encode-time
  21617. (cons 0
  21618. (mapcar
  21619. (lambda (prop) (or (org-element-property prop timestamp) 0))
  21620. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  21621. '(:minute-start :hour-start :day-start :month-start
  21622. :year-start))))))
  21623. (defun org-timestamp-has-time-p (timestamp)
  21624. "Non-nil when TIMESTAMP has a time specified."
  21625. (org-element-property :hour-start timestamp))
  21626. (defun org-timestamp-format (timestamp format &optional end utc)
  21627. "Format a TIMESTAMP object into a string.
  21628. FORMAT is a format specifier to be passed to
  21629. `format-time-string'.
  21630. When optional argument END is non-nil, use end of date-range or
  21631. time-range, if possible.
  21632. When optional argument UTC is non-nil, time will be expressed as
  21633. Universal Time."
  21634. (format-time-string
  21635. format (org-timestamp--to-internal-time timestamp end)
  21636. (and utc t)))
  21637. (defun org-timestamp-split-range (timestamp &optional end)
  21638. "Extract a TIMESTAMP object from a date or time range.
  21639. END, when non-nil, means extract the end of the range.
  21640. Otherwise, extract its start.
  21641. Return a new timestamp object."
  21642. (let ((type (org-element-property :type timestamp)))
  21643. (if (memq type '(active inactive diary)) timestamp
  21644. (let ((split-ts (org-element-copy timestamp)))
  21645. ;; Set new type.
  21646. (org-element-put-property
  21647. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  21648. ;; Copy start properties over end properties if END is
  21649. ;; non-nil. Otherwise, copy end properties over `start' ones.
  21650. (let ((p-alist '((:minute-start . :minute-end)
  21651. (:hour-start . :hour-end)
  21652. (:day-start . :day-end)
  21653. (:month-start . :month-end)
  21654. (:year-start . :year-end))))
  21655. (dolist (p-cell p-alist)
  21656. (org-element-put-property
  21657. split-ts
  21658. (funcall (if end #'car #'cdr) p-cell)
  21659. (org-element-property
  21660. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  21661. ;; Eventually refresh `:raw-value'.
  21662. (org-element-put-property split-ts :raw-value nil)
  21663. (org-element-put-property
  21664. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  21665. (defun org-timestamp-translate (timestamp &optional boundary)
  21666. "Translate TIMESTAMP object to custom format.
  21667. Format string is defined in `org-time-stamp-custom-formats',
  21668. which see.
  21669. When optional argument BOUNDARY is non-nil, it is either the
  21670. symbol `start' or `end'. In this case, only translate the
  21671. starting or ending part of TIMESTAMP if it is a date or time
  21672. range. Otherwise, translate both parts.
  21673. Return timestamp as-is if `org-display-custom-times' is nil or if
  21674. it has a `diary' type."
  21675. (let ((type (org-element-property :type timestamp)))
  21676. (if (or (not org-display-custom-times) (eq type 'diary))
  21677. (org-element-interpret-data timestamp)
  21678. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  21679. org-time-stamp-custom-formats)))
  21680. (if (and (not boundary) (memq type '(active-range inactive-range)))
  21681. (concat (org-timestamp-format timestamp fmt)
  21682. "--"
  21683. (org-timestamp-format timestamp fmt t))
  21684. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  21685. ;;; Other stuff.
  21686. (defvar reftex-docstruct-symbol)
  21687. (defvar org--rds)
  21688. (defun org-reftex-citation ()
  21689. "Use reftex-citation to insert a citation into the buffer.
  21690. This looks for a line like
  21691. #+BIBLIOGRAPHY: foo plain option:-d
  21692. and derives from it that foo.bib is the bibliography file relevant
  21693. for this document. It then installs the necessary environment for RefTeX
  21694. to work in this buffer and calls `reftex-citation' to insert a citation
  21695. into the buffer.
  21696. Export of such citations to both LaTeX and HTML is handled by the contributed
  21697. package ox-bibtex by Taru Karttunen."
  21698. (interactive)
  21699. (let ((reftex-docstruct-symbol 'org--rds)
  21700. org--rds bib)
  21701. (org-with-wide-buffer
  21702. (let ((case-fold-search t)
  21703. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  21704. (if (not (save-excursion
  21705. (or (re-search-forward re nil t)
  21706. (re-search-backward re nil t))))
  21707. (user-error "No bibliography defined in file")
  21708. (setq bib (concat (match-string 1) ".bib")
  21709. org--rds (list (list 'bib bib))))))
  21710. (call-interactively 'reftex-citation)))
  21711. ;;;; Functions extending outline functionality
  21712. (defun org-beginning-of-line (&optional n)
  21713. "Go to the beginning of the current visible line.
  21714. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21715. tags on the first attempt, and only move to after the tags when
  21716. the cursor is already beyond the end of the headline.
  21717. With argument N not nil or 1, move forward N - 1 lines first."
  21718. (interactive "^p")
  21719. (let ((origin (point))
  21720. (special (pcase org-special-ctrl-a/e
  21721. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  21722. deactivate-mark)
  21723. ;; First move to a visible line.
  21724. (if (bound-and-true-p visual-line-mode)
  21725. (beginning-of-visual-line n)
  21726. (move-beginning-of-line n)
  21727. ;; `move-beginning-of-line' may leave point after invisible
  21728. ;; characters if line starts with such of these (e.g., with
  21729. ;; a link at column 0). Really move to the beginning of the
  21730. ;; current visible line.
  21731. (beginning-of-line))
  21732. (cond
  21733. ;; No special behavior. Point is already at the beginning of
  21734. ;; a line, logical or visual.
  21735. ((not special))
  21736. ;; `beginning-of-visual-line' left point before logical beginning
  21737. ;; of line: point is at the beginning of a visual line. Bail
  21738. ;; out.
  21739. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  21740. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  21741. ;; At a headline, special position is before the title, but
  21742. ;; after any TODO keyword or priority cookie.
  21743. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  21744. (line-end-position)))
  21745. (bol (point)))
  21746. (if (eq special 'reversed)
  21747. (when (and (= origin bol) (eq last-command this-command))
  21748. (goto-char refpos))
  21749. (when (or (> origin refpos) (= origin bol))
  21750. (goto-char refpos)))))
  21751. ((and (looking-at org-list-full-item-re)
  21752. (memq (org-element-type (save-match-data (org-element-at-point)))
  21753. '(item plain-list)))
  21754. ;; Set special position at first white space character after
  21755. ;; bullet, and check-box, if any.
  21756. (let ((after-bullet
  21757. (let ((box (match-end 3)))
  21758. (cond ((not box) (match-end 1))
  21759. ((eq (char-after box) ?\s) (1+ box))
  21760. (t box)))))
  21761. (if (eq special 'reversed)
  21762. (when (and (= (point) origin) (eq last-command this-command))
  21763. (goto-char after-bullet))
  21764. (when (or (> origin after-bullet) (= (point) origin))
  21765. (goto-char after-bullet)))))
  21766. ;; No special context. Point is already at beginning of line.
  21767. (t nil))))
  21768. (defun org-end-of-line (&optional n)
  21769. "Go to the end of the line, but before ellipsis, if any.
  21770. If this is a headline, and `org-special-ctrl-a/e' is set, ignore
  21771. tags on the first attempt, and only move to after the tags when
  21772. the cursor is already beyond the end of the headline.
  21773. With argument N not nil or 1, move forward N - 1 lines first."
  21774. (interactive "^p")
  21775. (let ((origin (point))
  21776. (special (pcase org-special-ctrl-a/e
  21777. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  21778. deactivate-mark)
  21779. ;; First move to a visible line.
  21780. (if (bound-and-true-p visual-line-mode)
  21781. (beginning-of-visual-line n)
  21782. (move-beginning-of-line n))
  21783. (cond
  21784. ;; At a headline, with tags.
  21785. ((and special
  21786. (save-excursion
  21787. (beginning-of-line)
  21788. (let ((case-fold-search nil))
  21789. (looking-at org-complex-heading-regexp)))
  21790. (match-end 5))
  21791. (let ((tags (save-excursion
  21792. (goto-char (match-beginning 5))
  21793. (skip-chars-backward " \t")
  21794. (point)))
  21795. (visual-end (and (bound-and-true-p visual-line-mode)
  21796. (save-excursion
  21797. (end-of-visual-line)
  21798. (point)))))
  21799. ;; If `end-of-visual-line' brings us before end of line or
  21800. ;; even tags, i.e., the headline spans over multiple visual
  21801. ;; lines, move there.
  21802. (cond ((and visual-end
  21803. (< visual-end tags)
  21804. (<= origin visual-end))
  21805. (goto-char visual-end))
  21806. ((eq special 'reversed)
  21807. (if (and (= origin (line-end-position))
  21808. (eq this-command last-command))
  21809. (goto-char tags)
  21810. (end-of-line)))
  21811. (t
  21812. (if (or (< origin tags) (= origin (line-end-position)))
  21813. (goto-char tags)
  21814. (end-of-line))))))
  21815. ((bound-and-true-p visual-line-mode)
  21816. (let ((bol (line-beginning-position)))
  21817. (end-of-visual-line)
  21818. ;; If `end-of-visual-line' gets us past the ellipsis at the
  21819. ;; end of a line, backtrack and use `end-of-line' instead.
  21820. (when (/= bol (line-beginning-position))
  21821. (goto-char bol)
  21822. (end-of-line))))
  21823. (t (end-of-line)))))
  21824. (define-key org-mode-map "\C-a" 'org-beginning-of-line)
  21825. (define-key org-mode-map "\C-e" 'org-end-of-line)
  21826. (defun org-backward-sentence (&optional _arg)
  21827. "Go to beginning of sentence, or beginning of table field.
  21828. This will call `backward-sentence' or `org-table-beginning-of-field',
  21829. depending on context."
  21830. (interactive)
  21831. (let* ((element (org-element-at-point))
  21832. (contents-begin (org-element-property :contents-begin element))
  21833. (table (org-element-lineage element '(table) t)))
  21834. (if (and table
  21835. (> (point) contents-begin)
  21836. (<= (point) (org-element-property :contents-end table)))
  21837. (call-interactively #'org-table-beginning-of-field)
  21838. (save-restriction
  21839. (when (and contents-begin
  21840. (< (point-min) contents-begin)
  21841. (> (point) contents-begin))
  21842. (narrow-to-region contents-begin
  21843. (org-element-property :contents-end element)))
  21844. (call-interactively #'backward-sentence)))))
  21845. (defun org-forward-sentence (&optional _arg)
  21846. "Go to end of sentence, or end of table field.
  21847. This will call `forward-sentence' or `org-table-end-of-field',
  21848. depending on context."
  21849. (interactive)
  21850. (let* ((element (org-element-at-point))
  21851. (contents-end (org-element-property :contents-end element))
  21852. (table (org-element-lineage element '(table) t)))
  21853. (if (and table
  21854. (>= (point) (org-element-property :contents-begin table))
  21855. (< (point) contents-end))
  21856. (call-interactively #'org-table-end-of-field)
  21857. (save-restriction
  21858. (when (and contents-end
  21859. (> (point-max) contents-end)
  21860. ;; Skip blank lines between elements.
  21861. (< (org-element-property :end element)
  21862. (save-excursion (goto-char contents-end)
  21863. (skip-chars-forward " \r\t\n"))))
  21864. (narrow-to-region (org-element-property :contents-begin element)
  21865. contents-end))
  21866. (call-interactively #'forward-sentence)))))
  21867. (define-key org-mode-map "\M-a" 'org-backward-sentence)
  21868. (define-key org-mode-map "\M-e" 'org-forward-sentence)
  21869. (defun org-kill-line (&optional _arg)
  21870. "Kill line, to tags or end of line."
  21871. (interactive)
  21872. (cond
  21873. ((or (not org-special-ctrl-k)
  21874. (bolp)
  21875. (not (org-at-heading-p)))
  21876. (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
  21877. org-ctrl-k-protect-subtree
  21878. (or (eq org-ctrl-k-protect-subtree 'error)
  21879. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  21880. (user-error "C-k aborted as it would kill a hidden subtree"))
  21881. (call-interactively
  21882. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  21883. ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
  21884. (kill-region (point) (match-beginning 1))
  21885. (org-set-tags nil t))
  21886. (t (kill-region (point) (point-at-eol)))))
  21887. (define-key org-mode-map "\C-k" 'org-kill-line)
  21888. (defun org-yank (&optional arg)
  21889. "Yank. If the kill is a subtree, treat it specially.
  21890. This command will look at the current kill and check if is a single
  21891. subtree, or a series of subtrees[1]. If it passes the test, and if the
  21892. cursor is at the beginning of a line or after the stars of a currently
  21893. empty headline, then the yank is handled specially. How exactly depends
  21894. on the value of the following variables.
  21895. `org-yank-folded-subtrees'
  21896. By default, this variable is non-nil, which results in
  21897. subtree(s) being folded after insertion, except if doing so
  21898. would swallow text after the yanked text.
  21899. `org-yank-adjusted-subtrees'
  21900. When non-nil (the default value is nil), the subtree will be
  21901. promoted or demoted in order to fit into the local outline tree
  21902. structure, which means that the level will be adjusted so that it
  21903. becomes the smaller one of the two *visible* surrounding headings.
  21904. Any prefix to this command will cause `yank' to be called directly with
  21905. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  21906. will just
  21907. plainly yank the text as it is.
  21908. \[1] The test checks if the first non-white line is a heading
  21909. and if there are no other headings with fewer stars."
  21910. (interactive "P")
  21911. (org-yank-generic 'yank arg))
  21912. (defun org-yank-generic (command arg)
  21913. "Perform some yank-like command.
  21914. This function implements the behavior described in the `org-yank'
  21915. documentation. However, it has been generalized to work for any
  21916. interactive command with similar behavior."
  21917. ;; pretend to be command COMMAND
  21918. (setq this-command command)
  21919. (if arg
  21920. (call-interactively command)
  21921. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  21922. (and (org-kill-is-subtree-p)
  21923. (or (bolp)
  21924. (and (looking-at "[ \t]*$")
  21925. (string-match
  21926. "\\`\\*+\\'"
  21927. (buffer-substring (point-at-bol) (point)))))))
  21928. swallowp)
  21929. (cond
  21930. ((and subtreep org-yank-folded-subtrees)
  21931. (let ((beg (point))
  21932. end)
  21933. (if (and subtreep org-yank-adjusted-subtrees)
  21934. (org-paste-subtree nil nil 'for-yank)
  21935. (call-interactively command))
  21936. (setq end (point))
  21937. (goto-char beg)
  21938. (when (and (bolp) subtreep
  21939. (not (setq swallowp
  21940. (org-yank-folding-would-swallow-text beg end))))
  21941. (org-with-limited-levels
  21942. (or (looking-at org-outline-regexp)
  21943. (re-search-forward org-outline-regexp-bol end t))
  21944. (while (and (< (point) end) (looking-at org-outline-regexp))
  21945. (outline-hide-subtree)
  21946. (org-cycle-show-empty-lines 'folded)
  21947. (condition-case nil
  21948. (outline-forward-same-level 1)
  21949. (error (goto-char end))))))
  21950. (when swallowp
  21951. (message
  21952. "Inserted text not folded because that would swallow text"))
  21953. (goto-char end)
  21954. (skip-chars-forward " \t\n\r")
  21955. (beginning-of-line 1)
  21956. (push-mark beg 'nomsg)))
  21957. ((and subtreep org-yank-adjusted-subtrees)
  21958. (let ((beg (point-at-bol)))
  21959. (org-paste-subtree nil nil 'for-yank)
  21960. (push-mark beg 'nomsg)))
  21961. (t
  21962. (call-interactively command))))))
  21963. (defun org-yank-folding-would-swallow-text (beg end)
  21964. "Would hide-subtree at BEG swallow any text after END?"
  21965. (let (level)
  21966. (org-with-limited-levels
  21967. (save-excursion
  21968. (goto-char beg)
  21969. (when (or (looking-at org-outline-regexp)
  21970. (re-search-forward org-outline-regexp-bol end t))
  21971. (setq level (org-outline-level)))
  21972. (goto-char end)
  21973. (skip-chars-forward " \t\r\n\v\f")
  21974. (not (or (eobp)
  21975. (and (bolp) (looking-at-p org-outline-regexp)
  21976. (<= (org-outline-level) level))))))))
  21977. (define-key org-mode-map "\C-y" 'org-yank)
  21978. (defun org-truely-invisible-p ()
  21979. "Check if point is at a character currently not visible.
  21980. This version does not only check the character property, but also
  21981. `visible-mode'."
  21982. (unless (bound-and-true-p visible-mode)
  21983. (org-invisible-p)))
  21984. (defun org-invisible-p2 ()
  21985. "Check if point is at a character currently not visible.
  21986. If the point is at EOL (and not at the beginning of a buffer too),
  21987. move it back by one char before doing this check."
  21988. (save-excursion
  21989. (when (and (eolp) (not (bobp)))
  21990. (backward-char 1))
  21991. (org-invisible-p)))
  21992. (defun org-back-to-heading (&optional invisible-ok)
  21993. "Call `outline-back-to-heading', but provide a better error message."
  21994. (condition-case nil
  21995. (outline-back-to-heading invisible-ok)
  21996. (error (error "Before first headline at position %d in buffer %s"
  21997. (point) (current-buffer)))))
  21998. (defun org-before-first-heading-p ()
  21999. "Before first heading?"
  22000. (save-excursion
  22001. (end-of-line)
  22002. (null (re-search-backward org-outline-regexp-bol nil t))))
  22003. (defun org-at-heading-p (&optional ignored)
  22004. (outline-on-heading-p t))
  22005. (defun org-in-commented-heading-p (&optional no-inheritance)
  22006. "Non-nil if point is under a commented heading.
  22007. This function also checks ancestors of the current headline,
  22008. unless optional argument NO-INHERITANCE is non-nil."
  22009. (cond
  22010. ((org-before-first-heading-p) nil)
  22011. ((let ((headline (nth 4 (org-heading-components))))
  22012. (and headline
  22013. (let ((case-fold-search nil))
  22014. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  22015. headline)))))
  22016. (no-inheritance nil)
  22017. (t
  22018. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  22019. (defun org-at-comment-p nil
  22020. "Is cursor in a commented line?"
  22021. (save-excursion
  22022. (save-match-data
  22023. (beginning-of-line)
  22024. (looking-at "^[ \t]*# "))))
  22025. (defun org-at-drawer-p nil
  22026. "Is cursor at a drawer keyword?"
  22027. (save-excursion
  22028. (move-beginning-of-line 1)
  22029. (looking-at org-drawer-regexp)))
  22030. (defun org-at-block-p nil
  22031. "Is cursor at a block keyword?"
  22032. (save-excursion
  22033. (move-beginning-of-line 1)
  22034. (looking-at org-block-regexp)))
  22035. (defun org-point-at-end-of-empty-headline ()
  22036. "If point is at the end of an empty headline, return t, else nil.
  22037. If the heading only contains a TODO keyword, it is still still considered
  22038. empty."
  22039. (let ((case-fold-search nil))
  22040. (and (looking-at "[ \t]*$")
  22041. org-todo-line-regexp
  22042. (save-excursion
  22043. (beginning-of-line)
  22044. (looking-at org-todo-line-regexp)
  22045. (string= (match-string 3) "")))))
  22046. (defun org-at-heading-or-item-p ()
  22047. (or (org-at-heading-p) (org-at-item-p)))
  22048. (defun org-at-target-p ()
  22049. (or (org-in-regexp org-radio-target-regexp)
  22050. (org-in-regexp org-target-regexp)))
  22051. ;; Compatibility alias with Org versions < 7.8.03
  22052. (defalias 'org-on-target-p 'org-at-target-p)
  22053. (defun org-up-heading-all (arg)
  22054. "Move to the heading line of which the present line is a subheading.
  22055. This function considers both visible and invisible heading lines.
  22056. With argument, move up ARG levels."
  22057. (outline-up-heading arg t))
  22058. (defun org-up-heading-safe ()
  22059. "Move to the heading line of which the present line is a subheading.
  22060. This version will not throw an error. It will return the level of the
  22061. headline found, or nil if no higher level is found.
  22062. Also, this function will be a lot faster than `outline-up-heading',
  22063. because it relies on stars being the outline starters. This can really
  22064. make a significant difference in outlines with very many siblings."
  22065. (when (ignore-errors (org-back-to-heading t))
  22066. (let ((level-up (1- (funcall outline-level))))
  22067. (and (> level-up 0)
  22068. (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
  22069. (funcall outline-level)))))
  22070. (defun org-first-sibling-p ()
  22071. "Is this heading the first child of its parents?"
  22072. (interactive)
  22073. (let ((re org-outline-regexp-bol)
  22074. level l)
  22075. (unless (org-at-heading-p t)
  22076. (user-error "Not at a heading"))
  22077. (setq level (funcall outline-level))
  22078. (save-excursion
  22079. (if (not (re-search-backward re nil t))
  22080. t
  22081. (setq l (funcall outline-level))
  22082. (< l level)))))
  22083. (defun org-goto-sibling (&optional previous)
  22084. "Goto the next sibling, even if it is invisible.
  22085. When PREVIOUS is set, go to the previous sibling instead. Returns t
  22086. when a sibling was found. When none is found, return nil and don't
  22087. move point."
  22088. (let ((fun (if previous 're-search-backward 're-search-forward))
  22089. (pos (point))
  22090. (re org-outline-regexp-bol)
  22091. level l)
  22092. (when (ignore-errors (org-back-to-heading t))
  22093. (setq level (funcall outline-level))
  22094. (catch 'exit
  22095. (or previous (forward-char 1))
  22096. (while (funcall fun re nil t)
  22097. (setq l (funcall outline-level))
  22098. (when (< l level) (goto-char pos) (throw 'exit nil))
  22099. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  22100. (goto-char pos)
  22101. nil))))
  22102. (defun org-show-siblings ()
  22103. "Show all siblings of the current headline."
  22104. (save-excursion
  22105. (while (org-goto-sibling) (org-flag-heading nil)))
  22106. (save-excursion
  22107. (while (org-goto-sibling 'previous)
  22108. (org-flag-heading nil))))
  22109. (defun org-goto-first-child ()
  22110. "Goto the first child, even if it is invisible.
  22111. Return t when a child was found. Otherwise don't move point and
  22112. return nil."
  22113. (let (level (pos (point)) (re org-outline-regexp-bol))
  22114. (when (ignore-errors (org-back-to-heading t))
  22115. (setq level (outline-level))
  22116. (forward-char 1)
  22117. (if (and (re-search-forward re nil t) (> (outline-level) level))
  22118. (progn (goto-char (match-beginning 0)) t)
  22119. (goto-char pos) nil))))
  22120. (defun org-show-hidden-entry ()
  22121. "Show an entry where even the heading is hidden."
  22122. (save-excursion
  22123. (org-show-entry)))
  22124. (defun org-flag-heading (flag &optional entry)
  22125. "Flag the current heading. FLAG non-nil means make invisible.
  22126. When ENTRY is non-nil, show the entire entry."
  22127. (save-excursion
  22128. (org-back-to-heading t)
  22129. ;; Check if we should show the entire entry
  22130. (if entry
  22131. (progn
  22132. (org-show-entry)
  22133. (save-excursion
  22134. (and (outline-next-heading)
  22135. (org-flag-heading nil))))
  22136. (outline-flag-region (max (point-min) (1- (point)))
  22137. (save-excursion (outline-end-of-heading) (point))
  22138. flag))))
  22139. (defun org-get-next-sibling ()
  22140. "Move to next heading of the same level, and return point.
  22141. If there is no such heading, return nil.
  22142. This is like outline-next-sibling, but invisible headings are ok."
  22143. (let ((level (funcall outline-level)))
  22144. (outline-next-heading)
  22145. (while (and (not (eobp)) (> (funcall outline-level) level))
  22146. (outline-next-heading))
  22147. (unless (or (eobp) (< (funcall outline-level) level))
  22148. (point))))
  22149. (defun org-get-last-sibling ()
  22150. "Move to previous heading of the same level, and return point.
  22151. If there is no such heading, return nil."
  22152. (let ((opoint (point))
  22153. (level (funcall outline-level)))
  22154. (outline-previous-heading)
  22155. (when (and (/= (point) opoint) (outline-on-heading-p t))
  22156. (while (and (> (funcall outline-level) level)
  22157. (not (bobp)))
  22158. (outline-previous-heading))
  22159. (unless (< (funcall outline-level) level)
  22160. (point)))))
  22161. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  22162. "Goto to the end of a subtree."
  22163. ;; This contains an exact copy of the original function, but it uses
  22164. ;; `org-back-to-heading', to make it work also in invisible
  22165. ;; trees. And is uses an invisible-ok argument.
  22166. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  22167. ;; Furthermore, when used inside Org, finding the end of a large subtree
  22168. ;; with many children and grandchildren etc, this can be much faster
  22169. ;; than the outline version.
  22170. (org-back-to-heading invisible-ok)
  22171. (let ((first t)
  22172. (level (funcall outline-level)))
  22173. (if (and (derived-mode-p 'org-mode) (< level 1000))
  22174. ;; A true heading (not a plain list item), in Org
  22175. ;; This means we can easily find the end by looking
  22176. ;; only for the right number of stars. Using a regexp to do
  22177. ;; this is so much faster than using a Lisp loop.
  22178. (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
  22179. (forward-char 1)
  22180. (and (re-search-forward re nil 'move) (beginning-of-line 1)))
  22181. ;; something else, do it the slow way
  22182. (while (and (not (eobp))
  22183. (or first (> (funcall outline-level) level)))
  22184. (setq first nil)
  22185. (outline-next-heading)))
  22186. (unless to-heading
  22187. (when (memq (preceding-char) '(?\n ?\^M))
  22188. ;; Go to end of line before heading
  22189. (forward-char -1)
  22190. (when (memq (preceding-char) '(?\n ?\^M))
  22191. ;; leave blank line before heading
  22192. (forward-char -1)))))
  22193. (point))
  22194. (defun org-end-of-meta-data (&optional full)
  22195. "Skip planning line and properties drawer in current entry.
  22196. When optional argument FULL is non-nil, also skip empty lines,
  22197. clocking lines and regular drawers at the beginning of the
  22198. entry."
  22199. (org-back-to-heading t)
  22200. (forward-line)
  22201. (when (looking-at-p org-planning-line-re) (forward-line))
  22202. (when (looking-at org-property-drawer-re)
  22203. (goto-char (match-end 0))
  22204. (forward-line))
  22205. (when (and full (not (org-at-heading-p)))
  22206. (catch 'exit
  22207. (let ((end (save-excursion (outline-next-heading) (point)))
  22208. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  22209. (while (not (eobp))
  22210. (cond ((looking-at-p org-drawer-regexp)
  22211. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  22212. (forward-line)
  22213. (throw 'exit t)))
  22214. ((looking-at-p re) (forward-line))
  22215. (t (throw 'exit t))))))))
  22216. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  22217. "Move forward to the ARG'th subheading at same level as this one.
  22218. Stop at the first and last subheadings of a superior heading.
  22219. Normally this only looks at visible headings, but when INVISIBLE-OK is
  22220. non-nil it will also look at invisible ones."
  22221. (interactive "p")
  22222. (let ((backward? (and arg (< arg 0))))
  22223. (if (org-before-first-heading-p)
  22224. (if backward? (goto-char (point-min)) (outline-next-heading))
  22225. (org-back-to-heading invisible-ok)
  22226. (unless backward? (end-of-line)) ;do not match current headline
  22227. (let ((level (- (match-end 0) (match-beginning 0) 1))
  22228. (f (if backward? #'re-search-backward #'re-search-forward))
  22229. (count (if arg (abs arg) 1))
  22230. (result (point)))
  22231. (while (and (> count 0)
  22232. (funcall f org-outline-regexp-bol nil 'move))
  22233. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  22234. (cond ((< l level) (setq count 0))
  22235. ((and (= l level)
  22236. (or invisible-ok
  22237. (not (org-invisible-p
  22238. (line-beginning-position)))))
  22239. (cl-decf count)
  22240. (when (= l level) (setq result (point)))))))
  22241. (goto-char result))
  22242. (beginning-of-line))))
  22243. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  22244. "Move backward to the ARG'th subheading at same level as this one.
  22245. Stop at the first and last subheadings of a superior heading."
  22246. (interactive "p")
  22247. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  22248. (defun org-next-visible-heading (arg)
  22249. "Move to the next visible heading.
  22250. This function wraps `outline-next-visible-heading' with
  22251. `org-with-limited-levels' in order to skip over inline tasks and
  22252. respect customization of `org-odd-levels-only'."
  22253. (interactive "p")
  22254. (org-with-limited-levels
  22255. (outline-next-visible-heading arg)))
  22256. (defun org-previous-visible-heading (arg)
  22257. "Move to the previous visible heading.
  22258. This function wraps `outline-previous-visible-heading' with
  22259. `org-with-limited-levels' in order to skip over inline tasks and
  22260. respect customization of `org-odd-levels-only'."
  22261. (interactive "p")
  22262. (org-with-limited-levels
  22263. (outline-previous-visible-heading arg)))
  22264. (defun org-next-block (arg &optional backward block-regexp)
  22265. "Jump to the next block.
  22266. With a prefix argument ARG, jump forward ARG many blocks.
  22267. When BACKWARD is non-nil, jump to the previous block.
  22268. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  22269. Match data is set according to this regexp when the function
  22270. returns.
  22271. Return point at beginning of the opening line of found block.
  22272. Throw an error if no block is found."
  22273. (interactive "p")
  22274. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  22275. (case-fold-search t)
  22276. (search-fn (if backward #'re-search-backward #'re-search-forward))
  22277. (count (or arg 1))
  22278. (origin (point))
  22279. last-element)
  22280. (if backward (beginning-of-line) (end-of-line))
  22281. (while (and (> count 0) (funcall search-fn re nil t))
  22282. (let ((element (save-excursion
  22283. (goto-char (match-beginning 0))
  22284. (save-match-data (org-element-at-point)))))
  22285. (when (and (memq (org-element-type element)
  22286. '(center-block comment-block dynamic-block
  22287. example-block export-block quote-block
  22288. special-block src-block verse-block))
  22289. (<= (match-beginning 0)
  22290. (org-element-property :post-affiliated element)))
  22291. (setq last-element element)
  22292. (cl-decf count))))
  22293. (if (= count 0)
  22294. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  22295. (save-match-data (org-show-context)))
  22296. (goto-char origin)
  22297. (user-error "No %s code blocks" (if backward "previous" "further")))))
  22298. (defun org-previous-block (arg &optional block-regexp)
  22299. "Jump to the previous block.
  22300. With a prefix argument ARG, jump backward ARG many source blocks.
  22301. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  22302. (interactive "p")
  22303. (org-next-block arg t block-regexp))
  22304. (defun org-forward-paragraph ()
  22305. "Move forward to beginning of next paragraph or equivalent.
  22306. The function moves point to the beginning of the next visible
  22307. structural element, which can be a paragraph, a table, a list
  22308. item, etc. It also provides some special moves for convenience:
  22309. - On an affiliated keyword, jump to the beginning of the
  22310. relative element.
  22311. - On an item or a footnote definition, move to the second
  22312. element inside, if any.
  22313. - On a table or a property drawer, jump after it.
  22314. - On a verse or source block, stop after blank lines."
  22315. (interactive)
  22316. (unless (eobp)
  22317. (let* ((deactivate-mark nil)
  22318. (element (org-element-at-point))
  22319. (type (org-element-type element))
  22320. (post-affiliated (org-element-property :post-affiliated element))
  22321. (contents-begin (org-element-property :contents-begin element))
  22322. (contents-end (org-element-property :contents-end element))
  22323. (end (let ((end (org-element-property :end element)) (parent element))
  22324. (while (and (setq parent (org-element-property :parent parent))
  22325. (= (org-element-property :contents-end parent) end))
  22326. (setq end (org-element-property :end parent)))
  22327. end)))
  22328. (cond ((not element)
  22329. (skip-chars-forward " \r\t\n")
  22330. (or (eobp) (beginning-of-line)))
  22331. ;; On affiliated keywords, move to element's beginning.
  22332. ((< (point) post-affiliated)
  22333. (goto-char post-affiliated))
  22334. ;; At a table row, move to the end of the table. Similarly,
  22335. ;; at a node property, move to the end of the property
  22336. ;; drawer.
  22337. ((memq type '(node-property table-row))
  22338. (goto-char (org-element-property
  22339. :end (org-element-property :parent element))))
  22340. ((memq type '(property-drawer table)) (goto-char end))
  22341. ;; Consider blank lines as separators in verse and source
  22342. ;; blocks to ease editing.
  22343. ((memq type '(src-block verse-block))
  22344. (when (eq type 'src-block)
  22345. (setq contents-end
  22346. (save-excursion (goto-char end)
  22347. (skip-chars-backward " \r\t\n")
  22348. (line-beginning-position))))
  22349. (beginning-of-line)
  22350. (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
  22351. (if (not (re-search-forward "^[ \t]*$" contents-end t))
  22352. (goto-char end)
  22353. (skip-chars-forward " \r\t\n")
  22354. (if (= (point) contents-end) (goto-char end)
  22355. (beginning-of-line))))
  22356. ;; With no contents, just skip element.
  22357. ((not contents-begin) (goto-char end))
  22358. ;; If contents are invisible, skip the element altogether.
  22359. ((org-invisible-p (line-end-position))
  22360. (cl-case type
  22361. (headline
  22362. (org-with-limited-levels (outline-next-visible-heading 1)))
  22363. ;; At a plain list, make sure we move to the next item
  22364. ;; instead of skipping the whole list.
  22365. (plain-list (forward-char)
  22366. (org-forward-paragraph))
  22367. (otherwise (goto-char end))))
  22368. ((>= (point) contents-end) (goto-char end))
  22369. ((>= (point) contents-begin)
  22370. ;; This can only happen on paragraphs and plain lists.
  22371. (cl-case type
  22372. (paragraph (goto-char end))
  22373. ;; At a plain list, try to move to second element in
  22374. ;; first item, if possible.
  22375. (plain-list (end-of-line)
  22376. (org-forward-paragraph))))
  22377. ;; When contents start on the middle of a line (e.g. in
  22378. ;; items and footnote definitions), try to reach first
  22379. ;; element starting after current line.
  22380. ((> (line-end-position) contents-begin)
  22381. (end-of-line)
  22382. (org-forward-paragraph))
  22383. (t (goto-char contents-begin))))))
  22384. (defun org-backward-paragraph ()
  22385. "Move backward to start of previous paragraph or equivalent.
  22386. The function moves point to the beginning of the current
  22387. structural element, which can be a paragraph, a table, a list
  22388. item, etc., or to the beginning of the previous visible one if
  22389. point is already there. It also provides some special moves for
  22390. convenience:
  22391. - On an affiliated keyword, jump to the first one.
  22392. - On a table or a property drawer, move to its beginning.
  22393. - On a verse or source block, stop before blank lines."
  22394. (interactive)
  22395. (unless (bobp)
  22396. (let* ((deactivate-mark nil)
  22397. (element (org-element-at-point))
  22398. (type (org-element-type element))
  22399. (contents-begin (org-element-property :contents-begin element))
  22400. (contents-end (org-element-property :contents-end element))
  22401. (post-affiliated (org-element-property :post-affiliated element))
  22402. (begin (org-element-property :begin element)))
  22403. (cond
  22404. ((not element) (goto-char (point-min)))
  22405. ((= (point) begin)
  22406. (backward-char)
  22407. (org-backward-paragraph))
  22408. ((<= (point) post-affiliated) (goto-char begin))
  22409. ((memq type '(node-property table-row))
  22410. (goto-char (org-element-property
  22411. :post-affiliated (org-element-property :parent element))))
  22412. ((memq type '(property-drawer table)) (goto-char begin))
  22413. ((memq type '(src-block verse-block))
  22414. (when (eq type 'src-block)
  22415. (setq contents-begin
  22416. (save-excursion (goto-char begin) (forward-line) (point))))
  22417. (if (= (point) contents-begin) (goto-char post-affiliated)
  22418. ;; Inside a verse block, see blank lines as paragraph
  22419. ;; separators.
  22420. (let ((origin (point)))
  22421. (skip-chars-backward " \r\t\n" contents-begin)
  22422. (when (re-search-backward "^[ \t]*$" contents-begin 'move)
  22423. (skip-chars-forward " \r\t\n" origin)
  22424. (if (= (point) origin) (goto-char contents-begin)
  22425. (beginning-of-line))))))
  22426. ((not contents-begin) (goto-char (or post-affiliated begin)))
  22427. ((eq type 'paragraph)
  22428. (goto-char contents-begin)
  22429. ;; When at first paragraph in an item or a footnote definition,
  22430. ;; move directly to beginning of line.
  22431. (let ((parent-contents
  22432. (org-element-property
  22433. :contents-begin (org-element-property :parent element))))
  22434. (when (and parent-contents (= parent-contents contents-begin))
  22435. (beginning-of-line))))
  22436. ;; At the end of a greater element, move to the beginning of the
  22437. ;; last element within.
  22438. ((>= (point) contents-end)
  22439. (goto-char (1- contents-end))
  22440. (org-backward-paragraph))
  22441. (t (goto-char (or post-affiliated begin))))
  22442. ;; Ensure we never leave point invisible.
  22443. (when (org-invisible-p (point)) (beginning-of-visual-line)))))
  22444. (defun org-forward-element ()
  22445. "Move forward by one element.
  22446. Move to the next element at the same level, when possible."
  22447. (interactive)
  22448. (cond ((eobp) (user-error "Cannot move further down"))
  22449. ((org-with-limited-levels (org-at-heading-p))
  22450. (let ((origin (point)))
  22451. (goto-char (org-end-of-subtree nil t))
  22452. (unless (org-with-limited-levels (org-at-heading-p))
  22453. (goto-char origin)
  22454. (user-error "Cannot move further down"))))
  22455. (t
  22456. (let* ((elem (org-element-at-point))
  22457. (end (org-element-property :end elem))
  22458. (parent (org-element-property :parent elem)))
  22459. (cond ((and parent (= (org-element-property :contents-end parent) end))
  22460. (goto-char (org-element-property :end parent)))
  22461. ((integer-or-marker-p end) (goto-char end))
  22462. (t (message "No element at point")))))))
  22463. (defun org-backward-element ()
  22464. "Move backward by one element.
  22465. Move to the previous element at the same level, when possible."
  22466. (interactive)
  22467. (cond ((bobp) (user-error "Cannot move further up"))
  22468. ((org-with-limited-levels (org-at-heading-p))
  22469. ;; At a headline, move to the previous one, if any, or stay
  22470. ;; here.
  22471. (let ((origin (point)))
  22472. (org-with-limited-levels (org-backward-heading-same-level 1))
  22473. ;; When current headline has no sibling above, move to its
  22474. ;; parent.
  22475. (when (= (point) origin)
  22476. (or (org-with-limited-levels (org-up-heading-safe))
  22477. (progn (goto-char origin)
  22478. (user-error "Cannot move further up"))))))
  22479. (t
  22480. (let* ((elem (org-element-at-point))
  22481. (beg (org-element-property :begin elem)))
  22482. (cond
  22483. ;; Move to beginning of current element if point isn't
  22484. ;; there already.
  22485. ((null beg) (message "No element at point"))
  22486. ((/= (point) beg) (goto-char beg))
  22487. (t (goto-char beg)
  22488. (skip-chars-backward " \r\t\n")
  22489. (unless (bobp)
  22490. (let ((prev (org-element-at-point)))
  22491. (goto-char (org-element-property :begin prev))
  22492. (while (and (setq prev (org-element-property :parent prev))
  22493. (<= (org-element-property :end prev) beg))
  22494. (goto-char (org-element-property :begin prev)))))))))))
  22495. (defun org-up-element ()
  22496. "Move to upper element."
  22497. (interactive)
  22498. (if (org-with-limited-levels (org-at-heading-p))
  22499. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  22500. (let* ((elem (org-element-at-point))
  22501. (parent (org-element-property :parent elem)))
  22502. (if parent (goto-char (org-element-property :begin parent))
  22503. (if (org-with-limited-levels (org-before-first-heading-p))
  22504. (user-error "No surrounding element")
  22505. (org-with-limited-levels (org-back-to-heading)))))))
  22506. (defun org-down-element ()
  22507. "Move to inner element."
  22508. (interactive)
  22509. (let ((element (org-element-at-point)))
  22510. (cond
  22511. ((memq (org-element-type element) '(plain-list table))
  22512. (goto-char (org-element-property :contents-begin element))
  22513. (forward-char))
  22514. ((memq (org-element-type element) org-element-greater-elements)
  22515. ;; If contents are hidden, first disclose them.
  22516. (when (org-invisible-p (line-end-position)) (org-cycle))
  22517. (goto-char (or (org-element-property :contents-begin element)
  22518. (user-error "No content for this element"))))
  22519. (t (user-error "No inner element")))))
  22520. (defun org-drag-element-backward ()
  22521. "Move backward element at point."
  22522. (interactive)
  22523. (let ((elem (or (org-element-at-point)
  22524. (user-error "No element at point"))))
  22525. (if (eq (org-element-type elem) 'headline)
  22526. ;; Preserve point when moving a whole tree, even if point was
  22527. ;; on blank lines below the headline.
  22528. (let ((offset (skip-chars-backward " \t\n")))
  22529. (unwind-protect (org-move-subtree-up)
  22530. (forward-char (- offset))))
  22531. (let ((prev-elem
  22532. (save-excursion
  22533. (goto-char (org-element-property :begin elem))
  22534. (skip-chars-backward " \r\t\n")
  22535. (unless (bobp)
  22536. (let* ((beg (org-element-property :begin elem))
  22537. (prev (org-element-at-point))
  22538. (up prev))
  22539. (while (and (setq up (org-element-property :parent up))
  22540. (<= (org-element-property :end up) beg))
  22541. (setq prev up))
  22542. prev)))))
  22543. ;; Error out if no previous element or previous element is
  22544. ;; a parent of the current one.
  22545. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  22546. (user-error "Cannot drag element backward")
  22547. (let ((pos (point)))
  22548. (org-element-swap-A-B prev-elem elem)
  22549. (goto-char (+ (org-element-property :begin prev-elem)
  22550. (- pos (org-element-property :begin elem))))))))))
  22551. (defun org-drag-element-forward ()
  22552. "Move forward element at point."
  22553. (interactive)
  22554. (let* ((pos (point))
  22555. (elem (or (org-element-at-point)
  22556. (user-error "No element at point"))))
  22557. (when (= (point-max) (org-element-property :end elem))
  22558. (user-error "Cannot drag element forward"))
  22559. (goto-char (org-element-property :end elem))
  22560. (let ((next-elem (org-element-at-point)))
  22561. (when (or (org-element-nested-p elem next-elem)
  22562. (and (eq (org-element-type next-elem) 'headline)
  22563. (not (eq (org-element-type elem) 'headline))))
  22564. (goto-char pos)
  22565. (user-error "Cannot drag element forward"))
  22566. ;; Compute new position of point: it's shifted by NEXT-ELEM
  22567. ;; body's length (without final blanks) and by the length of
  22568. ;; blanks between ELEM and NEXT-ELEM.
  22569. (let ((size-next (- (save-excursion
  22570. (goto-char (org-element-property :end next-elem))
  22571. (skip-chars-backward " \r\t\n")
  22572. (forward-line)
  22573. ;; Small correction if buffer doesn't end
  22574. ;; with a newline character.
  22575. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  22576. (org-element-property :begin next-elem)))
  22577. (size-blank (- (org-element-property :end elem)
  22578. (save-excursion
  22579. (goto-char (org-element-property :end elem))
  22580. (skip-chars-backward " \r\t\n")
  22581. (forward-line)
  22582. (point)))))
  22583. (org-element-swap-A-B elem next-elem)
  22584. (goto-char (+ pos size-next size-blank))))))
  22585. (defun org-drag-line-forward (arg)
  22586. "Drag the line at point ARG lines forward."
  22587. (interactive "p")
  22588. (dotimes (_ (abs arg))
  22589. (let ((c (current-column)))
  22590. (if (< 0 arg)
  22591. (progn
  22592. (beginning-of-line 2)
  22593. (transpose-lines 1)
  22594. (beginning-of-line 0))
  22595. (transpose-lines 1)
  22596. (beginning-of-line -1))
  22597. (org-move-to-column c))))
  22598. (defun org-drag-line-backward (arg)
  22599. "Drag the line at point ARG lines backward."
  22600. (interactive "p")
  22601. (org-drag-line-forward (- arg)))
  22602. (defun org-mark-element ()
  22603. "Put point at beginning of this element, mark at end.
  22604. Interactively, if this command is repeated or (in Transient Mark
  22605. mode) if the mark is active, it marks the next element after the
  22606. ones already marked."
  22607. (interactive)
  22608. (let (deactivate-mark)
  22609. (if (and (called-interactively-p 'any)
  22610. (or (and (eq last-command this-command) (mark t))
  22611. (and transient-mark-mode mark-active)))
  22612. (set-mark
  22613. (save-excursion
  22614. (goto-char (mark))
  22615. (goto-char (org-element-property :end (org-element-at-point)))))
  22616. (let ((element (org-element-at-point)))
  22617. (end-of-line)
  22618. (push-mark (org-element-property :end element) t t)
  22619. (goto-char (org-element-property :begin element))))))
  22620. (defun org-narrow-to-element ()
  22621. "Narrow buffer to current element."
  22622. (interactive)
  22623. (let ((elem (org-element-at-point)))
  22624. (cond
  22625. ((eq (car elem) 'headline)
  22626. (narrow-to-region
  22627. (org-element-property :begin elem)
  22628. (org-element-property :end elem)))
  22629. ((memq (car elem) org-element-greater-elements)
  22630. (narrow-to-region
  22631. (org-element-property :contents-begin elem)
  22632. (org-element-property :contents-end elem)))
  22633. (t
  22634. (narrow-to-region
  22635. (org-element-property :begin elem)
  22636. (org-element-property :end elem))))))
  22637. (defun org-transpose-element ()
  22638. "Transpose current and previous elements, keeping blank lines between.
  22639. Point is moved after both elements."
  22640. (interactive)
  22641. (org-skip-whitespace)
  22642. (let ((end (org-element-property :end (org-element-at-point))))
  22643. (org-drag-element-backward)
  22644. (goto-char end)))
  22645. (defun org-unindent-buffer ()
  22646. "Un-indent the visible part of the buffer.
  22647. Relative indentation (between items, inside blocks, etc.) isn't
  22648. modified."
  22649. (interactive)
  22650. (unless (eq major-mode 'org-mode)
  22651. (user-error "Cannot un-indent a buffer not in Org mode"))
  22652. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  22653. (unindent-tree
  22654. (lambda (contents)
  22655. (dolist (element (reverse contents))
  22656. (if (memq (org-element-type element) '(headline section))
  22657. (funcall unindent-tree (org-element-contents element))
  22658. (save-excursion
  22659. (save-restriction
  22660. (narrow-to-region
  22661. (org-element-property :begin element)
  22662. (org-element-property :end element))
  22663. (org-do-remove-indentation))))))))
  22664. (funcall unindent-tree (org-element-contents parse-tree))))
  22665. (defun org-show-children (&optional level)
  22666. "Show all direct subheadings of this heading.
  22667. Prefix arg LEVEL is how many levels below the current level
  22668. should be shown. Default is enough to cause the following
  22669. heading to appear."
  22670. (interactive "p")
  22671. ;; If `orgstruct-mode' is active, use the slower version.
  22672. (if orgstruct-mode (call-interactively #'outline-show-children)
  22673. (save-excursion
  22674. (org-back-to-heading t)
  22675. (let* ((current-level (funcall outline-level))
  22676. (max-level (org-get-valid-level
  22677. current-level
  22678. (if level (prefix-numeric-value level) 1)))
  22679. (end (save-excursion (org-end-of-subtree t t)))
  22680. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  22681. (past-first-child nil)
  22682. ;; Make sure to skip inlinetasks.
  22683. (re (format regexp-fmt
  22684. current-level
  22685. (cond
  22686. ((not (featurep 'org-inlinetask)) "")
  22687. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  22688. 3))
  22689. (t (1- org-inlinetask-min-level))))))
  22690. ;; Display parent heading.
  22691. (outline-flag-region (line-end-position 0) (line-end-position) nil)
  22692. (forward-line)
  22693. ;; Display children. First child may be deeper than expected
  22694. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  22695. ;; MAX-LEVEL accordingly.
  22696. (while (re-search-forward re end t)
  22697. (unless past-first-child
  22698. (setq re (format regexp-fmt
  22699. current-level
  22700. (max (funcall outline-level) max-level)))
  22701. (setq past-first-child t))
  22702. (outline-flag-region
  22703. (line-end-position 0) (line-end-position) nil))))))
  22704. (defun org-show-subtree ()
  22705. "Show everything after this heading at deeper levels."
  22706. (interactive)
  22707. (outline-flag-region
  22708. (point)
  22709. (save-excursion
  22710. (org-end-of-subtree t t))
  22711. nil))
  22712. (defun org-show-entry ()
  22713. "Show the body directly following this heading.
  22714. Show the heading too, if it is currently invisible."
  22715. (interactive)
  22716. (save-excursion
  22717. (ignore-errors
  22718. (org-back-to-heading t)
  22719. (outline-flag-region
  22720. (max (point-min) (1- (point)))
  22721. (save-excursion
  22722. (if (re-search-forward
  22723. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  22724. (match-beginning 1)
  22725. (point-max)))
  22726. nil)
  22727. (org-cycle-hide-drawers 'children))))
  22728. (defun org-make-options-regexp (kwds &optional extra)
  22729. "Make a regular expression for keyword lines.
  22730. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  22731. when non-nil, is a regexp matching keywords names."
  22732. (concat "^[ \t]*#\\+\\("
  22733. (regexp-opt kwds)
  22734. (and extra (concat (and kwds "\\|") extra))
  22735. "\\):[ \t]*\\(.*\\)"))
  22736. ;;;; Integration with and fixes for other packages
  22737. ;;; Imenu support
  22738. (defvar-local org-imenu-markers nil
  22739. "All markers currently used by Imenu.")
  22740. (defun org-imenu-new-marker (&optional pos)
  22741. "Return a new marker for use by Imenu, and remember the marker."
  22742. (let ((m (make-marker)))
  22743. (move-marker m (or pos (point)))
  22744. (push m org-imenu-markers)
  22745. m))
  22746. (defun org-imenu-get-tree ()
  22747. "Produce the index for Imenu."
  22748. (dolist (x org-imenu-markers) (move-marker x nil))
  22749. (setq org-imenu-markers nil)
  22750. (let* ((case-fold-search nil)
  22751. (n org-imenu-depth)
  22752. (re (concat "^" (org-get-limited-outline-regexp)))
  22753. (subs (make-vector (1+ n) nil))
  22754. (last-level 0)
  22755. m level head0 head)
  22756. (org-with-wide-buffer
  22757. (goto-char (point-max))
  22758. (while (re-search-backward re nil t)
  22759. (setq level (org-reduced-level (funcall outline-level)))
  22760. (when (and (<= level n)
  22761. (looking-at org-complex-heading-regexp)
  22762. (setq head0 (match-string-no-properties 4)))
  22763. (setq head (org-link-display-format head0)
  22764. m (org-imenu-new-marker))
  22765. (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
  22766. (if (>= level last-level)
  22767. (push (cons head m) (aref subs level))
  22768. (push (cons head (aref subs (1+ level))) (aref subs level))
  22769. (cl-loop for i from (1+ level) to n do (aset subs i nil)))
  22770. (setq last-level level))))
  22771. (aref subs 1)))
  22772. (eval-after-load "imenu"
  22773. '(progn
  22774. (add-hook 'imenu-after-jump-hook
  22775. (lambda ()
  22776. (when (derived-mode-p 'org-mode)
  22777. (org-show-context 'org-goto))))))
  22778. (defun org-link-display-format (s)
  22779. "Replace links in string S with their description.
  22780. If there is no description, use the link target."
  22781. (save-match-data
  22782. (replace-regexp-in-string
  22783. org-bracket-link-analytic-regexp
  22784. (lambda (m)
  22785. (if (match-end 5) (match-string 5 m)
  22786. (concat (match-string 1 m) (match-string 3 m))))
  22787. s nil t)))
  22788. (defun org-toggle-link-display ()
  22789. "Toggle the literal or descriptive display of links."
  22790. (interactive)
  22791. (if org-descriptive-links
  22792. (progn (org-remove-from-invisibility-spec '(org-link))
  22793. (org-restart-font-lock)
  22794. (setq org-descriptive-links nil))
  22795. (progn (add-to-invisibility-spec '(org-link))
  22796. (org-restart-font-lock)
  22797. (setq org-descriptive-links t))))
  22798. ;; Speedbar support
  22799. (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
  22800. "Overlay marking the agenda restriction line in speedbar.")
  22801. (overlay-put org-speedbar-restriction-lock-overlay
  22802. 'face 'org-agenda-restriction-lock)
  22803. (overlay-put org-speedbar-restriction-lock-overlay
  22804. 'help-echo "Agendas are currently limited to this item.")
  22805. (delete-overlay org-speedbar-restriction-lock-overlay)
  22806. (defun org-speedbar-set-agenda-restriction ()
  22807. "Restrict future agenda commands to the location at point in speedbar.
  22808. To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
  22809. (interactive)
  22810. (require 'org-agenda)
  22811. (let (p m tp np dir txt)
  22812. (cond
  22813. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22814. 'org-imenu t))
  22815. (setq m (get-text-property p 'org-imenu-marker))
  22816. (with-current-buffer (marker-buffer m)
  22817. (goto-char m)
  22818. (org-agenda-set-restriction-lock 'subtree)))
  22819. ((setq p (text-property-any (point-at-bol) (point-at-eol)
  22820. 'speedbar-function 'speedbar-find-file))
  22821. (setq tp (previous-single-property-change
  22822. (1+ p) 'speedbar-function)
  22823. np (next-single-property-change
  22824. tp 'speedbar-function)
  22825. dir (speedbar-line-directory)
  22826. txt (buffer-substring-no-properties (or tp (point-min))
  22827. (or np (point-max))))
  22828. (with-current-buffer (find-file-noselect
  22829. (let ((default-directory dir))
  22830. (expand-file-name txt)))
  22831. (unless (derived-mode-p 'org-mode)
  22832. (user-error "Cannot restrict to non-Org mode file"))
  22833. (org-agenda-set-restriction-lock 'file)))
  22834. (t (user-error "Don't know how to restrict Org mode agenda")))
  22835. (move-overlay org-speedbar-restriction-lock-overlay
  22836. (point-at-bol) (point-at-eol))
  22837. (setq current-prefix-arg nil)
  22838. (org-agenda-maybe-redo)))
  22839. (defvar speedbar-file-key-map)
  22840. (declare-function speedbar-add-supported-extension "speedbar" (extension))
  22841. (eval-after-load "speedbar"
  22842. '(progn
  22843. (speedbar-add-supported-extension ".org")
  22844. (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
  22845. (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
  22846. (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
  22847. (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
  22848. (add-hook 'speedbar-visiting-tag-hook
  22849. (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
  22850. ;;; Fixes and Hacks for problems with other packages
  22851. (defun org--flyspell-object-check-p (element)
  22852. "Non-nil when Flyspell can check object at point.
  22853. ELEMENT is the element at point."
  22854. (let ((object (save-excursion
  22855. (when (looking-at-p "\\>") (backward-char))
  22856. (org-element-context element))))
  22857. (cl-case (org-element-type object)
  22858. ;; Prevent checks in links due to keybinding conflict with
  22859. ;; Flyspell.
  22860. ((code entity export-snippet inline-babel-call
  22861. inline-src-block line-break latex-fragment link macro
  22862. statistics-cookie target timestamp verbatim)
  22863. nil)
  22864. (footnote-reference
  22865. ;; Only in inline footnotes, within the definition.
  22866. (and (eq (org-element-property :type object) 'inline)
  22867. (< (save-excursion
  22868. (goto-char (org-element-property :begin object))
  22869. (search-forward ":" nil t 2))
  22870. (point))))
  22871. (otherwise t))))
  22872. (defun org-mode-flyspell-verify ()
  22873. "Function used for `flyspell-generic-check-word-predicate'."
  22874. (if (org-at-heading-p)
  22875. ;; At a headline or an inlinetask, check title only. This is
  22876. ;; faster than relying on `org-element-at-point'.
  22877. (and (save-excursion (beginning-of-line)
  22878. (and (let ((case-fold-search t))
  22879. (not (looking-at-p "\\*+ END[ \t]*$")))
  22880. (let ((case-fold-search nil))
  22881. (looking-at org-complex-heading-regexp))))
  22882. (match-beginning 4)
  22883. (>= (point) (match-beginning 4))
  22884. (or (not (match-beginning 5))
  22885. (< (point) (match-beginning 5))))
  22886. (let* ((element (org-element-at-point))
  22887. (post-affiliated (org-element-property :post-affiliated element)))
  22888. (cond
  22889. ;; Ignore checks in all affiliated keywords but captions.
  22890. ((< (point) post-affiliated)
  22891. (and (save-excursion
  22892. (beginning-of-line)
  22893. (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
  22894. (> (point) (match-end 0))
  22895. (org--flyspell-object-check-p element)))
  22896. ;; Ignore checks in LOGBOOK (or equivalent) drawer.
  22897. ((let ((log (org-log-into-drawer)))
  22898. (and log
  22899. (let ((drawer (org-element-lineage element '(drawer))))
  22900. (and drawer
  22901. (eq (compare-strings
  22902. log nil nil
  22903. (org-element-property :drawer-name drawer) nil nil t)
  22904. t)))))
  22905. nil)
  22906. (t
  22907. (cl-case (org-element-type element)
  22908. ((comment quote-section) t)
  22909. (comment-block
  22910. ;; Allow checks between block markers, not on them.
  22911. (and (> (line-beginning-position) post-affiliated)
  22912. (save-excursion
  22913. (end-of-line)
  22914. (skip-chars-forward " \r\t\n")
  22915. (< (point) (org-element-property :end element)))))
  22916. ;; Arbitrary list of keywords where checks are meaningful.
  22917. ;; Make sure point is on the value part of the element.
  22918. (keyword
  22919. (and (member (org-element-property :key element)
  22920. '("DESCRIPTION" "TITLE"))
  22921. (save-excursion
  22922. (search-backward ":" (line-beginning-position) t))))
  22923. ;; Check is globally allowed in paragraphs verse blocks and
  22924. ;; table rows (after affiliated keywords) but some objects
  22925. ;; must not be affected.
  22926. ((paragraph table-row verse-block)
  22927. (let ((cbeg (org-element-property :contents-begin element))
  22928. (cend (org-element-property :contents-end element)))
  22929. (and cbeg (>= (point) cbeg) (< (point) cend)
  22930. (org--flyspell-object-check-p element))))))))))
  22931. (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
  22932. (defun org-remove-flyspell-overlays-in (beg end)
  22933. "Remove flyspell overlays in region."
  22934. (and (bound-and-true-p flyspell-mode)
  22935. (fboundp 'flyspell-delete-region-overlays)
  22936. (flyspell-delete-region-overlays beg end)))
  22937. (defvar flyspell-delayed-commands)
  22938. (eval-after-load "flyspell"
  22939. '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
  22940. ;; Make `bookmark-jump' shows the jump location if it was hidden.
  22941. (eval-after-load "bookmark"
  22942. '(if (boundp 'bookmark-after-jump-hook)
  22943. ;; We can use the hook
  22944. (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
  22945. ;; Hook not available, use advice
  22946. (defadvice bookmark-jump (after org-make-visible activate)
  22947. "Make the position visible."
  22948. (org-bookmark-jump-unhide))))
  22949. ;; Make sure saveplace shows the location if it was hidden
  22950. (eval-after-load "saveplace"
  22951. '(defadvice save-place-find-file-hook (after org-make-visible activate)
  22952. "Make the position visible."
  22953. (org-bookmark-jump-unhide)))
  22954. ;; Make sure ecb shows the location if it was hidden
  22955. (eval-after-load "ecb"
  22956. '(defadvice ecb-method-clicked (after esf/org-show-context activate)
  22957. "Make hierarchy visible when jumping into location from ECB tree buffer."
  22958. (when (derived-mode-p 'org-mode)
  22959. (org-show-context))))
  22960. (defun org-bookmark-jump-unhide ()
  22961. "Unhide the current position, to show the bookmark location."
  22962. (and (derived-mode-p 'org-mode)
  22963. (or (org-invisible-p)
  22964. (save-excursion (goto-char (max (point-min) (1- (point))))
  22965. (org-invisible-p)))
  22966. (org-show-context 'bookmark-jump)))
  22967. (defun org-mark-jump-unhide ()
  22968. "Make the point visible with `org-show-context' after jumping to the mark."
  22969. (when (and (derived-mode-p 'org-mode)
  22970. (org-invisible-p))
  22971. (org-show-context 'mark-goto)))
  22972. (eval-after-load "simple"
  22973. '(defadvice pop-to-mark-command (after org-make-visible activate)
  22974. "Make the point visible with `org-show-context'."
  22975. (org-mark-jump-unhide)))
  22976. (eval-after-load "simple"
  22977. '(defadvice exchange-point-and-mark (after org-make-visible activate)
  22978. "Make the point visible with `org-show-context'."
  22979. (org-mark-jump-unhide)))
  22980. (eval-after-load "simple"
  22981. '(defadvice pop-global-mark (after org-make-visible activate)
  22982. "Make the point visible with `org-show-context'."
  22983. (org-mark-jump-unhide)))
  22984. ;; Make session.el ignore our circular variable
  22985. (defvar session-globals-exclude)
  22986. (eval-after-load "session"
  22987. '(add-to-list 'session-globals-exclude 'org-mark-ring))
  22988. ;;;; Finish up
  22989. (provide 'org)
  22990. (run-hooks 'org-load-hook)
  22991. ;;; org.el ends here